眷恋你的方圆

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

使用mnist 数据集,

softmax回归预测标签

使用交叉熵损失函数计算损失值

使用梯度下降法优化参数

# -*- coding: utf-8 -*-
import tensorflow as tf
#下载数据集
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x = tf.placeholder(tf.float32, [None, 784])
y_= tf.placeholder(tf.float32, [None, 10])    #实际标签
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, w) +b)          #预测标签
loss = -tf.reduce_sum(y_*tf.log(y))               #计算损失值
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)#梯度下降优化参数

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    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})#训练
    
    correct = tf.equal(tf.argmax(y,1), tf.argmax(y_ ,1))
    accuracy = tf.reduce_mean(tf.cast(correct, "float"))
    print (sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))  #传入测试集
            

 

posted on 2017-09-06 17:04  眷恋你的方圆  阅读(223)  评论(0编辑  收藏  举报