Sentiment Analysis

Two approaches

  • SimpleRNNCell

    • single layer

    • multi-layers

  • RNNCell

Single layer

import os
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers tf.random.set_seed(22)
np.random.seed(22)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
assert tf.__version__.startswith('2.') batchsz = 128 # the most frequest words
total_words = 10000
max_review_len = 80
embedding_len = 100
(x_train,
y_train), (x_test,
y_test) = keras.datasets.imdb.load_data(num_words=total_words)
# x_train:[b, 80]
# x_test: [b, 80]
x_train = keras.preprocessing.sequence.pad_sequences(x_train,
maxlen=max_review_len)
x_test = keras.preprocessing.sequence.pad_sequences(x_test,
maxlen=max_review_len) db_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))
db_train = db_train.shuffle(1000).batch(batchsz, drop_remainder=True)
db_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))
db_test = db_test.batch(batchsz, drop_remainder=True)
print('x_train shape:', x_train.shape, tf.reduce_max(y_train),
tf.reduce_min(y_train))
print('x_test shape:', x_test.shape) class MyRNN(keras.Model):
def __init__(self, units):
super(MyRNN, self).__init__() # [b, 64]
self.state0 = [tf.zeros([batchsz, units])]
self.state1 = [tf.zeros([batchsz, units])] # transform text to embedding representation
# [b, 80] => [b, 80, 100]
self.embedding = layers.Embedding(total_words,
embedding_len,
input_length=max_review_len) # [b, 80, 100] , h_dim: 64
# RNN: cell1 ,cell2, cell3
# SimpleRNN,units=64表示100个向量转成64个初始的状态
self.rnn_cell0 = layers.SimpleRNNCell(units, dropout=0.5)
self.rnn_cell1 = layers.SimpleRNNCell(units, dropout=0.5) # fc, [b, 80, 100] => [b, 64] => [b, 1]
self.outlayer = layers.Dense(1) def call(self, inputs, training=None):
"""
net(x) net(x, training=True) :train mode
net(x, training=False): test
:param inputs: [b, 80]
:param training:
:return:
"""
# [b, 80]
x = inputs
# embedding: [b, 80] => [b, 80, 100]
x = self.embedding(x)
# rnn cell compute
# [b, 80, 100] => [b, 64]
state0 = self.state0
state1 = self.state1
for word in tf.unstack(x, axis=1): # word: [b, 100]
# h1 = x*wxh+h0*whh
# out0: [b, 64]
out0, state0 = self.rnn_cell0(word, state0, training)
# out1: [b, 64]
out1, state1 = self.rnn_cell1(out0, state1, training) # out: [b, 64] => [b, 1]
x = self.outlayer(out1)
# p(y is pos|x)
prob = tf.sigmoid(x) return prob def main():
units = 64
epochs = 4 model = MyRNN(units)
model.compile(optimizer=keras.optimizers.Adam(0.001),
loss=tf.losses.BinaryCrossentropy(),
metrics=['accuracy'])
model.fit(db_train, epochs=epochs, validation_data=db_test) model.evaluate(db_test) if __name__ == '__main__':
main()

Multi-layers

import os
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers tf.random.set_seed(22)
np.random.seed(22)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
assert tf.__version__.startswith('2.') batchsz = 128 # the most frequest words
total_words = 10000 # 编码10000个单词
max_review_len = 80 # 句子长度80
embedding_len = 100
(x_train,
y_train), (x_test,
y_test) = keras.datasets.imdb.load_data(num_words=total_words)
# x_train:[b, 80]
# x_test: [b, 80]
x_train = keras.preprocessing.sequence.pad_sequences(x_train,
maxlen=max_review_len)
x_test = keras.preprocessing.sequence.pad_sequences(x_test,
maxlen=max_review_len) db_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))
# drop_remainder,丢弃最后一个大小不合适的batch
db_train = db_train.shuffle(1000).batch(batchsz, drop_remainder=True)
db_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))
db_test = db_test.batch(batchsz, drop_remainder=True)
print('x_train shape:', x_train.shape, tf.reduce_max(y_train),
tf.reduce_min(y_train))
print('x_test shape:', x_test.shape) class MyRNN(keras.Model):
def __init__(self, units):
super(MyRNN, self).__init__() # transform text to embedding representation
# [b, 80] => [b, 80, 100] # embedding_len=100表示一个单词为100的向量
self.embedding = layers.Embedding(total_words,
embedding_len,
input_length=max_review_len) # [b, 80, 100] , h_dim: 64
self.rnn = keras.Sequential([
layers.SimpleRNN(units,
dropout=0.5,
return_sequences=True,
unroll=True),
layers.SimpleRNN(units, dropout=0.5, unroll=True)
]) # fc, [b, 80, 100] => [b, 64] => [b, 1] # 得到分类结果
self.outlayer = layers.Dense(1) def call(self, inputs, training=None):
"""
net(x) net(x, training=True) :train mode
net(x, training=False): test
:param inputs: [b, 80]
:param training: 计算过程是train还是test
:return:
"""
# [b, 80]
x = inputs
# embedding: [b, 80] => [b, 80, 100]
x = self.embedding(x)
# rnn cell compute
# x: [b, 80, 100] => [b, 64]
x = self.rnn(x) # out: [b, 64] => [b, 1]
x = self.outlayer(x)
# p(y is pos|x)
prob = tf.sigmoid(x) return prob def main():
units = 64
epochs = 4 model = MyRNN(units)
model.compile(optimizer=keras.optimizers.Adam(0.001),
loss=tf.losses.BinaryCrossentropy(),
metrics=['accuracy'])
model.fit(db_train, epochs=epochs, validation_data=db_test) model.evaluate(db_test) if __name__ == '__main__':
main()

RNN与情感分类问题实战-加载IMDB数据集的更多相关文章

  1. pytorch 加载mnist数据集报错not gzip file

    利用pytorch加载mnist数据集的代码如下 import torchvision import torchvision.transforms as transforms from torch.u ...

  2. torchvision的理解和学习 加载常用数据集,对主流模型的调用.md

    torchvision的理解和学习 加载常用数据集,对主流模型的调用 https://blog.csdn.net/tsq292978891/article/details/79403617 加载常用数 ...

  3. 科学计算三维可视化---TVTK管线与数据加载(数据集)

    一:数据集 三维可视化的第一步是选用合适的数据结构来表示数据,TVTK提供了多种表示不同种类数据的数据集 (一)数据集--ImageData >>> from tvtk.api im ...

  4. Tensorflow之快速加载MNIST数据集

    from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf def myprint(v): p ...

  5. Pytorch文本分类(imdb数据集),含DataLoader数据加载,最优模型保存

    用pytorch进行文本分类,数据集为keras内置的imdb影评数据(二分类),代码包含六个部分(详见代码) 使用环境: pytorch:1.1.0 cuda:10.0 gpu:RTX2070 (1 ...

  6. [DeeplearningAI笔记]序列模型2.9情感分类

    5.2自然语言处理 觉得有用的话,欢迎一起讨论相互学习~Follow Me 2.9 Sentiment classification 情感分类 情感分类任务简单来说是看一段文本,然后分辨这个人是否喜欢 ...

  7. JVM学习二:JVM之类加载器之加载分析

    前面一遍,我们对类的加载有了一个整体的认识,而这一节我们细节分析一下类加载器的第一步,即:加载. 一.概念 类的加载指的是将类的.class文件中的二进制数据读入到内存中,将其放在运行时数据区的方法区 ...

  8. UIButton 加载网络图片

    以后就可以 用这个分类   UIButton轻松加载网络图片了, UIButton+WebCache.h #import <UIKit/UIKit.h> @interface UIButt ...

  9. Pytorch加载并可视化FashionMNIST指定层(Udacity)

    加载并可视化FashionMNIST 在这个notebook中,我们要加载并查看 Fashion-MNIST 数据库中的图像. 任何分类问题的第一步,都是查看你正在使用的数据集.这样你可以了解有关图像 ...

随机推荐

  1. icons使用

    1.将选中图标加入项目 2.unicode方式查看连接在线连接 3.复制代码到样式表 4.引用样式,并设置I标签,颜色和大小可以通过设置i标签color和font-size进行调整 <i cla ...

  2. 题解报告:hdu 1098 Ignatius's puzzle

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1098 题目中文是这样的: 伊格内修斯在数学上很差,他遇到了一个难题,所以他别无选择,只能上诉埃迪. 这 ...

  3. MAT使用入门

    原文出处: 高建武 (Granker,@高爷) MAT简介 MAT(Memory Analyzer Tool),一个基于Eclipse的内存分析工具,是一个快速.功能丰富的JAVA heap分析工具, ...

  4. h5学习-css3的一些内容整理

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. Jquery操作常用表单元素

    由于对前端的东西不是很熟练,导致jquery操作表单的东西总是忘记,每次用都要查一下,效率低下,记录下来,以便下次使用. CheckBox checkbox改变事件 $('#IsAllSearch') ...

  6. IOS 中使用token机制来验证用户的安全性

    登录的业务逻辑{    http:是短连接.         服务器如何判断当前用户是否登录?    // 1. 如果是即时通信类:长连接.    // 如何保证服务器跟客户端保持长连接状态? // ...

  7. 用idea+maven编译打包spark project core错误:java.lang.RuntimeException: Unable to load a Suite class

    Discovery starting. *** RUN ABORTED *** java.lang.RuntimeException: Unable to load a Suite class tha ...

  8. SQLServer性能优化专题

    SQLServer性能优化专题 01.SQLServer性能优化之----强大的文件组----分盘存储(水平分库) http://www.cnblogs.com/dunitian/p/5276431. ...

  9. 谈谈如何学习Linux操作系统

     献给初学者:为了能把这篇不错的文章分享给大家.所以请允许我暂时用原创的形式展现给大家. @hcy 更多资源:http://blog.sina.com.cn/iihcy 一. 选择适合自己的linux ...

  10. AIX 10201 HA RAC 安装+升级到10204

    1:查看系统版本 [rac1:root:/hacmp/hacmp5.4/ha5.4/installp/ppc] oslevel -s 6100-06-06-1140 lslpp -al bos.adt ...