在Tensor-flow上实现神经模型

时间:2017-12-07 07:04:29

标签: python tensorflow neural-network

我正在尝试在Tensor流上实现神经网络模型,但似乎在占位符的形状方面存在问题。我是TF的新手,因此它可能只是一个简单的误解。这是我的代码和数据样本:

_data=[[0.4,0.5,0.6,1],[0.7,0.8,0.9,0],....]

数据包含4列数组,每个数组的最后一列是标签。我想将每个数组分类为标签0,标签1或标签2。

import tensorflow as tf
import numpy as np

_data = datamatrix
X = tf.placeholder(tf.float32, [None, 3])
W = tf.Variable(tf.zeros([3, 1]))
b = tf.Variable(tf.zeros([3]))

init = tf.global_variables_initializer()
Y = tf.nn.softmax(tf.matmul(X, W) + b)

# placeholder for correct labels
Y_ = tf.placeholder(tf.float32, [None, 1])

# loss function
import time
start=time.time()

cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y))

# % of correct answers found in batch
is_correct = tf.equal(tf.argmax(Y,1), tf.argmax(Y_,1))
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))

optimizer = tf.train.GradientDescentOptimizer(0.003)
train_step = optimizer.minimize(cross_entropy)


sess = tf.Session()
sess.run(init)
for i in range(1000):
    # load batch of images and correct answers
    batch_X, batch_Y = [x[:3] for x in _data[:2000]],[x[-1] for x in _data[:2000]]
    train_data={X: batch_X, Y_: batch_Y}

    # train
    sess.run(train_step, feed_dict=train_data)

# success ?
a,c = sess.run([accuracy, cross_entropy], feed_dict=train_data)

运行我的代码后出现以下错误消息:

ValueError: Cannot feed value of shape (2000,) for Tensor 'Placeholder_1:0', which has shape '(?, 1)'

我想要的输出应该是使用交叉熵的模型的性能;以下代码行的准确度值:

a,c = sess.run([accuracy, cross_entropy], feed_dict=train_data)

我也很感激有关如何改进模型的建议,或者更适合我数据的模型。

1 个答案:

答案 0 :(得分:1)

Placeholder_1:0 Y_的形状和输入数据batch_Y不匹配,如错误消息所指定。注意1-D和2-D阵列。

所以你应该定义1-D占位符:

Y_ = tf.placeholder(tf.float32, [None])

或准备二维数据:

    batch_X, batch_Y = [x[:3] for x in _data[:2000]],[x[-1:] for x in _data[:2000]]