tensorflow-2

checkpoint

现在的你能手撸复现线性回归网络。了解网络的创建,损失函数的设计、优化方法的选择、Session的创建、数据的Feed和Fetch。

接下来的部分,需要使用框架实现卷积神经网络,做更复杂的Mnist手写数字识别。

Outline

`知识扫盲

`继续上篇,细节了解

`今日份实战

`知识扫盲

进阶的使用,需要对卷积神经网络有一定了解,大家可以去了解一下,推荐

吴恩达的机器学习课程,简单了解机器学习的知识,起码要知道什么是线性回归和逻辑回归、什么是梯度下降优化算法

还是吴恩达的Unsupervised Feature Learning and Deep Learning,记得沉下心来慢慢看一下,还是挺有收获的

zouxy的深度学习博客,通俗易懂

看完理论部分,然后上手撸tensorflow的代码、看tensorflow的Doc即可掌握。这里稍微讲几句。

卷积神经网络

网络有很多,不同网络在数据前向传播的过程中有不同的操作而已,不要被专有名词唬住。卷积神经网络创新点在于卷积层和池化层。

直接看这两个层是如何实现的。

卷积层

卷积操作就是用卷积模板作为滑动窗和输入做卷积操作,卷积操作说白了,就是元素对应相乘然后求和,相当于是加权求和。

运算中涉及操作术语:padding、stride。释义可以看大牛做的动画。

vdumoulin/conv_arithmetic

池化层

池化这个词,中文其实没有释义的,直翻,pooling layer。一般采用max_pooling,mean_pooling,就是选择一定区域的最大值或者所有元素的平均值作为这个区域的代表。池化层用于缩减网络规模。

卷积层使得网络的参数大为减少,池化层缩小了网络,两者都是网络的训练和运行提高了很大的效率。

`细节了解

先说一句,学习一个复杂的框架,通常需要迭代式的学习。

Tensor

回答以下问题:什么是Tensor、如何创建、如何打印ta的值、计算

1、 It does not hold the values of that operation's output, but instead provides a means of computing those values in a TensorFlow tf.Session.

tensor和operation构成了dataflow

2、 Tensor更多是由Op作为返回值使用。用户常用的是创建常量Tensor -- tf.constant()

使用list or numpy的narray创建常量

q = tf.constant(1)

a = tf.constant([1,2,3])

b = tf.constant(np.array([2,2]))

如果需要创建定制的矩阵,使用numpy中的函数,rand、zeros等

3、 如何打印

因为我们在建立graph的时候,只建立tensor的结构形状信息,并没有执行数据的操作。所以直接打印tensor不会打印他的值,只有在session中,才能看到!可以看下面的代码

import tensorflow as tfimport numpy as np# 创建numpy数组numpyData = np.array([[1,2],[2,4],[3,5]])# 创建tensortfData = tf.constant(numpyDate)print tfData# Tensor("Const_4:0", shape=(3, 2), dtype=int64)# 不会显示值,即使这个tensor是一个常量sess = tf.InteractiveSession()tfData.eval()# print tfData.eval() 可以看到tensor返回的值sess.close()

4、张量之间的运算

张量、numpy的矩阵相互之间可以使用函数或者运算符进行运算

tf.add(a, b) 与 a + b二者的区别

在计算精度上,二者并没有差别。运算符重载的形式a+b,会在内部转换为,a.__add__(b),而a.__add__(b)会再一次地映射为tf.add

常见的math操作,tensorflow版本不同,函数名略有变化

https://www.tensorflow.org/api_guides/python/math_ops?hl=zh-cn#Matrix_Math_Functions

Session

InteractiveSession与Session

The only difference with a regular Session is that an InteractiveSession installs itself as the default session on construction. The methods tf.Tensor.eval and tf.Operation.run will use that session to run ops.

Tensor.eval()是执行这个tensor之前的所有操作。

`今日份实战

说真的,代码看懂了,自己写一遍测试一遍,会掌握更多的细节

下面实现了简单的线性回归模型

细节:

numpy和tensor之间的转化需要考虑类型

numpy行向量和矩阵相乘,需要使用 np.dot()

tf.matmul不能有向量参与,需要tf.reshape将向量转化为矩阵

Variable参与的模型,需要在创建会话之后,先run初始化的部分

run(train)就是迭代了一次训练过程,数据fetch还是使用run,并且可以获取多个值

# implement simplest linear regressionimporttensorflowastfimportnumpyasnp# define input and ground truthnumpyX=np.array(np.random.rand(2,100),dtype=np.float32)wTruth=np.array([2.00,3.50])bTruth=np.array([4.60])# operands could not be broadcast together with shapes (2,) (2,100)# truth = wTruth*numpyX+bTruthtruth=np.dot(wTruth,numpyX)+bTruth# define the structure of networkw=tf.Variable([0.01,0.02])b=tf.Variable(0.01)inputX=tf.constant(numpyX,dtype=tf.float32)# wrong  vector multiple with matrix# outputY = w*inputX+bw=tf.reshape(w,[1,2])outputY=tf.matmul(w,inputX)+b# loss# although sum and mean have the same purpose, but sum will be inf# loss = tf.reduce_sum(tf.square(outputY-truth))loss=tf.reduce_mean(tf.square(outputY-truth))train=tf.train.GradientDescentOptimizer(0.01).minimize(loss)sess=tf.InteractiveSession()init=tf.initialize_all_variables()sess.run(init)fori1inrange(10000):sess.run(train)ifi1%100==0:printsess.run([w,b,loss])sess.close()

下面实现了softmax回归模型识别手写数字,需要下载Mnist数据集

细节:

1、 关于下载数据集,使用github上提供的inputdata.py调用相关函数下载,还能随机生成自定义数目的batch。方法:下载,放在同一文件夹,import input_data,mnist = input_data.read_data_sets('data/', one_hot=True),之后 batch = mnist.train.next_batch(50) 获取batch

2、 注意类型转换

accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(output,1),tf.argmax(truth,1)),tf.float32))

3、运行训练优化参数,可以使用sess.run,也可以train.run,并feed相应的data

4、事实可以存在多个网络结构,在运行会话时,哪些网络结构被激活,关键要看run中声明要获取的Tensor是什么


# implement a simple network to recognize the hand-written number import tensorflow as tf import input_data # input and ground truth input = tf.placeholder(tf.float32, shape=[None, 784]) truth = tf.placeholder(tf.float32, shape=[None, 10]) # establish network w = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) output = tf.nn.softmax(tf.matmul(input, w)+b) # loss cross_entropy = -tf.reduce_sum(truth*tf.log(output)) # how to train train = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) # test to evaluate # accuracy = tf.reduce_mean(tf.equal(tf.argmax(output,1),tf.argmax(truth,1))) accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(output,1),tf.argmax(truth,1)),tf.float32)) mnist = input_data.read_data_sets('data/', one_hot=True) init = tf.initialize_all_variables() sess = tf.InteractiveSession() sess.run(init) for i1 in range(1000): # get input batches batch = mnist.train.next_batch(50) sess.run(train,feed_dict={input: batch[0], truth: batch[1]}) # train.run(feed_dict={input: batch[0], truth: batch[1]}) if i1%100 == 0: print sess.run(accuracy,feed_dict={input: batch[0], truth: batch[1]}) sess.close()


程序的部分输出

0.32

0.94

0.9

0.94

0.98

下一篇实战如何用卷积神经网络来做手写数字的识别,如何安装使用GPU版本的tensorflow

你可能感兴趣的:(tensorflow-2)