机器人与人工智能爱好者论坛

 找回密码
 立即注册
查看: 10617|回复: 0
打印 上一主题 下一主题

【连载】深度学习笔记12:卷积神经网络的Tensorflow实现

[复制链接]

31

主题

34

帖子

363

积分

中级会员

Rank: 3Rank: 3

积分
363
跳转到指定楼层
楼主
发表于 2018-11-19 11:08:48 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
      在上一讲中,我们学习了如何利用 numpy 手动搭建卷积神经网络。但在实际的图像识别中,使用 numpy 去手写 CNN 未免有些吃力不讨好。在 DNN 的学习中,我们也是在手动搭建之后利用 Tensorflow 去重新实现一遍,一来为了能够对神经网络的传播机制能够理解更加透彻,二来也是为了更加高效使用开源框架快速搭建起深度学习项目。本节就继续和大家一起学习如何利用 Tensorflow 搭建一个卷积神经网络。
      我们继续以 NG 课题组提供的 sign 手势数据集为例,学习如何通过 Tensorflow 快速搭建起一个深度学习项目。数据集标签共有零到五总共 6 类标签,示例如下:

      先对数据进行简单的预处理并查看训练集和测试集维度:
  1. X_train = X_train_orig/255.
  2. X_test = X_test_orig/255.
  3. Y_train = convert_to_one_hot(Y_train_orig, 6).T
  4. Y_test = convert_to_one_hot(Y_test_orig, 6).T
  5. print ("number of training examples = " + str(X_train.shape[0]))
  6. print ("number of test examples = " + str(X_test.shape[0]))
  7. print ("X_train shape: " + str(X_train.shape))
  8. print ("Y_train shape: " + str(Y_train.shape))
  9. print ("X_test shape: " + str(X_test.shape))
  10. print ("Y_test shape: " + str(Y_test.shape))
复制代码


      可见我们总共有 1080 张 64643 训练集图像,120 张 64643 的测试集图像,共有 6 类标签。下面我们开始搭建过程。
创建 placeholder
      首先需要为训练集预测变量和目标变量创建占位符变量 placeholder ,定义创建占位符变量函数:
  1. def create_placeholders(n_H0, n_W0, n_C0, n_y):   
  2.     """
  3.     Creates the placeholders for the tensorflow session.

  4.     Arguments:
  5.     n_H0 -- scalar, height of an input image
  6.     n_W0 -- scalar, width of an input image
  7.     n_C0 -- scalar, number of channels of the input
  8.     n_y -- scalar, number of classes

  9.     Returns:
  10.     X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype "float"
  11.     Y -- placeholder for the input labels, of shape [None, n_y] and dtype "float"
  12.     """
  13.     X = tf.placeholder(tf.float32, shape=(None, n_H0, n_W0, n_C0), name='X')
  14.     Y = tf.placeholder(tf.float32, shape=(None, n_y), name='Y')   
  15.     return X, Y
复制代码

参数初始化
      然后需要对滤波器权值参数进行初始化:
  1. def initialize_parameters():   
  2.     """
  3.     Initializes weight parameters to build a neural network with tensorflow.
  4.     Returns:
  5.     parameters -- a dictionary of tensors containing W1, W2
  6.     """

  7.     tf.set_random_seed(1)                             

  8.     W1 = tf.get_variable("W1", [4,4,3,8], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
  9.     W2 = tf.get_variable("W2", [2,2,8,16], initializer = tf.contrib.layers.xavier_initializer(seed = 0))

  10.     parameters = {"W1": W1,                  
  11.                   "W2": W2}   
  12.     return parameters
复制代码

执行卷积网络的前向传播过程

      前向传播过程如下所示:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED

      可见我们要搭建的是一个典型的 CNN 过程,经过两次的卷积-relu激活-最大池化,然后展开接上一个全连接层。利用 Tensorflow  搭建上述传播过程如下:
  1. def forward_propagation(X, parameters):   
  2.     """
  3.     Implements the forward propagation for the model

  4.     Arguments:
  5.     X -- input dataset placeholder, of shape (input size, number of examples)
  6.     parameters -- python dictionary containing your parameters "W1", "W2"
  7.                   the shapes are given in initialize_parameters

  8.     Returns:
  9.     Z3 -- the output of the last LINEAR unit
  10.     """

  11.     # Retrieve the parameters from the dictionary "parameters"
  12.     W1 = parameters['W1']
  13.     W2 = parameters['W2']   
  14.     # CONV2D: stride of 1, padding 'SAME'
  15.     Z1 = tf.nn.conv2d(X,W1, strides = [1,1,1,1], padding = 'SAME')   
  16.     # RELU
  17.     A1 = tf.nn.relu(Z1)   
  18.     # MAXPOOL: window 8x8, sride 8, padding 'SAME'
  19.     P1 = tf.nn.max_pool(A1, ksize = [1,8,8,1], strides = [1,8,8,1], padding = 'SAME')   
  20.     # CONV2D: filters W2, stride 1, padding 'SAME'
  21.     Z2 = tf.nn.conv2d(P1,W2, strides = [1,1,1,1], padding = 'SAME')   
  22.     # RELU
  23.     A2 = tf.nn.relu(Z2)   
  24.     # MAXPOOL: window 4x4, stride 4, padding 'SAME'
  25.     P2 = tf.nn.max_pool(A2, ksize = [1,4,4,1], strides = [1,4,4,1], padding = 'SAME')   
  26.     # FLATTEN
  27.     P2 = tf.contrib.layers.flatten(P2)

  28.     Z3 = tf.contrib.layers.fully_connected(P2, 6, activation_fn = None)   
  29.     return Z3
复制代码

计算当前损失
      在 Tensorflow  中计算损失函数非常简单,一行代码即可:
  1. <font face="微软雅黑"><span style="font-size: 16px;">def compute_cost(Z3, Y):    </span></font>
  2. <font face="微软雅黑"><span style="font-size: 16px;">    """</span></font>
  3. <font face="微软雅黑"><span style="font-size: 16px;">    Computes the cost</span></font>
  4. <font face="微软雅黑"><span style="font-size: 16px;">    Arguments:</span></font>
  5. <font face="微软雅黑"><span style="font-size: 16px;">    Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)</span></font>
  6. <font face="微软雅黑"><span style="font-size: 16px;">    Y -- "true" labels vector placeholder, same shape as Z3</span></font>

  7. <font face="微软雅黑"><span style="font-size: 16px;">    Returns:</span></font>
  8.     cost - Tensor of the cost function
  9. <font face="微软雅黑"><span style="font-size: 16px;">    """</span></font>

  10. <font face="微软雅黑"><span style="font-size: 16px;">    cost = tf.reduce_mean(tf.nn.softmax_cROSs_entropy_with_logits(logits=Z3, labels=Y))    </span></font>
  11. <font face="微软雅黑"><span style="font-size: 16px;">    return cost</span></font>
复制代码

      定义好上述过程之后,就可以封装整体的训练过程模型。可能你会问为什么没有反向传播,这里需要注意的是 Tensorflow 帮助我们自动封装好了反向传播过程,无需我们再次定义,在实际搭建过程中我们只需将前向传播的网络结构定义清楚即可。
封装模型
  1. <span style="font-weight: normal;">def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009,
  2.           num_epochs = 100, minibatch_size = 64, print_cost = True):   
  3.     """
  4.     Implements a three-layer ConvNet in Tensorflow:
  5.     CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED

  6.     Arguments:
  7.     X_train -- training set, of shape (None, 64, 64, 3)
  8.     Y_train -- test set, of shape (None, n_y = 6)
  9.     X_test -- training set, of shape (None, 64, 64, 3)
  10.     Y_test -- test set, of shape (None, n_y = 6)
  11.     learning_rate -- learning rate of the optimization
  12.     num_epochs -- number of epochs of the optimization loop
  13.     minibatch_size -- size of a minibatch
  14.     print_cost -- True to print the cost every 100 epochs

  15.     Returns:
  16.     train_accuracy -- real number, accuracy on the train set (X_train)
  17.     test_accuracy -- real number, testing accuracy on the test set (X_test)
  18.     parameters -- parameters learnt by the model. They can then be used to predict.
  19.     """

  20.     ops.reset_default_graph()                        
  21.     tf.set_random_seed(1)                             
  22.     seed = 3                                       
  23.     (m, n_H0, n_W0, n_C0) = X_train.shape            
  24.     n_y = Y_train.shape[1]                           
  25.     costs = []                                      

  26.     # Create Placeholders of the correct shape
  27.     X, Y = create_placeholders(n_H0, n_W0, n_C0, n_y)   
  28.     # Initialize parameters
  29.     parameters = initialize_parameters()   
  30.     # Forward propagation
  31.     Z3 = forward_propagation(X, parameters)   
  32.     # Cost function
  33.     cost = compute_cost(Z3, Y)   
  34.     # Backpropagation
  35.     optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)    # Initialize all the variables globally
  36.     init = tf.global_variables_initializer()   
  37.     # Start the session to compute the tensorflow graph
  38.     with tf.Session() as sess:        
  39.         # Run the initialization
  40.         sess.run(init)        
  41.         # Do the training loop
  42.         for epoch in range(num_epochs):

  43.             minibatch_cost = 0.
  44.             num_minibatches = int(m / minibatch_size)
  45.             seed = seed + 1
  46.             minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)            
  47.             for minibatch in minibatches:               
  48.                 # Select a minibatch
  49.                 (minibatch_X, minibatch_Y) = minibatch
  50.                 _ , temp_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})
  51.                 minibatch_cost += temp_cost / num_minibatches            
  52.                 # Print the cost every epoch
  53.             if print_cost == True and epoch % 5 == 0:               
  54.                 print ("Cost after epoch %i: %f" % (epoch, minibatch_cost))            
  55.             if print_cost == True and epoch % 1 == 0:
  56.                 costs.append(minibatch_cost)        
  57.         # plot the cost
  58.         plt.plot(np.squeeze(costs))
  59.         plt.ylabel('cost')
  60.         plt.xlabel('iterations (per tens)')
  61.         plt.title("Learning rate =" + str(learning_rate))
  62.         plt.show()        # Calculate the correct predictions
  63.         predict_op = tf.argmax(Z3, 1)
  64.         correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))        
  65.         # Calculate accuracy on the test set
  66.         accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  67.         print(accuracy)
  68.         train_accuracy = accuracy.eval({X: X_train, Y: Y_train})
  69.         test_accuracy = accuracy.eval({X: X_test, Y: Y_test})
  70.         print("Train Accuracy:", train_accuracy)
  71.         print("Test Accuracy:", test_accuracy)      
  72.          
  73.         return train_accuracy, test_accuracy, parameters</span>
复制代码

     对训练集执行模型训练:
  1. _, _, parameters = model(X_train, Y_train, X_test, Y_test)
复制代码

     训练迭代过程如下:

    我们在训练集上取得了 0.67 的准确率,在测试集上的预测准确率为 0.58 ,虽然效果并不显著,模型也有待深度调优,但我们已经学会了如何用 Tensorflow  快速搭建起一个深度学习系统了。
本文来自《自兴人工智能》项目部:凯文

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

QQ|Archiver|手机版|小黑屋|陕ICP备15012670号-1    

GMT+8, 2024-4-29 00:20 , Processed in 0.059249 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表