Python Tensorflow 重塑张量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37868935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:02:16  来源:igfitidea点击:

Tensorflow reshape tensor

pythonmachine-learningneural-networkartificial-intelligencetensorflow

提问by Kendall Weihe

I have a prediction tensor (the actual network)

我有一个预测张量(实际网络)

(Pdb) pred
<tf.Tensor 'transpose_1:0' shape=(?, 200, 200) dtype=float32>

and a y tensor

和张量

y = tf.placeholder("float", [None, n_steps, n_classes])

(Pdb) y
<tf.Tensor 'Placeholder_1:0' shape=(?, 200, 200) dtype=float32>

I want to feed it into

我想喂它

f.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))

f.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))

However, it requires the dimensions to be [batch_size, num_classes]

但是,它要求尺寸为 [batch_size, num_classes]

So I want to reshape both predand yso that they look like this

所以我想重塑两者predy让它们看起来像这样

<tf.Tensor 'transpose_1:0' shape=(?, 40000) dtype=float32>

But when I run reshapeI get

但是当我跑步时reshape我得到

(Pdb) tf.reshape(pred, [40000])
<tf.Tensor 'Reshape_1:0' shape=(40000,) dtype=float32>

instead of (?,40000)how can I maintain that Nonedimension? (the batch size dimension)

而不是(?,40000)我如何保持那个None维度?(批量大小维度)

I've also posted all of the relevant code...

我还发布了所有相关代码...

# 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))

回答by weitang114

I'm the author of one of the answers of the other question in Yaroslav's comment. You can use -1 for the None dimension.

我是 Yaroslav 评论中另一个问题的答案之一的作者。您可以将 -1 用于 None 维度。



You can do it easily with tf.reshape() without knowing the batch size.

您可以使用 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"

The -1 in the last line means the whole column no matter what the batchsize is in the runtime. You can see it in tf.reshape().

最后一行中的 -1 表示整列,无论运行时的批次大小如何。你可以在 tf.reshape() 中看到它。