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

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

【连载】深度学习笔记8:利用Tensorflow搭建神经网络

[复制链接]

31

主题

34

帖子

363

积分

中级会员

Rank: 3Rank: 3

积分
363
跳转到指定楼层
楼主
发表于 2018-9-28 20:01:00 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 Game 于 2018-9-28 20:07 编辑

      在笔记7中,笔者和大家一起入门了  Tensorflow 的基本语法,并举了一些实际的例子进行了说明,终于告别了使用 numpy 手动搭建的日子。所以我们将继续往下走,看看如何利用  Tensorflow 搭建神经网络模型。
      尽管对于初学者而言使用 Tensorflow 看起来并不那么习惯,需要各种步骤,但简单来说,Tensorflow 搭建模型实际就是两个过程:创建计算图和执行计算图。在 deeplearningai 课程中,NG和他的课程组给我们提供了 Signs Dataset (手势)数据集,其中训练集包括1080张64x64像素的手势图片,并给定了 6 种标注,测试集包括120张64x64的手势图片,我们需要对训练集构建神经网络模型然后对测试集给出预测。
      先来简单看一下数据集:
  1. # Loading the datasetX_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()# Flatten the training and test imagesX_train_flatten = X_train_orig.reshape(X_train_orig.shape[0], -1).T
  2. X_test_flatten = X_test_orig.reshape(X_test_orig.shape[0], -1).T# Normalize image vectorsX_train = X_train_flatten/255.X_test = X_test_flatten/255.# Convert training and test labels to one hot matricesY_train = convert_to_one_hot(Y_train_orig, 6)
  3. Y_test = convert_to_one_hot(Y_test_orig, 6)print ("number of training examples = " + str(X_train.shape[1]))print ("number of test examples = " + str(X_test.shape[1]))print ("X_train shape: " + str(X_train.shape))print ("Y_train shape: " + str(Y_train.shape))print ("X_test shape: " + str(X_test.shape))print ("Y_test shape: " + str(Y_test.shape))
复制代码


      下面就根据 NG 给定的找个数据集利用 Tensorflow 搭建神经网络模型。我们选择构建一个包含 2 个隐层的神经网络,网络结构大致如下:
LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX
正如我们之前利用 numpy 手动搭建一样,搭建一个神经网络的主要步骤如下:
-定义网络结构
-初始化模型参数
-执行前向计算/计算当前损失/执行反向传播/权值更新
创建 placeholder
      根据 Tensorflow 的语法,我们首先创建输入X 和输出 Y 的占位符变量,这里需要注意 shape 参数的设置。
  1. def create_placeholders(n_x, n_y):
  2.     X = tf.placeholder(tf.float32, shape=(n_x, None), name='X')
  3.     Y = tf.placeholder(tf.float32, shape=(n_y, None), name='Y')   
  4.     return X, Y
复制代码

    return X, Y初始化模型参数
     其次就是初始化神经网络的模型参数,三层网络包括六个参数,这里我们采用Xavier初始化方法:

  1. def initialize_parameters():
  2.     tf.set_random_seed(1)                 
  3.     W1 = tf.get_variable("W1", [25, 12288], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
  4.     b1 = tf.get_variable("b1", [25, 1], initializer = tf.zeROS_initializer())
  5.     W2 = tf.get_variable("W2", [12, 25], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
  6.     b2 = tf.get_variable("b2", [12, 1], initializer = tf.zeros_initializer())
  7.     W3 = tf.get_variable("W3", [6, 12], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
  8.     b3 = tf.get_variable("b3", [6,1], initializer = tf.zeros_initializer())

  9.     parameters = {"W1": W1,                 
  10.                   "b1": b1,   
  11.                   "W2": W2,
  12.                   "b2": b2,
  13.                   "W3": W3,  
  14.                   "b3": b3}   
  15.     return parameters
复制代码

执行前向传播
  1. def forward_propagation(X, parameters):    """
  2.     Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX
  3.     """

  4.     W1 = parameters['W1']
  5.     b1 = parameters['b1']
  6.     W2 = parameters['W2']
  7.     b2 = parameters['b2']
  8.     W3 = parameters['W3']
  9.     b3 = parameters['b3']

  10.     Z1 = tf.add(tf.matmul(W1, X), b1)                    
  11.     A1 = tf.nn.relu(Z1)                              
  12.     Z2 = tf.add(tf.matmul(W2, A1), b2)               
  13.     A2 = tf.nn.relu(Z2)                                 
  14.     Z3 = tf.add(tf.matmul(W3, A2), b3)                  
  15.     return Z3
复制代码


计算损失函数
      在 Tensorflow 中损失函数的计算要比手动搭建时方便很多,一行代码即可搞定:
  1. def compute_cost(Z3, Y):
  2.     logits = tf.transpose(Z3)
  3.     labels = tf.transpose(Y)

  4.     cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = labels))   
  5.     return cost
复制代码


代码整合:执行反向传播和权值更新
      跟计算损失函数类似,Tensorflow 中执行反向传播的梯度优化非常简便,两行代码即可搞定,定义完整的神经网络模型如下:
  1. def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
  2.           num_epochs = 1500, minibatch_size = 32, print_cost = True):
  3.     ops.reset_default_graph()                    
  4.     tf.set_random_seed(1)                          
  5.     seed = 3                                         
  6.     (n_x, m) = X_train.shape                       
  7.     n_y = Y_train.shape[0]                          
  8.     costs = []                                   

  9.     # Create Placeholders of shape (n_x, n_y)
  10.     X, Y = create_placeholders(n_x, n_y)    # Initialize parameters
  11.     parameters = initialize_parameters()    # Forward propagation: Build the forward propagation in the tensorflow graph

  12.     Z3 = forward_propagation(X, parameters)    # Cost function: Add cost function to tensorflow graph
  13.     cost = compute_cost(Z3, Y)    # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer.
  14.     optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(cost)    # Initialize all the variables
  15.     init = tf.global_variables_initializer()    # Start the session to compute the tensorflow graph
  16.     with tf.Session() as sess:        # Run the initialization
  17.         sess.run(init)        # Do the training loop
  18.         for epoch in range(num_epochs):
  19.             epoch_cost = 0.                    
  20.             num_minibatches = int(m / minibatch_size)
  21.             seed = seed + 1
  22.             minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)            
  23.             for minibatch in minibatches:                # Select a minibatch
  24.                 (minibatch_X, minibatch_Y) = minibatch
  25.                 _ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})
  26.                 epoch_cost += minibatch_cost / num_minibatches            # Print the cost every epoch
  27.         if print_cost == True and epoch % 100 == 0:               
  28.             print ("Cost after epoch %i: %f" % (epoch, epoch_cost))           
  29.         if print_cost == True and epoch % 5 == 0:
  30.                 costs.append(epoch_cost)        # plot the cost
  31.         plt.plot(np.squeeze(costs))
  32.         plt.ylabel('cost')
  33.         plt.xlabel('iterations (per tens)')
  34.         plt.title("Learning rate =" + str(learning_rate))
  35.         plt.show()        # lets save the parameters in a variable
  36.         parameters = sess.run(parameters)        
  37.         print ("Parameters have been trained!")        # Calculate the correct predictions
  38.         correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))        # Calculate accuracy on the test set
  39.         accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))      
  40.         print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train}))        
  41.         print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test}))        
  42.         return parameters
复制代码

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

      根据模型的训练误差和测试误差可以看到:模型整体效果虽然没有达到最佳,但基本也能达到预测效果。
总结
  • Tensorflow 语法中两个基本的对象类是 Tensor 和 Operator.
  • Tensorflow 执行计算的基本步骤为
    • 创建计算图(张量、变量和占位符变量等)
    • 创建会话
    • 初始化会话
    • 在计算图中执行会话
      可以看到的是,在 Tensorflow 中编写神经网络要比我们手动搭建要方便的多,这也正是深度学习框架存在的意义之一。功能强大的深度学习框架能够帮助我们快速的搭建起复杂的神经网络模型,在经历了手动搭建神经网络的思维训练过程之后,这对于我们来说就不再困难了。
本文由《自兴动脑人工智能》项目部 凯文 投稿。


回复

使用道具 举报

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

本版积分规则

关闭

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

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

GMT+8, 2024-4-28 16:31 , Processed in 0.054223 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

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