本文参考了https://blog.csdn.net/weixin_47440593/article/details/107938235
欢迎来到课程4的第二次作业!在这个笔记本里,你会:
·实现在实现TensorFlow模型时将使用的辅助函数
·使用TensorFlow实现一个功能完整的卷积网络
After this assignment you will be able to:
·针对一个分类问题,在TensorFlow中建立并训练一个卷积网络
我们假设你已经熟悉TensorFlow了。如果你不是,请参考课程2第三周的TensorFlow教程(“改善深度神经网络”)。
1.0 - TensorFlow model TensorFlow模型
在上一个任务中,您使用numpy构建了帮助函数,以理解卷积神经网络背后的机制。目前,深度学习的大多数实际应用程序都是使用编程框架构建的,这些框架具有许多可以简单调用的内置函数。
像往常一样,我们将从装入包开始。
import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from cnn_utils import * %matplotlib inline np.random.seed(1)
这里好的答案或者参考都没有使用scipy,暂时还不知道原因
运行下一个单元格以加载将要使用的“sign”数据集。
# Loading the data (signs) X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
提醒一下,符号数据集是6个符号的集合,它们代表从0到5的数字。
下一个单元格将向您展示数据集中的标记图像示例。您可以随意更改下面的index值并重新运行以查看不同的示例。
# Example of a picture index = 8 plt.imshow(X_train_orig[index]) print ("y = " + str(np.squeeze(Y_train_orig[:, index])))
运行结果:
在课程2中,您已经为这个数据集构建了一个完全连接的网络。但由于这是一个图像数据集,应用卷积神经网络更自然。
首先,让我们研究一下数据的形状。
在课程2中,我们已经建立过一个神经网络,我想对这个数据集应该不陌生吧~我们再来看一下数据的维度,如果你忘记了独热编码的实现,请看这里
X_train = X_train_orig/255. X_test = X_test_orig/255. Y_train = convert_to_one_hot(Y_train_orig, 6).T Y_test = convert_to_one_hot(Y_test_orig, 6).T print ("number of training examples = " + str(X_train.shape[0])) print ("number of test examples = " + str(X_test.shape[0])) 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)) conv_layers = {}
执行结果:
number of training examples = 1080 number of test examples = 120 X_train shape: (1080, 64, 64, 3) Y_train shape: (1080, 6) X_test shape: (120, 64, 64, 3) Y_test shape: (120, 6)
1.1 - Create placeholders 创建占位符
TensorFlow要求您为运行会话时将输入到模型中的输入数据创建占位符。现在我们要实现创建占位符的函数,因为我们使用的是小批量数据块,输入的样本数量可能不固定,所以我们在数量那里我们要使用None作为可变数量。输入X的维度为**[None,n_H0,n_W0,n_C0],对应的Y是[None,n_y]**
1 # GRADED FUNCTION: create_placeholders 2 3 def create_placeholders(n_H0, n_W0, n_C0, n_y): 4 """ 5 Creates the placeholders for the tensorflow session. 为session创建占位符 6 7 Arguments: 8 n_H0 -- scalar, height of an input image 实数,输入图像的高度 9 n_W0 -- scalar, width of an input image 实数,输入图像的宽度 10 n_C0 -- scalar, number of channels of the input 实数,输入的通道数 11 n_y -- scalar, number of classes 实数, 分类数 12 13 Returns: 14 X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype "float" 15 输入数据的占位符,维度为[None, n_H0, n_W0, n_C0],类型为"float" 16 Y -- placeholder for the input labels, of shape [None, n_y] and dtype "float" 17 输入数据的标签的占位符,维度为[None, n_y],维度为"float" 18 """ 19 20 ### START CODE HERE ### (≈2 lines) 21 X = tf.compat.v1.placeholder(tf.float32, [None, n_H0, n_W0, n_C0]) 22 Y = tf.compat.v1.placeholder(tf.float32, [None, n_y]) 23 ### END CODE HERE ### 24 25 return X, Y