当前位置:网站首页>LSTM in tensorflow_ Layers actual combat
LSTM in tensorflow_ Layers actual combat
2022-06-26 05:04:00 【Rain and dew touch the real king】
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
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)
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__()
# 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
self.rnn = keras.Sequential([
# layers.SimpleRNN(units, dropout=0.5, return_sequences=True, unroll=True),
# layers.SimpleRNN(units, dropout=0.5, unroll=True)
layers.LSTM(units, dropout=0.5, return_sequences=True, unroll=True),
layers.LSTM(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:
: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,training=training)
# 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
import time
t0 = time.time()
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)
t1 = time.time()
# 69.3 secnods, 83%
print('total time cost:', t1-t0)
if __name__ == '__main__':
main()
边栏推荐
猜你喜欢
![[unity3d] rigid body component](/img/57/344aae65e4ac6a7d44b235584f95d1.png)
[unity3d] rigid body component

Stm8 MCU ADC sampling function is triggered by timer

PowerShell runtime system IO exceptions
![C# 39. string类型和byte[]类型相互转换(实测)](/img/33/046aef4e0c1d7c0c0d60c28e707546.png)
C# 39. string类型和byte[]类型相互转换(实测)

【Unity3D】碰撞体组件Collider

PSIM software learning ---08 call of C program block

Pycharm package import error without warning

Rsync common error messages (common errors on the window)

6.1 - 6.2 公钥密码学简介

86. (cesium chapter) cesium overlay surface receiving shadow effect (gltf model)
随机推荐
dijkstra
Astype conversion data type
What is UWB in ultra-high precision positioning system
[unity3d] collider assembly
2. < tag dynamic programming and conventional problems > lt.343 integer partition
Sort query
Datetime data type - min() get the earliest date and date_ Range() creates a date range, timestamp() creates a timestamp, and tz() changes the time zone
Difference between return and yield
Computer Vision Tools Chain
2022.1.24
Multipass Chinese document - use packer to package multipass image
Final review of brain and cognitive science
Numpy general function
Multipass Chinese document - use multipass service to authorize the client
【Latex】错误类型总结(持更)
2022.2.15
Status of processes and communication between processes
Method of saving pictures in wechat applet
A company crawling out of its grave
Use fill and fill in Matplotlib_ Between fill the blank area between functions