Tensorflow小样例-分类模型(识别mnist手写数字)

这个例子是用Tensorflow构建一个简单的两层神经网络,然后用于识别mnist手写数字:

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


# 导入mnist手写数字图像
mnist = input_data.read_data_sets('MNIST_data',one_hot=True)

# 增加网络层的函数
def add_layer(inputs, int_size,out_size,activation_function=None):

    # 神经元权重初值:从正态分布中输出随机值,shape为[int_size,out_size]
    Weights = tf.Variable(tf.random_normal([int_size,out_size]))
    # 偏差初值
    biases = tf.Variable(tf.zeros([1,out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    # 激活函数
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

# 计算准确度函数
def compute_accuracy(v_xs,v_ys):
    # Python中有局部变量和全局变量,当局部变量名字和全局变量名字重复时,局部变量会覆盖掉全局变量。
    # 如果要给全局变量在一个函数里赋值,必须使用global语句。global VarName的表达式会告诉Python,
    # VarName是一个全局变量,这样Python就不会在局部命名空间里寻找这个变量了。
    global prediction
    # 执行添加输出层命令
    y_pre = sess.run(prediction,feed_dict={xs:v_xs})
    # 由于是用于分类手写数字,所以输出层中10个神经元只有1个有值,在预测是否准备时,只需判断输出的向量中非零的元素的位置是否相等即可
    # tf.equal  : 判断两个tensor是否每个元素都相等。返回一个格式为bool的tensor
    # tf.argmax : 找到给定的张量tensor中在指定轴axis上的最大值的位置。
    correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
    # 求预测结果的平均值
    # cast(x, dtype, name=None):将x的数据格式转化成dtype
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    result = sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})
    return result

xs = tf.placeholder(tf.float32,[None, 784]) # 28*28
ys = tf.placeholder(tf.float32,[None, 10])

# 添加隐藏层,输入值是 xs,在隐藏层有 10 个神经元
prediction = add_layer(xs,784,10,activation_function=tf.nn.softmax)

# 损失函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))

# 定义优化器,目的是的损失函数尽可能小
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# 构建对话
sess = tf.Session()

# 对所有变量进行初始化
sess.run(tf.initialize_all_variables())

for i in range(1000):
    # 按批次训练,每批100行数据
    batch_xs,batch_ys = mnist.train.next_batch(100)
    # 开始训练
    sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
    # 每50次输出一次准确度
    if i % 50 == 0:
        print(compute_accuracy(mnist.test.images,mnist.test.labels))

结果如下:

这里写图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值