TF識別手寫體識別分類linux
#-*- 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))
顯示結果windows