Tensorflow2.0 循环神经网络单元

单层RNN

import tensorflow as tf

from tensorflow.keras import layers

# 模拟输入数据
x = tf.random.normal([4, 80, 100])
xt0 = x[:, 0, :]  # [4, 1, 100] 单个数据

# 创建循环神经网络
cell = layers.SimpleRNNCell(64)

# 初始参数 记忆参数
ht0 = [tf.zeros([4, 64])]

# 循环网络的输出  out == ht1 (输出等于 1层输出)
out, ht1 = cell(xt0, ht0)

# 显示维度与 数据地址   ht1 是一个列表
print(out.shape, len(ht1), ht1[0].shape)
print(id(out), id(ht1[0]))

print(cell.trainable_variables)

输出维度 一致,id也保持一致
在这里插入图片描述

多层RNN

import tensorflow as tf
from tensorflow.keras import layers

# 模拟输入 4个句子  80个 单词  100个one-hot选择
x = tf.random.normal([4, 80, 100])

# 获取句子的 第0个单词
xt0 = x[:, 0, :]

# RNN单元
cell = layers.SimpleRNNCell(64)
cell2 = layers.SimpleRNNCell(64)

# RNN单元 记忆参数
state0 = [tf.zeros([4, 64])]
state1 = [tf.zeros([4, 64])]

# h1的输出
out0, state0 = cell(xt0, state0)

# h2的输出
out1, state1 = cell2(out0, state1)

print(out1.shape, state1[0].shape)

在这里插入图片描述

keras搭建RNN

import tensorflow as tf
from tensorflow.keras import layers

# 使用sequential 搭建两层循环神经网络
# 自动管理记忆层
model = tf.keras.Sequential([
    # return_sequences=True state内部记忆参数传递至下一层
    layers.SimpleRNN(64, dropout=0.5, return_sequences=True, unroll=True),
    layers.SimpleRNN(64, dropout=0.5, unroll=True)
])

# build模型建立
model.build(input_shape=[None, 80, 100])
model.summary()

# 模拟输入
x = tf.random.normal([4, 80, 100])

# 前向运算
predict = model(x)

# 输出维度
print(predict.shape)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45875105/article/details/111869515