SimpleCell 函数 括号中的内容是 hidden len SimpleCell函数需要自己说明在哪个轴展开
# 四个句子 80种单词 每种单词用长度为100的特征向量表示
x tf.random.normal([4,80,100])
xt0 x[:,0,:]
cell tf.keras.layers.SimpleRNNCell(64)
# RNN的输出是ht和yt 其中yt表示当前的输出 ht表示传入到下一个网络的上一个网络的输出
# 在简单RNN网络种 yt和ht是相同的 但高级RNN中这两个量是有所不同的
out, xt1 cell(xto, [tf.zeros([4,64])])
a1 out.shape
a2 xt1[10].shape
a3 id(out)
a4 id(xt1[0])
多层RNN 有时候embeddding的结果可以经过多层网络 而不只是一层。这种情况下一般根据最高层的最后一层结果作为最后的判决依据
x tf.random.normal([4,80,100])
xt0 x[:,0,:]
cell tf.keras.layers.SimpleRNNCell(64)
cell_1 tf.keras.layers.SimpleRNNCell(64)
state [tf.zeros([4,64])]
state1 [tf.zeros([4,64])]
out, state cell(xto, state)
out1, state1 cell(out, state)
# 设置在时间轴 即 第二个维度上展开
for word in tf.unstack(x, axis 1):
out_real0 self.cell(word, state, training)
out_real1 self.cell(out_real0, state1, training)
SimpleRNN函数 SimpleRNN可以自动在时间轴上展开 通常搭配Sequential使用
self.rnn keras.Sequential([
layers.SimpleRNN(units, dropout 0.5, return_sequences True, unroll True)
layers.SimpleRNN(units, dropout 0.5, unroll True)
x self.rnn(x)
4. RNN实战
情感问题分类 采用两层embedding RNN采用SimpleRNNCell函数实现 SimpleRNNCell函数需要用户自行设定在哪个轴展开
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
import os
os.environ[ TF_CPP_MIN_LOG_LEVEL ] 2