欢迎来到本周的编程作业。到目前为止,您一直使用numpy来构建神经网络。现在我们将引导你通过一个深度学习框架,它将允许你更容易地建立神经网络。像TensorFlow, PaddlePaddle, Torch, Caffe, Keras等机器学习框架可以显著加快你机器学习的发展。所有这些框架都有大量文档,您可以随意阅读。在这个作业中,你将学习在TensorFlow中完成以下操作:
初始化变量
开始你自己的会话
训练算法
实现一个神经网络
编程框架不仅可以缩短您的编码时间,有时还可以执行优化来加速您的代码。
1 - Exploring the Tensorflow Library 探索Tensorflow库
首先,您将导入库:
1 import math 2 import numpy as np 3 import h5py 4 import matplotlib.pyplot as plt 5 import tensorflow as tf 6 from tensorflow.python.framework import ops 7 from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict 8 9 %matplotlib inline 10 np.random.seed(1)
现在您已经导入了库,我们将带您浏览它的不同应用程序。你将从一个例子开始,我们计算一个训练例子的损失。
原代码为:
y_hat = tf.constant(36, name='y_hat') # Define y_hat constant. Set to 36. y = tf.constant(39, name='y') # Define y. Set to 39 loss = tf.Variable((y - y_hat)**2, name='loss') # Create a variable for the loss init = tf.global_variables_initializer() # When init is run later (session.run(init)), # the loss variable will be initialized and ready to be computed 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
根据网上参考,适应tf2.0版本修改的:
import tensorflow as tf tf.compat.v1.disable_eager_execution() #保证session.run()能够正常运行 y_hat = tf.constant(36, name='y_hat') # Define y_hat constant. Set to 36. y = tf.constant(39, name='y') # Define y. Set to 39 loss = tf.Variable((y - y_hat)**2, name='loss') # Create a variable for the loss init = tf.compat.v1.global_variables_initializer() # When init is run later (session.run(init)),
# the loss variable will be initialized and ready to be computed with tf.compat.v1.Session () as session: # Create a session and print the output session.run(init) # Initializes the variables print(session.run(loss))
运行结果:
在TensorFlow中编写和运行程序有以下步骤:
1、创建Tensorflow变量(此时,尚未直接计算)
2、实现Tensorflow变量之间的操作定义。
3、初始化Tensorflow变量
4、创建一个会话,也就是session。
5、运行会话。这将运行您上面所写的操作。
因此,当我们为损失创建一个变量时,我们只是将损失定义为其他数量的函数,但没有计算它的值。要对它求值,我们必须运行init=tf.global_variables_initializer()。这样就初始化了loss变量,并且在最后一行中,我们终于能够计算loss的值并打印它的值。
现在让我们看一个简单的例子。运行下面的单元格:
(链接:https://blog.csdn.net/weixin_47440593/article/details/107721334
参考的博客为https://blog.csdn.net/u013733326/article/details/79971488
原博客中作者用的是tf1.x版本的,本文用的是tf2.x版本,这里挂一下网友整理的两个版本更新的对比https://docs.qq.com/sheet/DZkR6cUZpdFJ2bUxS?tab=BB08J2
)
a = tf.constant(2) b = tf.constant(10) c = tf.multiply(a,b) print(c)
运行结果:
正如所料,您不会看到20!你得到一个变量,说结果是一个没有形状属性的张量(没有维度),类型是“int32”。你所做的一切都被放到了“计算图(computation graph)”中,但是你还没有运行这个计算。为了实际地将两个数字相乘,您必须创建一个会话并运行它。
sess = tf.compat.v1.Session() print(sess.run(c))
运行结果:
20
太棒了!总之,请记住初始化变量、创建会话并在会话内运行操作。
接下来,您还需要了解占位符。占位符是只能在以后指定其值的对象。要为占位符指定值,可以使用“feed字典”(feed_dict变量)传入值。下面,我们为x创建了一个占位符。这允许我们在稍后运行会话时传入一个数字。
# Change the value of x in the feed_dict x = tf.compat.v1.placeholder(tf.int64, name = 'x') print(sess.run(2 * x, feed_dict = {x: 3})) sess.close()
运行结果:
6
placeholder means '占位符'
当你第一次定义x时,你不需要为它指定一个值。占位符只是一个变量,您将在稍后运行会话时将数据分配给它。我们说,在运行会话时向这些占位符提供数据。
当您指定一个计算所需的操作时,您正在告诉TensorFlow如何构造一个计算图。计算图中可以有一些占位符,它们的值将稍后指定。最后,当您运行会话时,您告诉TensorFlow执行计算图。
1.1 - Linear function 线性函数
你可能会发现以下功能有帮助:
·tf.matmul(…,…)来做一个矩阵乘法 #matmul 就是matrix和multiply
·tf.add(…,…)做加法
·随机初始化n .random.randn(…)
# GRADED FUNCTION: linear_function def linear_function(): """ Implements a linear function: Initializes W to be a random tensor of shape (4,3) Initializes X to be a random tensor of shape (3,1) Initializes b to be a random tensor of shape (4,1) Returns: result -- runs the session for Y = WX + b """ np.random.seed(1) ### START CODE HERE ### (4 lines of code) X = tf.constant(np.random.randn(3, 1), name = 'X') W = tf.constant(np.random.randn(4, 3), name = 'W') b = tf.constant(np.random.randn(4, 1), name = 'b') Y = tf.add((tf.matmul(W, X)), b) ### END CODE HERE ### # Create the session using tf.Session() and run it with sess.run(...) on the variable you want to calculate ### START CODE HERE ### sess = tf.compat.v1.Session() result = sess.run(Y) ### END CODE HERE ### # close the session sess.close() return result