张量流softmax_cross_entropy_with_logits_v2引发ValueError

时间:2018-07-28 18:41:37

标签: python python-2.7 tensorflow

我已经定义了一个单一输入层和一个输出层的神经网络。我的数据为csv格式,已转换为tfrecord格式。我使用tf.data api对其进行批处理并按以下方式进行输入:

  • 功能:32(批量大小)x 24(功能列)
  • 标签:32(批量大小)x 4(onehot编码)

在运行图形时会引发ValueError。这是回溯:

  

文件“ dummy.py”,第60行,在       train_summary,_ = sess.run([trainStep],feed_dict = {ground_truth:标签,功能:功能})

     

文件“ /usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py”,行895,正在运行       run_metadata_ptr)

     

文件“ /usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py”,行1104,在_run中       %(np_val.shape,subfeed_t.name,str(subfeed_t.get_shape())))

     

ValueError:无法为Tensor u'softmax_cross_entropy_with_logits / Reshape_2:0'输入形状为((,,)'的Tensor形状(32,4)的值

以下是可以重现该错误的最少代码:

import tensorflow as tf
import numpy as np

num_columns=24
num_classes=4
train_steps = 2

def model():

   ground_truth_input = tf.placeholder(tf.float32,[None,num_classes]) #onehotencoded with depth 4
   bottleneck_input = tf.placeholder(tf.float32,[None,num_columns])  #num_columns=24 keypoint features

   #fully connected 1 : 24(num_input_features)x100
   initial_value = tf.truncated_normal([num_columns, 100], stddev=0.001)
   layer1_weights = tf.Variable(initial_value, name='hidden1_weights')
   layer1_biases = tf.Variable(tf.zeros([100]), name='hidden1_biases')
   logits_hidden1 = tf.matmul(bottleneck_input, layer1_weights) + layer1_biases
   inp_activated=tf.nn.relu(logits_hidden1,name='hidden1_activation')

   #fully connected 2 : 100x4(num_classes)
   initial_value = tf.truncated_normal([100, num_classes], stddev=0.001)
   layer_weights = tf.Variable(initial_value, name='final_weights')
   layer_biases = tf.Variable(tf.zeros([num_classes]), name='final_biases')
   logits = tf.matmul(inp_activated, layer_weights) + layer_biases

   # loss function 
   loss_mean = tf.nn.softmax_cross_entropy_with_logits_v2(labels=ground_truth_input, logits=logits)

   with tf.name_scope('train'):
      optimizer = tf.train.MomentumOptimizer(learning_rate=0.1,use_nesterov=True,momentum=0.9)
      train_op = optimizer.minimize(loss_mean, global_step=tf.train.get_global_step())

   with tf.name_scope('SoftMax_Layer'):
      final_tensor = tf.nn.softmax(logits,name='Softmax')

   return train_op, ground_truth_input, bottleneck_input, loss_mean

trainStep, cross_entropy, features, ground_truth = model()

with tf.Session() as sess:
  for i in range(2):
       Label = np.eye(4)[np.random.choice(4,32)]
       Features = np.random.rand(32,24)
       train_summary, _ = sess.run([trainStep],feed_dict = {ground_truth : Label, features :Features})

1 个答案:

答案 0 :(得分:1)

trainStep, cross_entropy, features, ground_truth = model()

这4个返回值与您的return语句不匹配:

return train_op, ground_truth_input, bottleneck_input, loss_mean