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

你可能感兴趣的:(人工智能及Python,Tensorflow,Placeholder,人工智能,Python)