本文是Deep Learning Specialization系列课程的第1课《Neural Networks and Deep Learning》中Logistic Regression with a Neural Network mindset练习部分的笔记。
在《02 神经网络 - 神经网络和深度学习 [Deep Learning Specialization系列]》中,我们了解了神经网络的大部分理论知识。通过该编程实例,我们能构建一个简答的逻辑回归的分类器来识别猫,以复习神经网路的知识并了解具体的编程实现。
概述
本试验使用的是h5
格式的数据集,该数据集包含有标注结果的训练数据和测试数据,通过以下7个步骤来完成神经网络的训练和预测:
- 数据加载
- 数据处理
- 参数初始化
- 逻辑回归函数的实现(正向传播)
- 损失/代价函数的实现(正向传播)
- 梯度递减算法的实现(反向传播)
- 预测
1. 数据加载
h5
格式的数据的读取是通过h5py库来实现的,简单的介绍可以参考我的上一篇文章《h5py - HDF5 for Python的简单入门》。
首先构建一个load_dataset()
函数来完成数据的加载,该函数通过h5py.File()
函数来读取h5
格式的数据文件,将训练数据和测试数据做一个简单处理后,输出train_set_x_orig
, train_set_y_orig
, test_set_x_orig
, test_set_y_orig
, 和classes
。
在通过相对路径来读取h5
文件时,会报错:
OSError: Unable to open file (unable to open file: name = 'datasets/mytestfile.hdf5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)
目前还没找到比较好的方式,只能在h5py.File()
函数中指定该文件的绝对路径来读取。
这是该数据的一些特点:
- train_set_x_orig shape: (209, 64, 64, 3)
- train_set_y_orig shape: (1, 209)
- test_set_x_orig shape: (50, 64, 64, 3)
- test_set_y_orig shape: (1, 50)
数据加载:
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
2. 数据处理
数据处理分为两部分:
- 向量化:需要把三维的图像数据
(num_px, num_px, 3)
向量化,reshape成一维向量(num_px * num_px * 3, 1)
: - 标准化:由于图像的像素值是0-255,这里除以255以将其标准化为0-1的数据。
# Vectorization
train_set_x_orig_flatten = train_set_x_orig.reshape(train_set_x_orig[:].shape[0], -1).T
# Standardization
train_set_x = train_set_x_orig_flatten/255
3. 参数初始化
将参数w
和b
初始化为0的向量。这里需要注意的是参数的维度,需要与训练数据一致。
def initialize_with_zeros(dim):
w = np.zeros((dim, 1))
b = 0
return w, b
4. 逻辑回归函数的实现
从这里开始就进入了正向传播(Forward Propagation)了。
逻辑回归函数的实现主要包含两部分:
- 逻辑回归函数: z ( i ) = w T x ( i ) + b z^{(i)} = w^T x^{(i)} + b z(i)=wTx(i)+b
- 激活函数: y ^ ( i ) = a ( i ) = s i g m o i d (