基于tensorflow的mnist的softmax分类
softmax回归是一个简单的分类模型,正确率在mnist测试集上达到91.74%。
主要由以下几个模块构成:
- 预处理部分:数据的读取,占位符和变量的定义;
- 迭代处理部分:损失函数和优化损失函数的优化方法定义;
- 后续评估部分:准确率的定义;
- 最后,启动sess实现,通过优化损失函数得到最优的参数,并在测试集上进行预测得到模型准确率。
import os, sys
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import cv2
#read data
mnist = input_data.read_data_sets('MNIST_data\\', one_hot=True)
#define variable
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 and gradientdescent
tmp = tf.reduce_sum(y_ * tf.log(y))
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y)))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
#accuracy
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#session
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for i in range(5000):
batch_x, batch_y_ = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x:batch_x, y_:batch_y_})
if (i%10 == 0):
acc = sess.run(accuracy, feed_dict={x:mnist.test.images,y_:mnist.test.labels})
print("step ",i,acc)