(11-9)基于大模型的情感分析系统(Tensorflow+BERT+RoBERTa+Sklearn):基于BERT大模型情感分析

11.10  基于BERT大模型情感分析

在这个项目中,BERT情感分析的功能是利用预训练的BERT模型对微博文本进行情感分类。首先,通过对文本进行深度清理和探索性数据分析,针对不同情感类别进行数据预处理。然后,使用BERT的tokenizer对文本进行编码,并构建了一个深度学习模型,通过微调(fine-tuning)BERT模型在训练集上进行训练。最后,通过对测试集进行预测,生成了情感分类结果,并通过混淆矩阵和分类报告进行性能评估。BERT情感分析旨在实现对微博文本情感的准确分类,从而为情感分析提供了更高水平的性能。

11.10.1  分词器

(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)

11.10.2  训练BERT模型并微调

(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

11.10.3  测试BERT大模型

(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模型在情感分析任务中能够有效地区分不同的情感类别,具有较高的分类性能。

  • 28
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农三叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值