实现回归模型
使用TensorFlow之前,首先导入它:
import tensorflow as tf
#x不是一个特定的值,而是一个占位符placeholder,我们在#TensorFlow运行计算时输入这个值。我们希望能够输入任意数量的#MNIST图像,每一张图展平成784维的向量。
x = tf.placeholder("float", [None, 784])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x,W) + b) #模型表示
y_ = tf.placeholder("float", [None,10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# 在运行计算之前,我们需要添加一个操作来初始化我们创建的变量
init = tf.initialize_all_variables()
# 现在我们可以在一个Session里面启动我们的模型,并初始化变量:
sess = tf.Session()
sess.run(init)
# 开始训练模型,1000次
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={
x: batch_xs, y_: batch_ys})
以上是斯坦福官网教程。今天自己跟着做了一遍,具体代码如下:
>>> import tensorflow as tf
>>> x = tf.placeholder("float",[None, 784])
>>> w = tf.Variable(tf.zeros([784,10]))
>>> b = tf.Variable(tf.zeros([10]))
>>> y = tf.nn.softmax(tf.matmul(x,w)+ b)
>>> y_= tf.placeholder("float",[None,10])
>>> cross_entropy = -tf.reduce_sum(y_*tf.log(y))
>>> train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
>>> init = tf.initialize_all_variables()
>>> sess = tf.Session()
>>> sess.run(init)
>>> for i in range(1000):
... batch_xs, batch_ys = mnist.