手写数字识别 ----Softmax回归模型官方案例注释(基于Tensorflow,Python)

# 手写数字识别  ----Softmax回归模型
# regression
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets("/tmp/data/", one_hot=True)  # 获取数据 mnist是一个轻量级的类,其中以Numpy数组的形式中存储着训练集、验证集、测试集。


# 一个对手写数字进行识别的模型。
# 思路:
# 1、将训练集中获取的手写数字图像进行某一统一方式(全部按行或全部按列)的展开,
# 得到一个长向量(这是为了利用softmax做一维的回归,不过损失了二维信息),
# 用一个二维张量来索引某一个样本中的某一像素。
# 2、softmax模型:用来给不同的对象分配概率(即使在更精细的模型中,最后一步,往往也需要用softmax来分配概率)
# 两步:
# ① 加权求和,并引入偏置
# 对于给定输入图片x,其代表图像为数字i的证据为
# evidencei =∑i(wi, jxj) + bi
# evidence_i =∑_i(w_{i, j}x_j)+b_ievidencei=∑i​(wi, jxj) + bi
# ② 用softmax函数将evidence转换成概率,即
# y = softmax(evidence)
# y = softmax(evidence)
# y = softmax(evidence)
# 将输入值当成幂指数求值,再正则化这些结果
# 更紧凑的写法为
# y = softmax(Wx + b)
# y = softmax(Wx + b)
# y = softmax(Wx + b)
# 3、为了节省在python外使用别的语言进行复杂矩阵运算带来的开销,TensorFlow做出的优化为,先用图描述一系列可交互的操作,最后统一放在python外执行。
# 用占位符placeholder来描述这些可交互的单元:
# ---------------------
# 作者:Crystal 
# 来源:CSDN
# 原文:https: // blog.csdn.net / weixin_43226400 / article / details / 82749769
# 版权声明:本文为博主原创文章,转载请附上博文链接!


#http://www.cnblogs.com/rgvb178/p/6052541.html 相关说明
# Softmax Regression Model        Softmax回归模型
def regression(x):
    W = tf.Variable(tf.zeros([784, 10]), name="W")
    b = tf.Variable(tf.zeros([10]), name="b")
    y = tf.nn.softmax(tf.matmul(x, W) + b)
    # print(y)
    return y, [W, b]


# model 声明占位符
with tf.variable_scope("regression"):
    x = tf.placeholder(tf.float32, [None, 784])
    y, variables = regression(x)

# 用交叉熵(cross - entropy)来评判模型的好坏,其表达式为
# Hy′(y) =−∑iy′ilog(yi)
# 其中y是预测的概率分布,y’是实际的概率分布(即训练集对应的真实标签,是一个one - hotvector)定义


# train  开始训练模型
y_ = tf.placeholder("float", [None, 10])
# 计算交叉熵
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
# tensorflow可以自动利用反向传播算法,根据选择的优化器来最小化你的目标函数
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# tf.argmax给出对象在某一维度上最大值所对应的索引值,可以用来判断预测是否准确,即
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# equal函数返回布尔值,用cast函数转化为浮点数后求均值来计算正确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

saver = tf.train.Saver(variables)
with tf.Session() as sess:
    # 初始化操作
    sess.run(tf.global_variables_initializer())
    for _ in range(10000):
        batch_xs, batch_ys = data.train.next_batch(100)
        # 此为随机梯度下降训练,每次训练随机抓取训练集中的100个数据作为一个batch
        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

    # 计算学习到的模型在训练集上的准确率
    print(sess.run(accuracy, feed_dict={x: data.test.images, y_: data.test.labels}))

    # 保存训练结果
    # print(os.path.join(os.path.dirname(__file__), 'data', 'regression.ckpt'))
    # //绝对路径包含中文字符可能导致路径不可用  相对路径:'mnist/data/regression.ckpt'
    path = saver.save(
        sess, 'mnist/data/regression.ckpt',
        write_meta_graph=False, write_state=False)
    print("Saved:", path)

    # path = saver.save(
    #     sess, os.path.join(os.path.dirname(__file__), 'mnist\data', 'regression.ckpt'),write_meta_graph=False, write_state=False)
    # print("Saved:", path)        write_meta_graph=False, write_state=False)
    print("Saved:", path)

    # path = saver.save(
    #     sess, os.path.join(os.path.dirname(__file__), 'mnist\data', 'regression.ckpt'),write_meta_graph=False, write_state=False)
    # print("Saved:", path)

 

转载于:https://www.cnblogs.com/motao9527/p/10190794.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于TensorFlow实现Mnist手写数字识别的详细步骤,包括可视化界面和中文注释。 1. 导入必要的包 ```python import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt import numpy as np ``` 2. 加载数据集 ```python mnist = input_data.read_data_sets('MNIST_data', one_hot=True) ``` 3. 定义占位符 ```python x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) ``` 4. 初始化权重和偏置 ```python def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) ``` 5. 定义卷积和池化操作 ```python def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') ``` 6. 构建卷积神经网络模型 ```python x_image = tf.reshape(x, [-1,28,28,1]) W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 ``` 7. 定义损失函数和优化器 ```python cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) ``` 8. 定义评估准确率的操作 ```python correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) ``` 9. 运行训练过程 ```python sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) for i in range(20000): batch = mnist.train.next_batch(50) if i % 100 == 0: train_accuracy = accuracy.eval(feed_dict={ x: batch[0], y: batch[1], keep_prob: 1.0}) print('step %d, training accuracy %g' % (i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y: batch[1], keep_prob: 0.5}) print('test accuracy %g' % accuracy.eval(feed_dict={ x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0})) ``` 10. 可视化卷积层的输出结果 ```python def plot_conv_layer(layer, image): feed_dict = {x: [image], keep_prob: 1.0} values = sess.run(layer, feed_dict=feed_dict) num_filters = values.shape[3] fig, axes = plt.subplots(1, num_filters) for i, ax in enumerate(axes.flat): img = values[0, :, :, i] ax.imshow(img, interpolation='nearest', cmap='binary') ax.set_xticks([]) ax.set_yticks([]) plt.show() image = mnist.test.images[0] plot_conv_layer(h_conv1, image) ``` 以上就是基于TensorFlow实现Mnist手写数字识别的详细步骤,包括可视化界面和中文注释

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值