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

运行结果可视化:

相关推荐
智算菩萨2 分钟前
【How Far Are We From AGI】5 AGI的“道德罗盘“——价值对齐的技术路径与伦理边界
论文阅读·人工智能·深度学习·ai·接口·agi·对齐技术
lisw054 分钟前
用于实时数据处理的边缘计算!
人工智能·机器学习·边缘计算
全栈开发圈5 分钟前
干货分享|R语言聚类分析2
人工智能·机器学习·r语言
Sakuraba Ema9 分钟前
从零理解 MoE(Mixture of Experts)混合专家:原理、数学、稀疏性、专家数量影响与手写 PyTorch 实现
人工智能·pytorch·python·深度学习·数学·llm·latex
shangjian00718 分钟前
AI-大语言模型-模型训练-数据集1-总述
人工智能·机器学习·语言模型
柯儿的天空21 分钟前
【OpenClaw 全面解析:从零到精通】第 006 篇:OpenClaw 在 Windows/WSL2 上的安装与部署实战
人工智能·windows·语言模型·chatgpt·ai作画
freewlt33 分钟前
科技热点速递:AI技术集中爆发
人工智能·深度学习·计算机视觉
驕傲的兎孒34 分钟前
基于 SpringBoot + Vue3 + AI 打造企业级售后服务支持平台 | 实战方案分享
人工智能·spring boot·后端
guoji778834 分钟前
2026年AI编程辅助实战:国内镜像站如何使用Claude提升开发效率?
人工智能·ai编程
程序猿炎义35 分钟前
Agent Skills入门 - Datawhale共学
人工智能