tensorflow入门 数字手写体识别python实现

第一部分:训练模型

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

import tensorflow as tf

sess = tf.InteractiveSession()

x = tf.placeholder(tf.float32, shape=[None, 784])      # placeholder( dtype, shape=None, name=None )
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))        # tf.Variable(, name=, dtype=None, trainable=True)
b = tf.Variable(tf.zeros([10]))            # 创建一个值为initial-value的新变量
sess.run(tf.global_variables_initializer())

y = tf.matmul(x,W) + b        # tf.matmul()是专门矩阵或者tensor乘法

cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))   # tf.reduce_mean()对所有的元素求平均

train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)   # 梯度下降优化器,(0.1)学习率,最小化损失函数

for _ in range(5000):          #迭代 5000 次学习
  batch = mnist.train.next_batch(100)
  train_step.run(feed_dict={x: batch[0], y_: batch[1]})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))  #tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反正返回False

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))     # cast(x, dtype, name=None) 将x的数据格式转化成dtype

print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)   # 截断的正态分布噪声,标准差为0.1(给W制造一些随机噪声打破完全对称)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)    # 会使用到ReLU,增加一些小的正值(0.1)用来避免死亡节点
  return tf.Variable(initial)

def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1],
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值