Python Tensorflow错误,无法为Tensor占位符提供形状值

Python Tensorflow错误,无法为Tensor占位符提供形状值,python,numpy,tensorflow,deep-learning,Python,Numpy,Tensorflow,Deep Learning,我正试图开发一个用于分类的神经网络。这就是我所拥有的: m, n = X_train.shape alpha, epochs = 0.0035, 500 print(m) -> 26374 print(n) -> 75 X = tf.placeholder(tf.float32, [None, n]) Y = tf.placeholder(tf.float32, [None, 2]) W = tf.Variable(tf.zeros([n, 2])) b = tf.Variable

我正试图开发一个用于分类的神经网络。这就是我所拥有的:

m, n = X_train.shape
alpha, epochs = 0.0035, 500
print(m) -> 26374
print(n) -> 75

X = tf.placeholder(tf.float32, [None, n])
Y = tf.placeholder(tf.float32, [None, 2])
W = tf.Variable(tf.zeros([n, 2]))
b = tf.Variable(tf.zeros([2]))

Y_hat = tf.nn.sigmoid(tf.add(tf.matmul(X, W), b)) 
cost = tf.nn.sigmoid_cross_entropy_with_logits( 
                    logits = Y_hat, labels = Y) 
optimizer = tf.train.GradientDescentOptimizer( 
         learning_rate = alpha).minimize(cost) 
init = tf.global_variables_initializer() 

# Starting the Tensorflow Session 
x = X_train.values
y = y_train.values
with tf.Session() as sess: 

    # Initializing the Variables 
    sess.run(init) 

    # Lists for storing the changing Cost and Accuracy in every Epoch 
    cost_history, accuracy_history = [], [] 

    # Iterating through all the epochs 
    for epoch in range(epochs): 
        cost_per_epoch = 0

        # Running the Optimizer 
        sess.run(optimizer, feed_dict = {X : x, Y : y}) 

        # Calculating cost on current Epoch 
        c = sess.run(cost, feed_dict = {X : x, Y : y}) 

        # Calculating accuracy on current Epoch 
        correct_prediction = tf.equal(tf.argmax(Y_hat, 1), 
                                          tf.argmax(Y, 1)) 
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, 
                                                 tf.float32)) 

        # Storing Cost and Accuracy to the history 
        cost_history.append(sum(sum(c))) 
        accuracy_history.append(accuracy.eval({X : x, Y : y}) * 100) 

        # Displaying result on current Epoch 
        if epoch % 100 == 0 and epoch != 0: 
            print("Epoch " + str(epoch) + " Cost: "
                            + str(cost_history[-1])) 

    Weight = sess.run(W) # Optimized Weight 
    Bias = sess.run(b)   # Optimized Bias 

    # Final Accuracy 
    correct_prediction = tf.equal(tf.argmax(Y_hat, 1), 
                                      tf.argmax(Y, 1)) 
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,  
                                             tf.float32)) 
    print("\nAccuracy:", accuracy_history[-1], "%") 
我得到这个错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-8d85989454ef> in <module>
     15 
     16         # Running the Optimizer
---> 17         sess.run(optimizer, feed_dict = {X : x, Y : y})
     18 
     19         # Calculating cost on current Epoch

~\AppData\Local\Continuum\anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    948     try:
    949       result = self._run(None, fetches, feed_dict, options_ptr,
--> 950                          run_metadata_ptr)
    951       if run_metadata:
    952         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~\AppData\Local\Continuum\anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1147                              'which has shape %r' %
   1148                              (np_val.shape, subfeed_t.name,
-> 1149                               str(subfeed_t.get_shape())))
   1150           if not self.graph.is_feedable(subfeed_t):
   1151             raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (26374, 1) for Tensor 'Placeholder_7:0', which has shape '(?, 2)'
---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-44-6d9b8231b8b1> in <module>
      4 # Encoding x_orig
      5 oneHot.fit(X_train.values)
----> 6 x = oneHot.transform(X_train.values).toarray()
      7 
      8 # Encoding y_orig

~\AppData\Local\Continuum\anaconda3\envs\tf-gpu\lib\site-packages\scipy\sparse\compressed.py in toarray(self, order, out)
   1022         if out is None and order is None:
   1023             order = self._swap('cf')[0]
-> 1024         out = self._process_toarray_args(order, out)
   1025         if not (out.flags.c_contiguous or out.flags.f_contiguous):
   1026             raise ValueError('Output array must be C or F contiguous')

~\AppData\Local\Continuum\anaconda3\envs\tf-gpu\lib\site-packages\scipy\sparse\base.py in _process_toarray_args(self, order, out)
   1184             return out
   1185         else:
-> 1186             return np.zeros(self.shape, dtype=self.dtype, order=order)
   1187 
   1188 

MemoryError: 
并收到此错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-8d85989454ef> in <module>
     15 
     16         # Running the Optimizer
---> 17         sess.run(optimizer, feed_dict = {X : x, Y : y})
     18 
     19         # Calculating cost on current Epoch

~\AppData\Local\Continuum\anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    948     try:
    949       result = self._run(None, fetches, feed_dict, options_ptr,
--> 950                          run_metadata_ptr)
    951       if run_metadata:
    952         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~\AppData\Local\Continuum\anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1147                              'which has shape %r' %
   1148                              (np_val.shape, subfeed_t.name,
-> 1149                               str(subfeed_t.get_shape())))
   1150           if not self.graph.is_feedable(subfeed_t):
   1151             raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (26374, 1) for Tensor 'Placeholder_7:0', which has shape '(?, 2)'
---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-44-6d9b8231b8b1> in <module>
      4 # Encoding x_orig
      5 oneHot.fit(X_train.values)
----> 6 x = oneHot.transform(X_train.values).toarray()
      7 
      8 # Encoding y_orig

~\AppData\Local\Continuum\anaconda3\envs\tf-gpu\lib\site-packages\scipy\sparse\compressed.py in toarray(self, order, out)
   1022         if out is None and order is None:
   1023             order = self._swap('cf')[0]
-> 1024         out = self._process_toarray_args(order, out)
   1025         if not (out.flags.c_contiguous or out.flags.f_contiguous):
   1026             raise ValueError('Output array must be C or F contiguous')

~\AppData\Local\Continuum\anaconda3\envs\tf-gpu\lib\site-packages\scipy\sparse\base.py in _process_toarray_args(self, order, out)
   1184             return out
   1185         else:
-> 1186             return np.zeros(self.shape, dtype=self.dtype, order=order)
   1187 
   1188 

MemoryError: 
---------------------------------------------------------------------------
MemoryError回溯(上次最近调用)
在里面
4#编码x源
5 oneHot.fit(X_系列值)
---->6x=oneHot.transform(x_train.values).toarray()
7.
8#编码源代码
~\AppData\Local\Continuum\anaconda3\envs\tf gpu\lib\site packages\scipy\sparse\compressed.py in-toarray(self、order、out)
1022如果out为None且order为None:
1023订单=自交换('cf')[0]
->1024 out=self.\u进程\u到阵列\u参数(订单,输出)
1025如果不是(out.flags.c_连续或out.flags.f_连续):
1026 raise VALUERROR('输出数组必须是C或F连续')
~\AppData\Local\Continuum\anaconda3\envs\tf gpu\lib\site packages\scipy\sparse\base.py in\u process\u toarray\u args(self、order、out)
1184返回
1185其他:
->1186返回np.0(self.shape,dtype=self.dtype,order=order)
1187
1188
记忆错误:

我不确定错误是什么,也不确定我如何解决它。

y=y\u train.values
的形状为(26374,1),但您定义了
y=tf.placeholder(tf.float32,[None,2])
。可能您没有将标签转换为一个热编码。@zihaozhao y_train.value只是0和1。我需要应用一个热编码有什么原因吗?因为您的
Y
的形状为(无,2),所以您需要匹配该形状。0->[1,0]和1->[0,1]@zihaozhihao请查看Updated您不需要将X转换为一个热。X是特征,Y是标签。前面的错误是由Y和Y之间的形状不一致引起的。