TensorFlow 實現最簡單的 RNN
TensorFlow 最簡潔的 RNN 實現,比較容易理解。
代碼來自:《Hands-On Machine Learning with Scikit-Learn and TensorFlow》
博客:TensorFlow 安裝,TensorFlow 教程,TensorFlow 資源,TensorFlow 導航。
import tensorflow as tfnnimport numpy as npn# Mini-batch: instance 0,instance 1,instance 2,instance 3nX0_batch = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 0, 1]]) # t = 0nX1_batch = np.array([[9, 8, 7], [0, 0, 0], [6, 5, 4], [3, 2, 1]]) # t = 1nnn_inputs = 3nn_neurons = 5nX0 = tf.placeholder(tf.float32, [None, n_inputs])nX1 = tf.placeholder(tf.float32, [None, n_inputs])nWx = tf.Variable(tf.random_normal(shape=[n_inputs, n_neurons],dtype=tf.float32))nWy = tf.Variable(tf.random_normal(shape=[n_neurons,n_neurons],dtype=tf.float32))nb = tf.Variable(tf.zeros([1, n_neurons], dtype=tf.float32))nY0 = tf.tanh(tf.matmul(X0, Wx) + b)nY1 = tf.tanh(tf.matmul(Y0, Wy) + tf.matmul(X1, Wx) + b)ninit = tf.global_variables_initializer()nnwith tf.Session() as sess:n init.run()n Y0_val, Y1_val = sess.run([Y0, Y1], feed_dict={X0: X0_batch, X1: X1_batch})n print(Y0_val)n print(Y0_val)n
輸出:
[[ 0.99726343 0.95937806 -0.99868864 -0.97029704 -0.99751657]n [ 0.99999988 0.99985486 -1. -0.99804956 -0.99979889]n [ 1. 0.99999958 -1. -0.99987364 -0.99998385]n [ 0.9999091 0.69876397 0.99348551 0.97668368 0.99999994]]n[[ 0.99726343 0.95937806 -0.99868864 -0.97029704 -0.99751657]n [ 0.99999988 0.99985486 -1. -0.99804956 -0.99979889]n [ 1. 0.99999958 -1. -0.99987364 -0.99998385]n [ 0.9999091 0.69876397 0.99348551 0.97668368 0.99999994]]n
推薦閱讀:
※TensorFlow從1到2 | 第五章 非專家莫入!TensorFlow實現CNN
※Github|如何用TensorFlow實現DenseNet和DenseNet-BC(附源代碼)
※深度學習對話系統實戰篇--老版本tf.contrib.legacy_seq2seq API介紹和源碼解析
※Google開源模塊化多任務訓練庫Tensor2Tensor
TAG:TensorFlow |