与Tensorflow占位符不兼容的形状

时间:2016-09-15 15:31:40

标签: numpy tensorflow

我收到以下错误:

ValueError: Cannot feed value of shape (2, 2) for Tensor u'Placeholder_1:0', which has shape '(2,)'

在以下行:

nn_index = sess.run(pred, feed_dict={xtr: training_input, xte: test_input[index, :]})

训练输入数据的形状为(24, 2),测试输入数据为(300, 2)

虽然提供数据的占位符初始化为

xtr = tf.placeholder("float", [None, 2])
xte = tf.placeholder("float", [2])

# Nearest Neighbor calculation using L1 Distance
def metric_single(training, test):
  distance = tf.sqrt(tf.reduce_sum(tf.square(tf.sub(training, test)),
    reduction_indices=1, keep_dims=True))

  return distance

# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(metric_single(xtr, xte), 0)

无法弄清楚我的代码中要更改的内容以解决此问题。

~~~~编辑~~~~

test_input.shape
>>>(300, 2)

*Updated*
test_input[index, :].shape
>>>(2, )

training_input.shape
>>>(24, 2)

*Updated*
index
>>>index: 0

~~~~~ FULL ML SOURCE ~~~~~

# Nearest Neighbor calculation using L1 Distance
def metric_single(training, test):
  distance = tf.sqrt(tf.reduce_sum(tf.square(tf.sub(training, test)),
    reduction_indices=1, keep_dims=True))

  return distance


xtr = tf.placeholder("float", [None, 2])
xte = tf.placeholder("float", [None, 2])

# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(metric_single(xtr, xte), 0)

accuracy = 0

# Initializing the variables
init = tf.initialize_all_variables()

def calculate_knn(training_input, training_output, test_input, test_output, k, index):
  print 'training_input'
  print training_input
  print 'test_input'
  print test_input
  for j in range(k):
    print 'training_input.shape'
    print training_input.shape
    print 'test_input[index, :].shape'
    print test_input[index, :].shape
    print 'index: ' + str(index)

    nn_index = sess.run(pred, feed_dict={xtr: training_input, xte: test_input[index, :]})

    print 'knn #: ' + str(j+1)
    print 'nn_index: ' + str(nn_index)
    # Get nearest neighbor class label and compare it to its true label
    print("Test", \
      "Sample:",  test_input[i], \
      "Nearest Neightbor:", training_input[nn_index], \
     i, "Prediction:", np.argmax(training_output[nn_index]), \
        "True Class:", np.argmax(test_output[i]))

    ## Remove nearest neighbor from test data to
    ## find (k-1)nn
    # training_input = tf.slice(training_input, [nn_index, 0], [-1, -1])
    training_input = np.delete(training_input, nn_index, 0)

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    Tr = TrainingData()
    Te = TestData()

    ## TODO: process test data in batches

    # loop over test data
    test_examples = Te.get_Xte()
    for i in test_examples:
      print 'in test data loop'
      # Get nearest neighbor={xtr: Xtr, xte: Xte[i, :]})
      print 'Tr.get_Xtr()'
      print Tr.get_Xtr()

      print 'Te.get_Xte()'
      print Te.get_Xte()

      calculate_knn(Tr.get_Xtr(), Tr.get_Ytr(), Te.get_Xte(), Te.get_Yte(), 2, i)


      #Calculate accuracy
      if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
          accuracy += 1./len(Xte)

    print("Done!")
    print("Accuracy:", accuracy)

1 个答案:

答案 0 :(得分:1)

问题似乎是index是一个列表而不是Python整数,在这一行:

nn_index = sess.run(pred, feed_dict={xtr: training_input, xte: test_input[index, :]})

如果您有一个大小为4x4的numpy数组,如下所示,您的索引表达式将具有以下行为:

data = np.arange(0, 16).reshape(4, 4)  # ==> [[ 0,  1,  2,  3],
                                              [ 4,  5,  6,  7],
                                              [ 8,  9, 10, 11],
                                              [12, 13, 14, 15]]  

# 1. index is an int
print data[0, :]       # ==> [0, 1, 2, 3]  (4-element vector)

# 2. index is a list of one int
print data[[0], :]     # ==> [[0, 1, 2, 3]]  (1x4 matrix)

# 3. index is a list of two ints
print data[[0, 0], :]  # ==> [[0, 1, 2, 3], [0, 1, 2, 3]]  (2x4 matrix)

因为当你打印index时得到了结果[0 0],看起来你的情况就是3。如果不了解index的含义,我怀疑您可能希望更改feed_dict以将index转换为int,例如:

nn_index = sess.run(pred, feed_dict={xtr: training_input, xte: test_input[index[0], :]})