赞
踩
在这个项目中,BERT情感分析的功能是利用预训练的BERT模型对微博文本进行情感分类。首先,通过对文本进行深度清理和探索性数据分析,针对不同情感类别进行数据预处理。然后,使用BERT的tokenizer对文本进行编码,并构建了一个深度学习模型,通过微调(fine-tuning)BERT模型在训练集上进行训练。最后,通过对测试集进行预测,生成了情感分类结果,并通过混淆矩阵和分类报告进行性能评估。BERT情感分析旨在实现对微博文本情感的准确分类,从而为情感分析提供了更高水平的性能。
(1)现在已经对标记化的句子进行了基本分析,接下来只需要定义一个自定义分词器函数并调用BERT分词器的encode_plus方法。下面代码定义了一个名为tokenize的函数,用于将输入的文本数据进行分词。该函数使用BERT分词器的encode_plus方法,将输入文本转换为模型可以处理的格式,包括输入的词索引(input_ids)和关注掩码(attention_masks)。函数还允许指定最大长度,并在需要时进行填充。最终,函数返回分词后的输入和关注掩码的NumPy数组。
- MAX_LEN=128
-
- def tokenize(data,max_len=MAX_LEN) :
- input_ids = []
- attention_masks = []
- for i in range(len(data)):
- encoded = tokenizer.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)
'运行
(2)然后,我们将分词器函数应用于训练、验证和测试集。下面代码使用之前定义的tokenize函数,将训练集、验证集和测试集的文本数据进行分词,得到相应的输入词索引和关注掩码。这样,文本数据就准备好输入BERT模型进行训练和测试。
- train_input_ids, train_attention_masks = tokenize(X_train, MAX_LEN)
- val_input_ids, val_attention_masks = tokenize(X_valid, MAX_LEN)
- test_input_ids, test_attention_masks = tokenize(X_test, MAX_LEN)
(1)接下来可以从Hugging Face的预训练库中导入BERT模型,例如下面的代码使用Hugging Face的transformers库从预训练的BERT模型('bert-base-uncased')中导入TFBertModel。这个模型是TensorFlow的BERT模型,它已经在大规模语料上进行了预训练,并可以用于进一步的微调或下游任务,如情感分析。
bert_model = TFBertModel.from_pretrained('bert-base-uncased')
执行后会输出:
- Some layers from the model checkpoint at bert-base-uncased were not used when initializing TFBertModel: ['mlm___cls', 'nsp___cls']
- - This IS expected if you are initializing TFBertModel 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 TFBertModel 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 TFBertModel were initialized from the model checkpoint at bert-base-uncased.
- If your task is similar to the task the model of the checkpoint was trained on, you can already use TFBertModel for predictions without further training.
上面的输出信息表明,BERT模型在初始化时没有使用模型检查点 'bert-base-uncased' 中的一些层,具体为 ['mlm___cls', 'nsp___cls']。在本项目中,TFBertModel的所有层都已从 'bert-base-uncased' 的模型检查点中初始化。如果你的任务与检查点模型上训练的任务相似,可以直接使用TFBertModel进行预测,而无需进一步训练。
(2)接下来创建一个自定义函数,用于加载预训练的BERT模型,并连接一个具有3个神经元输出层的层,以执行对数据集的3个不同类别(3种情感)进行分类。例如下面的代码定义了一个名为create_model的函数,用于创建一个基于BERT模型的情感分析模型。该函数接受一个预训练的BERT模型(bert_model)和最大长度(max_len)作为参数。
- def create_model(bert_model, max_len=MAX_LEN):
-
- ##params###
- 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')
- embeddings = bert_model([input_ids,attention_masks])[1]
- output = tf.keras.layers.Dense(3, activation="softmax")(embeddings)
- model = tf.keras.models.Model(inputs = [input_ids,attention_masks], outputs = output)
- model.compile(opt, loss=loss, metrics=accuracy)
- return model
在函数create_model的内部,首先定义了优化器(opt)、损失函数(loss)和准确率作为度量标准(accuracy)。接着,创建了两个输入层,分别用于输入BERT模型的input_ids和attention_masks。然后,通过调用BERT模型并仅保留其第二个输出(对应于BertModel的[1]),获取了嵌入层(embeddings)。最后,通过一个具有3个神经元和softmax激活函数的密集层(Dense)进行多类别分类,并构建了整个模型。最后,使用Adam优化器、交叉熵损失函数和准确率作为度量标准来编译模型,并将其返回。
(3)创建了一个情感分析模型,并输出了该模型的概要信息(summary)。情感分析模型是基于BERT模型的,使用了BERT的嵌入层,并在顶部添加了一个具有3个神经元和softmax激活函数的输出层。
- model = create_model(bert_model, MAX_LEN)
- model.summary()
执行后会输出如下所示的模型的概要信息,包括模型的层次结构、参数数量等详细信息。
- Model: "model_1"
- __________________________________________________________________________________________________
- Layer (type) Output Shape Param # Connected to
- ==================================================================================================
- input_5 (InputLayer) [(None, 128)] 0
- __________________________________________________________________________________________________
- input_6 (InputLayer) [(None, 128)] 0
- __________________________________________________________________________________________________
- tf_bert_model_1 (TFBertModel) TFBaseModelOutputWit 109482240 input_5[0][0]
- input_6[0][0]
- __________________________________________________________________________________________________
- dense_1 (Dense) (None, 3) 2307 tf_bert_model_1[0][1]
- ==================================================================================================
- Total params: 109,484,547
- Trainable params: 109,484,547
- Non-trainable params: 0
- __________________________________________________________________________________________________
(4)下面代码用于对BERT transformer模型进行微调,它使用了训练数据(train_input_ids和train_attention_masks)和验证数据(val_input_ids和val_attention_masks)进行指定数量的训练轮次(在此为4轮),并使用批处理大小为32。训练的进展情况将存储在history_bert变量中,可用于进一步的分析或可视化。
history_bert = model.fit([train_input_ids,train_attention_masks], y_train, validation_data=([val_input_ids,val_attention_masks], y_valid), epochs=4, batch_size=32)
执行后会输出:
- Epoch 1/4
- 1519/1519 [==============================] - 758s 490ms/step - loss: 0.5609 - categorical_accuracy: 0.7754 - val_loss: 0.3937 - val_categorical_accuracy: 0.8578
- Epoch 2/4
- 1519/1519 [==============================] - 742s 489ms/step - loss: 0.2872 - categorical_accuracy: 0.8974 - val_loss: 0.2986 - val_categorical_accuracy: 0.8981
- Epoch 3/4
- 1519/1519 [==============================] - 742s 488ms/step - loss: 0.1936 - categorical_accuracy: 0.9333 - val_loss: 0.2445 - val_categorical_accuracy: 0.9191
- Epoch 4/4
- 1519/1519 [==============================] - 742s 488ms/step - loss: 0.1281 - categorical_accuracy: 0.9561 - val_loss: 0.2399 - val_categorical_accuracy: 0.9252
(1)下面代码用于对测试数据进行预测,得到BERT模型的输出结果。result_bert包含了每个测试样本在三个情感类别上的预测概率,而y_pred_bert则将概率最高的类别设为1,其余为0,得到了模型的最终预测结果。这些结果可以用于后续的评估和分析,比如计算准确度、F1分数等性能指标。
- result_bert = model.predict([test_input_ids,test_attention_masks])
- y_pred_bert = np.zeros_like(result_bert)
- y_pred_bert[np.arange(len(y_pred_bert)), result_bert.argmax(1)] = 1
(2)下面代码用于生成并显示BERT模型在测试数据上的混淆矩阵,以评估模型在各个情感类别上的性能。混淆矩阵显示了模型的预测结果与实际标签之间的关系,有助于了解模型在不同类别上的准确性、召回率等指标。
conf_matrix(y_test.argmax(1), y_pred_bert.argmax(1),'BERT Sentiment Analysis\nConfusion Matrix')
生成的可视化图的效果如图11-6所示。
图11-6 BERT模型在测试数据上的混淆矩阵
(3)通过如下代码生成并打印苏处BERT模型在测试数据上的分类报告。在分类报告中包含了各个类别上的精确度、召回率、F1分数等指标,提供了对模型性能的详细评估。通过这些指标,可以更全面地了解BERT模型在情感分析任务上的表现。
print('\tClassification Report for BERT:\n\n',classification_report(y_test,y_pred_bert, target_names=['Negative', 'Neutral', 'Positive']))
执行后会输出:
- Classification Report for BERT:
-
- precision recall f1-score support
-
- Negative 0.88 0.91 0.89 1629
- Neutral 0.89 0.75 0.82 614
- Positive 0.89 0.91 0.90 1544
-
- micro avg 0.89 0.89 0.89 3787
- macro avg 0.89 0.86 0.87 3787
- weighted avg 0.89 0.89 0.88 3787
- samples avg 0.89 0.89 0.89 3787
通过上面输出的报告可知,该BERT模型在测试数据上的分类报告包含了针对三个情感类别(Negative、Neutral、Positive)的精确度、召回率、F1分数等指标。模型在各个类别上的性能相当不错,特别是在Negative和Positive两个类别上表现较为出色,整体F1分数达到了0.89。这表明BERT模型在情感分析任务中能够有效地区分不同的情感类别,具有较高的分类性能。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。