我正在尝试将张量从2d调整为1d,但是当我尝试时,我遇到了一个非常奇怪的错误,即2、2无法调整为4。我做错了什么? >
import tensorflow as tf
x_size = 2
y_size = 2
batch_size = 10
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, (batch_size, x_size, y_size))
y_ = tf.placeholder(tf.float32, (None, 1))
x = tf.reshape(x, (batch_size, x_size * y_size))
y = tf.layers.dense(x, 1)
loss = tf.reduce_mean(tf.losses.mean_squared_error(y, y_))
a = [[list(range(y_size)) for i in range(x_size)] for i in range(batch_size)]
b = [[1] for i in range(batch_size)]
sess.run(loss, feed_dict={x: a, y_: b})
这给了我
ValueError: Cannot feed value of shape (10, 2, 2) for Tensor 'Reshape:0', which has shape '(10, 4)'
答案 0 :(得分:1)
错误是因为我将x传递到feed_dict中,但是我用重塑形状覆盖了x。通过将第12和13行替换为
nn = tf.reshape(x, (batch_size, x_size * y_size))
y = tf.layers.dense(nn, 1)
并添加
sess.run(tf.global_variables_initializer())
我能够使其完美运行。讲故事的寓意,请始终将占位符分开。
答案 1 :(得分:0)
您定义的x张量实际上是等级2(3d)设置为[10,2,2]。那么,假设您想使用2D,那么
这只是黑暗中的镜头,个人还没有进行重塑,但是在示例中,“ flatten”参数为-1?
因此,从API doc复制就可以了:
# tensor 't' is [[[1, 1, 1],
# [2, 2, 2]],
# [[3, 3, 3],
# [4, 4, 4]],
# [[5, 5, 5],
# [6, 6, 6]]]
# pass '[-1]' to flatten 't'
reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]
# -1 can also be used to infer the shape
# -1 is inferred to be 9:
reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]]
# -1 is inferred to be 2:
reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]]
因此,如果想从[10,2,2]变为[10,4],从理论上讲这行不通吗?
x = tf.reshape(x, [batch_size, -1])
或者,如果您实际上想一直下降到一维,则:
x = tf.reshape(x, [-1])