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教程中的一个文本分类的实 ...
随机推荐
- textarea 转HTML
Text2Html(str) { if (str == null) { return ""; } else if (str.length == 0) { return " ...
- LeetCode93 Restore IP Addresses
题目: Given a string containing only digits, restore it by returning all possible valid IP address com ...
- Mybatis表关联多对多
创建表 创建表对应的 JavaBean 对象 package com.tanlei.newer.model; import java.util.List; /** * @author:Mr.Tan * ...
- [考试维护]之IIS发布 标签: iis 2015-06-07 22:11 627人阅读 评论(18) 收藏
考试维护也进行了一段时间了,总结一下这段时间学习到的东西,今天写一下在服务器上如何发布IIS,一开始,我们准备了两台服务器,一台Win Server2003的服务器(IIS版本6.0),另一台是Win ...
- AspNetPager 样式
使用方法: 1.引入样式表. 将 想要使用的样式表加入到本页面<style type="text/css"></style>标记中,或者新建一个css文件如 ...
- ROS通过图形化界面控制和查看小乌龟参数
ROS图形化界面能够让我们快速开发ROS,也有利于我们观测数据. 下面介绍一下利用图形化界面控制小乌龟按照指令行进和查看小乌龟的行进参数. 首先我们需要做一些准备工作: 在Terminal中运行以下命 ...
- shell awk杂项
awk '{ ;++i<=NF;){ a[i]=a[i]?a[i]",'\''"$i"'\''":"'\''"$i"'\'' ...
- maxCompute odps 行转列
select name ,REGEXP_REPLACE(str,"[\\[\"\\]]",'') from ( select trans_array(, ",& ...
- SpringBoot 获取properties配置文件的属性
自定义properties文件获取属性 使用 @ConfigurationProperties((prefix = "demo")) 和 @PropertySource(" ...
- LRJ-Example-06-04-Uva11988
单向链表的元素存放在数组s[]中,next指针存放在数组next[]中. 链表初始为空,next[0] == 0 代表链表结尾,类似NULL指针,在最后打印链表的时候作为for循环结束的条件. 依次插 ...