提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
一、所需要的包
Numpy 是使用 Python 进行科学计算的基本软件包。
H5py 是与存储在 H5文件中的数据集交互的常用包。
Matplotlib 是在 Python 中绘制图形的著名库。
在这里使用 PIL 和 scipy 来测试您的模型与您自己的图片在最后。
二、整体步骤
-
加载数据
-
重塑数据
-
进行数据预处理:数据预处理的常见步骤:
1.找出问题的大小和形状(m _ train,m _ test,num _ px,…)
2.重新塑造数据集,使每个示例现在都是一个大小向量(num _ px * num _ px * 3,1)
3.“标准化”数据 -
构造算法:将执行以下步骤:
-
初始化模型参数
-
尽量减低成本,以了解模型的参数
-
使用学到的参数作出预测(在测试集上)
-
分析结果并得出结论
-
-
进行优化
-
进行预测
-
整合模型并运行
三、实现步骤
1.导包
代码如下(示例):
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
# 在Notebook中显示matplotlib绘制的图形,并将图形嵌入到Notebook中
%matplotlib inline
2.标题加载数据(猫/不是猫)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()```
train_set_x_orig: 原始训练集特征
train_set_y: 训练集标签
test_set_x_orig: 原始测试集特征
test_set_y: 测试集标签
classes: 包含两个元素的numpy数组,分别表示两个分类标签,例如[“non-cat”, “cat”]
3.图片显示的例子
index = 5#设置了要显示的图片在训练集中的索引,即第6张图片(索引从0开始)。
plt.imshow(train_set_x_orig[index]) #显示训练集中第 index 张图片,train_set_x_orig[index] 是一个三维数组,表示图片的像素值。
# train_set_y[:, index] 是一个形状为 (1, m_train) 的数组,表示第 index 张图片的标签,其中 m_train 是训练样本数量。
#np.squeeze(train_set_y[:, index]) 将数组的维度为1的维度去除,得到一个标量值,即图片的标签。
#classes[np.squeeze(train_set_y[:, index])].decode("utf-8") 使用图片的标签作为索引,从 classes 数组中获取相应的分类标签,并转换为字符串格式。
print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") + "' picture.")
4.获取m_train,m_test,num_px
m_train =train_set_x_orig.shape[0]#返回训练集中图像的数量。
m_test = test_set_x_orig.shape[0]# 返回测试集中图像的数量。
num_px = train_set_x_orig.shape[1]#返回训练集中每张图像的宽度和高度。由于图像是正方形的,所以它们的宽度和高度相等。
5.重塑训练和测试范例
# 重新塑形训练集
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
#将训练集的原始图像数据 train_set_x_orig 展开成一个一维数组,并转置。-1表示将剩余的维度压缩成一维数组. train_set_x_flatten 的形状为 (num_px * num_px * 3, m_train),m_train 是训练样本数量。
# 重新塑形测试集
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
# 与上面相同
6.归一化处理
#由于像素值的范围通常在0到255之间,除以255将所有像素值限制在0到1之间
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
7.构造算法
sigmoid公式
}}
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
s= 1/(1+np.exp(-z))
return s
8.对参数进行初始化
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
Argument:
dim -- size of the w vector we want (or number of parameters in this case)
Returns:
w -- initialized vector of shape (dim, 1)
b -- initialized scalar (corresponds to the bias)
"""
w = np.zeros((dim, 1))
b = 0
assert(w.shape == (dim, 1))#使用断言来验证权重参数 w 的形状是否为 (dim, 1),确保初始化正确。
assert(isinstance(b, float) or isinstance(b, int))#使用断言来验证偏置参数 b 是否为浮点数或整数类型,确保初始化正确。
return w, b
9.计算代价函数和梯度的传播
def propagate(w, b, X, Y):
"""
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)
Return:
cost -- negative log-likelihood cost for logistic regression
dw -- gradient of the loss with respect to w, thus same shape as w
db -- gradient of the loss with respect to b, thus same shape as b
"""
m = X.shape[1]#获取样本数量,即数据集 X 的第二维度。
# 前向传播
A = sigmoid(np.dot(w.T, X) + b) # 前向传播第一步,激活函数,计算预测值 使用 sigmoid 函数将线性函数 w^TX+b 的输出转换为范围在0到1之间的值,表示样本为正类的概率。
#计算损失函数。损失函数使用负对数似然函数表示,包括两部分:真实标签为1时的损失和真实标签为0时的损失。这里使用向量化计算来提高效率。
cost = -1/m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
# 反向传播(从输出到输入)
dw = 1/m * np.dot(X, (A - Y).T) # 相对于w的损失梯度
db = 1/m * np.sum(A - Y) # 相对于b的损失梯度
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)#将损失函数值转换为标量值。
assert(cost.shape == ())
#将计算得到的梯度存储在字典中。
grads = {"dw": dw,
"db": db}
return grads, cost
10.进行优化
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
costs = []
for i in range(num_iterations):
grads, cost = propagate(w, b, X, Y)#调用前面实现的 propagate 函数计算当前模型参数下的梯度和损失函数值。
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
#使用梯度下降算法更新权重参数 w 和偏置 b
w = w - learning_rate * dw
b = b - learning_rate * db
if i % 100 == 0:
costs.append(cost)#每100次迭代记录一次损失函数值
if print_cost and i % 100 == 0:#如果 print_cost 为真且当前迭代是100的倍数,则打印当前迭代次数和损失函数值
print ("Cost after iteration %i: %f" %(i, cost))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs
11.进行预测
def predict(w, b, X):
m = X.shape[1]
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0], 1)#将权重参数w 转换为形状与测试集特征数据 X 相同的二维数组。
A = sigmoid(np.dot(w.T, X) + b) # 计算预测概率
# 将预测概率转换为预测标签
for i in range(A.shape[1]):
# 如果预测概率大于等于0.5,则将对应的预测结果设置为1(正类);否则设置为0(非正类)。
if A[0, i] >= 0.5:
Y_prediction[0, i] = 1
else:
Y_prediction[0, i] = 0
assert(Y_prediction.shape == (1, m))#使用断言验证预测结果的形状为 (1, m)
return Y_prediction
12.整合模型
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)
X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)
num_iterations -- hyperparameter representing the number of iterations to optimize the parameters
learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()
print_cost -- Set to true to print the cost every 100 iterations
Returns:
d -- dictionary containing information about the model.
"""
w, b = initialize_with_zeros(X_train.shape[0])
parameters, gradients, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
w = parameters["w"]
b = parameters["b"]
Y_prediction_train = predict(w, b, X_train)
Y_prediction_test = predict(w, b, X_test)
# Print train/test Errors
print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train" : Y_prediction_train,
"w" : w,
"b" : b,
"learning_rate" : learning_rate,
"num_iterations": num_iterations}
return d
13.运行
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
14.例子
预测一个图片是否是猫
index = 1
plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[int(d["Y_prediction_test"][0,index])].decode("utf-8") + "\" picture.")
15.绘制学习曲线(含成本)
costs = np.squeeze(d['costs'])#从字典 d 中获取损失函数值列表,并使用 np.squeeze() 函数将其转换为一维数组
plt.plot(costs)#使用 plt.plot() 函数绘制损失函数值随迭代次数的变化曲线。
plt.ylabel('cost')#添加 y 轴标签,表示损失函数值。
plt.xlabel('iterations (per hundreds)')#添加 x 轴标签,表示迭代次数(每百次迭代)。
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show()
16.选择学习率
learning_rates = [0.01, 0.001, 0.0001]
models = {}
for i in learning_rates:
print ("learning rate is: " + str(i))
#调用之前实现的 model 函数训练模型,并将训练好的模型存储在字典 models 中。每个模型使用不同的学习率进行训练。
models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)
print ('\n' + "-------------------------------------------------------" + '\n')
for i in learning_rates:
# 使用 plt.plot() 函数绘制每个学习率对应模型的损失函数值随迭代次数的变化曲线,并添加相应的学习率标签。
plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"]))
plt.ylabel('cost')
plt.xlabel('iterations')
legend = plt.legend(loc='upper center', shadow=True)#添加图例,并设置图例的位置和阴影效果。
frame = legend.get_frame()#获取图例的背景框架
frame.set_facecolor('0.90')#设置其背景色。
plt.show()
总结
以上就是本次记录的内容,本文介绍了如何建立一个识别猫的模型分类器