#基于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. 笔记:html常见的兼容问题

    IE: IE的双边距bug: 块级元素float后设置横向的margin,IE6显示的margin比较大. 解决办法:display:inline 双边距bug:在IE6下,如果对元素设置浮动,同时又 ...

  2. jq向元素附加数据

    --------data() 方法向被选元素附加数据,或者从被选元素获取数据.--------- --------removeData() 方法删除之前通过 data() 方法设置的数据.------ ...

  3. 一维数组的初始化及遍历 Day06

    package com.sxt.arraytest1; import java.util.Arrays; /* * 一维数组 */ public class ArrayTest2 { public s ...

  4. 复杂SQL示例 (排行榜需求)

    公司项目要求做出排行榜,根据六组数据依次排行,关联多表,SQL记录下来方便日后查看 " ?><!DOCTYPE mapper PUBLIC "-//mybatis.or ...

  5. 计算php程序运行时间

    <?php   //程序运行时间 $starttime = explode(' ',microtime()); echo microtime(); /*········以下是代码区······· ...

  6. 威胁快报|新兴挖矿团伙借助shodan作恶,非web应用安全再鸣警钟

    近日,阿里云安全发现了一个使用未授权访问漏洞部署恶意Docker镜像进行挖矿的僵尸网络团伙.我们给这一团伙取名为Xulu,因为该团伙使用这个字符串作为挖矿时的用户名. Xulu并不是第一个攻击Dock ...

  7. Spring读取配置文件,地址问题,绝对路径,相对路径

    Spring在读取配置文件时,是相对于bin,或者WEB-INF的: “applicationContext.xml”就是找bin或WEB-INF及子文件夹下的文件: “/res/applicatio ...

  8. RequestMapping中produces属性作用

    注解RequestMapping中produces属性可以设置返回数据的类型以及编码,可以是json或者xml: @RequestMapping(value="/xxx",prod ...

  9. 关于心跳ajax请求pending状态(被挂起),stalled时间过长的问题。涉及tcp连接异常。

    环境:景安快云服务器(听说很垃圾,但是公司买的,我也刚来),CentOS-6.8-x86_64,Apache,MySQL5.1,PHP5.3. 问题:现公司有一个php系统,需要重复向后台发送ajax ...

  10. Typeahead

    翻译自官网:https://angular-ui.github.io/bootstrap/#/typeahead Typeahead可以在输入框输入时有只能提示的作用. 参数设置: 1) ng-mod ...