#!/usr/bin/env python
# coding=utf- import numpy as np
import pandas as pd
import re
from bs4 import BeautifulSoup
import os from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical from keras.models import Model
from keras.layers import Dense, Input, Layer
from keras.layers import Convolution1D, MaxPooling1D, Embedding, Merge, Dropout, LSTM, GRU, Bidirectional
from keras import backend as K
from sklearn.model_selection import train_test_split MAX_SEQUENCE_LENGTH=
MAX_NB_WORDS =
EMBEDDING_DIM = def load_data(path='~/workspace/data/imdb/labeledTrainData.tsv'):
"""
载入imdb评论的训练数据
"""
def clean_str(sent):
sent = re.sub(r"\\|\'|\"", '', sent)
return sent.strip().lower() data, label = [], []
df = pd.read_csv(path, sep='\t')
print df.shape
for idx in range(df['review'].shape[]):
text = BeautifulSoup(df['review'][idx], 'lxml')
data.append(clean_str(text.get_text().encode('ascii', 'ignore')))
label.append(int(df['sentiment'][idx]))
if idx>:
break
return data, label def load_weights(fname, word_index):
"""
导入预先训练好的glove词向量
"""
emb_weights = {}
with open(fname) as fr:
for line in fr:
values = line.strip().split()
emb_weights[values[]] = values[:] emb_matrix = np.random.random((len(word_index)+, EMBEDDING_DIM))
for word, i in word_index.items():
if word in emb_weights:
emb_matrix[i] = emb_weights[word]
return emb_matrix texts, label = load_data() tokenizer = Tokenizer(nb_words=MAX_NB_WORDS)
tokenizer.fit_on_texts(texts)
word_index = tokenizer.word_index
sequences = tokenizer.texts_to_sequences(texts) data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
label_onehot = to_categorical(label) x_train, x_test, y_train, y_test = train_test_split(data, label_onehot, test_size=0.1)
print('Training %d positive reviews', y_train.sum(axis=))
print('Training %d negative reviews', y_test.sum(axis=)) emb_matrix = load_weights(fname='/home/jkmiao/workspace/data/glove/glove.6B.100d.txt', word_index=word_index)
embedding_layer = Embedding(len(word_index)+, EMBEDDING_DIM, weights=[emb_matrix], input_length=MAX_SEQUENCE_LENGTH, trainable=True) input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
embedded_sequences = embedding_layer(input)
bi_lstm = Bidirectional(LSTM())(embedded_sequences)
output = Dense(, activation='softmax')(bi_lstm) model = Model(input=input, output=output)
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics='accuracy') print('model fitting - Bidirectional LSTM')
model.summary()
model.fit(x_train, y_train, validation_data=(x_test, y_test), nb_epoch=, batch_size=)
model.save('model/text_clf_lstm.h5')

text clf rnn的更多相关文章

  1. 论文阅读(Weilin Huang——【ECCV2016】Detecting Text in Natural Image with Connectionist Text Proposal Network)

    Weilin Huang——[ECCV2016]Detecting Text in Natural Image with Connectionist Text Proposal Network 目录 ...

  2. [Tensorflow] RNN - 04. Work with CNN for Text Classification

    Ref: Combining CNN and RNN for spoken language identification Ref: Convolutional Methods for Text [1 ...

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

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

  4. 论文阅读(Weilin Huang——【AAAI2016】Reading Scene Text in Deep Convolutional Sequences)

    Weilin Huang--[AAAI2016]Reading Scene Text in Deep Convolutional Sequences 目录 作者和相关链接 方法概括 创新点和贡献 方法 ...

  5. 论文阅读(Xiang Bai——【PAMI2017】An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition)

    白翔的CRNN论文阅读 1.  论文题目 Xiang Bai--[PAMI2017]An End-to-End Trainable Neural Network for Image-based Seq ...

  6. RNN 入门教程 Part 4 – 实现 RNN-LSTM 和 GRU 模型

    转载 - Recurrent Neural Network Tutorial, Part 4 – Implementing a GRU/LSTM RNN with Python and Theano ...

  7. RNN 入门教程 Part 2 – 使用 numpy 和 theano 分别实现RNN模型

    转载 - Recurrent Neural Networks Tutorial, Part 2 – Implementing a RNN with Python, Numpy and Theano 本 ...

  8. RNN 入门教程 Part 1 – RNN 简介

    转载 - Recurrent Neural Networks Tutorial, Part 1 – Introduction to RNNs Recurrent Neural Networks (RN ...

  9. 循环神经网络(RNN, Recurrent Neural Networks)介绍(转载)

    循环神经网络(RNN, Recurrent Neural Networks)介绍    这篇文章很多内容是参考:http://www.wildml.com/2015/09/recurrent-neur ...

随机推荐

  1. 20165313 《Java程序设计》第七周学习总结

    教材学习总结 1.下载安装MySQL数据库管理系统. 2.MySQL数据库基本操作. 3.利用JAVA程序对MySQL数据库系统进行查找,更新,添加和删除操作. 学习中的问题与解决方案 1.运行书上安 ...

  2. 【BZOJ2154】Crash的数字表格

    算是学会反演了……(其实挺好学的一天就能学会…… 原题: 今天的数学课上,Crash小朋友学习了最小公倍数(Least Common Multiple).对于两个正整数a和b,LCM(a, b)表示能 ...

  3. 下载并安装oracle 11g客户端

    之所以一直没安装成功是因为找不到安装程序,找到的那些要么没有安装程序,要么安装时出错或者安装后用不了,反正一大堆问题 先给个oracle客户端的下载链接 https://pan.baidu.com/s ...

  4. java.lang.NoClassDefFoundError: org/apache/jute/CsvOutputArchive

    1. 问题 看到上面的错误 你怎么想? 包冲突?我这里不是.项目用到了zookeeper,这个类是zookeeper的核心包里的类. 控制台一直打印这个错误 但是项目不影响使用,奇怪! 2. 解决办法 ...

  5. System.Windows.Forms.Timer、System.Timers.Timer、System.Threading.Timer的 区别和用法

    System.Windows.Forms.Timer执行的时候,如果你在过程中间加一个sleep整个的界面就死掉了,但是另外两个没有这个情况,System.Timers.Timer.System.Th ...

  6. PHP获取站点根目录

    http://rmingwang.com/php-access-to-the-site-root-directory.html php绝对路径与相对路径详解完整版 http://www.phpthin ...

  7. 20165308 预备作业3 Linux安装及学习

    Linux安装及学习 Linux的安装 因为做的比较晚, 安装过程按照老师给出的步骤和同学指导并未出现很多问题,只是安装VirtualBox虚拟机增强功能时,代码没输正确,结果一直无法正确安装,后来也 ...

  8. React Native 学习资料

    React Native 学习资料 学习资料 网址 React Native中文网 https://reactnative.cn/

  9. ps 和 top 的cpu的区别

    cpu的计算 ps cpu的定义 man page中给出的定义: cpu utilization of the process in "##.#" format. Currentl ...

  10. SpringMVC和Struts是线程安全的吗?为什么?

    线程不安全的.(其实我觉得回答为:存在线程安全问题 这样比较好点) 原因如下: 第一点,先理解为何线程不安全 1 struts1的action是单例的,所以存在线程安全问题(struts2是多例的,不 ...