本文主要是介绍【机器学习笔记2.6】用Softmax回归做mnist手写体识别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
MNIST是什么
MNIST是一个手写数字数据集,它有60000个训练样本集和10000个测试样本集。可以将MNIST手写体识别看做是深度学习的HelloWorld。
MNIST数据集官方网址:http://yann.lecun.com/exdb/mnist/
从官网下载的MNIST数据集是二进制形式存储的,可以通过如下代码将其转换为图片形式。
代码示例1:
# mnist数据集转成图片
import os
import numpy as np
import cv2
import tensorflow.examples.tutorials.mnist.input_data as input_datadatapath = "MNIST_data/"
mnist = input_data.read_data_sets(datapath, validation_size=0, one_hot=True)def get_train_data():train_images = mnist.train.imagestrain_labels = mnist.train.labelsreturn train_images, train_labelsdef get_test_data():test_images = mnist.test.imagestest_labels = mnist.test.labelsreturn test_images, test_labelsdef save_data(images, labels, train_test_str):for i in range(images.shape[0]):image = images[i].reshape([28, 28]) * 255label = labels[i]index = np.argmax(label)index_path = os.path.join(datapath, train_test_str, str(index))if not os.path.exists(index_path):os.makedirs(index_path)cv2.imwrite(os.path.join(index_path, str(index) + "_" + str(i) + ".jpg"), image)images, labels = get_train_data()
save_data(images, labels, "train")
images, labels = get_test_data()
save_data(images, labels, "test")print('end')
用Softmax回归做mnist手写体识别
loss 用最小二乘法
代码示例2[1]:
import numpy as np
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", validation_size=0, one_hot=True)x_data = tf.placeholder("float32", [None, 784])
weight = tf.Variable(tf.ones([784, 10]))
bias = tf.Variable(tf.ones([10]))
y_model = tf.nn.softmax(tf.matmul(x_data, weight) + bias)
y_data = tf.placeholder("float32", [None, 10])loss = tf.reduce_sum(tf.pow((y_model - y_data), 2))train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)# 为了能print出array的所有元素,而不是中间是省略号
np.set_printoptions(threshold=np.inf)accuracy_rate_list = []
for _ in range(1000):batch_xs, batch_ys = mnist.train.next_batch(100)sess.run(train_step, feed_dict={x_data:batch_xs, y_data:batch_ys})if _ % 50 == 0:accuracy_bool_vec = tf.equal(tf.argmax(y_model, 1), tf.argmax(y_data, 1)) # tf.argmax解析accuracy_float_vec = tf.cast(accuracy_bool_vec, "float")accuracy_rate = tf.reduce_mean(accuracy_float_vec)accuracy_rate = sess.run(accuracy_rate, feed_dict={x_data: mnist.test.images, y_data: mnist.test.labels})accuracy_rate_list.append(accuracy_rate)print(accuracy_rate)# 为便于理解上述准确率的计算过程,可将程序拆解如下分析"""test_batch_size = 2data = mnist.test.images[0:test_batch_size]label = mnist.test.labels[0:test_batch_size]data = data.reshape([test_batch_size, 784])label = label.reshape([test_batch_size, 10])rslt1 = sess.run(y_model, feed_dict={x_data: data})rslt2 = sess.run(y_data, feed_dict={y_data: label})rslt3 = sess.run(tf.argmax(y_model, 1), feed_dict={x_data: data})rslt4 = sess.run(tf.argmax(y_data, 1), feed_dict={y_data: label})rslt5 = sess.run(fcorrect, feed_dict={x_data: data, y_data: label})rslt6 = sess.run(accuracy, feed_dict={x_data: data, y_data: label})print(rslt1, rslt2, rslt3, rslt4, rslt5, rslt6)"""import matplotlib.pyplot as plt
accuracy_rate_arr = np.array(accuracy_rate_list)
size = np.arange(len(accuracy_rate_arr))
plt.plot(size, accuracy_rate_arr, 'b+', label='accuracy_rate')
plt.show()
准确率曲线图如下:
loss 用交叉熵, 使用relu激活函数
对代码示例2做如下修改[1]:
激活函数用relu
y_model = tf.nn.relu(tf.matmul(x_data, weight) + bias)
损失函数用交叉熵
loss = -tf.reduce_sum(y_data*tf.log(y_model))
完整代码示例3:
略
输出结果如下:
0.1328
0.4654
……
0.5596
……
0.6175
0.6237
实验结果准确率并未如[1](12.2.4)中所说有所提升,反而下降了。是文献[1]代码写错了吗?该如何修改呢?
(后来掌握的知识多了,发现其实文献[1]写的挺搓的,代码有很多坑。)
增加隐藏层
将代码示例2中的weight、bias、y_model进行修改,将weight、bias修改为weight1、bias1,并增加weight2、bias2,具体如下[1]:
weight1 = tf.Variable(tf.ones([784, 256]))
bias1 = tf.Variable(tf.ones([256]))
y1_model1 = tf.matmul(x_data, weight1) + bias1weight2 = tf.Variable(tf.ones([256, 10]))
bias2 = tf.Variable(tf.ones([10]))
y_model = tf.nn.softmax(tf.matmul(y1_model1, weight2) + bias2)
# y_model = tf.nn.relu(tf.matmul(y1_model1, weight2) + bias2)
完整代码示例4:
import numpy as np
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)x_data = tf.placeholder("float32", [None, 784])# weight = tf.Variable(tf.ones([784, 10]))
# bias = tf.Variable(tf.ones([10]))
# y_model = tf.nn.softmax(tf.matmul(x_data, weight) + bias)# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
weight1 = tf.Variable(tf.ones([784, 256]))
bias1 = tf.Variable(tf.ones([256]))
y1_model1 = tf.matmul(x_data, weight1) + bias1weight2 = tf.Variable(tf.ones([256, 10]))
bias2 = tf.Variable(tf.ones([10]))
y_model = tf.nn.softmax(tf.matmul(y1_model1, weight2) + bias2)
# y_model = tf.nn.relu(tf.matmul(y1_model1, weight2) + bias2)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~y_data = tf.placeholder("float32", [None, 10])loss = tf.reduce_sum(tf.pow((y_model - y_data), 2))
# loss = -tf.reduce_sum(y_data*tf.log(y_model))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)# 为了能print出array的所有元素,而不是中间是省略号
np.set_printoptions(threshold=np.inf)accuracy_rate_list = []
for _ in range(1000):batch_xs, batch_ys = mnist.train.next_batch(50)sess.run(train_step, feed_dict={x_data:batch_xs, y_data:batch_ys})if _ % 50 == 0:accuracy_bool_vec = tf.equal(tf.argmax(y_model, 1), tf.argmax(y_data, 1)) # tf.argmax解析accuracy_float_vec = tf.cast(accuracy_bool_vec, "float")accuracy_rate = tf.reduce_mean(accuracy_float_vec)accuracy_rate = sess.run(accuracy_rate, feed_dict={x_data: mnist.test.images, y_data: mnist.test.labels})accuracy_rate_list.append(accuracy_rate)print(accuracy_rate)# 为便于理解上述准确率的计算过程,可将程序拆解如下分析'''test_batch_size = 2data = mnist.test.images[0:test_batch_size]label = mnist.test.labels[0:test_batch_size]data = data.reshape([test_batch_size, 784])label = label.reshape([test_batch_size, 10])rslt1 = sess.run(y_model, feed_dict={x_data: data})rslt2 = sess.run(y_data, feed_dict={y_data: label})rslt3 = sess.run(tf.argmax(y_model, 1), feed_dict={x_data: data})rslt4 = sess.run(tf.argmax(y_data, 1), feed_dict={y_data: label})rslt5 = sess.run(fcorrect, feed_dict={x_data: data, y_data: label})rslt6 = sess.run(accuracy, feed_dict={x_data: data, y_data: label})print(rslt1, rslt2, rslt3, rslt4, rslt5, rslt6)'''import matplotlib.pyplot as plt
accuracy_rate_arr = np.array(accuracy_rate_list)
size = np.arange(len(accuracy_rate_arr))
plt.plot(size, accuracy_rate_arr, 'b+', label='accuracy_rate')
plt.show()
输出结果:
0.1032
识别率反而更低了,比示例3的识别率还低。文献[1]作者是想通过此例来说明,对于MNIST手写体识别,单靠在softmax回归中增加隐藏层是不可行的。
参考文献
[1] 王晓华. TensorFlow深度学习应用实践
这篇关于【机器学习笔记2.6】用Softmax回归做mnist手写体识别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!