[英]Tensorflow reshape tensor
我有一个预测张量(实际网络)
(Pdb) pred
<tf.Tensor 'transpose_1:0' shape=(?, 200, 200) dtype=float32>
和张力
y = tf.placeholder("float", [None, n_steps, n_classes])
(Pdb) y
<tf.Tensor 'Placeholder_1:0' shape=(?, 200, 200) dtype=float32>
我想把它喂进去
f.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
但是,它要求维度为[batch_size, num_classes]
因此,我想重塑pred
和y
使它们看起来像这样
<tf.Tensor 'transpose_1:0' shape=(?, 40000) dtype=float32>
但是,当我进行reshape
我得到了
(Pdb) tf.reshape(pred, [40000])
<tf.Tensor 'Reshape_1:0' shape=(40000,) dtype=float32>
而不是(?,40000)
我怎么能保持这种None
维? (批量大小)
我还发布了所有相关代码......
# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
y = tf.placeholder("float", [None, n_steps, n_classes])
# Define weights
weights = {
'hidden': tf.Variable(tf.random_normal([n_hidden, n_classes]), dtype="float32"),
'out': tf.Variable(tf.random_normal([n_hidden, n_classes]), dtype="float32")
}
biases = {
'hidden': tf.Variable(tf.random_normal([n_hidden]), dtype="float32"),
'out': tf.Variable(tf.random_normal([n_classes]), dtype="float32")
}
def RNN(x, weights, biases):
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, n_steps, n_input)
# Permuting batch_size and n_steps
x = tf.transpose(x, [1, 0, 2])
# Reshaping to (n_steps*batch_size, n_input)
x = tf.reshape(x, [-1, n_input])
# Split to get a list of 'n_steps' tensors of shape (batch_size, n_hidden)
# This input shape is required by `rnn` function
x = tf.split(0, n_steps, x)
# Define a lstm cell with tensorflow
lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True)
outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)
output_matrix = []
for i in xrange(n_steps):
temp = tf.matmul(outputs[i], weights['out']) + biases['out']
# temp = tf.matmul(weights['hidden'], outputs[i]) + biases['hidden']
output_matrix.append(temp)
pdb.set_trace()
return output_matrix
pred = RNN(x, weights, biases)
# temp = RNN(x)
# pdb.set_trace()
# pred = tf.shape(temp)
pred = tf.pack(tf.transpose(pred, [1,0,2]))
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
我是雅罗斯拉夫评论中另一个问题的答案之一的作者。 您可以使用-1作为None维度。
您可以使用tf.reshape()轻松完成,而无需了解批量大小。
x = tf.placeholder(tf.float32, shape=[None, 9,2])
shape = x.get_shape().as_list() # a list: [None, 9, 2]
dim = numpy.prod(shape[1:]) # dim = prod(9,2) = 18
x2 = tf.reshape(x, [-1, dim]) # -1 means "all"
无论批处理大小在运行时中是什么,最后一行中的-1表示整个列。 你可以在tf.reshape()中看到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.