Keras lstm 文本分类示例
#基于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 文本分类示例的更多相关文章
- 文本分类:Keras+RNN vs传统机器学习
摘要:本文通过Keras实现了一个RNN文本分类学习的案例,并详细介绍了循环神经网络原理知识及与机器学习对比. 本文分享自华为云社区<基于Keras+RNN的文本分类vs基于传统机器学习的文本分 ...
- 万字总结Keras深度学习中文文本分类
摘要:文章将详细讲解Keras实现经典的深度学习文本分类算法,包括LSTM.BiLSTM.BiLSTM+Attention和CNN.TextCNN. 本文分享自华为云社区<Keras深度学习中文 ...
- keras 文本分类 LSTM
首先,对需要导入的库进行导入,读入数据后,用jieba来进行中文分词 # encoding: utf-8 #载入接下来分析用的库 import pandas as pd import numpy as ...
- LSTM 文本情感分析/序列分类 Keras
LSTM 文本情感分析/序列分类 Keras 请参考 http://spaces.ac.cn/archives/3414/ neg.xls是这样的 pos.xls是这样的neg=pd.read_e ...
- AI - TensorFlow - 示例02:影评文本分类
影评文本分类 文本分类(Text classification):https://www.tensorflow.org/tutorials/keras/basic_text_classificatio ...
- [深度应用]·Keras实现Self-Attention文本分类(机器如何读懂人心)
[深度应用]·Keras实现Self-Attention文本分类(机器如何读懂人心) 配合阅读: [深度概念]·Attention机制概念学习笔记 [TensorFlow深度学习深入]实战三·分别使用 ...
- 基于keras中IMDB的文本分类 demo
本次demo主题是使用keras对IMDB影评进行文本分类: import tensorflow as tf from tensorflow import keras import numpy a ...
- 文本分类实战(七)—— Adversarial LSTM模型
1 大纲概述 文本分类这个系列将会有十篇左右,包括基于word2vec预训练的文本分类,与及基于最新的预训练模型(ELMo,BERT等)的文本分类.总共有以下系列: word2vec预训练词向量 te ...
- tensorflow实现基于LSTM的文本分类方法
tensorflow实现基于LSTM的文本分类方法 作者:u010223750 引言 学习一段时间的tensor flow之后,想找个项目试试手,然后想起了之前在看Theano教程中的一个文本分类的实 ...
随机推荐
- Android Binder简介
Android使用Linux的进程管理机制,以进程为单位分配虚拟地址空间.为了安全考虑,Android的不同进程之间是相互隔离的(进程之间被禁止直接交互).如果进程间需要通信,必须通过Android的 ...
- Java练习 SDUT-2670_3-1 Point类的构造函数
3-1 Point类的构造函数 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 通过本题目的练习可以掌握类的构造函数的定 ...
- js错误处理Try-catch和throw
1.try-catch语句 Try{ //可能会导致错误的代码 }catch(error){ //在错误发生时怎么处理 } 例如: try{ window.someNonexistentFunct ...
- MaxCompute 图计算开发指南
快速入门step by step MaxCompute Studio 创建完成 MaxCompute Java Module后,即可以开始开发Graph了. 代码示例 在examples目录下有gra ...
- 关于redis的问题:RedisException with message read error on connection
最近碰到在REDIS执行一步get操作的时候报出错误:Uncaught RedisException: read error on connection,感觉不可理解,REDIS连接没有发现问题,但是 ...
- Xcode编译报错:< Apple Mach-O Linker Warning > clang: error: no such file or directory: 'xxxx'
Xcode编译报错概述: clang: error: no such file or directory: 'CoreGraphics' 一般原因是链接库内容导入丢失,这种的排查下target - B ...
- 2019-1-9-WPF-最小的代码使用-DynamicRenderer-书写
title author date CreateTime categories WPF 最小的代码使用 DynamicRenderer 书写 lindexi 2019-1-9 14:7:26 +080 ...
- YUI css reset
*{ margin:0; padding:0; } 以前写CSS都会在会在样式的开头部分添加上述的内容,今天才发现这种写法很不友好,会导致很多样式显示问题,所以并不适合所有的浏览器. 下面的是雅虎的c ...
- LeetCode75 Sort Colors
题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...
- oracle函数 ASCII(x1)
[功能]:返回字符表达式最左端字符的ASCII 码值. [参数]:x1,字符表达式 [返回]:数值型 [示例] SQL> select ascii('A') A,ascii('a') a,asc ...