使用LSTM网络实现文本情感分析

一、实验目的:

理解循环神经网络的基本概念和原理;了解循环神经网络处理文本数据的基本方法;掌握循环神经网络处理文本数据的实践方法,并实现文本情感分析任务。

  • 实验要求:

使用Keras框架定义并训练循环神经网络模型,并进行文本情感分析。

python 复制代码
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt

import numpy as np

# 加载 IMDB 数据
imdb = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
print("训练记录数量:{},标签数量:{}".format(len(train_data), len(train_labels)))
print(train_data[0])

# 数据标准化
train_data = keras.preprocessing.sequence.pad_sequences(train_data, padding='post', maxlen=256)
test_data = keras.preprocessing.sequence.pad_sequences(test_data, padding='post', maxlen=256)
print(train_data[0])
# 构建模型
vocab_size = 10000
model = tf.keras.Sequential([tf.keras.layers.Embedding(vocab_size, 64),
                             tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)), tf.keras.
                            layers.Dense(64, activation='relu'), tf.keras.layers.Dense(1)
                             ])
model.summary()
# 配置并训练模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
x_val = train_data[:10000]
partial_x_train = train_data[10000:]
y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]
history = model.fit(partial_x_train, partial_y_train, epochs=10, batch_size=512, validation_data=(x_val, y_val),
                    verbose=1)

result = model.evaluate(test_data, test_labels, verbose=2)
print(result)
# 训练过程可视化
history_dict = history.history
print(history_dict.keys())


def plot_graphs(history, string):
    plt.plot(history.history[string])
    plt.plot(history.history['val_' + string])
    plt.xlabel("Epochs")
    plt.ylabel(string)
    plt.legend([string, 'val_' + string])
    plt.show()


plot_graphs(history, "accuracy")


plot_graphs(history, "loss")

运行结果可视化:

相关推荐
满怀101544 分钟前
【生成式AI文本生成实战】从GPT原理到企业级应用开发
人工智能·gpt
微刻时光1 小时前
影刀处理 Excel:智能工具带来的高效变革
人工智能·python·低代码·自动化·excel·rpa·影刀rpa
小技工丨2 小时前
LLaMA-Factory:环境准备
机器学习·大模型·llama·llama-factory
聚客AI3 小时前
ChatGPT到Claude全适配:跨模型Prompt高级设计规范与迁移技巧
人工智能·机器学习·语言模型·自然语言处理·langchain·transformer·llama
小羊Linux客栈3 小时前
自动化:批量文件重命名
运维·人工智能·python·自动化·游戏程序
Mr数据杨7 小时前
【Dv3Admin】插件 dv3admin_chatgpt 集成大语言模型智能模块
人工智能·语言模型·chatgpt
zm-v-159304339867 小时前
AI 赋能 Copula 建模:大语言模型驱动的相关性分析革新
人工智能·语言模型·自然语言处理
phoenix@Capricornus8 小时前
反向传播算法——矩阵形式递推公式——ReLU传递函数
算法·机器学习·矩阵
zhz52149 小时前
AI数字人融合VR全景:从技术突破到可信场景落地
人工智能·vr·ai编程·ai数字人·ai agent·智能体
数据与人工智能律师9 小时前
虚拟主播肖像权保护,数字时代的法律博弈
大数据·网络·人工智能·算法·区块链