[英]TensorFlow logical operation ((A == B) && (C == D)) results in “Incompatible shapes: [2] vs. [3]”
我正在嘗試構建以下邏輯表達式-
tf.logical_and(tf.equal(tf.argmax(y_conv,0), tf.argmax(y_,0)),
tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)), name=None)
但這會導致以下錯誤-
不兼容的形狀:[2]與[3]
tf.equal(tf.argmax(y_conv,0), tf.argmax(y_,0))
和tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
工作正常,僅tf.logical_and
會發生錯誤。 tf.logical_and
期望布爾張量,而tf.equal
返回布爾張量,因此所有參數都順序正確,因此不確定為什么失敗。
給予一定的情況下,原來的代碼如下,我只是想更新correct_prediction
包括兩個0和1 tf.argmax
UPDATE1開始(這將添加所有變量聲明)
sess = tf.InteractiveSession()
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
W_conv1 = weight_variable([3, 3, 1, 32])
b_conv1 = bias_variable([32])
x = tf.placeholder(tf.float32, shape=[None, 9])
x_image = tf.reshape(x, [-1,3,3,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
h_pool2_flat = tf.reshape(h_conv1, [-1, 3 * 3 * 32])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
W_fc2 = weight_variable([64, 2])
b_fc2 = bias_variable([2])
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
UPDATE1 End(這將添加所有變量聲明)
這是問題所在的位置-
y_ = tf.placeholder(tf.float32, shape=[None, 2])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
#This works - correct_prediction = tf.equal(tf.argmax(y_conv,0), tf.argmax(y_,0)) . Changed it to -
correct_prediction = tf.logical_and(tf.equal(tf.argmax(y_conv,0), tf.argmax(y_,0)),
tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)),
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.global_variables_initializer())
train_step.run(feed_dict={x: xtrain, y_: ytrain, keep_prob: 0.5})
#In debugging mode, code breaks at the below line
print("test accuracy %g"%accuracy.eval(feed_dict={x: xtest, y_: ytest, keep_prob: 1.0}))
如何調試此錯誤?
出現問題是因為tf.equal()
是元素操作,並且它返回張量的形狀與其參數相同。 修復你表達的最簡單方法是使用tf.reduce_all()
聚合的結果tf.equal()
計算之前下降到標tf.logical_and()
如下所示:
tf.logical_and(
tf.reduce_all(tf.equal(tf.argmax(y_conv, 0), tf.argmax(y_, 0))),
tf.reduce_all(tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.