python初实现
MNIST数据集数字识别
这里是新入门的感知机识别数字的代码详解
感知机(Perceptron)实现MNIST数字识别
在 jupyter notebook 中进行实现。网络结构是,具体代码如下
1. 导入包
// 导入numpy; tensorflow; input_data包
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
2. 载入MNIST数据集,并创建默认的Interactive Session
// 载入MNIST数据集,one_hot=True表示一个长度为n的数组只有一个元素是1.0,其它元素是0.0;而非one_hot标签类似0 1 2 3 … n
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
// 创建默认的Interactive Session
sess = tf.InteractiveSession()
3. 感知机网络结构
// 声明输入张量的格式,具体的数值在正式运行时给出 None 表示数据的行数不确定。也就是每个图像是个784的列的向量,不确定有多少张图像
x = tf.placeholder(tf.float32, [None, 784])
// 将784行,10列的二维数组中的所有值初始化为0,W 表示权重(也就是重要程度,越重要,权重的值越大)
W = tf.Variable(tf.zeros([784, 10]))
// 初始化一个含有100个值的一维数组中,全部初始化为0
b = tf.Variable(tf.zeros([10]))
// 输出神经元,输出矩阵 x 和 W 的乘积加上偏置 b
y = tf.nn.softmax(tf.matmul(x, W)+b)
4. 损失和优化器
交叉熵损失函数
// 真实的y标签
y_ = tf.placeholder(tf.float32, [None, 10])
// 损失loss,此处用的为交叉熵损失函数,多输入单输出。
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
// 优化器。用随机梯度下降算法寻找最优点。但是SGD容易陷入局部最优,学习率为0.5
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
5. 初始化和准确率
// 将所有变量初始化,并直接执行 run() 方法
tf.global_variables_initializer().run()
// tf.argmax(data,axis)是返回一维数组中张量最大的值所在的位置,axis=0,按列计算每列最大数的下标。axis=1,按行计算。
// tf.equal返回的是长度为100(因为每个批次有100条样本)的一维数组,内容是布尔值true或者false
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
// tf.cast(data,dtype)的作用是将data的类型转换为dtype类型
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
// 比如这里,把bool类型的correct_prediction转换成tf.float32,就实现了true或者false变成了0或者1的转换
6. 训练
// 训练阶段,迭代10000次
for i in range(1000):
// 每次随机从训练集中抽取100条样本构成一个mini-batch
batch_xs, batch_ys = mnist.train.next_batch(100)
// train_step.run带着有实际输入的x和y_执行train_step这个operation
train_step.run({x: batch_xs, y_: batch_ys})
// 这里使用的是eval,和run的区别是eval只能接收一个operation返回一个tensor结果
// 这里是将mnist.train.images和mnist.train.labels作为x和y的值feed给了accuracy这个operation
train_accuracy = accuracy.eval({x: mnist.train.images, y_: mnist.train.labels})
print("Step%d, Training accuracy %g" % (i, train_accuracy))
print("准确率:",accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))
7. 注意
若在训练过程中有input_data的警告,加入以下代码
import logging
// 下面的类用于解决read_data_sets抛出的警告
class WarningFilter(logging.Filter):
def filter(self, record):
msg = record.getMessage()
tf_warning = 'retry (from tensorflow.contrib.learn.python.learn.datasets.base)' or 'from tensorflow.contrib.learn.python.learn.datasets.base' in msg
return not tf_warning
logger = logging.getLogger('tensorflow')
logger.addFilter(WarningFilter())
PS: 初学图像处理,还是小白,大家有问题多多交流。文中代码借鉴官网及部分博客,有问题还请指正,十分感谢!