共计 1299 个字符,预计需要花费 4 分钟才能阅读完成。
代码如下:
#!/usr/bin/python
#-*- coding:utf-8 -*-
############################
#File Name: Softmax_Regression.py
#Author: yang
#Mail: milkyang2008@126.com
#Created Time: 2017-08-22 20:51:58
############################
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
#load training data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
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.global_variables_initializer()
sess = tf.Session()
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_predition = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predition, "float"))
result =sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels})
print("the accuracy is: %g " % result)
训练结果如下:
cting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
the accuracy is: 0.9154
正文完
请博主喝杯咖啡吧!