二、tensorflow新手入门之MNIST初级教程

一、准备工作

1、MNIST概念

  是一个识别手写数字图片的计算机视觉集,它包含各种手写数字图片和每张图片对应的标签

2、softmax回归

  softmax回归是logistic回归的一种,它是多元分类(包含二分类)。

  sotfmax回归可以把多分类任务多输出转换为各种类别的可能概率,把最大概率值对应的类别作为输入样本的输出类别预测

  sotfmax激活函数公式:

    z[l]=W[l]a[l]+b[l]

    g(z[l])=e(z[l])

  理解sotfmax:

  sotfmax的loss function:

    单个样本 L(ŷ ,y)=∑yjlogŷj, j=[1,...,x] y为标签值,ŷ为预测概率,x为输入特征数量

    样本集J(w[1],b[1],)=1/mL(ŷ (i),y(i)) 

  sotfmax梯度下降公式:  J/z[L]=dz[L]=ŷ y

3、softmax数据集分析

  训练样本:60000个(mnist.train),其中55000个用于训练,5000个用于验证

  测试样本:10000个(mnist.test)

  每一个MNIST数据单元包含两部分:图片(mnist.train.images)和标签(mnist.train.labels),每张图片包含28像素X28像素,用向量表示长度是28X28=784,因此图片(mnist.train.images)为[60000, 784]的张量,第一个维度用了索引图片,第二个维度用来索引每张图片的像素点,标签介于0-9的数字,向量化表示为[1,0,0,0,0,0,0,0,0],因此标签mnist.train.labels)为[60000, 10]的张量

二、实现回归模型

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)

# 输入特征占位
x = tf.placeholder('float', [None, 784])

# 权重和偏置值
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# 预测值
y = tf.nn.softmax(tf.matmul(x,W) + b)

# 标签占位
y_ = tf.placeholder('float', [None, 10])

# 计算损失函数
cross_entropy = -tf.reduce_sum(y_*tf.log(y))

# 梯度下降
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

# 初始化所有变量
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    
    # 开始训练模型
    for _ in range(1000):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        sess.run(train_step, feed_dict={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, 'float'))
    print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_:mnist.test.labels}))
原文地址:https://www.cnblogs.com/jp-mao/p/10400866.html