ValueError: Cannot feed value of shape (100, 160) for Tensor 'Placeholder:0', which has shape '(?,

Python在使用Tensorflow過程中,運行程序出現如下錯誤:
ValueError: Cannot feed value of shape (100, 160) for Tensor ‘Placeholder:0’, which has shape '(?,16000)
錯誤的含義是TensorFlow無法爲Tensor’佔位符:0’提供形狀值。

placeholder是TensorFlow的佔位符節點,由placeholder方法創建,也是一種常量,是由用戶在調用run方法是傳遞的,也可以將placeholder理解爲一種形參。本例創建如下:

#佔位符,通過爲輸入圖像和目標輸出類別創建節點,來開始構建計算圖。
x = tf.placeholder("float", shape=[None, 16000]) #160*100
y_ = tf.placeholder("float", shape=[None, 4])

參數說明:

  • dtype:數據類型,必填,默認爲value的數據類型,傳入參數爲tensorflow下的枚舉值(float32,float64…)
  • shape:數據形狀,選填,不填則隨傳入數據的形狀自行變動,可以在多次調用中傳入不同形狀的數據
  • name:常量名,選填,默認值不重複,根據創建順序爲(Placeholder,Placeholder_1,Placeholder_2…)

給模型喂數據,傳參如下:

x_train,x_test,y_train,y_test = train_test_split(x_data,y_data,test_size=0.2,random_state=1)
......
    batch_x = x_train[i]
    if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={x:batch_x, y_: batch_y, keep_prob: 1.0})
        print ("step {}, training accuracy {}".format(i, train_accuracy))

圖片數據獲取及數據源如下;

for j in [file_name for file_name in list][1]:
    for i in data_read(datapath + '/' + j):
        a = cv2.imread('./' + datapath + '/' + j + '/' + i + '.jpg', cv2.IMREAD_GRAYSCALE)
        sum.append([a, j])

y_data = [v[1] for v in sum]
x_data = [v[0] for v in sum]
x_data = np.array(x_data)

在調試程序過程中,出現瞭如下等錯誤提示:

ValueError: Cannot feed value of shape (10,100, 160) for Tensor ‘Placeholder:0’, which has shape ‘(?, 16000)’

ValueError: Cannot feed value of shape (100, 160) for Tensor ‘Placeholder:0’, which has shape ‘(?, 16000)’

ValueError: Cannot feed value of shape (16000,) for Tensor ‘Placeholder:0’, which has shape ‘(?, 16000)’

根本原因是給模型喂數據的形狀(shape)不一致,解決方案如下:

    batch_x = x_train[i]
    batch_x = np.reshape(batch_x, (-1, 16000))
    if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={x:batch_x, y_: batch_y, keep_prob: 1.0})
        print ("step {}, training accuracy {}".format(i, train_accuracy))    

使用Python numpy函數:reshape(),修改數組對象形狀爲(?,16000),batch_x = np.reshape(batch_x, (-1, 16000))。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章