tensorflow 学习 softmax Regression 识别手写数字

下面代码是来自 tensorflow 实战一书,

主要包括三个部分:
1.构建模型 y=w*x+b
2.构建损失函数模型-交叉熵
3.构建查找最优值方法–梯度下降

#!/user/bin/env python
import tensorflow as tf

sess = tf.InteractiveSession()

 # x is feature value
x = tf.placeholder(tf.float32, [None, 784])

 # w is weight for feature
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
#构建模型
y = tf.nn.softmax(tf.matmul(x,w) + b)

 # y_ is true value 
y_ = tf.placeholder(tf.float32, [None, 10])
#通过交叉熵计算损失函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))

learn_rate = 0.5
train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(cross_entropy)

tf.global_variables_initializer().run()
#开始训练
for _ in range(10000):
    #select 100 data as training set
    batch_xs, batch_ys = mnist_data.train.next_batch(100)
    train_step.run({x: batch_xs, y_: batch_ys})
#计算准确率  
correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval({x: mnist_data.test.images,y_: mnist_data.test.labels}))

猜你喜欢

转载自blog.csdn.net/shiluohuashengmi/article/details/82698519
今日推荐