且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TF之LoR:基于tensorflow利用逻辑回归算LoR法实现手写数字图片识别提高准确率

更新时间:2022-05-12 19:42:14

输出结果

TF之LoR:基于tensorflow利用逻辑回归算LoR法实现手写数字图片识别提高准确率

设计代码


#TF之LoR:基于tensorflow实现手写数字图片识别准确率

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

import numpy as np  

import matplotlib.pyplot as plt

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

print(mnist)

#设置超参数

lr=0.001                      #学习率

training_iters=100       #训练次数

batch_size=100                #每轮训练数据的大小,如果一次训练5000张图片,电脑会卡死,分批次训练会更好

display_step=1

#tf Graph的输入

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]))

#设定运行模式

pred =tf.nn.softmax(tf.matmul(x,w)+b)  #

#设置cost function为cross entropy

cost =tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))

#GD算法

optimizer=tf.train.GradientDescentOptimizer(lr).minimize(cost)

#初始化权重

init=tf.global_variables_initializer()

#开始训练

with tf.Session() as sess:

   sess.run(init)

   avg_cost_list=[]

   for epoch in range(training_iters):  #输入所有训练数据

       avg_cost=0.

       total_batch=int(mnist.train.num_examples/batch_size)

   

       for i in range(total_batch): #遍历每个batch

……

       if (epoch+1) % display_step ==0:  #显示每次迭代日志

           print("迭代次数Epoch:","%04d" % (epoch+1),"下降值cost=","{:.9f}".format(avg_cost))

           avg_cost_list.append(avg_cost)

   print("Optimizer Finished!")

   print(avg_cost_list)

   

   #测试模型

   correct_prediction=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))

   accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

   print("Accuracy:",accuracy.eval({x:mnist.test.images[:3000],y:mnist.test.labels[:3000]}))

   

   xdata=np.linspace(0,training_iters,num=len(avg_cost_list))  

   plt.figure()  

   plt.plot(xdata,avg_cost_list,'r')

   plt.xlabel('训练轮数')

   plt.ylabel('损失函数')

   plt.title('TF之LiR:基于tensorflow实现手写数字图片识别准确率——Jason Niu')    

   plt.show()