基于python-tensorflow的机器视觉学习手札 (3.1)tensorflow基础篇-mnist处理

穿插着总结一点点tensorflow的东西吧!
我是在极客学院网站上,跟着官方文档自学的,学的很慢。
关于深度学习、人工智能方面的入门,推荐
本段摘于极客学院的TensorFlow 官方文档中文版,算是tensorflow的来源:

2015年11月9日,Google发布人工智能系统TensorFlow并宣布开源,同日,极客学院组织在线TensorFlow中文文档翻译。
机器学习作为人工智能的一种类型,可以让软件根据大量的数据来对未来的情况进行阐述或预判。如今,领先的科技巨头无不在机器学习下予以极大投入。Facebook、苹果、微软,甚至国内的百度。Google 自然也在其中。「TensorFlow」是 Google 多年以来内部的机器学习系统。如今,Google 正在将此系统成为开源系统,并将此系统的参数公布给业界工程师、学者和拥有大量编程能力的技术人员,这意味着什么呢?
打个不太恰当的比喻,如今 Google 对待 TensorFlow 系统,有点类似于该公司对待旗下移动操作系统 Android。如果更多的数据科学家开始使用 Google 的系统来从事机器学习方面的研究,那么这将有利于 Google 对日益发展的机器学习行业拥有更多的主导权。
为了让国内的技术人员在最短的时间内迅速掌握这一世界领先的 AI 系统,极客学院 Wiki 团队发起对 TensorFlow 官方文档的中文协同翻译,一周之内,全部翻译认领完成,一个月后,全部30章节翻译校对完成,上线极客学院Wiki平台并提供下载。
Google TensorFlow项目负责人Jeff Dean为该中文翻译项目回信称:”看到能够将TensorFlow翻译成中文我非常激动,我们将TensorFlow开源的主要原因之一是为了让全世界的人们能够从机器学习与人工智能中获益,类似这样的协作翻译能够让更多的人更容易地接触到TensorFlow项目,很期待接下来该项目在全球范围内的应用!”

一般用tensorflow做的第一个机器视觉程序,所用的库都是mnist。mnist是一个入门级的计算机视觉数据集,它包含各种手写数字图片。
用这句语句来导入:

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

导完会出现一个文件夹mnist_data,内有4个文件。有时候可能因为超时下载不了,可以自己下载好放进文件夹里。
然后就可以开始写第一个了!
当然写之前可以看一下极客学院的初学者手册,内有对mnist数据集、softmax回归的较详细介绍:
http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_beginners.html
先给出最基础的,梯度下降随机跑1000个数据,无视过拟合啥啥的,直接运行的代码:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

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

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("float", [None,10])#占位
cross_entropy = -tf.reduce_sum(y_*tf.log(y))#交叉熵

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#梯度下降算法,最小化交叉熵
init = tf.initialize_all_variables()#初始化
sess = tf.Session()
sess.run(init)#直接跑起来
for i in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})#跑1000次

#评估模型
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print (sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

每一步其实那个网站上都有说明,我只是搬运过来,造个轮子自己跑一下,每一步确认一下,学习到一点基础的东西,欢迎每个人来与我讨论!
这里说的是最简单的tensorflow初步用法,其实深度学习实际上是多层的卷积网络。
这里同样加上极客学院的源码作为例子(主要是都差不多,关键是分析每句语句的原因和使用):

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

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

sess = tf.InteractiveSession()

x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
sess.run(tf.initialize_all_variables())
y = tf.nn.softmax(tf.matmul(x,W) + b)

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)

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')
#第一层:卷积+池化,1输入32输出
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
#第二层卷积+池化,32输入64输出
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)
#dropout 防止过拟合
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#输出 softmax
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
#评估
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
sess.run(tf.initialize_all_variables())
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}))

如果对卷积,池化等有初步的了解,其实看清楚这些是不难的。整个系统就是从28*28的图片中,通过patch来得到n个特征值,n是由卷积核的参数得到的。池化一次后变为14*14,再进入第二层,从32个特征值与14*14的图像中得到64个特征值。再池化一次变为7*7,直接进入一个1024的密集连接层,用于处理整个图片。我们把输出的张量reshape成向量,然后使用ReLU。值得注意的是,为了防止ReLU神经元die掉,我们初始化偏置的时候,会加上一个较小的常量。
然后加入dropout层,这个可能会单独列一篇详细总结,现在简要提出以下。dropout作用就是隐藏掉一部分神经元,一方面可以减少复杂度,一方面可以防止过拟合的产生。
最后还是用添加softmax来做拟合。
后面就是20000次训练,每次训练随机抓取50个,每100次输出一次正确率的日志。
值得注意的是,20000*50远远超出了训练集的大小,不过卷积神经网络,是可以取重复样品的,这才是卷积神经网络的核心,为了增加不同样品之间的关联。
搬运为主,感谢极客学院,再次给出链接:http://wiki.jikexueyuan.com/project/tensorflow-zh/
这里十分详细!初学者一定要去看啊!
溜了溜了

猜你喜欢

转载自blog.csdn.net/dimei0938/article/details/81636197
今日推荐