使用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")

运行结果可视化:

相关推荐
ayingmeizi163几秒前
电子及通信设备制造业CRM解决方案,AI赋能线索+商机+销售+服务,助力企业降本增效与价值升级
人工智能·crm·数智化
也许是_2 分钟前
大模型应用技术之 Spring AI 2.0 变更说明
java·人工智能·spring
黑客思维者13 分钟前
机器学习006:监督学习【回归算法】(概论)--教AI从历史中预测未来
人工智能·学习·机器学习·监督学习·回归算法
高洁0117 分钟前
DNN案例一步步构建深层神经网络(二)
人工智能·python·深度学习·算法·机器学习
qq_4182478841 分钟前
Linux上部署conda环境
linux·运维·神经网络·机器学习·conda
合方圆~小文1 小时前
4G定焦球机摄像头综合介绍产品指南
数据结构·数据库·人工智能
Coding茶水间1 小时前
基于深度学习的螺栓螺母检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·深度学习·yolo·目标检测·机器学习·计算机视觉
yiersansiwu123d1 小时前
AI全球善治的困境突破与中国方案的实践路径
人工智能
老蒋新思维1 小时前
反脆弱性设计:创始人IP与AI智能体如何构建愈动荡愈强大的知识商业|创客匠人
人工智能·网络协议·tcp/ip·算法·机器学习·创始人ip·创客匠人