IMDB数据集是Keras内部集成的,初次导入需要下载一下,之后就可以直接用了。

IMDB数据集包含来自互联网的50000条严重两极分化的评论,该数据被分为用于训练的25000条评论和用于测试的25000条评论,训练集和测试集都包含50%的正面评价和50%的负面评价。该数据集已经经过预处理:评论(单词序列)已经被转换为整数序列,其中每个整数代表字典中的某个单词。

加载数据集

from keras.datasets import imdb(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

参数num_words = 10000的意思是仅保留训练数据的前10000个最常见出现的单词,低频单词将被舍弃。这样得到的向量数据不会太大,便于处理。

train_data[0]

[1,
14,
22,
16,
43,
530,
973,
1622,
1385,
65,
458,…

train_labels[0]

0表示负面,1表示正面。

下面的代码可以将某条评论迅速解码为英文单词:

# word_index is a dictionary mapping words to an integer index
word_index = imdb.get_word_index()
# We reverse it, mapping integer indices to words
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
# We decode the review; note that our indices were offset by 3
# because 0, 1 and 2 are reserved indices for "padding", "start of sequence", and "unknown".
decoded_review = ' '.join([reverse_word_index.get(i - 3, '?') for i in train_data[0]])

我们这里,key是单词,value是数字,转换索引之后,就让数字变成键了。我们使用join方法,使用空格来分隔每个单词。

展示结果如下:

"? this film was just brilliant casting location scenery story direction everyone’s really suited the part they played and you could just imagine being there robert ? is an amazing actor and now the same being director ? father came from the same scottish island as myself so i loved the fact there was a real connection with this film the witty remarks throughout the film were great it was just brilliant so much that i bought the film as soon as it was released for ? and would recommend it to everyone to watch and the fly fishing was amazing really cried at the end it was so sad and you know what they say if you cry at a film it must have been good and this definitely was also ? to the two little boy’s that played the ? of norman and paul they were just brilliant children are often left out of the ? list i think because the stars that play them all grown up are such a big profile for the whole film but these children are amazing and should be praised for what they have done don’t you think the whole story was so lovely because it was true and was someone’s life after all that was shared with us all"


准备数据

我们不能将整数序列直接输入神经网络,需要先将列表转换为张量。转换方式有以下两种:

  • 填充列表

  • 对列表进行one-hot编码 :比如序列[3, 5]将会被转换为10000维向量,只有索引为3和5的元素是1,其余元素是0,然后网络第一层可以用Dense层,它能够处理浮点数向量数据。

这里,我们采用one-hot编码的方式进行。

import numpy as npdef vectorize_sequences(sequences, dimension=10000):results = np.zeros((len(sequences), dimension))for i, sequence in enumerate(sequences):results[i, sequence] = 1.  # 索引results矩阵中的位置,赋值为1,全部都是从第0行0列开始的return results# Our vectorized training data
x_train = vectorize_sequences(train_data)
# Our vectorized test data
x_test = vectorize_sequences(test_data)
x_train[0]

样本变成了如下样子:

array([ 0., 1., 1., …, 0., 0., 0.])

还需要将标签向量化

y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')

下面可以把数据输入神经网络了。


构建网络

from keras import models
from keras import layersmodel = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

最后需要选择损失函数和优化器,由于面对的是一个二分类问题,网络输出是一个概率值,那么最好使用binary_crossentropy(二元交叉熵)。对于输出概率值的模型,交叉熵(crossentropy)往往是最好的选择。

model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])

有时你可能希望配置自定义优化器的参数,或传入自定义的损失函数或指标函数。前者可以通过向optimizer参数传入一个优化器类实例来实现,后者可以通过向losshemetric参数传入函数对象来实现。

from keras import optimizersmodel.compile(optimizer=optimizers.RMSprop(lr=0.001),loss='binary_crossentropy',metrics=['accuracy'])
from keras import losses
from keras import metricsmodel.compile(optimizer=optimizers.RMSprop(lr=0.001),loss=losses.binary_crossentropy,metrics=[metrics.binary_accuracy])

验证

在训练过程中对模型进行监控,将原始训练集留出10000个样本作为验证集。

x_val = x_train[:10000]
partial_x_train = x_train[10000:]y_val = y_train[:10000]
partial_y_train = y_train[10000:]

下面使用512个样本组成的小批量,将模型训练20次。与此同时,还要监控留出的10000个样本上的损失函数和精度,可以通过将验证数据传入validation_data参数来完成。

history = model.fit(partial_x_train,partial_y_train,epochs=20,batch_size=512,validation_data=(x_val, y_val))

当我们调用model.fit()的时候,返回一个History对象。这个对象有一个成员history,它是一个字典,包含训练过程中的所有数据。

history_dict = history.history
history_dict.keys()

输出:dict_keys([‘val_acc’, ‘acc’, ‘val_loss’, ‘loss’])

我们下面在matplotlib中用同一张图绘制训练损失和验证损失,以及训练精度和验证精度。

import matplotlib.pyplot as pltacc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']epochs = range(1, len(acc) + 1)# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')  # bo表示蓝色圆点
# b is for "solid blue line"
plt.plot(epochs, val_loss, 'b', label='Validation loss')  # b表示蓝色实线
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()  #如果不加这一句就不会显示图例plt.show()

plt.clf()   # clear figure
acc_values = history_dict['acc']
val_acc_values = history_dict['val_acc']plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()plt.show()


最终训练和用于预测

重新写一遍整个训练模型代码

model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])model.fit(x_train, y_train, epochs=4, batch_size=512)
results = model.evaluate(x_test, y_test)

最终results输出的结果是:
[0.29184698499679568, 0.88495999999999997]
我们得到了88%的精度。

如果我们想要用于预测,可以使用predict方法:

model.predict(x_test)

array([[ 0.91966152],
[ 0.86563045],
[ 0.99936908],
…,
[ 0.45731062],
[ 0.0038014 ],
[ 0.79525089]], dtype=float32)

更多精彩内容,欢迎关注我的微信公众号:数据瞎分析

电影评论分类:二分类问题(IMDB数据集)相关推荐

  1. 使用逻辑回归和词向量进行(英文)电影评论情感(二)分类

    问题描述:对电影评论进行情感分类,类型一共有两种:正面评价 (pos) 和负面评价 (neg). 训练数据集:英文电影评论及对应的分类标签,保存在工作路径下.样本举例如下: 使用的算法:sklearn ...

  2. 基于Keras的IMDB数据集电影评论情感二分类

    原创不易,如果有转载需要的话,请在首行附上本文地址,谢谢. 第一步加载IMDB数据集,如若加载不成功,这里提供一种解决方法:点开IMDB数据下载链接(喜欢的话给个小星星和follow一下),fork到 ...

  3. 4.使用Keras和Tensorflow Hub对电影评论进行文本分类

    使用Keras和Tensorflow Hub对电影评论进行文本分类 本指南使用tf.keras(一个在TensorFlow中用于构建和训练模型的高级API)和tensorflow_hub(一个用于在一 ...

  4. Deep Learing 记录:电影评论分类——二分类问题

    文章目录 一.数据集介绍与可视化展示 1.数据集介绍 2.数据展示--评论解码 二.数据处理与说明 1.train_data处理(列表处理) 2.train_labels处理(标签向量化) 三.网络构 ...

  5. 自然语言处理-应用场景-文本分类:基于LSTM模型的情感分析【IMDB电影评论数据集】--(重点技术:自定义分词、文本序列化、输入数据批次化、词向量迁移使用)

    文本情感分类 1. 案例介绍 现在我们有一个经典的数据集IMDB数据集,地址:http://ai.stanford.edu/~amaas/data/sentiment/,这是一份包含了5万条流行电影的 ...

  6. 深度学习实战案例:电影评论二分类

    第一个深度学习实战案例:电影评论分类 公众号:机器学习杂货店 作者:Peter 编辑:Peter 大家好,我是Peter~ 这里是机器学习杂货店 Machine Learning Grocery~ 本 ...

  7. 深度学习入门系列21:项目:用LSTM+CNN对电影评论分类

    大家好,我技术人Howzit,这是深度学习入门系列第二十一篇,欢迎大家一起交流! 深度学习入门系列1:多层感知器概述 深度学习入门系列2:用TensorFlow构建你的第一个神经网络 深度学习入门系列 ...

  8. 英文文本分类——电影评论情感判别

    目录 1.导入所需的库 2.用Pandas读入训练数据 3.构建停用词列表数据 4.对数据做预处理 5.将清洗的数据添加到DataFrame里 6.计算训练集中每条评论数据的向量 7.构建随机森林分类 ...

  9. LESSON 10.110.210.3 SSE与二分类交叉熵损失函数二分类交叉熵损失函数的pytorch实现多分类交叉熵损失函数

    在之前的课程中,我们已经完成了从0建立深层神经网络,并完成正向传播的全过程.本节课开始,我们将以分类深层神经网络为例,为大家展示神经网络的学习和训练过程.在介绍PyTorch的基本工具AutoGrad ...

  10. 机器学习中的数学原理——二分类问题

    今天是2022年的最后一天,提前祝大家新年快乐!这个专栏主要是用来分享一下我在机器学习中的学习笔记及一些感悟,也希望对你的学习有帮助哦!感兴趣的小伙伴欢迎私信或者评论区留言!这一篇就更新一下<白 ...

最新文章

  1. solr安装笔记与定时器任务
  2. 朴素贝叶斯算法实现分类以及Matlab实现
  3. Linux环境下安装Mysql5.7
  4. 在LINUX中如何把2个文件中的内容合到另一个文件中
  5. python 优先队列_Python Queue队列实现线程通信
  6. js进阶 14-6 $.ajax()方法如何使用
  7. 深入C++“准”标准库,Boost你的力量
  8. appium和airtest_Airtest自动化测试工具
  9. 微信小程序教程、微信小程序开发资源下载汇总
  10. [郝斌/王卓]数据结构C语句—链表
  11. 模板引擎jade/ejs,模板适配
  12. caffe框架学习(layer)
  13. 常用的操作系统有哪些?起什么作用?
  14. PhotoScan软件进行无人机数据处理流程
  15. 实用计算机技术光盘,《计算机网络技术学习宝典》教学光盘使用说明.doc
  16. 怎样用投资的逻辑来填报志愿?
  17. 笔记本外接显示器,过一段会自动休眠
  18. video标签和videojs配置(vue视频弹窗组件)
  19. DDIM代码详细解读(3):核心采样代码、超分辨率重建
  20. (附源码)计算机毕业设计SSM旅游分享平台

热门文章

  1. win8 配置IIS和添加网站
  2. D:\ProgramData\Anaconda3\envs\test_onnx\python.exe: No module named pip
  3. 空间和时间 ----节选《时间简史》 霍金
  4. 计算机资源管理器经常停止运行,解决win10资源管理器经常停止工作的方法
  5. 全球海底光缆及我国海底光缆分布
  6. 安全专业委员会发言_企业安全委员会发言
  7. 北漂真的是你的归宿吗?
  8. Android5.1 快捷开关如何添加和刷新状态
  9. OPPO小布助手正在改变普罗米修斯的世界
  10. 工信部发布八项互联网新通用顶级域名服务技术要求