[英]Trouble with understanding how TensorFlow receives and processes data
我最近開始學習深度學習,並且對我對RNN和LSTM的理論以及深入的實際實現的理解充滿信心。 我寫了一個非常簡單的RNN,它學會了僅使用numpy將兩個二進制數相加。 我現在正試圖熟悉TensorFlow API,以便不再需要從頭開始構建模型。
盡管我對NN的理解和編程能力充滿信心,但在理解TensorFlow對模型進行抽象的高層以及應該如何使用數據的結構方面不斷遇到障礙時,我仍然感到非常沮喪。 我碰到的牆的一個示例在下面的代碼中,我在其中嘗試實現一個簡單的RNN,該RNN接受一個整數列表/序列的列表,然后將學習如何將單個序列分類為遞增還是遞減。 generate_data()
輸出兩個列表:
data
的格式為[[1, 2, 3], [9, 8, 7]]
,是輸入序列。 labels
是1
s或0
s的列表-1表示相應的序列在增加,而0表示在減少。 x
是輸入序列的占位符, y
是相應標簽的占位符。 我的思維過程是RNN將每個輸入序列作為x
接收,即單列張量,每行是序列的單個整數-展開的RNN中的單個時間步。 然后,在每次對RNN進行完全正向傳播(處理完一個完整的x
張量后)之后,RNN將輸出一個整數( 0
或1
)。
我收到一個錯誤,即輸入的最后一行必須是一個序列。 我無法理解如何不將此單列張量視為序列,以及如何對其進行整形以使其成為序列。
順便說一句,我接下來的最大誤解是,在我對RNN進行的所有理論解釋中,共有3種加權矩陣-一種從輸入到隱藏狀態,一個從隱藏狀態到輸出,以及一個在隱藏狀態之間每個時間步長。 我使用TensorFlow看到的所有編碼示例似乎都只有一個加權矩陣。 怎么了 TensorFlow如何使用這個單一矩陣作為3個深層矩陣的抽象? 我是否在W = tf.Variable(tf.random_normal([sequence_len, output_dim]))
行中正確成形此矩陣?
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib import rnn
import random
sequence_len = 5 # Input Dimension
max_num = 1000 # Must be >= than (sequence_len - 1)
output_dim = 1
hidden_dim = 16
batch_size = 1000
def generate_data(sample_size, seq_len=sequence_len, max = max_num):
data = []
labels = []
for _ in range(sample_size):
type = (1 if random.random() < 0.5 else 0)
temp = []
if type == 1:
labels.append(1)
temp.append(random.randint(0, max_num - seq_len + 1))
for i in range(1, seq_len):
temp.append(random.randint(temp[i - 1] + 1, max_num - seq_len + i + 1))
data.append(temp)
if type == 0:
labels.append(0)
temp.append(random.randint(0 + seq_len - 1, max_num))
for i in range(1, seq_len):
temp.append(random.randint( 0 + seq_len - i - 1, temp[i - 1] - 1))
data.append(temp)
return data, labels
input_data, labels = generate_data(100000)
x = tf.placeholder(tf.int32, [None, sequence_len])
y = tf.placeholder(tf.int32, [None, output_dim])
W = tf.Variable(tf.random_normal([sequence_len, output_dim]))
b = tf.Variable(tf.random_normal([output_dim]))
cell = rnn.BasicRNNCell(hidden_dim)
outputs, states = tf.nn.static_rnn(cell, x, dtype=tf.int32)
tf.static_rnn
預計清單Tensors
按文檔因此它可以決定你的RNN的長度(注意,這必須運行之前確定,這就是為什么你需要傳遞的一個Python列表Tensors
,而不是Tensor
):
輸入:輸入的長度T列表,每個輸入為張量,形狀為[batch_size,input_size],或此類元素的嵌套元組。
outputs, states = tf.nn.static_rnn(cell, [x], dtype=tf.int32)
應該可以工作。
關於您的附帶問題,部分答案可以在BasicRNNCell
的實現中BasicRNNCell
:
def call(self, inputs, state):
"""Most basic RNN: output = new_state = act(W * input + U * state + B)."""
output = self._activation(_linear([inputs, state], self._num_units, True))
return output, output
但這實際上取決於您選擇使用的RNNCell
。 這是模型的一部分,它將實現input
到state
, state
到state
以及state
到output
邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.