TF识别手写体识别分类
#-*- coding: utf-8 -*-
# @Time : 2017/12/26 15:42
# @Author : Z
# @Email : S
# @File : 1.9classification.py
#该程序在windows上报错,linux上没问题
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#网上下载数据包,也可以下载好指定
#http://yann.lecun.com/exdb/mnist/
mnist = input_data.read_data_sets('D:\\BigData\\Data\\MNIST_data', one_hot=True) print(mnist.train.num_examples)
#
def add_layer(inputs,in_size,out_size,activation_function=None):
#定义权重--随机生成inside和outsize的矩阵
Weights=tf.Variable(tf.random_normal([in_size,out_size]))
#不是矩阵,而是类似列表
biaes=tf.Variable(tf.zeros([1,out_size])+0.1)
Wx_plus_b=tf.matmul(inputs,Weights)+biaes
if activation_function is None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
return outputs
def compute_accuracy(v_xs,v_ys):
global prediction
y_pre=sess.run(prediction,feed_dict={xs:v_xs})
correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})
return result
#添加placeholder对于输入网络层
xs=tf.placeholder(tf.float32,[None,784]) #28*28
ys=tf.placeholder(tf.float32,[None,10])
#增加输出层
prediction=add_layer(xs,784,10,activation_function=tf.nn.softmax)
#定义loss损失---信息熵
cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduce_indices=[1]))
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy) sess=tf.Session()
#变量的初始化
sess.run(tf.global_variables_initializer()) for i in range(1000):
batch_xs,batch_ys=mnist.train.next_batch(100) #取一部分数据
sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
if i%50:
print (compute_accuracy(mnist.test.images,mnist.test.labels))
显示结果