tensorflow实现手写数字识别

从torch入门的我,很排斥tensorflow, 不过最近不得不学了,不然我刚找的工作怕是要换人了。

ok,那让我们愉快的学习吧。

我们先来一个AI届的Hello World !! . 手写数字识别。然后遇到其中的问题我们再来一一解释,毕竟最快的学习方式还是项目!

本系列计划在我完成手写识别后直接找工作的领域尝试再现经典的推荐算法模型。完成复制,然后重新补充理论。

[En]

This series is planned to try to reproduce the classic recommendation algorithm model in the field where I am looking for a job directly after completing handwriting recognition. Complete the reproduction and then re-supplement the theory.

由于工业界对于tensorflow 1 系列的依赖太强,我们选用tensorflow 1.13.1 版本来进行。

  1. 环境准备

  2. tensorflow=1.13.1

  3. 数据准备

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

我们看一下这个 数据规模,以train为例:

mnist.train.images.shape

得到的结果为:

(55000, 784)

这个784实际上为24*24,就是每个图片的784个像素现在被拉成一行了。我们随便取一个数据,将其拉伸回24 × 24 24\times24 2 4 ×2 4,就可以看到整个图片了。

import pylab
im = mnist.train.images[1]
im = im.reshape(-1,28)
pylab.imshow(im)
pylab.show()

tensorflow实现手写数字识别

既然数据这么小,我们先试试线性回归吧。

[En]

Since the data is so small, let’s try linear regression first.

  1. 构建模型和初始化参数

线性模型没啥好说的:

y = X W T + b y = \bold{X}\bold{W^T} + b y =X W T +b

其中的参数只有W \bold{W}W和b b b。对于静态图为依托的tensorflow 1.x来说,我们需要先构建完成整个模型的传输体系,然后将其放在sess中,才能真正的开始运行。

现在,让我们构建模型和参数。

[En]

Now let’s build the model and parameters.

对于数据,我们需要首先指定它的大小,但没有真正的数据,所以我们可以在运行时提供它。指定尺寸的方法是使用占位符:

[En]

For data, we need to specify its size first, but there is no real data, so we can feed it in at run time. The way to specify dimensions is to use placeholders:


tf.reset_default_graph()
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
x.shape,y.shape

对于初始化参数来说,这个模型中的参数无非就是包含W和b,对于卷积来说,其参数无非就是卷积核和偏置。那个在后续中会讲解。

W = tf.Variable(tf.random_normal(([784,10])))
b = tf.Variable(tf.zeros([10]))
W,b

输出


pred = tf.nn.softmax(tf.matmul(x,W)+b)

  1. 定义训练过程

cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

training_epochs = 25
batch_size = 100
display_step = 1

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())

  for epoch in range(training_epochs):
    avg_cost = 0
    total_batch = int(mnist.train.num_examples/batch_size)
    for i in range(total_batch):
      batch_xs,batch_ys = mnist.train.next_batch(batch_size)
      _, c = sess.run([optimizer,cost],feed_dict={x:batch_xs,y:batch_ys})
      avg_cost += c/total_batch
    if (epoch + 1)%display_step == 0:
      print(f"Epoch:{epoch+1},cost={avg_cost:.9f}")
  print("fnished")

  correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
  print("Accuracy:",accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))

我们分析一下,其与torch的不同之处,

  1. tensor训练时必须要在sess之内,否则不会真实运行
  2. tensor取数据的时候是x.next_batch(batch_size)
  3. sess.run([优化器,损失函数],feed_dict={数据字典}) –> _,cost
  4. 评估方式,method = tf.xx(), method.eval({数据字典})

ok,最后的运行结果是这样的。

Epoch:1,cost=7.546023723
Epoch:2,cost=4.171652060
Epoch:3,cost=2.972595831
Epoch:4,cost=2.377042001
Epoch:5,cost=2.016216151
Epoch:6,cost=1.779922282
Epoch:7,cost=1.617819570
Epoch:8,cost=1.489061758
Epoch:9,cost=1.393508704
Epoch:10,cost=1.312454587
Epoch:11,cost=1.255874819
Epoch:12,cost=1.191187488
Epoch:13,cost=1.152227032
Epoch:14,cost=1.099380152
Epoch:15,cost=1.076827528
Epoch:16,cost=1.038087001
Epoch:17,cost=1.014115727
Epoch:18,cost=0.983060481
Epoch:19,cost=0.969432110
Epoch:20,cost=0.936379928
Epoch:21,cost=0.926966454
Epoch:22,cost=0.899857285
Epoch:23,cost=0.897358320
Epoch:24,cost=0.867424971
Epoch:25,cost=0.862724741
fnished
Accuracy: 0.8281

Original: https://blog.csdn.net/qq_34271349/article/details/123557862
Author: 古承风
Title: tensorflow实现手写数字识别

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/496689/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球