#基于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. Java练习 SDUT-2401最大矩形面积

    最大矩形面积 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 在一个矩形区域内有很多点,每个点的坐标都是整数.求一个矩形 ...

  2. 分享 KubeCon 2019 (上海)关于 Serverless 及 Knative 相关演讲会议

    有幸参加了 KubeCon 2019 上海大会,并参加了 Knative 及 Serverless 相关的几场分享会,收获满满.这里简单介绍一下各个演讲主题的主要内容.详细的演讲主题文档可以在Kube ...

  3. asp 与php 的不同之处

    1.asp语句完成后不用加逗号:php要: 2.asp连接字符窜是用&:php用.; 3.asp需要用dim声明变量才能使用:php不用: 4.asp数组用(),php用[]; 5.asp的条 ...

  4. 【转载】Combination Sum

    Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...

  5. F4NNIU 的 KiCad EDA 技巧 (2019-05-09 更新)

    F4NNIU 的 KiCad EDA 技巧 已经慢慢切换到 KiCadEDA 上来画板,优点很多. 开源: 自动推挤: 无限的元件库: 强大的 3D 显示: 这里整理一下个人使用的技巧: 原理图 Ee ...

  6. part12.5-定时器去抖

  7. Java练习 SDUT-1184_拍皮球

    C语言实验--拍皮球 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 小瑜3岁了,很喜欢玩皮球,看来今后喜欢打篮球的^_ ...

  8. HZOJ Tree

    看到换根果断lct啊,然而其实我板子还没有打熟,还不会维护子树信息,于是就挂掉了…… 然而正解并不是lct. 其实好像很久很久以前将lca的时候好像讲到过一道换根的题,当时没有听懂. 直接说正解吧: ...

  9. P2P四红线

    P2P四红线 刘张君指出,P2P网络借贷平台是一种新兴金融业态,在鼓励其创新发展的同时,要记住四点:一是要明确这个平台的中介性质,二是要明确平台本身不得提供担保,三是不得将归集资金搞资金池,四是不得非 ...

  10. ViewPager封装工具类: 轻松实现APP导航或APP中的广告栏

    相信做app应用开发的,绝对都接触过ViewPager,毕竟ViewPager的应用可以说无处不在:APP第一次启动时的新手导航页,APP中结合Fragment实现页面滑动,APP中常见的广告栏的自动 ...