【发布时间】:2019-12-13 04:08:39
【问题描述】:
我在这里阅读了一个使用带有 tensorflow 的 RNN 的示例:ptb_word_lm.py
我不知道embedding 和embedding_lookup 在这里做什么。它如何为张量添加另一个维度?从 (20, 25) 到 (20, 25, 200)。在这种情况下,(20,25) 是 20 的批量大小,有 25 个时间步长。我不明白您如何/为什么可以将单元格的hidden_size 添加为输入数据的维度?通常,输入数据将是大小为[batch_size, num_features] 的矩阵,模型将映射num_features ---> hidden_dims 与大小为[num_features, hidden_dims] 的矩阵,从而产生大小为[batch-size, hidden-dims] 的输出。那么hidden_dims怎么可能是输入张量的一个维度呢?
input_data, targets = reader.ptb_producer(train_data, 20, 25)
cell = tf.nn.rnn_cell.BasicLSTMCell(200, forget_bias=1.0, state_is_tuple=True)
initial_state = cell.zero_state(20, tf.float32)
embedding = tf.get_variable("embedding", [10000, 200], dtype=tf.float32)
inputs = tf.nn.embedding_lookup(embedding, input_data)
input_data_train # <tf.Tensor 'PTBProducer/Slice:0' shape=(20, 25) dtype=int32>
inputs # <tf.Tensor 'embedding_lookup:0' shape=(20, 25, 200) dtype=float32>
outputs = []
state = initial_state
for time_step in range(25):
if time_step > 0:
tf.get_variable_scope().reuse_variables()
cell_output, state = cell(inputs[:, time_step, :], state)
outputs.append(cell_output)
output = tf.reshape(tf.concat(1, outputs), [-1, 200])
outputs # list of 20: <tf.Tensor 'BasicLSTMCell/mul_2:0' shape=(20, 200) dtype=float32>
output # <tf.Tensor 'Reshape_2:0' shape=(500, 200) dtype=float32>
softmax_w = tf.get_variable("softmax_w", [config.hidden_size, config.vocab_size], dtype=tf.float32)
softmax_b = tf.get_variable("softmax_b", [config.hidden_size, config.vocab_size], dtype=tf.float32)
logits = tf.matmul(output, softmax_w) + softmax_b
loss = tf.nn.seq2seq.sequence_loss_by_example([logits], [tf.reshape(targets, [-1])],[tf.ones([20*25], dtype=tf.float32)])
cost = tf.reduce_sum(loss) / batch_size
【问题讨论】:
标签: python tensorflow deep-learning