《tensorflow实战》之实现softmax pegression识别手写体(一)

xiaoxiao2021-02-28  41

一 概述

1.数据集

minist有55000个样本,测试集有10000个样本,验证集有5000个样本,每个样本都有标签。每张图片是28*28的灰度图像,所以说每个样本有28*28=784维的特征。数据集总的特征为55000*784,标签是一个10维的向量。

2.softmax pegression算法

工作原理:将判断为某类的特征相加,然后将这些特征转化为判定这是一类的的概率。 将特征写成如下公式:i代表第i类,j代表一张图片的第j个像素。b是数据本身的某些倾向,比如大部分数字都是0,那么0的倾向就大一点。 对所有特征计算softmax。简单来说就是对所有特征计算一个exp函数,然后再进行标准化(然输出概率值和为1)。 判定为i类的概率为 总结后,可以简写为

y=sofftmax(Wx+b)

3.损失函数cross-entropy

二 TensorFlow实现

1.导入库

from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)#下载数据 print(mnist.train.images.shape, mnist.train.labels.shape) print(mnist.test.images.shape, mnist.test.labels.shape) print(mnist.validation.images.shape, mnist.validation.labels.shape) import tensorflow as tf

2.初始化参数模型

sess = tf.InteractiveSession()#注册为默认的Session x = tf.placeholder(tf.float32, [None, 784])#定义输入数据的地方,第一个参数是参数类型,第二个参数是shape W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b)#matmul矩阵乘法 y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))#tf.reduce_mean对每个批次数据求均值 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) tf.global_variables_initializer().run()#初始化参数

3.开始训练

对模型准确率进行验证。tf.argmax(y_, 1)是预测数据中概率最大的,tf.argmax(y_, 1)样本真实数字类别。将correct_prediction输出的bool值,用tf.cast转化为float32,再求平均。在测试集上评估,并输出。 for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100)#每次取100个数据为一个批次 train_step.run({x: batch_xs, y_: batch_ys})#训练 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))

三 总结

需要注意的是使用Tensorflow时,我们定义的公式其实只是computation graph(计算图),在执行这些代码时计算还没有发生,只有调用run方法,并feed数据时计算才真正执行。

转载请注明原文地址: https://www.6miu.com/read-2629835.html

最新回复(0)