我是TensorFlow的新人,最近我需要使用它来训练ANN而不使用TensorFlow的高级API。
但是,以下代码出了问题:
n_inputs = getVectorLength(instance2Path)
n_outputs = 1
n_hidden1 = 66
n_hidden2 = 24
learning_rate = 0.01
n_epochs = 400
batch_size = 50
def neuron_layer(X, n_neurons, name, activation=None):
with tf.name_scope(name):
n_inputs = int(X.get_shape()[1])
stddevValue = 2 / np.sqrt(n_inputs)
initWeight = tf.truncated_normal((n_inputs, n_neurons), stddev=stddevValue)
W = tf.Variable(initWeight, name='weights', dtype='float')
b = tf.Variable(tf.zeros([n_neurons]), name='biases')
z = tf.matmul(X, W) + b
if activation == 'relu':
return tf.nn.relu(z)
elif name == 'outputs':
return tf.sigmoid(z)
pass
pass
X = tf.placeholder(dtype=tf.float32, shape=(None, n_inputs), name='X')
y = tf.placeholder(dtype=tf.float32, shape=(None), name='y')
hidden1 = neuron_layer(X, n_hidden1, 'hidden1', activation='relu')
hidden2 = neuron_layer(hidden1, n_hidden2, 'hidden2', activation='relu')
outputs = neuron_layer(hidden2, n_outputs, 'outputs')
init = tf.global_variables_initializer()
with tf.Session() as sess:
print n_inputs
sess.run(init)
samples, labels = prepareSampleAndLabelAndFeature(ConfigVars.FeatureSelectionStrategy2, instance2Path)
sample = np.array(samples[0])
sample = sample.reshape(1, 170)
sess.run(outputs, feed_dict={X: sample})
print outputs.eval()
运行上面的代码后,我得到以下例外:
Caused by op u'X', defined at:
File "/Users/apple/PycharmProjects/TesTensorFlow/TrainANN/ANNTest.py", line 45, in <module>
X = tf.placeholder(dtype=tf.float32, shape=(None, n_inputs), name='X')
File "/Users/apple/anaconda/envs/TensorFlow_GPU/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.py", line 1507, in placeholder
name=name)
File "/Users/apple/anaconda/envs/TensorFlow_GPU/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1997, in _placeholder
name=name)
File "/Users/apple/anaconda/envs/TensorFlow_GPU/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
op_def=op_def)
File "/Users/apple/anaconda/envs/TensorFlow_GPU/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/Users/apple/anaconda/envs/TensorFlow_GPU/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'X' with dtype float
[[Node: X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
在我看来,问题可能依赖于X的数据类型,但我已经检查过了! X的输入向量类似于[0,1,0,1 .....],仅包含0-1值,标签为0和1,或典型的二元分类问题。
答案 0 :(得分:0)
有两件事可能是错误的来源:
When reshaping a np.ndarray, the shape is considered as one variable.例如sample = sample.reshape([1, 170])
其中[1, 170]
是所需的形状。
由于X
被定义为大小为[none, n_inputs]
的占位符,因此sample
的形状必须与该形状匹配。例如n_inputs
是170。