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)

1
    2
    3

1
    2
    3

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

train_data[0]

1

1

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

train_labels[0]

1

1

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]])

1
    2
    3
    4
    5
    6
    7

1
    2
    3
    4
    5
    6
    7

我们这里,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 np

def 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)

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

x_train[0]

1

1

样本变成了如下样子:

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

还需要将标签向量化

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

1
    2

1
    2

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

from keras import models
from keras import layers

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'))

1
    2
    3
    4
    5
    6
    7

1
    2
    3
    4
    5
    6
    7

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

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

1
    2
    3

1
    2
    3

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

from keras import optimizers

model.compile(optimizer=optimizers.RMSprop(lr=0.001),
              loss='binary_crossentropy',
              metrics=['accuracy'])

1
    2
    3
    4
    5

1
    2
    3
    4
    5

from keras import losses
from keras import metrics

model.compile(optimizer=optimizers.RMSprop(lr=0.001),
              loss=losses.binary_crossentropy,
              metrics=[metrics.binary_accuracy])

1
    2
    3
    4
    5
    6

1
    2
    3
    4
    5
    6

验证

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

x_val = x_train[:10000]
partial_x_train = x_train[10000:]

y_val = y_train[:10000]
partial_y_train = y_train[10000:]

1
    2
    3
    4
    5

1
    2
    3
    4
    5

下面使用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))

1
    2
    3
    4
    5

1
    2
    3
    4
    5

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

history_dict = history.history
history_dict.keys()

1
    2

1
    2

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

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

import matplotlib.pyplot as plt

acc = 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()

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

这里写图片描述

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()

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

这里写图片描述
最终训练和用于预测

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

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)

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

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

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

model.predict(x_test)

1

1

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

更多精彩内容,欢迎关注我的微信公众号:数据瞎分析
---------------------  
作者:Einstellung  
来源:CSDN  
原文:https://blog.csdn.net/Einstellung/article/details/82683652  
版权声明:本文为博主原创文章,转载请附上博文链接!

电影评论分类:二分类问题(IMDB数据集)的更多相关文章

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

    IMDB数据集下载速度慢,可以在我的repo库中找到下载,下载后放到~/.keras/datasets/目录下,即可正常运行.)中找到下载,下载后放到~/.keras/datasets/目录下,即可正 ...

  2. Python深度学习案例1--电影评论分类(二分类问题)

    我觉得把课本上的案例先自己抄一遍,然后将书看一遍.最后再写一篇博客记录自己所学过程的感悟.虽然与课本有很多相似之处.但自己写一遍感悟会更深 电影评论分类(二分类问题) 本节使用的是IMDB数据集,使用 ...

  3. kaggle之电影评论文本情感分类

    电影文本情感分类 Github地址 Kaggle地址 这个任务主要是对电影评论文本进行情感分类,主要分为正面评论和负面评论,所以是一个二分类问题,二分类模型我们可以选取一些常见的模型比如贝叶斯.逻辑回 ...

  4. scikit-learn机器学习(二)逻辑回归进行二分类(垃圾邮件分类),二分类性能指标,画ROC曲线,计算acc,recall,presicion,f1

    数据来自UCI机器学习仓库中的垃圾信息数据集 数据可从http://archive.ics.uci.edu/ml/datasets/sms+spam+collection下载 转成csv载入数据 im ...

  5. Python深度学习读书笔记-6.二分类问题

    电影评论分类:二分类问题   加载 IMDB 数据集 from keras.datasets import imdb (train_data, train_labels), (test_data, t ...

  6. tensorflow 教程 文本分类 IMDB电影评论

    昨天配置了tensorflow的gpu版本,今天开始简单的使用一下 主要是看了一下tensorflow的tutorial 里面的 IMDB 电影评论二分类这个教程 教程里面主要包括了一下几个内容:下载 ...

  7. kaggle——Bag of Words Meets Bags of Popcorn(IMDB电影评论情感分类实践)

    kaggle链接:https://www.kaggle.com/c/word2vec-nlp-tutorial/overview 简介:给出 50,000 IMDB movie reviews,进行0 ...

  8. Pytorch文本分类(imdb数据集),含DataLoader数据加载,最优模型保存

    用pytorch进行文本分类,数据集为keras内置的imdb影评数据(二分类),代码包含六个部分(详见代码) 使用环境: pytorch:1.1.0 cuda:10.0 gpu:RTX2070 (1 ...

  9. 机器学习-MNIST数据集使用二分类

    一.二分类训练MNIST数据集练习 %matplotlib inlineimport matplotlibimport numpy as npimport matplotlib.pyplot as p ...

随机推荐

  1. 文件的概念、标准IO其一

    1.文件的概念 文件是一种存储在磁盘(掉电不丢失存储设备)上,掉电不丢失的一种存储数据的方式,文件在系统中有以下层次的结构来实现. 系统调用.文件IO.标准IO的关系如下: 2.linux系统的文件分 ...

  2. c++程序—浮点数

    #include<iostream> using namespace std; int main() { //2.单精度float //3.双精度double //默认情况下会输出6位有效 ...

  3. 51nod 1022 石子归并 环形+四边形优化

    1022 石子归并 V2 基准时间限制:1 秒 空间限制:131072 KB 分值: 160 难度:6级算法题  收藏  关注 N堆石子摆成一个环.现要将石子有次序地合并成一堆.规定每次只能选相邻的2 ...

  4. python scipy库

    三.假定正态分布,求解1倍标准差和0.5倍标准差的概率? 二.求解多元线性或非线性方程组解 一.求解3元一次方程 1.学习资料  https://github.com/lijin-THU/notes- ...

  5. 【数据结构】二叉树的遍历(前、中、后序及层次遍历)及leetcode107题python实现

    文章目录 二叉树及遍历 二叉树概念 二叉树的遍历及python实现 二叉树的遍历 python实现 leetcode107题python实现 题目描述 python实现 二叉树及遍历 二叉树概念 二叉 ...

  6. Vue.js(2)- 过滤器

    概念:过滤器本质上就是一个函数,可被用作一些常见的文本格式化. 过滤器只可以用在两个地方:mustache 插值表达式和 v-bind 表达式. 过滤器应该被添加在 JavaScript 表达式的尾部 ...

  7. 尝试用kotlin做一个app(二)

    导航条 我想实现的效果是这样的 类似于ViewPager的效果,子类导航页面可以滑动,当滑动某个子类导航页面,导航线会平滑地向父类导航移动 ·添加布局 <!--导航分类:编程语言/技术文档/源码 ...

  8. PAT 2012 冬

    A Shortest Distance 题意相当于一个环,找出两点间从不同方向得到的距离中的最小值. #include <cstdio> #include <iostream> ...

  9. POJ 1519:Digital Roots

    Digital Roots Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 25766   Accepted: 8621 De ...

  10. kafka 零拷贝

    kafka通过零拷贝实现高效的数据传输 https://blog.csdn.net/lxlmycsdnfree/article/details/78973864 Kafka零拷贝 https://bl ...