详解卷积神经网络CNN学习笔记

微信公众号:小白图像与视觉

关于技术、关注yysilence00。有问题或建议,请公众号留言。


主题:详解卷积神经网络CNN学习笔记

平台:使用谷歌深度学习平台Colab

版本:tensorflow-gpu = 1.15

#TensorFlow versions in Colab

##Background
Colab has two versions of TensorFlow pre-installed: a 2.x version and a 1.x version. Colab uses TensorFlow 2.x by default, though you can switch to 1.x by the method shown below.

##Specifying the TensorFlow version

Running import tensorflow will import the default version (currently 2.x). You can use 1.x by running a cell with the tensorflow_version magic before you run import tensorflow.

一:tensor基本操作

%tensorflow_version 1.x
TensorFlow 1.x selected.

Once you have specified a version via this magic, you can run import tensorflow as normal and verify which version was imported as follows:

import tensorflow as tf
import numpy


def f():
  x = tf.constant([[1., 2., 3.],[4., 5., 6.]], dtype=tf.float32)
  x = tf.reshape(x, [1, 2, 3, 1])
  valid_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
  same_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')

  print(valid_pad.get_shape())
  print(same_pad.get_shape())
  init = tf.global_variables_initializer()
  sess = tf.Session()
  sess.run(init)
  print(sess.run(x))
  rank_0_tensor = tf.constant(4)
  print(rank_0_tensor)
  rank_0_tensor = tf.constant(4)
  print(rank_0_tensor)  
    
if __name__ == "__main__":
  f()


def f1():
  # This will be an int32 tensor by default; see "dtypes" below.
  rank_0_tensor = tf.constant(4)
  print(rank_0_tensor)

  # Let's make this a float tensor.
  rank_1_tensor = tf.constant([2.0, 3.0, 4.0])
  print(rank_1_tensor)

  # If we want to be specific, we can set the dtype (see below) at creation time
  rank_2_tensor = tf.constant([[1, 2],
                  [3, 4],
                  [5, 6]], dtype=tf.float16)
  print(rank_2_tensor)


  # There can be an arbitrary number of
  # axes (sometimes called "dimensions")
  # There can be an arbitrary number of
  # axes (sometimes called "dimensions")
  rank_3_tensor = tf.constant([
    [[0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9]],
    [[10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19]],
    [[20, 21, 22, 23, 24],
    [25, 26, 27, 28, 29]],])
                      
  print(rank_3_tensor)

  a=tf.constant([[1, 2],
            [3, 4]])
  b=tf.constant([[1, 1],
            [1, 1]]) # Could have also said `tf.ones([2,2])`

print(tf.add(a, b), "\n")
print(tf.multiply(a, b), "\n")
print(tf.matmul(a, b), "\n")
with tf.Session() as sess:
  sess = sess.run(rank_2_tensor)
  print("sess:", sess)
  an_array=rank_2_tensor.eval()
  print("an_array:", an_array)

  an_array_2=np.array(sess)
  print("an_array_2:", an_array_2)
  

if __name__ == "__main__":
  f1()
import tensorflow as tf
W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)
import tensorflow as tf

two_node = tf.constant(2)
another_two_node = tf.constant(2)
two_node = tf.constant(2)
tf.constant(3)
print(two_node)

two_node = tf.constant(2)
another_pointer_at_two_node = two_node
two_node = None
print(two_node)
print(another_pointer_at_two_node)
two_node = tf.constant(2., dtype=tf.float32)
three_node = tf.constant(3., dtype=tf.float32)
#creat compute graph
sum_node = tf.add(two_node,three_node)
print(sum_node)#计算图只包含计算步骤;不包含结果。至少……现在还没有
#run graph seesion
sess = tf.Session() #会话包含一个指向全局图的指针对象
print(sess.run([two_node, three_node, sum_node])) #可以一次性运行多个节点

占位符placeholder 和 feed_dict and fetch

创建变量用于接受输入,以某种方式(+ - * / 矩阵运算等)作为创建的计算图

其中,占位符可以有效的接受外部输入

x_input = tf.placeholder(shape=[3,3], dtype=tf.float32)
#sess = tf.Session()
with tf.Session() as sess:
  print(sess.run(x_input, feed_dict={x_input: [[1,2,3], [4,5,9], [7,8,9]] }))
def ops_demo():
    a = tf.constant([[1, 2, 3], [4, 5, 6]])
    b = tf.constant(4)
    c = tf.Variable(tf.random_normal([2,3], 1.0,3.0), dtype=tf.float32)
    d = tf.add(c, tf.cast(tf.divide(a, b), dtype=tf.float32))

    m1 = tf.Variable(tf.random_normal([3, 3], 1.0, 3), dtype=tf.float32)
    m2 = tf.Variable(tf.random_normal([3, 3], 3.0, 1), dtype=tf.float32)
    m3 = tf.add(m1, m2)
    m4 = tf.subtract(m1, m2)
    m5 = tf.divide(m1, m2)
    m6 = tf.multiply(m1, m2)

    mm = tf.matmul(m1, m2)

    x = tf.placeholder(shape=[3,3], dtype=tf.float32)
    y = tf.placeholder(shape=[3,2], dtype=tf.float32)

    xy = tf.matmul(x, y)

    init = tf.global_variables_initializer()
    sess = tf.Session()
    sess.run(init)
    xy_result = sess.run(xy, feed_dict={x: [[1,1,1], [2,2,2],[3,3,3]], y:[[4,4],[5,5],[6,6]]})
    print(xy_result)
if __name__ == "__main__":
  ops_demo()

If you want to switch TensorFlow versions after import, you will need to restart your runtime with ‘Runtime’ -> ‘Restart runtime…’ and then specify the version before you import it again.

import tensorflow as tf

### build the graph
## first set up the parameters
m = tf.get_variable("m", [], initializer=tf.constant_initializer(0.))
b = tf.get_variable("b", [], initializer=tf.constant_initializer(0.))
init = tf.global_variables_initializer()

## then set up the computations
input_placeholder = tf.placeholder(tf.float32)
output_placeholder = tf.placeholder(tf.float32)

x = input_placeholder
y = output_placeholder
y_guess = m * x + b

loss = tf.square(y - y_guess)

## finally, set up the optimizer and minimization node
optimizer = tf.train.GradientDescentOptimizer(1e-3)
train_op = optimizer.minimize(loss)

### start the session
sess = tf.Session()
sess.run(init)

### perform the training loop
import random

## set up problem
true_m = random.random()
true_b = random.random()

for update_i in range(100000):
  ## (1) get the input and output
  input_data = random.random()
  output_data = true_m * input_data + true_b

  ## (2), (3), and (4) all take place within a single call to sess.run()!
  _loss, _ = sess.run([loss, train_op], feed_dict={input_placeholder: input_data, output_placeholder: output_data})
  print(update_i, _loss) 

### finally, print out the values we learned for our two variables
print("True parameters:     m=%.4f, b=%.4f" % (true_m, true_b))
print("Learned parameters:  m=%.4f, b=%.4f" % tuple(sess.run([m, b])))


0 2.3205383
1 0.5792742
2 1.55254
3 1.5733259
4 0.6435648
5 2.4061265
6 1.0746256
7 2.1998715
8 1.6775116
9 1.6462423
10 2.441034
...
99990 2.9878322e-12
99991 5.158629e-11
99992 4.53646e-11
99993 9.422685e-12
99994 3.991829e-11
99995 1.134115e-11
99996 4.9467985e-11
99997 1.3219648e-11
99998 5.684342e-14
99999 3.007017e-11
True parameters:     m=0.3519, b=0.3242
Learned parameters:  m=0.3519, b=0.3242

###二、编码实现

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jtGenyEl-1591758687698)(https://img-1256179949.cos.ap-shanghai.myqcloud.com/18-10-9-24953964.jpg)]

定义 weight、bias;

卷积、激活、池化、下一层;

然后接 2 个全连接层,softmax,交叉熵、loss

(代码对应:6-1卷积神经网络应用于MNIST数据集分类.py,有修改——增加很多命名空间 scope)


import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 每个批次的大小
batch_size = 100
# 计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
# 初始化权值
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):
    # x input tensor of shape '[batch,in_height,in_width,in_channles]'
    # W filter / kernel tensor of shape [filter_height,filter_width,in_channels,out_channels]
    # `strides[0] = strides[3] = 1`. strides[1]代表x方向的步长,strides[2]代表y方向的步长
    # padding: A `string` from: `"SAME", "VALID"`
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')  # 2d的意思是二维的卷积操作
# 池化层
def max_pool_2x2(x):
    # ksize [1,x,y,1]
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 定义两个placeholder
x = tf.placeholder(tf.float32, [None, 784])  # 28*28
y = tf.placeholder(tf.float32, [None, 10])
# 改变x的格式转为4D的向量[batch, in_height, in_width, in_channels]`
x_image = tf.reshape(x, [-1, 28, 28, 1])
# 初始化第一个卷积层的权值和偏置
W_conv1 = weight_variable([5, 5, 1, 32])  # 5*5的采样窗口,32个卷积核从1个平面抽取特征
b_conv1 = bias_variable([32])  # 每一个卷积核一个偏置值
# 把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)  # 进行max-pooling
# 初始化第二个卷积层的权值和偏置
W_conv2 = weight_variable([5, 5, 32, 64])  # 5*5的采样窗口,64个卷积核从32个平面抽取特征
b_conv2 = bias_variable([64])  # 每一个卷积核一个偏置值
# 把h_pool1和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)  # 进行max-pooling
# 28*28的图片第一次卷积后还是28*28(数组变小了,但是图像大小不变),第一次池化后变为14*14
# 第二次卷积后为14*14(卷积不会改变平面的大小),第二次池化后变为了7*7
# 进过上面操作后得到64张7*7的平面
# 初始化第一个全连接层的权值
W_fc1 = weight_variable([7 * 7 * 64, 1024])  # 上一层有7*7*64个神经元,全连接层有1024个神经元
b_fc1 = bias_variable([1024])  # 1024个节点
# 把池化层2的输出扁平化为1维
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)
# keep_prob用来表示神经元的输出概率
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 初始化第二个全连接层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
# 计算输出
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# 交叉熵代价函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
# 使用AdamOptimizer进行优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# 结果存放在一个布尔列表中
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))  # argmax返回一维张量中最大的值所在的位置
# 求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.7})
        acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0})
        print("Iter " + str(epoch) + ", Testing Accuracy= " + str(acc))

Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
Iter 0, Testing Accuracy= 0.8637
Iter 1, Testing Accuracy= 0.9654
Iter 2, Testing Accuracy= 0.9733
Iter 3, Testing Accuracy= 0.9783
Iter 4, Testing Accuracy= 0.9829
Iter 5, Testing Accuracy= 0.9832
Iter 6, Testing Accuracy= 0.9847
Iter 7, Testing Accuracy= 0.9873
Iter 8, Testing Accuracy= 0.9867
Iter 9, Testing Accuracy= 0.988
Iter 10, Testing Accuracy= 0.9901
Iter 11, Testing Accuracy= 0.9908
Iter 12, Testing Accuracy= 0.989
Iter 13, Testing Accuracy= 0.991
Iter 14, Testing Accuracy= 0.9903
Iter 15, Testing Accuracy= 0.9911
Iter 16, Testing Accuracy= 0.9909
Iter 17, Testing Accuracy= 0.9916
Iter 18, Testing Accuracy= 0.9913
Iter 19, Testing Accuracy= 0.9901
Iter 20, Testing Accuracy= 0.991

使用传统的神经网络我们可能只能达到 98% 点多的准确率,可以看到,使用卷积神经网络之后,我们可以达到 99% 的准确率,虽说差了百分之一,但是接近 100%,应该说算是比较大的提升。

补充内容:关于TensorFlow中的CNN卷积和池化的API详解

(1)卷积

TensorFlow 中的卷积一般是通过tf.nn.conv2d()函数实现的具体可以查看官网:https://www.tensorflow.org/api_docs/python/tf/nn/conv2d

如:tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

# tf.nn.conv2d非常方便实现卷积层前向传播算法
# 第一个输入为当前层的节点矩阵,这个矩阵为四维矩阵,第一维对应一个输入batch,后三维为节点矩阵
# 例如,input[0,:,:,:]表示第一张图片,input[1,:,:,:]为第二张图片
# 第二个输入为卷积层的权重,第三个输入为不同维度上的步长
# 第三个输入提供的是一个长度为4的数组,但是数组第一位和第四位一定要是1,因为卷积层的步长只对矩阵的长和宽有效
# 第四个输入时填充的方法,TensorFlow只提供两种选择,SAME为全0填充,VALID为不添加

定义如下:


def conv2d(input, 
           filter, 
           strides,
           padding, 
           use_cudnn_on_gpu=None,
           data_format=None, 
           name=None)

其中参数分别为:

  • 第一个参数为当前层的矩阵,在卷积神经网络中它是一个四维的矩阵,即 [batch, image.size.height, image.size.width, depth]
  • 第二个参数为卷积核(滤波器),由 tf.get_variable 函数创建得到;
  • 第三个参数为不同维度上的步长,其实对应的是第一个参数,虽然它也是四维的,但是第一维和第四维的数一定为 1,因为我们不能间隔的选择 batch 和 depth;
  • 第四个参数为边界填充方法。

补充,strides:第 1,第 4 参数都为 1,中间两个参数为卷积步幅,如:[1, 1, 1, 1][1, 2, 2, 1]

  1. 使用 VALID 方式,feature map 的尺寸为 (3,3,1,32) 卷积权重

    out_height=ceil(float(in_height-filter_height+1)/float(strides[1])) (28-3+1)/1= 26,(28-3+1)/2=13
    
    out_width=ceil(float(in_width-filter_width+1)/float(strides[2])) (28-3+1)/1 = 26,(28-3+1)/2=13
    
    
  2. 使用 SAME 方式,feature map 的尺寸为 (3,3,1,32)卷积权重

    out_height= ceil(float(in_height)/float(strides[1]))  28/1=28,28/2=14
    
    out_width = ceil(float(in_width)/float(strides[2]))   28/1=28,28/2=14
    

    其中:ceil 表示为向上取整。

(2)池化

TensorFlow 中的池化有几种方式,举个例子,通过 tf.nn.max_pool 函数实现的具体可以查看官网:https://www.tensorflow.org/api_docs/python/tf/nn/max_pool

如:tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

# tf.nn.max_pool函数实现了平均池化层,用法与avg_pool相似
# tf.nn.max_pool实现了最大池化层的前向传播过程,参数和conv2d类似
# ksize提供了过滤器的尺寸,数组第一位和第四位一定要是1,比较常用的是[1,2,2,1]和[1,3,3,1]
# strides提供了步长,数组第一位和第四位一定要是1
# padding提供了是否全0填充

定义如下:

def max_pool(value, 
             ksize, 
             strides, 
             padding, 
             data_format="NHWC", 
             name=None)

其中的参数:

  • 第一个参数 value:需要池化的输入,一般池化层接在卷积层后面,所以输入通常是 feature map,依然是[batch, height, width, channels] 这样的 shape
  • 第二个参数 ksize:池化窗口的大小,取一个四维向量,一般是 [1, height, width, 1],因为我们不想在 batch 和 channels 上做池化,所以这两个维度设为了 1
  • 第三个参数 strides:和卷积类似,窗口在每一个维度上滑动的步长,一般也是 [1, stride,stride, 1]
  • 第四个参数 padding:和卷积类似,可以取 ‘VALID’ 或者 ‘SAME’

补充,

  • ksize:第 1,第 4 参数都为 1,中间两个参数为池化窗口的大小,如:[1,1,1,1][1,2,2,1]

    实验证明:对于实际的池化后的数据尺寸,ksize没有影响,只是计算的范围不同。

  • strides:第 1,第 4 参数都为 1,中间两个参数为池化窗口的步幅,如:[1,1,1,1][1,2,2,1]

    实验证明:对于实际的池化后的数据尺寸,strides 产生影响,具体的计算方式和卷积中的 strides 相同。

padding 总结

**关于 TensorFlow 中两种 padding 方式“SAME” 和 “VALID” 的到底怎么理解,**先阅读下这两篇文章:

个人总结:

  • 在 TensorFlow 中,对于 “VALID” 方式的 padding,按照指定步伐滑动的过程中,一个完整的卷积核覆盖不到余下窗口覆盖,则丢弃。计算方式,官方定义:

    The TensorFlow Convolution example gives an overview about the difference between SAME and VALID :
    
        For the SAME padding, the output height and width are computed as:
    
        out_height = ceil(float(in_height) / float(strides[1]))
    
        out_width = ceil(float(in_width) / float(strides[2]))
    
    And
    
        For the VALID padding, the output height and width are computed as:
    
        out_height = ceil(float(in_height - filter_height + 1) / float(strides1))
    
        out_width = ceil(float(in_width - filter_width + 1) / float(strides[2]))
    

    根据文章[1]中讲到的,对于VALID输出的形状可以这样计算:(「 为向上取整。)

  • 在 TensorFlow 中,对于 “SAME” 方式的 padding,按照指定步伐滑动的过程中,一个完整的卷积核覆盖不到余下窗口覆盖,则补充 0 使得能覆盖到。计算方式,官方定义在上面。根据文章[1]中讲到的,对于SAME输出的形状可以这样计算:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yp3Cj9CE-1591758687715)(https://img-1256179949.cos.ap-shanghai.myqcloud.com/20181229201052.png)]

!!!注:使用代码亲自实践得出的结果,和使用上面公式计算结果是一致的。 所以计算卷积后得到的尺寸按照公式计算即可。

#keras 代码
from keras.layers import Input, Conv2D
def Test():
    input = Input([513, 513, 3])
    con1 = Conv2D(32, (5, 5), strides=(2, 2), activation="relu", padding="same")(input)
    con2 = Conv2D()(con1)
    
if __name__ == '__main__':
    Test()
    
# debug 可以看到,conv1 大小为 257x257,即 513/2 向上取整。

对于 “SAME” 方式的 padding,我要补充说明的是,也是我的理解:在 TensorFlow 的实现中,比如左右 padding 多少圈 0 不一定是对称的,可能是只有右边 padding 了 0,可能左右都 padding 了 0,但数量不对称。

可以看下文章[2]中例子:Input width=13,Filter width=6,Stride=5,不同的 padding 方式如下图:

其中可以看到 “SAME” 方式,在左侧 padding 了一列 0,在右侧 padding 了两列 0。

个人理解:就是说采用 ”SAME“ 方式,在滑动过程中余下窗口元素不够的情况下,一定会 padding 一定数量的 0 以至能覆盖到余下窗口元素。

TensorFlow中CNN的两种padding方式“SAME”和“VALID”

让我们来看看变量 x 是一个 2×3 的矩阵,max pooling 窗口为2×2,两个维度的步长 strides=2。

第一次由于窗口可以覆盖,橙色区域做 max pooling,没什么问题,如下:

接下来就是SAME和VALID的区别所在:由于步长为 2,当向右滑动两步之后,VALID方式发现余下的窗口不到 2×2 所以直接将第三列舍弃,而 SAME 方式并不会把多出的一列丢弃,但是只有一列了不够 2×2 怎么办?填充!

如上图所示,SAME 会增加第四列以保证可以达到 2×2,但为了不影响原始信息,一般以 0 来填充。这就不难理解不同的 padding 方式输出的形状会有所不同了。

当 CNN 用于文本中时,一般卷积层设置卷积核的大小为 n×k,其中k为输入向量的维度(即[n,k,input_channel_num,output_channel_num]),这时候我们就需要选择“VALID”填充方式,这时候窗口仅仅是沿着一个维度扫描而不是两个维度。可以理解为统计语言模型当中的 N-gram。


完成卷积神经网络,记录下准确率和 loss 率的变化,完整代码如下:

# coding: utf-8
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 每个批次的大小
batch_size = 100
# 计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
# 参数概要
def variable_summaries(var):
    with tf.name_scope('summaries'):
        mean = tf.reduce_mean(var)
        tf.summary.scalar('mean', mean)  # 平均值
        with tf.name_scope('stddev'):
            stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
        tf.summary.scalar('stddev', stddev)  # 标准差
        tf.summary.scalar('max', tf.reduce_max(var))  # 最大值
        tf.summary.scalar('min', tf.reduce_min(var))  # 最小值
        tf.summary.histogram('histogram', var)  # 直方图
补充内容:TensorFlow中Summary的用法

关于这里的 Summary 用法在此顺带补充些内容,方便查阅。参考【Tensorflow学习笔记——Summary用法

tf.summary() 的各类方法,能够保存训练过程以及参数分布图并在tensorboard显示。tf.summary 有诸多函数:

  1. tf.summary.scalar

    用来显示标量信息,其格式为:tf.summary.scalar(tags, values, collections=None, name=None)

    例如:tf.summary.scalar('mean', mean),一般在画 loss,accuary 时会用到这个函数。

  2. tf.summary.histogram

    用来显示直方图信息,其格式为:tf.summary.histogram(tags, values, collections=None, name=None)

    例如:tf.summary.histogram('histogram', var),一般用来显示训练过程中变量的分布情况

  3. tf.summary.distribution

  4. tf.summary.text

  5. tf.summary.image

  6. tf.summary.audio

  7. tf.summary.merge_all

    merge_all 可以将所有 summary 全部保存到磁盘,以便 tensorboard 显示。如果没有特殊要求,一般用这一句就可一显示训练时的各种信息了。格式:tf.summaries.merge_all(key='summaries')

  8. tf.summary.FileWriter

    指定一个文件用来保存图。格式:tf.summary.FileWritter(path,sess.graph),可以调用其add_summary()方法将训练过程数据保存在 filewriter 指定的文件中

  9. tf.summary.merge

    格式:tf.summary.merge(inputs, collections=None, name=None),一般选择要保存的信息还需要用到tf.get_collection()函数

# 初始化权值
def weight_variable(shape, name):
    initial = tf.truncated_normal(shape, stddev=0.1)  # 生成一个截断的正态分布
    return tf.Variable(initial, name=name)
# 初始化偏置
def bias_variable(shape, name):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial, name=name)
# 卷积层
def conv2d(x, W):
    # x input tensor of shape `[batch, in_height, in_width, in_channels]`
    # W filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels]
    # `strides[0] = strides[3] = 1`. strides[1]代表x方向的步长,strides[2]代表y方向的步长
    # padding: A `string` from: `"SAME", "VALID"`
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# 池化层
def max_pool_2x2(x):
    # ksize [1,x,y,1]
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 命名空间
with tf.name_scope('input'):
    # 定义两个placeholder
    x = tf.placeholder(tf.float32, [None, 784], name='x-input')
    y = tf.placeholder(tf.float32, [None, 10], name='y-input')
    with tf.name_scope('x_image'):
        # 改变x的格式转为4D的向量[batch, in_height, in_width, in_channels]`
        x_image = tf.reshape(x, [-1, 28, 28, 1], name='x_image')
with tf.name_scope('Conv1'):
    # 初始化第一个卷积层的权值和偏置
    with tf.name_scope('W_conv1'):
        W_conv1 = weight_variable([5, 5, 1, 32], name='W_conv1')  # 5*5的采样窗口,32个卷积核从1个平面抽取特征
    with tf.name_scope('b_conv1'):
        b_conv1 = bias_variable([32], name='b_conv1')  # 每一个卷积核一个偏置值
    # 把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
    with tf.name_scope('conv2d_1'):
        conv2d_1 = conv2d(x_image, W_conv1) + b_conv1
    with tf.name_scope('relu'):
        h_conv1 = tf.nn.relu(conv2d_1)
    with tf.name_scope('h_pool1'):
        h_pool1 = max_pool_2x2(h_conv1)  # 进行max-pooling
with tf.name_scope('Conv2'):
    # 初始化第二个卷积层的权值和偏置
    with tf.name_scope('W_conv2'):
        W_conv2 = weight_variable([5, 5, 32, 64], name='W_conv2')  # 5*5的采样窗口,64个卷积核从32个平面抽取特征
    with tf.name_scope('b_conv2'):
        b_conv2 = bias_variable([64], name='b_conv2')  # 每一个卷积核一个偏置值
    # 把h_pool1和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
    with tf.name_scope('conv2d_2'):
        conv2d_2 = conv2d(h_pool1, W_conv2) + b_conv2
    with tf.name_scope('relu'):
        h_conv2 = tf.nn.relu(conv2d_2)
    with tf.name_scope('h_pool2'):
        h_pool2 = max_pool_2x2(h_conv2)  # 进行max-pooling
# 28*28的图片第一次卷积后还是28*28,第一次池化后变为14*14
# 第二次卷积后为14*14,第二次池化后变为了7*7
# 进过上面操作后得到64张7*7的平面
with tf.name_scope('fc1'):
    # 初始化第一个全连接层的权值
    with tf.name_scope('W_fc1'):
        W_fc1 = weight_variable([7 * 7 * 64, 1024], name='W_fc1')  # 上一场有7*7*64个神经元,全连接层有1024个神经元
    with tf.name_scope('b_fc1'):
        b_fc1 = bias_variable([1024], name='b_fc1')  # 1024个节点
    # 把池化层2的输出扁平化为1维
    with tf.name_scope('h_pool2_flat'):
        h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64], name='h_pool2_flat')
    # 求第一个全连接层的输出
    with tf.name_scope('wx_plus_b1'):
        wx_plus_b1 = tf.matmul(h_pool2_flat, W_fc1) + b_fc1
    with tf.name_scope('relu'):
        h_fc1 = tf.nn.relu(wx_plus_b1)
    # keep_prob用来表示神经元的输出概率
    with tf.name_scope('keep_prob'):
        keep_prob = tf.placeholder(tf.float32, name='keep_prob')
    with tf.name_scope('h_fc1_drop'):
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob, name='h_fc1_drop')
with tf.name_scope('fc2'):
    # 初始化第二个全连接层
    with tf.name_scope('W_fc2'):
        W_fc2 = weight_variable([1024, 10], name='W_fc2')
    with tf.name_scope('b_fc2'):
        b_fc2 = bias_variable([10], name='b_fc2')
    with tf.name_scope('wx_plus_b2'):
        wx_plus_b2 = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
    with tf.name_scope('softmax'):
        # 计算输出
        prediction = tf.nn.softmax(wx_plus_b2)
# 交叉熵代价函数
with tf.name_scope('cross_entropy'):
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction),name='cross_entropy')
    tf.summary.scalar('cross_entropy', cross_entropy)
# 使用AdamOptimizer进行优化
with tf.name_scope('train'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# 求准确率
with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        # 结果存放在一个布尔列表中
        correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))  # argmax返回一维张量中最大的值所在的位置
    with tf.name_scope('accuracy'):
        # 求准确率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        tf.summary.scalar('accuracy', accuracy)
# 合并所有的summary
merged = tf.summary.merge_all()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter('logs/train', sess.graph)
    test_writer = tf.summary.FileWriter('logs/test', sess.graph)
    for i in range(1001):	
        # 训练模型
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.5})
        # 记录训练集计算的参数
        summary = sess.run(merged, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.0})
        train_writer.add_summary(summary, i)
        # 记录测试集计算的参数
        batch_xs, batch_ys = mnist.test.next_batch(batch_size)
        summary = sess.run(merged, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.0})
        test_writer.add_summary(summary, i)
        if i % 100 == 0:
            test_acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0})
            train_acc = sess.run(accuracy, feed_dict={x: mnist.train.images[:10000], y: mnist.train.labels[:10000],
                                                      keep_prob: 1.0})
            print("Iter " + str(i) + ", Testing Accuracy= " + str(test_acc) + ", Training Accuracy= " + str(train_acc))
with tf.name_scope('softmax'):
        # 计算输出
        prediction = tf.nn.softmax(wx_plus_b2)
# 交叉熵代价函数
with tf.name_scope('cross_entropy'):
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction),name='cross_entropy')
    tf.summary.scalar('cross_entropy', cross_entropy)

阅读 【TensorFlow】tf.nn.softmax_cross_entropy_with_logits的用法 该文可以了解到 tf.nn.softmax_cross_entropy_with_logits 函数的 logits 参数传入的是未经过 softmax 的 label 值。

import tensorflow as tf  
#our NN's output  
logits=tf.constant([[1.0,2.0,3.0],[1.0,2.0,3.0],[1.0,2.0,3.0]])  
#step1:do softmax  
y=tf.nn.softmax(logits)  
#true label  
y_=tf.constant([[0.0,0.0,1.0],[0.0,0.0,1.0],[0.0,0.0,1.0]])  
#step2:do cross_entropy  
cross_entropy = -tf.reduce_sum(y_*tf.log(y))  

两步可以用这一步代替:

#do cross_entropy just one step  
cross_entropy2=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits, y_))#dont forget tf.reduce_sum()!!  

但是视频里该例子的程序,prediction 已经经历了一次 softmax 呢!

prediction = tf.nn.softmax(wx_plus_b2)

然后又经过了 tf.nn.softmax_cross_entropy_with_logits 函数,这相当于经过两个 softmax 了。(我觉得可能是视频里老师没注意到这点问题,虽然大的值的概率值还是越大,这点上倒是没影响。)

不管那么多,运行程序,结果如下:(用的实验室电脑,显卡 GTX 1080ti 跑的)

Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
Iter 0, Testing Accuracy= 0.1051, Training Accuracy= 0.1119
Iter 100, Testing Accuracy= 0.595, Training Accuracy= 0.5961
Iter 200, Testing Accuracy= 0.7324, Training Accuracy= 0.7365
Iter 300, Testing Accuracy= 0.7594, Training Accuracy= 0.7579
Iter 400, Testing Accuracy= 0.8423, Training Accuracy= 0.8376
Iter 500, Testing Accuracy= 0.9393, Training Accuracy= 0.9327
Iter 600, Testing Accuracy= 0.9509, Training Accuracy= 0.9468
Iter 700, Testing Accuracy= 0.9562, Training Accuracy= 0.953
Iter 800, Testing Accuracy= 0.9589, Training Accuracy= 0.9582
Iter 900, Testing Accuracy= 0.9624, Training Accuracy= 0.9584
Iter 1000, Testing Accuracy= 0.9633, Training Accuracy= 0.9617

程序运行完成之后会在当前程序路径下生成 logs 文件夹,logs 文件夹下会有:

可视化网络训练过程:tensorboard --logdir=logs目录的路径

准确率:

在 logs 文件夹下有两个子文件夹,对应着图中两条线,橙色对应测试集测出来的数据,蓝色对应训练集训练出来的数据,可以看到,两条线非常接近,代表模型没有欠拟合和过拟合现象。如果是过拟合情况,那么蓝色的线就会比较高,橙色的线就会比较低。

交叉熵:

网络结构:

fc2 内部:

更多请参考

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
卷积神经网络CNN)是深度学习中应用最成功的领域之一。它包括一维、二维和三维卷积神经网络。一维卷积神经网络主要用于序列型数据的处理,二维卷积神经网络常用于像文本的识别,而三维卷积神经网络主要应用于医学像和视频数据的识别。 卷积神经网络的结构包括卷积层和池化层。在卷积层中,每个神经元只与部分邻层神经元连接,而不是与所有神经元连接。卷积层中通常包含多个特征,每个特征由矩形排列的神经元组成,同一特征中的神经元共享权值。这里的权值就是卷积核。通过学习训练,卷积核将获得合理的权值。卷积核的共享权值减少了层与层之间的连接,并降低了过拟合的风险。同时,池化层,也称为子采样层,也可以看作一种特殊的卷积过程。池化层进一步简化了模型的复杂度,并减少了模型的参数。 卷积神经网络的基本原理可以归结为以下几点: 1. 特征提取:通过卷积层和池化层来提取输入数据的特征。 2. 分类和预测:通过全连接层将特征映射到输出类别,实现分类和预测。 卷积神经网络有许多经典模型,其中包括: 1. LeNet:最早用于数字识别的CNN。 2. AlexNet:在2012年的ILSVRC比赛中远超第2名的CNN,比LeNet更深,使用多层小卷积层叠加替代单大卷积层。 3. ZF Net:在2013年的ILSVRC比赛中获得冠军。 4. GoogLeNet:在2014年的ILSVRC比赛中获得冠军。 5. VGGNet:在2014年的ILSVRC比赛中的模型,在像识别上略逊于GoogLeNet,但在许多像转化学习问题上效果非常好。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值