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

运行结果可视化:

相关推荐
ajassi20005 分钟前
AI语音智能体开发日记(十五)智能体LCD屏幕GIF动画显示方案——从GIF到BMP的完整实战
人工智能·ai·ai编程
Dfreedom.15 分钟前
目标检测后处理核心:NMS非极大值抑制详解
图像处理·人工智能·深度学习·目标检测·目标跟踪
枫叶丹417 分钟前
实时语音 Agent:从语音机器人到连续协作界面
人工智能·chatgpt·机器人·语音识别·agent·codex
戴西软件29 分钟前
戴西iDWS.3DViz Suite数据轻量化可视化软件,从传统桌面软件向云端协同的重大突破
大数据·运维·网络·人工智能·机器学习·3d
AIkk8632 分钟前
2026年AI证件照工具功能速览:三款实用方案对比
人工智能
ReleaseU32 分钟前
Harness + MCP:打通企业工具链的最后一步
人工智能·大模型
衡石科技1 小时前
衡石科技携手超聚变联合发布HENGSHI BOX,引领私域ChatBI规模化落地
大数据·人工智能·科技
新知图书1 小时前
10.4 交互优化与用户体验提升
人工智能·多模态·智能体
IT_陈寒1 小时前
JavaScript数组排序踩的坑,差点让我加班到凌晨
前端·人工智能·后端