尝试填充占位符时出现Tensorflow错误

尝试填充占位符时出现Tensorflow错误,tensorflow,Tensorflow,我正在练习mnist数据,由于此错误,我无法输入占位符: ValueError: Cannot feed value of shape (20,) for Tensor 'Placeholder_1:0', which has shape '(?, 10)' 到目前为止,我的代码是: import gzip #https://stackoverflow.com/questions/37132899/installing-cpickle-with-python-3-5 import _p

我正在练习mnist数据,由于此错误,我无法输入占位符:

ValueError: Cannot feed value of shape (20,) for Tensor 'Placeholder_1:0', which has shape '(?, 10)'
到目前为止,我的代码是:

    import gzip
#https://stackoverflow.com/questions/37132899/installing-cpickle-with-python-3-5
import _pickle as cPickle

import tensorflow as tf
import numpy as np


# Translate a list of labels into an array of 0's and one 1.
# i.e.: 4 -> [0,0,0,0,1,0,0,0,0,0]
def one_hot(x, n):
    """
    :param x: label (int)
    :param n: number of bits
    :return: one hot code
    """
    if type(x) == list:
        x = np.array(x)
    x = x.flatten()
    o_h = np.zeros((len(x), n))
    o_h[np.arange(len(x)), x] = 1
    return o_h


f = gzip.open('mnist.pkl.gz', 'rb')
#https://stackoverflow.com/questions/40493856/python-pickle-unicodedecodeerror
train_set, valid_set, test_set = cPickle.load(f, encoding='latin1')
f.close()



train_x, train_y = train_set



# ---------------- Visualizing some element of the MNIST dataset --------------

import matplotlib.cm as cm
import matplotlib.pyplot as plt

plt.imshow(train_x[57].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()  # Let's see a sample
print (train_y[57])


# TODO: the neural net!!

# OJO hace falta formatear los datos.
#x_data = train_set[:, 0:784].astype('f4')
#y_data = one_hot(train_set[:, 785].astype(int), 10)

#Conocemos que las imagenes son de 28x28 entonces las columnas son 784, las filas se dejan para el momento del relleno
x = tf.placeholder("float", [None, 784])

#Necesitamos albergar las etiquetas reales del 0-9 para luego comparar y hallar el error.
y_ = tf.placeholder("float", [None, 10])

#Recibimos las 784 entradas y las sumamos a trav�s de 10 neuronas
W1 = tf.Variable(np.float32(np.random.rand(784, 10)) * 0.1)
#El umbral es 10 porque queremos que todas las neuronas participen �? AND �?
b1 = tf.Variable(np.float32(np.random.rand(10)) * 0.1)
#La funcion que clasifica la aplicamos a las entradas x con los pesos W1 adicionando el b1
y = tf.nn.softmax(tf.matmul(x, W1) + b1)

#Nuestro error es la diferencia entre las etiquetas reales de los n y las predichas por la red, al cuadrado; haciendo la media.
loss = tf.reduce_sum(tf.square(y_ - y))

#Minimizamos el error con un factor de aprendizaje de 0.01
train = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

init = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init)

print ("----------------------")
print ("   Start training...  ")
print ("----------------------")

batch_size = 20

for epoch in range(100):
    #https://stackoverflow.com/questions/19824721/i-keep-getting-this-error-for-my-simple-python-program-typeerror-float-obje
    for jj in range(len(train_x) // batch_size):
        batch_xs = train_x[jj * batch_size: jj * batch_size + batch_size]
        batch_ys = train_y[jj * batch_size: jj * batch_size + batch_size]
        tf.reshape(batch_ys, [2, 10])
        sess.run(train, feed_dict={x: batch_xs, y_: batch_ys})

    print ("Epoch #:", epoch, "Error: ", sess.run(loss, feed_dict={x: batch_xs, y_: batch_ys}))
    result = sess.run(y, feed_dict={x: batch_xs})
    for b, r in zip(batch_ys, result):
        print (b, "-->", r)
    print ("----------------------------------------------------------------------------------")

###�Como usamos el conjunto de validacion????
我真的很感激任何帮助。我也读过这个话题:


但是我需要帮助。

您没有在
列车y
的元素上应用
one\u hot
(如图所示,行
#y\u data=one\u hot(列车集合[:,785]。astype(int),10)
,这只是一条注释,也是您在代码中唯一使用
one\u hot
的地方)

因此,
batch_ys
是一个数字数组,如果要将其馈送到
feed_dict
,则需要将其转换为一个
one_hot
数组,因为
y_
是一个占位符,对应于
one_hot

y_ = tf.placeholder("float", [None, 10])

另外,删除行
tf.reformate(batch_ys,[2,10])
,因为您不需要重塑
batch_ys
。相反,您需要使用上面讨论的
one_hot
对其进行转换。

您没有在
train_y
的元素上应用
one_hot
(如行
所示y_data=one_hot(train_set[:,785]。astype(int),10)
,这只是一个注释,也是您代码中唯一使用了
one\u hot
)的地方

因此,
batch_ys
是一个数字数组,如果要将其馈送到
feed_dict
,则需要将其转换为一个
one_hot
数组,因为
y_
是一个占位符,对应于
one_hot

y_ = tf.placeholder("float", [None, 10])

另外,删除行
tf.reformate(batch_ys,[2,10])
,因为您不需要重塑
batch_ys
。相反,您需要使用上面讨论过的
one\u hot
来转换它。

谢谢Miriam Farber,您帮助了我,因为我试图强制将数字从0-9转换为占位符,名为y_,需要一个10个元素的单键数组谢谢你Miriam Farber你帮了我,因为我试图将数字从0-9输入一个名为y_的占位符,它需要一个10个元素的单键数组