改善深层神经网络week3学习笔记

TensorFlow Tutorial

本周作业主要是一个有关tensorflow的指导教程。

编写并运行tensorflow需要以下几个步骤:

1.创建还没有被执行或者计算过的tensor(变量)

2.编写变量间相关操作

3.初始化tensor,代码如:init = tf.global_variables_initializer()  

4.创建一个session。

5.运行session,所有相关操作都会被执行。

第4.5步骤代码如下:

with tf.Session() as session:                    # Create a session and print the output
    session.run(init)                            # Initializes the variables
    print(session.run(loss))                     # Prints the loss

如果不进行第3,4,5步骤变量只是被定义出来但不会被计算,如下:

关于placeholder

placeholder相当于是一个占位符一样的东西,可以暂时不对其进行处理而在稍后对其赋值,而后面的这一过程称为feed data。

具体代码示例如下:

实际上,TensorFlow 程序一般可划分为两个流程:

  • construction phase,构建过程,会构建出一个图(graph),即所谓的计算图(computation graph)
  • evaluation phase,执行过程,使用 session 执行构建过程中生成的图中的操作;

而当定义计算所需要的操作时,你只是告诉tensorflow如何构建一个计算图,此时tensorflow可以有一些空缺来等着以后来填补,而当运行session的时候,你就是在告诉tensorflow来执行这个计算图。方法如下:

Method 1:

sess = tf.Session()
# Run the variables initialization (if needed), run the operations
result = sess.run(..., feed_dict = {...})
sess.close() # Close the session

Method 2:

with tf.Session() as sess: 
    # run the variables initialization (if needed), run the operations
    result = sess.run(..., feed_dict = {...})
    # This takes care of closing the session for you :)

对于之前完成的损失函数公式

tensorflow库中提供了更加简便的函数

tf.nn.sigmoid_cross_entropy_with_logits(logits = ..., labels = ...)

其中,z,y分别对应logits和labels。

作业中提供了一种称为one hot 的方法。将一个向量转变成能表示其的矩阵,示意图如下:

  • tf.one_hot(labels, depth, axis)

labels为向量数组,depth为深度,即向量数组中的数据范围(0~depth-1),axis=0则表示跨行,用列向量表示;axis=1则表示跨列,用行向量表示,如上图就是axis=0的情况。

tensorflow中还提供了不少函数以简化编写,作业中要求完成的神经网络中给出了几个例子。

optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(cost)
_ , c = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})

在运行optimizer时,后向传播和优化会自动进行。

猜你喜欢

转载自blog.csdn.net/stezio/article/details/81133922