RNN GRU LSTM

RNN GRU LSTM 的学习来自:

https://zybuluo.com/hanbingtao/note/541458

https://zybuluo.com/hanbingtao/note/581764

RNN的实例化

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist
# import keras

physical_devices = tf.config.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0],True)

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0

model = keras.Sequential()
model.add(keras.Input(shape=(None, 28)))
model.add(
    layers.SimpleRNN(512, return_sequences=True, activation='relu')
)
model.add(layers.SimpleRNN(512, activation='relu'))
model.add(layers.Dense(10))

print(model.summary())

model.compile(
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer=keras.optimizers.Adam(lr=0.001),
    metrics=['accuracy']
)

model.fit(x_train, y_train, batch_size=64, epochs=10, verbose=2)
model.evaluate(x_test, y_test, batch_size=64, verbose=2)
Epoch 10/10
938/938 - 174s - loss: 0.0755 - accuracy: 0.9798
157/157 - 5s - loss: 0.0602 - accuracy: 0.9834

GRU

model = keras.Sequential()
model.add(keras.Input(shape=(None, 28)))
model.add(
    layers.GRU(512, return_sequences=True, activation='relu')
)
model.add(layers.GRU(512, activation='relu'))
model.add(layers.Dense(10))
Epoch 10/10
938/938 - 523s - loss: 0.0161 - accuracy: 0.9950
157/157 - 29s - loss: 0.0411 - accuracy: 0.9879

LSTM and 双向

model = keras.Sequential()
model.add(keras.Input(shape=(None, 28)))
model.add(
    layers.Bidirectional(
        layers.GRU(512, return_sequences=True, activation='relu')
    )
)    
model.add(layers.Bidirectional(
    layers.GRU(512, activation='relu'))
)
model.add(layers.Dense(10))

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值