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

运行结果可视化:

相关推荐
ai产品老杨21 小时前
打通各大芯片厂商相互间的壁垒,省去繁琐重复的适配流程的智慧工业开源了
人工智能·开源·音视频·能源
小陈phd1 天前
高级RAG策略学习(五)——llama_index实现上下文窗口增强检索RAG
人工智能
凯禾瑞华养老实训室1 天前
人才教育导向下:老年生活照护实训室助力提升学生老年照护服务能力
人工智能
湫兮之风1 天前
Opencv: cv::LUT()深入解析图像块快速查表变换
人工智能·opencv·计算机视觉
Christo31 天前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
qq_508823401 天前
金融量化指标--2Alpha 阿尔法
大数据·人工智能
黑金IT1 天前
`.cursorrules` 与 `.cursorcontext`:Cursor AI 编程助手时代下的“双轨配置”指南
人工智能
非门由也1 天前
《sklearn机器学习——管道和复合估计器》回归中转换目标
机器学习·回归·sklearn
dlraba8021 天前
基于 OpenCV 的信用卡数字识别:从原理到实现
人工智能·opencv·计算机视觉
IMER SIMPLE1 天前
人工智能-python-深度学习-经典神经网络AlexNet
人工智能·python·深度学习