#!/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. Linux常用命令详解-目录文件操作命令

    来源:https://www.linuxidc.com/Linux/2018-04/151801.htm 现实中,服务器(包含Linux,Unix,Windows Server)一般都摆放在机房里,因 ...

  2. jsp页面继承

    功能类似 django template 中的  extends 功能 使用 1.需要下载rapid-core-4.0.jar    导入到web-inf下lib中   下载地址   http://w ...

  3. Cassandra基础

    Apache Cassandra特性 Apache Cassandra由Facebook基于Amazon的Dynamo及其在Google的Bigtable上的数据模型设计开发的面相列的数据库,实现没有 ...

  4. Writing and playing with custom Terraform Providers

    转自:https://petersouter.xyz/writing-and-playing-with-custom-terraform-providers/ I’ve been digging de ...

  5. ipfs cluster 模式部署使用(docker-compose 环境运行)

    ipfs 点对点的分布式文件系统,官方提供了集群模式运行的docker 镜像,以及docker-compose 文件 所以测试下 环境准备 docker-compose   version: '3.4 ...

  6. L老师 Shader编程教程 学习

    Shader "VoidGame/FixedShader" { Properties{ //颜色 _Color("Color",Color)=(1,1,1,1) ...

  7. mysql杂谈

    本文主要记录一些零碎知识点 1.mysql默认存储引擎变更InnoDB as Default Storage Engine从mysql-5.5.5开始,InnoDB作为默认存储引擎,InnoDB作为支 ...

  8. egg 官方文档之:框架扩展(Application、Context、Request、Response、Helper的访问方式及扩展)

    地址:https://eggjs.org/zh-cn/basics/extend.html Application app 对象指的是 Koa 的全局应用对象,全局只有一个,在应用启动时被创建. 访问 ...

  9. centos git server 的搭建

    安装环境  centos7 说明:centos  yum 库里面的git  好像是不区分 客户端和服务器端, 安装 git 以后 就可以创建  仓库,也可以检出 别的 git 仓库的  代码了.所以不 ...

  10. spark机器学习

    多层感知器(MLP) from __future__ import print_function from pyspark.ml.classification import MultilayerPer ...