这次我们会介绍如何使用Tensorflow解决Classification(分类)问题。在之前的文章中介绍的都是Regression(回归)问题。分类和回归的区别在于输出变量的类型上。通俗理解定量输出是回归,或者说是连续变量预测;定性输出是分类,或者说是离散变量预测。如预测房价这是一个回归任务;把东西分成几类,比如猫狗猪牛,就是一个分类任务。
一、MNIST数据。
首先准备数据(MNIST库)
from tensorflow.examples.tutorials.mnist import input_data # number 1 to 10 data mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
MNIST库是手写体数字库,差不多是这个样子的:
数据中包含55000张训练图片,每张图片的分辨率是28*28,所以我们的训练网络输入应该是28*28=784个像素数据。
二、搭建网络
(1)定义网络的输入
# define placeholder for inputs to network xs = tf.placeholder(tf.float32, [None,784]) # 28*28
其中None表示忽略样本的个数,784表示每个样本为784个像素点。
(2)因为神经网络是有监督学习,所以我们要输入标签。
ys = tf.placeholder(tf.float32, [None,10])
每张图片都表示一个数字,所以我们的输出是数字0到9,共10类。
(3)调用add_layer函数搭建一个最简单的训练网络结构,只有输入层和输出层。
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)
其中输入数据是784个特征,输出数据是个10个特征,激励函数采用的是softmax函数,网络结构图是下面这个样子:
三、交叉熵损失函数(Cross entropy loss)
loss函数(即最优化目标函数)选用交叉熵函数。交叉熵用来衡量预测值和真实值的相似程度,如果完全相同,它们的交叉熵等于零。
# the error between prediction and real data cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1])) #loss
train方法(最优化算法)采用梯度下降法。
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess =tf.Session() # important step sess.run(tf.initialize_all_variables())
四、训练
现在开始train,每次只取100张图片,免得数据太多训练太慢。并且每训练50次输出一下预测精度。
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 ==0: # print(sess.run(prediction,feed_dict={xs:batch_xs})) print(compute_accuracy(mnist.test.images,mnist.test.labels))
五、结果
分析:结果还是很令人吃惊的,如此简单的神经网络结构竟然可以达到这样的图像识别精度,其实稍作改动之后,识别的精度将大幅度提高。
六、给出完整的代码
#coding:utf-8 # 导入本次需要的模块 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # number 1 to 10 data mnist = input_data.read_data_sets("MNIST_data",one_hot=True) ''' inputs:输入值 in_size:输入的大小 out_size:输出的大小 activation_function:激活函数 ''' # 构造添加一个神经层的函数 def add_layer(inputs,in_size,out_size,activation_function=None): # 定义weights为一个in_size行,out_size列的随机变量矩阵 Weights = tf.Variable(tf.random_normal([in_size,out_size])) biases = tf.Variable(tf.zeros([1,out_size]) + 0.1) Wx_plus_b = tf.add(tf.matmul(inputs,Weights),biases) 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 # #################导入数据################################## # define placeholder for inputs to network 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) # print(prediction) # the error between prediction and real data cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1])) #loss train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess =tf.Session() # important step sess.run(tf.initialize_all_variables()) # #################搭建神经网络################################## 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 ==0: # print(sess.run(prediction,feed_dict={xs:batch_xs})) print(compute_accuracy(mnist.test.images,mnist.test.labels))
观看视频笔记:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-01-classifier/