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

在笔记7中,和大家一起入门了  tensorflow 的基本语法,并举了一些实际的例子进行了说明,终于告别了使用 numpy 手动搭建的日子。所以我们将继续往下走,看看如何利用  tensorflow 搭建神经网络模型。
      尽管对于初学者而言使用 tensorflow 看起来并不那么习惯,需要各种步骤,但简单来说,tensorflow 搭建模型实际就是两个过程:创建计算图和执行计算图。在 deeplearningai 课程中,ng和他的课程组给我们提供了 signs dataset (手势)数据集,其中训练集包括1080张64x64像素的手势图片,并给定了 6 种标注,测试集包括120张64x64的手势图片,我们需要对训练集构建神经网络模型然后对测试集给出预测。
先来简单看一下数据集:
# 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).tx_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)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 参数的设置。
def create_placeholders(n_x, n_y):    x = tf.placeholder(tf.float32, shape=(n_x, none), name='x')    y = tf.placeholder(tf.float32, shape=(n_y, none), name='y')    
   return x, y初始化模型参数     其次就是初始化神经网络的模型参数,三层网络包括六个参数,这里我们采用xavier初始化方法:
def initialize_parameters():    tf.set_random_seed(1)                    w1 = tf.get_variable(w1, [25, 12288], initializer = tf.contrib.layers.xavier_initializer(seed = 1))    b1 = tf.get_variable(b1, [25, 1], initializer = tf.zeros_initializer())    w2 = tf.get_variable(w2, [12, 25], initializer = tf.contrib.layers.xavier_initializer(seed = 1))    b2 = tf.get_variable(b2, [12, 1], initializer = tf.zeros_initializer())    w3 = tf.get_variable(w3, [6, 12], initializer = tf.contrib.layers.xavier_initializer(seed = 1))    b3 = tf.get_variable(b3, [6,1], initializer = tf.zeros_initializer())    parameters = {w1: w1,                
                 b1: b1,  
                 w2: w2,
                 b2: b2,
                 w3: w3,  
                 b3: b3}  
   return parameters执行前向传播def forward_propagation(x, parameters):        implements the forward propagation for the model: linear -> relu -> linear -> relu -> linear -> softmax        w1 = parameters['w1']    b1 = parameters['b1']    w2 = parameters['w2']    b2 = parameters['b2']    w3 = parameters['w3']    b3 = parameters['b3']    z1 = tf.add(tf.matmul(w1, x), b1)                        a1 = tf.nn.relu(z1)                                   z2 = tf.add(tf.matmul(w2, a1), b2)                    a2 = tf.nn.relu(z2)                                      z3 = tf.add(tf.matmul(w3, a2), b3)                      return z3计算损失函数      在 tensorflow 中损失函数的计算要比手动搭建时方便很多,一行代码即可搞定:
def compute_cost(z3, y):    logits = tf.transpose(z3)    labels = tf.transpose(y)    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = labels))    
   return cost代码整合:执行反向传播和权值更新      跟计算损失函数类似,tensorflow 中执行反向传播的梯度优化非常简便,两行代码即可搞定,定义完整的神经网络模型如下:
def model(x_train, y_train, x_test, y_test, learning_rate = 0.0001,          num_epochs = 1500, minibatch_size = 32, print_cost = true):    ops.reset_default_graph()                        tf.set_random_seed(1)                              seed = 3                                            (n_x, m) = x_train.shape                          n_y = y_train.shape[0]                              costs = []                                      # create placeholders of shape (n_x, n_y)    x, y = create_placeholders(n_x, n_y)    # initialize parameters    parameters = initialize_parameters()    # forward propagation: build the forward propagation in the tensorflow graph    z3 = forward_propagation(x, parameters)    # cost function: add cost function to tensorflow graph    cost = compute_cost(z3, y)    # backpropagation: define the tensorflow optimizer. use an adamoptimizer.    optimizer = tf.train.gradientdescentoptimizer(learning_rate = learning_rate).minimize(cost)    # initialize all the variables    init = tf.global_variables_initializer()    # start the session to compute the tensorflow graph    with tf.session() as sess:        # run the initialization        sess.run(init)        # do the training loop        for epoch in range(num_epochs):            epoch_cost = 0.                                num_minibatches = int(m / minibatch_size)            seed = seed + 1            minibatches = random_mini_batches(x_train, y_train, minibatch_size, seed)            
           for minibatch in minibatches:                # select a minibatch                (minibatch_x, minibatch_y) = minibatch                _ , minibatch_cost = sess.run([optimizer, cost], feed_dict={x: minibatch_x, y: minibatch_y})                epoch_cost += minibatch_cost / num_minibatches            # print the cost every epoch        if print_cost == true and epoch % 100 == 0:                
           print (cost after epoch %i: %f % (epoch, epoch_cost))          
       if print_cost == true and epoch % 5 == 0:                costs.append(epoch_cost)        # plot the cost        plt.plot(np.squeeze(costs))        plt.ylabel('cost')        plt.xlabel('iterations (per tens)')        plt.title(learning rate = + str(learning_rate))        plt.show()        # lets save the parameters in a variable        parameters = sess.run(parameters)        
       print (parameters have been trained!)        # calculate the correct predictions        correct_prediction = tf.equal(tf.argmax(z3), tf.argmax(y))        # calculate accuracy on the test set        accuracy = tf.reduce_mean(tf.cast(correct_prediction, float))      
       print (train accuracy:, accuracy.eval({x: x_train, y: y_train}))        
       print (test accuracy:, accuracy.eval({x: x_test, y: y_test}))        
       return parameters      执行模型:
parameters = model(x_train, y_train, x_test, y_test)
      根据模型的训练误差和测试误差可以看到:模型整体效果虽然没有达到最佳,但基本也能达到预测效果。
总结tensorflow 语法中两个基本的对象类是 tensor 和 operator.
tensorflow 执行计算的基本步骤为
创建计算图(张量、变量和占位符变量等)
创建会话
初始化会话
在计算图中执行会话
      可以看到的是,在 tensorflow 中编写神经网络要比我们手动搭建要方便的多,这也正是深度学习框架存在的意义之一。功能强大的深度学习框架能够帮助我们快速的搭建起复杂的神经网络模型,在经历了手动搭建神经网络的思维训练过程之后,这对于我们来说就不再困难了。
本文由《自兴动脑人工智能》项目部 凯文 投稿。

医疗物联网解决方案的亮点有哪些
荣耀9、荣耀V9对比评测:华为荣耀9、华为荣耀V9谁更具性价比?五点让你知道该如何抉择
喜讯!中微电科技正式获准设立博士后创新实践基地
如何利用HAL库去驱动W5500芯片呢
物联网四个阶段所面临的数字化风险是什么?
深度学习笔记8:利用Tensorflow搭建神经网络
Amazfit智能运动手表3评测 不玩噱头多了些用心和诚意
智慧安全用电管理系统,让用电更加安全规范
国内PCB厂商如何在“黄金时代”的洗牌中持续前行?
音频技术:去整合化和MEMS麦克风成趋势
泰克将在ICEMI2013现场演示S参数级联时防止失真的最新方法
密歇根大学制造出世界上最小的计算机,长度仅有0.3毫米
国内智能音箱出货量首现下滑
利用RFID技术实现科学安全的血液管理
使用 Kria SoM 部署基于边缘的人工智能
关于开源的AMBA(APB/AHB/AXI) VIP
5G怎样进行室内定位?
Vishay发布新款超薄的SMD 0604封装的ChipLED-VLMx1300
力科推出SimPASS仿真设计验证工具,用于PCI-Expr
BC电池是什么意思 bc电池和topcon的区别