1 问题背景
不借助工具包,从0开始搭建一个5层或多层的二类分类器,也就是对图片中是否有小猫进行分类。问题输入为64*64的RGB图像,当然也可以改变输入大小,有2个途径:一个改变图片大小,二是改变输入层大小。问题输入为0或1,当前也可以改变输出层大小实现更多目标分类。
2 环境设置
import numpy as np #基本操作
import h5py #数据集
import matplotlib.pyplot as plt #画图
from PIL import Image #图像处理
from dnn_app_utils_v2 import * #
%matplotlib inline #画图的设置
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
3 数据处理
输入是一张图片,大小为64*64*3,值范围为(0,255),需要处理为12288*1,值范围(0,1)。
#数据导入
train_x_orig, train_y, test_x_orig, test_y, classes = load_data()
#数据大小和数量
m_train = train_x_orig.shape[0] #209
num_px = train_x_orig.shape[1] #64
m_test = test_x_orig.shape[0] #50
#
train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T
test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T
train_x = train_x_flatten/255. #shape(12288, 209)
test_x = test_x_flatten/255. #shape(12288, 50)
4 模型框架
#模型层数
layers_dims = [12288, 20, 7, 5, 1]
#循环训练
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
np.random.seed(1)
costs = [] # 损失记录
#初始化W、b
parameters = initialize_parameters_deep(layers_dims)
#迭代训练
for i in range(0, num_iterations):
#前向传播
AL, caches = L_model_forward(X, parameters)
#损失计算
cost = compute_cost(AL, Y)
#反向传播
grads = L_model_backward(AL, Y, caches)
#更新W、b
parameters = update_parameters(parameters, grads, learning_rate)
# 损失值观测
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
if print_cost and i % 100 == 0:
costs.append(cost)
# 损失曲线
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
5 模型训练
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True)
Cost after iteration 0: 0.771749
Cost after iteration 100: 0.672053
Cost after iteration 200: 0.648263
Cost after iteration 300: 0.611507
Cost after iteration 400: 0.567047
Cost after iteration 500: 0.540138
Cost after iteration 600: 0.527930
Cost after iteration 700: 0.465477
Cost after iteration 800: 0.369126
Cost after iteration 900: 0.391747
Cost after iteration 1000: 0.315187
Cost after iteration 1100: 0.272700
Cost after iteration 1200: 0.237419
Cost after iteration 1300: 0.199601
Cost after iteration 1400: 0.189263
Cost after iteration 1500: 0.161189
Cost after iteration 1600: 0.148214
Cost after iteration 1700: 0.137775
Cost after iteration 1800: 0.129740
Cost after iteration 1900: 0.121225
Cost after iteration 2000: 0.113821
Cost after iteration 2100: 0.107839
Cost after iteration 2200: 0.102855
Cost after iteration 2300: 0.100897
Cost after iteration 2400: 0.092878
6 模型预测
pred_train = predict(train_x, train_y, parameters)
pred_test = predict(test_x, test_y, parameters)
Accuracy: 0.9856459330143539
Accuracy: 0.8
7 误差分析
print_mislabeled_images(classes, test_x, test_y, pred_test)
- 猫的身体处于不寻常的位置