#基于IMDB数据集的简单文本分类任务

#一层embedding层+一层lstm层+一层全连接层

#基于Keras 2.1.1 Tensorflow 1.4.0

代码:

 '''Trains an LSTM model on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF + LogReg.
# Notes
- RNNs are tricky. Choice of batch size is important,
choice of loss and optimizer is critical, etc.
Some configurations won't converge.
- LSTM loss decrease patterns during training can be quite different
from what you see with CNNs/MLPs/etc.
'''
from __future__ import print_function from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding
from keras.layers import LSTM
from keras.datasets import imdb max_features = 20000
maxlen = 80 # cut texts after this number of words (among top max_features most common words)
batch_size = 32 print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences') print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape) print('Build model...')
model = Sequential()
model.add(Embedding(max_features, 128))
model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))
model.summary() # try using different optimizers and different optimizer configs
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) print('Train...')
model.fit(x_train, y_train,batch_size=batch_size,epochs=15,validation_data=(x_test, y_test))
score, acc = model.evaluate(x_test, y_test,batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)

结果:

Test accuracy: 0.81248

Keras lstm 文本分类示例的更多相关文章

  1. 文本分类:Keras+RNN vs传统机器学习

    摘要:本文通过Keras实现了一个RNN文本分类学习的案例,并详细介绍了循环神经网络原理知识及与机器学习对比. 本文分享自华为云社区<基于Keras+RNN的文本分类vs基于传统机器学习的文本分 ...

  2. 万字总结Keras深度学习中文文本分类

    摘要:文章将详细讲解Keras实现经典的深度学习文本分类算法,包括LSTM.BiLSTM.BiLSTM+Attention和CNN.TextCNN. 本文分享自华为云社区<Keras深度学习中文 ...

  3. keras 文本分类 LSTM

    首先,对需要导入的库进行导入,读入数据后,用jieba来进行中文分词 # encoding: utf-8 #载入接下来分析用的库 import pandas as pd import numpy as ...

  4. LSTM 文本情感分析/序列分类 Keras

    LSTM 文本情感分析/序列分类 Keras 请参考 http://spaces.ac.cn/archives/3414/   neg.xls是这样的 pos.xls是这样的neg=pd.read_e ...

  5. AI - TensorFlow - 示例02:影评文本分类

    影评文本分类 文本分类(Text classification):https://www.tensorflow.org/tutorials/keras/basic_text_classificatio ...

  6. [深度应用]·Keras实现Self-Attention文本分类(机器如何读懂人心)

    [深度应用]·Keras实现Self-Attention文本分类(机器如何读懂人心) 配合阅读: [深度概念]·Attention机制概念学习笔记 [TensorFlow深度学习深入]实战三·分别使用 ...

  7. 基于keras中IMDB的文本分类 demo

      本次demo主题是使用keras对IMDB影评进行文本分类: import tensorflow as tf from tensorflow import keras import numpy a ...

  8. 文本分类实战(七)—— Adversarial LSTM模型

    1 大纲概述 文本分类这个系列将会有十篇左右,包括基于word2vec预训练的文本分类,与及基于最新的预训练模型(ELMo,BERT等)的文本分类.总共有以下系列: word2vec预训练词向量 te ...

  9. tensorflow实现基于LSTM的文本分类方法

    tensorflow实现基于LSTM的文本分类方法 作者:u010223750 引言 学习一段时间的tensor flow之后,想找个项目试试手,然后想起了之前在看Theano教程中的一个文本分类的实 ...

随机推荐

  1. 关闭myeclipse可视化视图

    ctrl+w  关闭各个文件  重新打开即可 方法二:

  2. Python基础:19类和实例的内建函数

    1:issubclass() issubclass()布尔函数,判断一个类是否是另一个类的子类或子孙类.它有如下语法:issubclass(sub,sup) 这个函数也允许“不严格”的子类,意味着,一 ...

  3. tp3 key json 分页

    //json 强制转换为array $arr[$key]['checkpro'] = json_decode($val['checkpro'],JSON_FORCE_ARRAY);    $arr[$ ...

  4. 2018-3-22-win10-uwp-设置-HttpClient-浏览器标识

    title author date CreateTime categories win10 uwp 设置 HttpClient 浏览器标识 lindexi 2018-3-22 9:1:55 +0800 ...

  5. 07Redis入门指南笔记(主从复制、哨兵)

    现实项目中通常需要若干台Redis服务器的支持: 结构上,单个 Redis 服务器会发生单点故障,而且一台服务器需要承受所有的请求负载.这就需要为数据生成多个副本并分配在不同的服务器上: 容量上,单个 ...

  6. 开发者说:如何参与定义一款 IDE 插件

    摘要: If not now,when? If not you,who?共同定义 Cloud Toolkit 的未来! 自从产品经理银时小伙和他的开发小哥们在去年12月发布 Cloud Toolkit ...

  7. uni-app设置 video开始播放进入全屏状态

    有一video标签 <video id="myVideo" :src="videoUrl"></video> 获取 video 上下文 ...

  8. uni-app获取dom元素到顶部的距离以及操作dom元素的一些样式

    一. 1.首先有一个元素 <view class="activity" ref="btn"></view> 2.确认指针指向 this. ...

  9. oracle sum()聚合函数

    原文链接:https://blog.csdn.net/cizatu5130/article/details/100291347 oracle sum()聚合函数 2016-05-13 20:08:00 ...

  10. setTimeout与setInterval有何区别?

    ①setTimeout和setInterval的语法相同.它们都有两个参数,一个是将要执行的代码字符串,还有一个是以毫秒为单位的时间间隔,当过了那个时间段之后就将执行那段代码. ②不过这两个函数还是有 ...