1 - Exploring the Tensorflow Library

导入库:

import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
import os
import tensorflow.python.util.deprecation as deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
import tensorflow as tf
if type(tf.contrib) != type(tf): tf.contrib._warning = None%matplotlib inline
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 39loss = tf.Variable((y - y_hat)**2, name='loss')  # Create a variable for the lossinit = 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 outputsession.run(init)                            # Initializes the variablesprint(session.run(loss))                     # Prints the loss

结果为9

在TensorFlow中编写和运行程序有以下步骤:

  1. 创建尚未执行/计算的张量(变量)。
  2. 编写在这些张量之间进行的操作。
  3. 初始化张量。
  4. 创建一个会话。
  5. 运行会话,将会运行以上所编写的操作。

因此,当我们为损失创建一个变量时,我们简单地将损失定义为其他量的函数,但没有计算其值。为了计算它,需要运行init=tf.global_variables_initializer(),这样就初始化了损失变量,最后一行能够计算损失的值并且打印出来。

1.1 - Linear function

计算如下式子:Y=WX+b,其中W和X是随机矩阵,b是随机向量。

练习:计算WX+b,其中W,X和b由随机正态分布中提取。W的形状为(4,3),X为(3,1),b为(4,1),举个例子,下面是如何定义一个形状为(3,1)的常量X:

x=tf.constant(np.random.randn(3,1), name="X")

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.matmul(W, X) + b# Create the session using tf.Session() and run it with sess.run(...) on the variable you want to calculatesess = tf.Session()
result = sess.run(Y)

1.2 - Computing the sigmoid

Tensorflow提供了许多常用的神经网络函数包括tf.sigmoid和tf.softmax等等,接下来计算sigmoid。

使用占位符变量x,当运行会话时,需要使用feed字典来传入输入z,作业中要做如下几件事:

  1. 创建一个占位符x
  2. 定义操作,使用tf.sigmoid计算
  3. 运行会话

练习:实现sigmoid函数。

两种创建并使用会话的方法:

# Create a placeholder for x. Name it 'x'.
x = tf.placeholder(tf.float32, name='x')# compute sigmoid(x)
sigmoid = tf.sigmoid(x)# Create a session, and run it. Please use the method 2 explained above.
# You should use a feed_dict to pass z's value to x.
with tf.Session() as sess:# Run session and call the output "result"result = sess.run(sigmoid, feed_dict={x:z})

1.3 - Computing the Cost

也可以使用内置函数来计算神经网络的损失,计算下列损失函数只需要一行代码:

练习:实现交叉熵损失函数。

# Create the placeholders for "logits" (z) and "labels" (y) (approx. 2 lines)
z = tf.placeholder(tf.float32, name='z')
y = tf.placeholder(tf.float32, name='y')# Use the loss function (approx. 1 line)
cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=z, labels=y)# Create a session (approx. 1 line). See method 1 above.
sess = tf.Session()# Run the session (approx. 1 line).
cost = sess.run(cost, feed_dict={z:logits, y:labels})# Close the session (approx. 1 line). See method 1 above.
sess.close()

1.4 - Using One Hot encodings

将y向量转化为one-hot向量:

只需要一行代码:

tf.one_hot(labels, depth, axis)

练习:实现下面的函数,获取标签的一个向量和类别的总数C,并返回一个one-hot编码。

# Create a tf.constant equal to C (depth), name it 'C'. (approx. 1 line)
C = tf.constant(C, name='C')# Use tf.one_hot, be careful with the axis (approx. 1 line)
one_hot_matrix = tf.one_hot(labels, C, axis=0)# Create the session (approx. 1 line)
sess = tf.Session()# Run the session (approx. 1 line)
one_hot = sess.run(one_hot_matrix)# Close the session (approx. 1 line). See method 1 above.
sess.close()

1.5 - Initialize with zeros and ones

初始化一个全0向量和一个全1向量,将要用到的是tf.ones()和tf.zeros()函数。

练习:实现下面的函数以形成一个形状并返回数组(形状的维数为1)。

# Create "ones" tensor using tf.ones(...). (approx. 1 line)
ones = tf.ones(shape=shape)# Create the session (approx. 1 line)
sess = tf.Session()# Run the session to compute 'ones' (approx. 1 line)
ones = sess.run(ones)# Close the session (approx. 1 line). See method 1 above.
sess.close()

2 - Building your first neural network in tensorflow

使用Tensorflow构建一个神经网络,一个Tensorflow模块需要实现的两步:

  1. 创建一个计算图
  2. 运行它

2.0 - Problem statement: SIGNS Dataset

  • 训练集:1080张手势图片(64 x 64像素)表示0到5之间的数字(每个数字180张图片)
  • 测试集:120张手势图片(64 x 64像素)表示0到5之间的数字(每个数字20张图片)

这就是SIGNS数据集的一个子集,完整的数据集包含更多手势。

数据集中的原始图片:

载入数据:

# Loading the dataset
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()

更改下面的索引并运行单元以可视化数据集中的一些示例。

# Example of a picture
index = 0
plt.imshow(X_train_orig[index])
print ("y = " + str(np.squeeze(Y_train_orig[:, index])))

结果为y = 5

像往常一样,将图像数据集展平,然后除以255将其归一化。除此之外,把每个标签转换为一个one-hot向量。运行下面的单元进行此操作。

# Flatten the training and test images
X_train_flatten = X_train_orig.reshape(X_train_orig.shape[0], -1).T
X_test_flatten = X_test_orig.reshape(X_test_orig.shape[0], -1).T
# Normalize image vectors
X_train = X_train_flatten/255.
X_test = X_test_flatten/255.
# Convert training and test labels to one hot matrices
Y_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))

结果为:

number of training examples = 1080

number of test examples = 120

X_train shape: (12288, 1080)

Y_train shape: (6, 1080)

X_test shape: (12288, 120)

Y_test shape: (6, 120)

注意12288来自于64×64×3,每张图片都是64×64像素,RGB3通道。

目标是建立一种能够高精度识别手势的算法。要做到这一点,您将构建一个TensorFlow模型,该模型几乎与以前在numpy中为cat识别构建的模型相同(但现在使用的是softmax输出)。这是一个比较Numpy实现和TensorFlow实现的好时机。

模型是LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX,SIGMOID输出层换成了SOFTMAX,当有两个以上的类时,由SIGMOID泛化为SOFTMAX层。

2.1 - Create placeholders

第一步是创建X和Y的占位符,使得之后运行会话时能喂入训练数据。

练习:创建占位符。

X = tf.placeholder(shape=[n_x, None], dtype=tf.float32)
Y = tf.placeholder(shape=[n_y, None], dtype=tf.float32)

2.2 - Initializing the parameters

第二步是初始化参数。

练习:使用Xavier初始化权重,Zero初始化偏置。

W1 = tf.get_variable(name='W1', shape=[25, 12288], initializer=tf.contrib.layers.xavier_initializer(seed=1))
b1 = tf.get_variable(name='b1', shape=[25, 1], initializer=tf.zeros_initializer())
W2 = tf.get_variable(name='W2', shape=[12, 25], initializer=tf.contrib.layers.xavier_initializer(seed=1))
b2 = tf.get_variable(name='b2', shape=[12, 1], initializer=tf.zeros_initializer())
W3 = tf.get_variable(name='W3', shape=[6, 12], initializer=tf.contrib.layers.xavier_initializer(seed=1))
b3 = tf.get_variable(name='b3', shape=[6, 1], initializer=tf.zeros_initializer())

2.3 - Forward propagation in tensorflow

实现前向传播模块,函数将接受一个参数字典,它将完成前向传递。

问题:需要注意的是,正向传播在z3处停止。其原因是,在Tensorflow中,最后一个线性层输出作为计算损失的函数的输入。因此,您不需要A3!

Z1 = tf.matmul(W1, X) + b1                          # Z1 = np.dot(W1, X) + b1
A1 = tf.nn.relu(Z1)                                 # A1 = relu(Z1)
Z2 = tf.matmul(W2, A1) + b2                         # Z2 = np.dot(W2, a1) + b2
A2 = tf.nn.relu(Z2)                                 # A2 = relu(Z2)
Z3 = tf.matmul(W3, A2) + b3                         # Z3 = np.dot(W3,Z2) + b3

2.4 Compute cost

问题:实现损失函数。

  • 重要的是要知道tf.nn.softmax_cross_entropy_with_logits的输入"logits"和"labels"的形状应该是(number of examples, num_classes),因此需要转置Z3和Y。
  • 此外,tf.reduce_mean会对所有样本进行求和。
# to fit the tensorflow requirement for tf.nn.softmax_cross_entropy_with_logits(...,...)
logits = tf.transpose(Z3)
labels = tf.transpose(Y)cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels))

2.5 - Backward propagation & parameter updates

在计算损失函数之后。您将创建一个“optimizer”对象。在运行tf.session时,您必须调用这个对象以及损失。当调用时,它将使用所选的优化方法和学习率对给定的损失进行优化。

举个例子,梯度下降的优化器如下:

optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(cost)

为了优化需要如下一步:

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

2.6 - Building the model

练习:实现整个模型。

def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,num_epochs = 1500, minibatch_size = 32, print_cost = True):"""Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.Arguments:X_train -- training set, of shape (input size = 12288, number of training examples = 1080)Y_train -- test set, of shape (output size = 6, number of training examples = 1080)X_test -- training set, of shape (input size = 12288, number of training examples = 120)Y_test -- test set, of shape (output size = 6, number of test examples = 120)learning_rate -- learning rate of the optimizationnum_epochs -- number of epochs of the optimization loopminibatch_size -- size of a minibatchprint_cost -- True to print the cost every 100 epochsReturns:parameters -- parameters learnt by the model. They can then be used to predict."""tf.reset_default_graph()                         # to be able to rerun the model without overwriting tf variablestf.set_random_seed(1)                             # to keep consistent resultsseed = 3                                          # to keep consistent results(n_x, m) = X_train.shape                          # (n_x: input size, m : number of examples in the train set)n_y = Y_train.shape[0]                            # n_y : output sizecosts = []                                        # To keep track of the cost# Create Placeholders of shape (n_x, n_y)### START CODE HERE ### (1 line)X, Y = create_placeholders(n_x, n_y)### END CODE HERE #### Initialize parameters### START CODE HERE ### (1 line)parameters = initialize_parameters()### END CODE HERE #### Forward propagation: Build the forward propagation in the tensorflow graph### START CODE HERE ### (1 line)Z3 = forward_propagation(X, parameters)### END CODE HERE #### Cost function: Add cost function to tensorflow graph### START CODE HERE ### (1 line)cost = compute_cost(Z3, Y)### END CODE HERE #### Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer.### START CODE HERE ### (1 line)optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)### END CODE HERE #### Initialize all the variablesinit = tf.global_variables_initializer()# Start the session to compute the tensorflow graphwith tf.Session() as sess:# Run the initializationsess.run(init)# Do the training loopfor epoch in range(num_epochs):epoch_cost = 0.                       # Defines a cost related to an epochnum_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train setseed = seed + 1minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)for minibatch in minibatches:# Select a minibatch(minibatch_X, minibatch_Y) = minibatch# IMPORTANT: The line that runs the graph on a minibatch.# Run the session to execute the "optimizer" and the "cost", the feedict should contain a minibatch for (X,Y).### START CODE HERE ### (1 line)_ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X:minibatch_X,Y:minibatch_Y})### END CODE HERE ###epoch_cost += minibatch_cost / num_minibatches# Print the cost every epochif 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 costplt.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 variableparameters = sess.run(parameters)print ("Parameters have been trained!")# Calculate the correct predictionscorrect_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))# Calculate accuracy on the test setaccuracy = 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

结果如下:

思考:

  • 模型似乎过拟合了,考虑到训练集和测试集准确率的不同,可以加上L2正则化或者dropout正则化来减少过拟合。
  • 把会话看作是训练模型的代码块。每次在mini-batch上运行会话时,它都会训练参数。总的来说,在获得良好的训练参数之前,您已经多次运行该会话(1500个epoch)。

2.7 - Test with your own image (optional / ungraded exercise)

import scipy
from PIL import Image
from scipy import ndimage## START CODE HERE ## (PUT YOUR IMAGE NAME)
my_image = "thumbs_up.jpg"
## END CODE HERE ### We preprocess your image to fit your algorithm.
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(64,64)).reshape((1, 64*64*3)).T
my_image_prediction = predict(my_image, parameters)plt.imshow(image)
print("Your algorithm predicts: y = " + str(np.squeeze(my_image_prediction)))

结果为Your algorithm predicts: y = 3

deeplearning.ai——TensorFlow指南相关推荐

  1. 吴恩达 deeplearning.ai 新课上线:TensorFlow 移动和 web 端机器学习

    点击上方"深度学习技术前沿",选择"星标"公众号 资源干货,第一时间送达 转自 | 机器之心 参与 | 杜伟.一鸣 Coursera 又有 TensorFlow ...

  2. 吴恩达深度学习课程deeplearning.ai课程作业:Class 2 Week 3 TensorFlow Tutorial

    吴恩达deeplearning.ai课程作业,自己写的答案. 补充说明: 1. 评论中总有人问为什么直接复制这些notebook运行不了?请不要直接复制粘贴,不可能运行通过的,这个只是notebook ...

  3. 吴恩达deeplearning.ai新课上线:TensorFlow移动和web端机器学习

    点上方蓝字计算机视觉联盟获取更多干货 在右上方 ··· 设为星标 ★,与你不见不散 编辑:Sophia 计算机视觉联盟  报道  | 公众号 CVLianMeng 转载于 :Coursera ,机器之 ...

  4. STM32运行深度学习指南基础篇(3)(STM32CubeMX.AI+Tensorflow)

    STM32运行深度学习指南基础篇(3)(STM32CubeMX.AI+Tensorflow) 在上一篇文章中我们已经有训练好的tflite模型,接下来我们要在Clion中实现,如果是Keil的朋友可以 ...

  5. 《DeepLearning.ai 深度学习笔记》发布,黄海广博士整理

    深度学习入门首推课程就是吴恩达的深度学习专项课程系列的 5 门课.该专项课程最大的特色就是内容全面.通俗易懂并配备了丰富的实战项目.今天,给大家推荐一份关于该专项课程的核心笔记!这份笔记只能用两个字形 ...

  6. 吴恩达Deeplearning.ai国庆节上新:生成对抗网络(GAN)专项课程

    机器之心报道 作者:蛋酱 Coursera 刚刚上新了 GAN 的专项课程,或许在这个国庆假期,你应该学习一波了. 生成对抗网络(Generative Adversarial Network,GAN) ...

  7. 吴恩达deeplearning.ai发布NLP课程!

    来源:大数据文摘 本文约6000字,建议阅读10分钟 吴恩达的自然语言处理课程开课啦! 虽然眨眼半年过去,马上就放暑假了,大家宅家里有好好学习吗? 今天的这个重磅炸弹,或许可以帮助你改掉拖延症. 没错 ...

  8. 独家 | 一文读懂序列建模(deeplearning.ai)

    作者:Pulkit Sharma,2019年1月21日 翻译:陈之炎 校对:丁楠雅 本文约11000字,建议阅读10+分钟. 本文为你详细介绍序列模型,并分析其在不同的真实场景中的应用. 简介 如何预 ...

  9. 一文读懂序列建模(deeplearning.ai)之序列模型与注意力机制

    https://www.toutiao.com/a6663809864260649485/ 作者:Pulkit Sharma,2019年1月21日 翻译:陈之炎 校对:丁楠雅 本文约11000字,建议 ...

  10. 心得丨吴恩达Deeplearning.ai 全部课程学习心得分享

    选自Medium作者:Ryan Shrott    机器之心编译 本文作者,加拿大国家银行首席分析师 Ryan Shrott 完成了迄今为止(2017 年 10 月 25 日)吴恩达在 Courser ...

最新文章

  1. LevelDb系列之简介
  2. Android 开源库获取途径整理
  3. boost::math::barycentric_rational用法的测试程序
  4. JavaBean的get、set方法生成器
  5. mysql 的驱动是多少_mysql驱动参数变化
  6. 基于JAVA springboot+mybatis 电商书城平台系统设计和实现
  7. EXP-00091: Exporting questionable statistics.问题解决!(转)
  8. css3实现动画的三种方式
  9. keil5 c语言函数库,C语言中KeilC51库函数大全.doc
  10. 销售开发新客户的方法 如何开拓新客户
  11. 代理服务器介绍及种类划分
  12. matlab编程刀尖频响,用半理论法预测主轴系统刀尖点频响函数
  13. Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask
  14. 计算机无法连接富士网络打印机,网络打印机无法连接的解决方法是什么
  15. 效果最好的助眠好物,帮助睡眠的好方法
  16. 数据库DB之MySQLOracle
  17. ​Excel如何转换成Word文档?教你如何实现转换
  18. 元宇宙文旅ar技术方案及场景
  19. 中国风水墨风廉洁公正行政汇报PPT模板
  20. (linux自学笔记)linux系统初体验与编程基础

热门文章

  1. 转:用Winform实现屏幕小键盘
  2. 【从C到C++学习笔记】程序/结构化程序设计/面向对象的程序设计
  3. 【GDB调试学习笔记】利用core文件调试程序
  4. 【GDB调试学习笔记】Makefile生成多个可执行文件
  5. 组合模式与职责链模式编程实现
  6. 智能优化算法:金鹰优化算法-附代码
  7. 【C++】指针遍历二维数组若干种方法小结
  8. Flutter之Binding简单梳理
  9. Flutter动画系列之SizeTransition
  10. 计算机解决的气象复杂问题,自动气象站更换时计算机遇到的疑难问题及解决办法...