V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cralison
V2EX  ›  TensorFlow

学习笔记 TF024:TensorFlow 实现 Softmax Regression(回归)识别手写数字

  •  1
     
  •   cralison · 2017-07-08 12:46:22 +08:00 · 2922 次点击
    这是一个创建于 2476 天前的主题,其中的信息可能已经有所发展或是发生改变。

    TensorFlow 实现 Softmax Regression(回归)识别手写数字。MNIST(Mixed National Institute of Standards and Technology database),简单机器视觉数据集,28X28 像素手写数字,只有灰度值信息,空白部分为 0,笔迹根据颜色深浅取[0, 1], 784 维,丢弃二维空间信息,目标分 0~9 共 10 类。数据加载,data.read_data_sets, 55000 个样本,测试集 10000 样本,验证集 5000 样本。样本标注信息,label,10 维向量,10 种类 one-hot 编码。训练集训练模型,验证集检验效果,测试集评测模型(准确率、召回率、F1-score)。

    算法设计,Softmax Regression 训练手写数字识别分类模型,估算类别概率,取概率最大数字作模型输出结果。类特征相加,判定类概率。模型学习训练调整权值。softmax,各类特征计算 exp 函数,标准化(所有类别输出概率值为 1)。y = softmax(Wx+b)。

    NumPy 使用 C、fortran,调用 openblas、mkl 矩阵运算库。TensorFlow 密集复杂运算在 Python 外执行。定义计算图,运算操作不需要每次把运算完的数据传回 Python,全部在 Python 外面运行。

    import tensor flow as tf,载入 TensorFlow 库。less = tf.InteractiveSession(),创建 InteractiveSession,注册为默认 session。不同 session 的数据、运算,相互独立。x = tf.placeholder(tf.float32, [None,784]),创建 Placeholder 接收输入数据,第一参数数据类型,第二参数代表 tensor shape 数据尺寸。None 不限条数输入,每条输入为 784 维向量。

    tensor 存储数据,一旦使用掉就会消失。Variable 在模型训练迭代中持久化,长期存在,每轮迭代更新。Softmax Regression 模型的 Variable 对象 weights、biases 初始化为 0。模型训练自动学习合适值。复杂网络,初始化方法重要。w = tf.Variable(tf.zeros([784, 10])),784 特征维数,10 类。Label,one-hot 编码后 10 维向量。

    Softmax Regression 算法,y = tf.nn.softmax(tf.matmul(x, W) + b)。tf.nn 包含大量神经网络组件。tf.matmul,矩阵乘法函数。TensorFlow 将 forward、backward 内容自动实现,只要定义好 loss,训练自动求导梯度下降,完成 Softmax Regression 模型参数自动学习。

    定义 loss function 描述问题模型分类精度。Loss 越小,模型分类结果与真实值越小,越精确。模型初始参数全零,产生初始 loss。训练目标是减小 loss,找到全局最优或局部最优解。cross-entropy,分类问题常用 loss function。y 预测概率分布,y'真实概率分布(Label one-hot 编码),判断模型对真实概率分布预测准确度。cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))。定义 placeholder,输入真实 label。tf.reduce_sum 求和,tf.reduce_mean 每个 batch 数据结果求均值。

    定义优化算法,随机梯度下降 SGD(Stochastic Gradient Descent)。根据计算图自动求导,根据反向传播(Back Propagation)算法训练,每轮迭代更新参数减小 loss。提供封装优化器,每轮迭代 feed 数据,TensorFlow 在后台自动补充运算操作(Operation)实现反向传播和梯度下降。train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)。调用 tf.train.GradientDescentOptimizer,设置学习速度 0.5,设定优化目标 cross-entropy,得到训练操作 train_step。

    tf.global_variables_initializer().run()。TensorFlow 全局参数初始化器 tf.golbal_variables_initializer。

    batch_xs,batch_ys = mnist.train.next_batch(100)。训练操作 train_step。每次随机从训练集抽取 100 条样本构成 mini-batch,feed 给 placeholder,调用 train_step 训练样本。使用小部分样本训练,随机梯度下降,收敛速度更快。每次训练全部样本,计算量大,不容易跳出局部最优。

    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmzx(y_,1)),验证模型准确率。tf.argmax 从 tensor 寻找最大值序号,tf.argmax(y,1)求预测数字概率最大,tf.argmax(y_,1)找样本真实数字类别。tf.equal 判断预测数字类别是否正确,返回计算分类操作是否正确。

    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)),统计全部样本预测正确度。tf.cast 转化 correct_prediction 输出值类型。

    print(accuracy.eval({x: mnist.test.images,y_: mnist.test.labels}))。测试数据特征、Label 输入评测流程,计算模型测试集准确率。Softmax Regression MNIST 数据分类识别,测试集平均准确率 92%左右。

    TensorFlow 实现简单机器算法步骤: 1 、定义算法公式,神经网络 forward 计算。 2 、定义 loss,选定优化器,指定优化器优化 loss。 3 、迭代训练数据。 4 、测试集、验证集评测准确率。

    定义公式只是 Computation Graph,只有调用 run 方法,feed 数据,计算才执行。

    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
    sess = tf.InteractiveSession()
    x = tf.placeholder(tf.float32, [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(tf.float32, [None, 10])
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
    tf.global_variables_initializer().run()
    for i in range(1000):
        batch_xs, batch_ys = mnist.train.next_batch(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 实践》

    欢迎付费咨询(150 元每小时),我的微信:qingxingfengzi

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5233 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 09:16 · PVG 17:16 · LAX 02:16 · JFK 05:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.