如何在Tensorflow中进行预测

3

我对tensorflow是个新手。我正在尝试解决Xor问题,我的问题是如何在tensorflow中进行预测。当我输入[1,0]时,我希望它能给我一个1或0。另外,在不同的情况下,如果是一个模型,它应该有多个值(回归器),例如股票。我该怎么做?谢谢。

import tensorflow as tf
import numpy as np
X = tf.placeholder(tf.float32, shape=([4,2]), name = "Input")
y = tf.placeholder(tf.float32, shape=([4,1]), name = "Output")
#weights
W = tf.Variable(tf.random_uniform([2,2], -1,1), name = "weights1")
w2 = tf.Variable(tf.random_uniform([2,1], -1,1), name = "weights2")
Biases1 = tf.Variable(tf.zeros([2]), name = "Biases1")
Biases2 = tf.Variable(tf.zeros([1]), name = "Biases2")
#Setting up the model
Node1 = tf.sigmoid(tf.matmul(X, W)+ Biases1)
Output = tf.sigmoid(tf.matmul(Node1, w2)+ Biases2)
#Setting up the Cost function
cost = tf.reduce_mean(((y* tf.log(Output))+ 
                       ((1-y)* tf.log(1.0 - Output)))* -1)
#Now to training and optimizing
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
xorX = np.array([[0,0], [0,1], [1,0], [1,1]])
xorY = np.array([[0], [1], [1], [0]])
#Now to creating the session
initial = tf.initialize_all_variables()
sess = tf.Session()
sess.run(initial)
for i in range(100000):
    sess.run(train_step, feed_dict={X: xorX, y: xorY })

如果您能更具体一些会更有帮助:您所说的“预测”是指什么? - wwl
所以基本上我输入了两个值[1,0]。我希望它告诉我0或1,这就是全部,对此感到抱歉。 - sam202252012
1个回答

2

由于您的分类仅在Output<0.5时为0,因此可以添加新的预测节点:

prediction_op = tf.round(Output)

然后再调用它

print(sess.run(prediction_op, feed_dict={X: np.array([[1., 0.]])}))

请您能否解释一下正在发生的事情,因为我是一个完全的新手。谢谢。 - sam202252012
另外,您如何预测它是否为回归模型,例如对于股票等有多个输出的情况? - sam202252012
你只需要在你的图操作中添加产生输出的部分,并在会话中运行它,因为你的图从sigmoid函数生成概率,你也可以直接在Output节点上使用sess.run,我加入了“round”使其成为一个类。对于回归问题,你只需要运行你的Output节点,就这样简单。 - lejlot
在回归中,输出不是来自于Sigmoid函数的概率吗?谢谢。 - sam202252012
请提出单独的问题,并准确描述您的意思。 - lejlot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接