赞
踩
在这个项目中,基于RoBERTa大模型的情感分析的功能是借助预训练的RoBERTa模型对微博文本进行情感分类。通过RoBERTa的tokenizer对文本进行编码,并构建深度学习模型,在训练集上进行微调。通过对测试集进行预测,生成情感分类结果,并通过混淆矩阵和分类报告进行性能评估。RoBERTa模型的应用旨在提高对微博文本情感的准确分类,为情感分析提供更强大的性能。
(1)与前面使用BERT模型的方法一样,首先导入用于训练原始RoBERTa模型的Transformer标记器。下面的代码用于从Hugging Face的模型库中导入预训练的RoBERTa Transformer的标记器(tokenizer),使用的是"roberta-base"预训练模型。在这里,标记器负责将文本数据转换成模型可以理解的标记形式。
tokenizer_roberta = RobertaTokenizerFast.from_pretrained("roberta-base")
(2)首先,检查RoBERTa标记器生成的最长标记化句子的长度。下面的代码使用 RoBERTa 的 tokenizer 对训练集文本进行编码,通过遍历每个文本,检查其经过编码后的 token 数量,并找出最长编码的句子长度。
- # 通过 RoBERTa 的 tokenizer 对训练集文本进行编码,并检查最长编码的句子长度
- token_lens = []
-
- for txt in X_train:
- tokens = tokenizer_roberta.encode(txt, max_length=512, truncation=True)
- token_lens.append(len(tokens))
- max_length=np.max(token_lens)
- max_length
执行后会输出最大句子长度,用于后续模型的参数设置。
89
'运行
(3)请看下面的代码,首先,检查了通过RoBERTa标记器标记的最长句子的长度,并确定最大长度为128。接下来,定义了用于RoBERTa标记的自定义函数tokenize_roberta(),该函数将原始文本转换为RoBERTa模型可以理解的格式。最后,使用函数tokenize_roberta()对训练集、验证集和测试集进行了标记,得到了输入ID和注意力掩码。
- MAX_LEN=128
-
- def tokenize_roberta(data,max_len=MAX_LEN) :
- input_ids = []
- attention_masks = []
- for i in range(len(data)):
- encoded = tokenizer_roberta.encode_plus(
- data[i],
- add_special_tokens=True,
- max_length=max_len,
- padding='max_length',
- return_attention_mask=True
- )
- input_ids.append(encoded['input_ids'])
- attention_masks.append(encoded['attention_mask'])
- return np.array(input_ids),np.array(attention_masks)
-
- train_input_ids, train_attention_masks = tokenize_roberta(X_train, MAX_LEN)
- val_input_ids, val_attention_masks = tokenize_roberta(X_valid, MAX_LEN)
- test_input_ids, test_attention_masks = tokenize_roberta(X_test, MAX_LEN)
(1)下面的代码定义了函数create_model,该函数用于创建RoBERTa模型。函数create_model接受一个预训练的RoBERTa模型和最大序列长度作为参数,然后构建了一个分类模型。该模型包含两个输入(输入ID和注意力掩码),通过RoBERTa模型的输出(其中的第一个元素)获得表示,然后连接一个具有3个神经元和softmax激活函数的全连接层,最终输出分类概率。模型使用Adam优化器、分类交叉熵损失和分类准确率作为评估指标进行编译。此外,还从Hugging Face的transformers库中导入了RoBERTa模型的预训练权重,并创建了一个RoBERTa模型roberta_model。
- def create_model(bert_model, max_len=MAX_LEN):
-
- opt = tf.keras.optimizers.Adam(learning_rate=1e-5, decay=1e-7)
- loss = tf.keras.losses.CategoricalCrossentropy()
- accuracy = tf.keras.metrics.CategoricalAccuracy()
-
- input_ids = tf.keras.Input(shape=(max_len,),dtype='int32')
- attention_masks = tf.keras.Input(shape=(max_len,),dtype='int32')
- output = bert_model([input_ids,attention_masks])
- output = output[1]
- output = tf.keras.layers.Dense(3, activation=tf.nn.softmax)(output)
- model = tf.keras.models.Model(inputs = [input_ids,attention_masks],outputs = output)
- model.compile(opt, loss=loss, metrics=accuracy)
- return model
(2)使用函数create_model创建RoBERTa模型,具体实现代码如下所示。
roberta_model = TFRobertaModel.from_pretrained('roberta-base')
执行后会输出:
- Some layers from the model checkpoint at roberta-base were not used when initializing TFRobertaModel: ['lm_head']
- - This IS expected if you are initializing TFRobertaModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- - This IS NOT expected if you are initializing TFRobertaModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
- All the layers of TFRobertaModel were initialized from the model checkpoint at roberta-base.
- If your task is similar to the task the model of the checkpoint was trained on, you can already use TFRobertaModel for predictions without further training.
上面的输出、表示从预训练的RoBERTa模型中加载的权重,其中的'lm_head'层在我们的分类任务中未被使用。这种情况在从预训练模型加载权重时是正常的,因为RoBERTa模型通常包括用于掩码语言模型(Masked Language Modeling,MLM)预训练任务的头部('lm_head'),但在我们的情感分类任务中不需要。
(3)创建基于RoBERTa模型的情感分类模型,通过函数summary()查看这个模型的摘要(summary)信息。
- model = create_model(roberta_model, MAX_LEN)
- model.summary()
执行后会输出显示这个模型的摘要信息,包括每一层的参数数量和结构。
- Model: "model_2"
- __________________________________________________________________________________________________
- Layer (type) Output Shape Param # Connected to
- ==================================================================================================
- input_7 (InputLayer) [(None, 128)] 0
- __________________________________________________________________________________________________
- input_8 (InputLayer) [(None, 128)] 0
- __________________________________________________________________________________________________
- tf_roberta_model_1 (TFRobertaMo TFBaseModelOutputWit 124645632 input_7[0][0]
- input_8[0][0]
- __________________________________________________________________________________________________
- dense_2 (Dense) (None, 3) 2307 tf_roberta_model_1[0][1]
- ==================================================================================================
- Total params: 124,647,939
- Trainable params: 124,647,939
- Non-trainable params: 0
- __________________________________________________________________________________________________
(4)在下面的这段代码中,使用RoBERTa模型进行了微调,通过定义一个自定义的神经网络模型,其中包含RoBERTa模型的权重,并在最后一层添加了一个包含3个神经元的softmax激活层,以进行情感分类任务。然后,使用训练和验证数据集对模型进行了4个时期的训练。
history_2 = model.fit([train_input_ids,train_attention_masks], y_train, validation_data=([val_input_ids,val_attention_masks], y_valid), epochs=4, batch_size=30)
执行后会输出:
- Epoch 1/4
- 1620/1620 [==============================] - 783s 475ms/step - loss: 0.5798 - categorical_accuracy: 0.7707 - val_loss: 0.4027 - val_categorical_accuracy: 0.8454
- Epoch 2/4
- 1620/1620 [==============================] - 768s 474ms/step - loss: 0.3428 - categorical_accuracy: 0.8787 - val_loss: 0.3188 - val_categorical_accuracy: 0.8861
- Epoch 3/4
- 1620/1620 [==============================] - 783s 484ms/step - loss: 0.2586 - categorical_accuracy: 0.9080 - val_loss: 0.2669 - val_categorical_accuracy: 0.9089
- Epoch 4/4
- 1620/1620 [==============================] - 768s 474ms/step - loss: 0.1938 - categorical_accuracy: 0.9328 - val_loss: 0.2406 - val_categorical_accuracy: 0.9194
在这个模型的训练过程中,经过4个时期的训练,训练集和验证集的损失逐渐减小,同时分类准确率逐步提高。这表明模型在训练期间逐渐学习到了数据的模式,并在验证集上表现良好。可以通过这个模型在测试集上进行情感分析,并检查其性能。
(1)使用RoBERTa模型在测试集上进行情感分析,将结果保存在result_roberta和y_pred_roberta中,这些结果可以用于进一步的分析和评估模型的性能。
- result_roberta = model.predict([test_input_ids,test_attention_masks])
- y_pred_roberta = np.zeros_like(result_roberta)
- y_pred_roberta[np.arange(len(y_pred_roberta)), result_roberta.argmax(1)] = 1
(2)通过下面代码生成了RoBERTa情感分析模型的混淆矩阵,用于评估模型在测试集上的性能。这个混淆矩阵展示了模型对每个类别的分类情况,包括真正例、假正例、真负例和假负例。通过混淆矩阵,可以更详细地了解模型在不同类别上的表现。
conf_matrix(y_test.argmax(1),y_pred_roberta.argmax(1),'RoBERTa Sentiment Analysis\nConfusion Matrix')
执行后会绘制一个混淆矩阵图,如图11-7所示。
图11-7 混淆矩阵图
(3)通过下面的代码段生成并打印输出RoBERTa模型在测试集上的分类报告信息,该报告包括了关于负面、中性和正面情感类别的精度、召回率、F1分数等详细信息,这有助于全面评估模型在情感分析任务中的性能。
print('\tClassification Report for RoBERTa:\n\n',classification_report(y_test,y_pred_roberta, target_names=['Negative', 'Neutral', 'Positive']))
执行后会输出:
- Classification Report for RoBERTa:
-
- precision recall f1-score support
-
- Negative 0.91 0.89 0.90 1629
- Neutral 0.74 0.84 0.78 614
- Positive 0.92 0.88 0.90 1544
-
- micro avg 0.88 0.88 0.88 3787
- macro avg 0.85 0.87 0.86 3787
- weighted avg 0.88 0.88 0.88 3787
- samples avg 0.88 0.88 0.88 3787
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。