keras—多层感知器MLP—IMDb情感分析
import urllib.request
import os
import tarfile
from keras.datasets import imdb
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
import re
def rm_tags(text):
re_tag=re.compile(r'<[^>]+>')
return re_tag.sub('',text)
def read_files(filetype):
path="C:/Users/admin/.keras/aclImdb/"
file_list=[]
positive_path=path+filetype+"/pos/"
for f in os.listdir(positive_path):
file_list+=[positive_path+f]
negative_path=path+filetype+"/pos/"
for f in os.listdir(negative_path):
file_list+=[negative_path+f]
print('read',filetype,'files:',len(file_list))
all_labels=([]*+[]*)
all_texts=[]
for fi in file_list:
with open(fi,encoding='utf8') as file_input:
all_texts+=[rm_tags(" ".join(file_input.readlines()))]
return all_labels,all_texts
y_train,train_text=read_files("train")
y_test,test_text=read_files("test")
print(train_text[])
print(y_train[])
token=Tokenizer(num_words=)
token.fit_on_texts(train_text)
print(token.document_count)
print(token.word_index)
x_train_seq=token.texts_to_sequences(train_text)
x_test_seq=token.texts_to_sequences(test_text)
print(train_text[])
print(x_train_seq[])
x_train=sequence.pad_sequences(x_train_seq,maxlen=)
x_test=sequence.pad_sequences(x_test_seq,maxlen=)
print('before pad_sequences lenfth=',len(x_train_seq[]))
print(x_train_seq[])
print('after pad_sequences lenfth=',len(x_train[]))
print(x_train[])
from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten,Activation
from keras.layers.embeddings import Embedding
model=Sequential()
model.add(Embedding(output_dim=,
input_dim=,
input_length=))
model.add(Dropout(0.2))
#model.add(SimpleRNN(units=))
model.add(Flatten())
model.add(Dense(units=,
activation='relu'))
model.add(Dropout(0.35))
model.add(Dense(units=,
activation='sigmoid'))
print(model.summary())
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
train_history=model.fit(x=x_train,y=y_train,batch_size=,
epochs=,verbose=,
validation_split=0.2)
scores=model.evaluate(x_test,y_test,verbose=)
print('accuracy',scores[])
predict=model.predict_classes(x_test)
print("prediction[:10]",predict[:])
predict_classes=predict.reshape(-)
print(predict_classes[:])
SentimentDict = {: '正面的', : '负面的'}
def display_test_Sentiment(i):
print(test_text[i])
print('label真实值:', SentimentDict[y_test[i]],
'预测结果:', SentimentDict[predict_classes[i]])
display_test_Sentiment()
input_text='''
I saw this film with my -year-old a couple weeks ago. While there's plenty about which to gripe, here's one of
my biggest problems: I can't stand this constant CGI-heavy everything-must-be-a-sequel-or- a- remake era of film
making. It's making movie makers lazy.
'''
input_seq=token.texts_to_sequences([input_text])
len(input_seq[])
print(input_seq[])
pad_input_seq=sequence.pad_sequences(input_seq,maxlen=)
len(pad_input_seq[])
print(pad_input_seq[])
predict_result=model.predict_classes(pad_input_seq)
print(predict_result)
print(predict_result[][])
print(SentimentDict[predict_result[][]])
def predict_review(input_text):
input_seq=token.texts_to_sequences([input_text])
pad_input_seq=sequence.pad_sequences(input_seq,maxlen=)
predict_result=model.predict_classes(pad_input_seq)
print(SentimentDict[predict_result[][]]) predict_review('''
They poured on the whole "LeFou is gay" thing a bit thick for my taste. It was the only thing that added levity to the movie (despite how much fun it should have been already), but it seemed a bit cheap. I'm not going to apologize for wanting more for my LGBTQ characters than to be just the comic relief.
''')



验证的准确率为0问题待解决

keras—多层感知器MLP—IMDb情感分析的更多相关文章
- keras—多层感知器MLP—MNIST手写数字识别
一.手写数字识别 现在就来说说如何使用神经网络实现手写数字识别. 在这里我使用mind manager工具绘制了要实现手写数字识别需要的模块以及模块的功能: 其中隐含层节点数量(即神经细胞数量)计算 ...
- 4.2tensorflow多层感知器MLP识别手写数字最易懂实例代码
自己开发了一个股票智能分析软件,功能很强大,需要的点击下面的链接获取: https://www.cnblogs.com/bclshuai/p/11380657.html 1.1 多层感知器MLP(m ...
- "多层感知器"--MLP神经网络算法
提到人工智能(Artificial Intelligence,AI),大家都不会陌生,在现今行业领起风潮,各行各业无不趋之若鹜,作为技术使用者,到底什么是AI,我们要有自己的理解. 目前,在人工智能中 ...
- TFboy养成记 多层感知器 MLP
内容总结与莫烦的视频. 这里多层感知器代码写的是一个简单的三层神经网络,输入层,隐藏层,输出层.代码的目的是你和一个二次曲线.同时,为了保证数据的自然,添加了mean为0,steddv为0.05的噪声 ...
- MLPclassifier,MLP 多层感知器的的缩写(Multi-layer Perceptron)
先看代码(sklearn的示例代码): from sklearn.neural_network import MLPClassifier X = [[0., 0.], [1., 1.]] y = [0 ...
- 神经网络与机器学习 笔记—多层感知器(MLP)
多层感知器(MLP) Rosenblatt感知器和LMS算法,都是单层的并且是单个神经元构造的神经网络,他们的局限性是只能解决线性可分问题,例如Rosenblatt感知器一直没办法处理简单异或问题.然 ...
- tensorflow学习笔记——自编码器及多层感知器
1,自编码器简介 传统机器学习任务很大程度上依赖于好的特征工程,比如对数值型,日期时间型,种类型等特征的提取.特征工程往往是非常耗时耗力的,在图像,语音和视频中提取到有效的特征就更难了,工程师必须在这 ...
- 使用TensorFlow v2.0构建多层感知器
使用TensorFlow v2.0构建一个两层隐藏层完全连接的神经网络(多层感知器). 这个例子使用低级方法来更好地理解构建神经网络和训练过程背后的所有机制. 神经网络概述 MNIST 数据集概述 此 ...
- Spark Multilayer perceptron classifier (MLPC)多层感知器分类器
多层感知器分类器(MLPC)是基于前馈人工神经网络(ANN)的分类器. MLPC由多个节点层组成. 每个层完全连接到网络中的下一层. 输入层中的节点表示输入数据. 所有其他节点,通过输入与节点的权重w ...
随机推荐
- php7 数据库操作的 方法
连接数据库的方法PHP7.0以上的: 方法一: <?php/* Connect to a MySQL server 连接数据库服务器 */$link = mysqli_connect('loca ...
- [转]C# 系统应用之鼠标模拟技术及自动操作鼠标
原文网址: C# 系统应用之鼠标模拟技术及自动操作鼠标 游戏程序的操作不外乎两种——键盘输入控制和鼠标输入控制,几乎所有游戏中都使用鼠标来改变角色的位置和方向,本文主要是讲述如何使用C# ...
- mysql binlog协议分析--具体event
这几天在修改canal, 连接mysql和maria接收到的event有所区别 拿一个简单的insert sql来举例 mysql 会有以下几个event写入到binlog里 1.ANONYMOUS_ ...
- tomcat 乱码问题
页面提交都是utf8编码进后台,但是后台入库有些中文数据是正常,有些是乱码,可以完全排除数据库层面的问题 比较一下正常和异常的http请求,一个是Get,一个是Post, 原因就找到了 tomcat4 ...
- php 学习笔记 设计和管理
代码管理 文件路径.数据库名.密码禁止 hard coded 避免重复代码在多个页面复制粘贴 Gang of Four eXtreme Programming 的主要原则是坚决主张测试是项目成功的关键 ...
- HTML5之viewport使用
好久都没更新博客了,最近一年转型移动端,当然网页端也得兼顾,慢慢写一写基本性的文章,多积累. 本期介绍下viewport的一些使用: 先看看viewport在页面中的样子: <meta name ...
- node和yarn
nvm 版本管理工具 https://github.com/coreybutler/nvm-windows/releases nvm-setup nvm install +版本号 加版本 ...
- jmeter建立JDBC连接池时遇到“A Test is currently running,stop or shutdown test to execute this command”
1.显示如下图,打开日志可以看到:Variable Name must not be empty for element:JDBC Connection Configuration,即JDBC Con ...
- os模块和sys模块,以及random模块
os模块 os模块是与操作系统交互的一个接口 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工 ...
- ubuntu 安装 环境
svn https://blog.csdn.net/leibris/article/details/72982804 https://blog.csdn.net/frankchen ...