整理-具有神经网络思维的Logistic回归-涉及的函数均作详解-适合新手
首先声明本文参考【何宽】的CSDN论坛的博客,本文参考(https://blog.csdn.net/u013733326/article/details/79639509),我基于他的文章,为了更方便新手,整理对程序中涉及的函数一一备注,作出适当解释,力求让大家以最轻松最快速的姿态理解吴恩达的具有神经网络思维的Logistic回归作业,如有不妥的地方欢迎大家指正。
下面直接上程序,十分建议结合上文连接和本文来学习Logistic回归,资料也请从上面链接去获取。
import numpy as np
"""Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy、matplotlib一起使用。
其实,list已经提供了类似于矩阵的表示形式,不过numpy为我们提供了更多的函数。
NumPy数组是一个多维数组对象,称为ndarray。数组的下标从0开始,同一个NumPy数组中所有元素的类型
必须是相同的。
np.ones: 创建一个数组, 其中的元素全为 1
np.zeros: 创建元素全为 0 的数组, 类似 np.ones
np.empty创建一个内容随机并且依赖与内存状态的数组。
np.eye: 创建一个对角线为 1 其他为 0 的矩阵.
np.identity: 创建一个主对角线为 1 其他为 0 的方阵.
"""
import matplotlib.pyplot as plt
import h5py
from lr_utils import load_dataset
train_set_x_orig,train_set_y,test_set_x_orig,test_set_y,classes = load_dataset()
index=25
plt.imshow(train_set_x_orig[index])
plt.show()
print("y=" + str(train_set_y[:,index]) + ",it's a " + classes[np.squeeze(train_set_y[:,index])].decode("utf-8") + "' picture")
"""
#打印出当前的训练标签值
#使用np.squeeze的目的是压缩维度,【未压缩】train_set_y[:,index]的值为[1] , 【压缩后】np.squeeze(train_set_y[:,index])的值为1
#print("【使用np.squeeze:" + str(np.squeeze(train_set_y[:,index])) + ",不使用np.squeeze: " + str(train_set_y[:,index]) + "】")
#只有压缩后的值才能进行解码操作
"""
m_train = train_set_y.shape[1] #训练集里图片的数量
m_test = test_set_y.shape[1] #测试集里图片的数量
num_px = train_set_x_orig.shape[1] #训练、测试集里面的图片的宽度和高度(均为64*64)
#看一看加载的东西的具体情况
print("训练集的数量:m_train = " + str(m_train))
print("测试集的数量:m_test = " + str(m_test))
print("每张图片的宽/高:num_px = " + str(num_px))
print("每张图片的大小:(" + str(num_px) + "," + str(num_px) + ",3)")
print("训练集_图片的维数:" + str(train_set_x_orig.shape))
print("训练集_标签的维数:" + str(train_set_y.shape))
print("测试集_图片的维数:" + str(test_set_x_orig.shape))
print("测试集_标签的维数:" + str(test_set_y.shape))
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T #将训练集的维度降低并转置
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T #将测试集的维度降低并转置
print("训练集降维最后的维度:" + str(train_set_x_flatten.shape))
print("训练集_标签的维数:" + str(train_set_y.shape))
print("测试集降维之后的维度:" + str(test_set_x_flatten.shape))
print("测试集_标签的维数:" + str(test_set_y.shape))
train_set_x = train_set_x_flatten / 255
test_set_x = test_set_x_flatten / 255
def sigmoid(z):
"""参数z:任何大小的标量或numpy数组"""
s = 1 / (1 + np.exp(-z)) #np.exp(-z)即是e^-z
return s
#测试sigmoid()
print("------测试sigmoid------")
print("sigmoid(0) = " + str(sigmoid(0)))
print("sigmoid(9.2) = " + str(sigmoid(9.2)))
def initialize_with_zeros(dim):
"""
此函数为w创建一个维度为(dim,1)的0向量,并将b初始化为0
参数dim:我们想要的w矢量的大小(或者这种情况下的参数数量)
返回:w - 维度为(dim,1)的初始化向量,b - 初始化的标量(对应于偏差)
"""
w = np.zeros(shape = (dim,1)) #创建一个维度为(dim,1)的0向量
b = 0 #初始化的标量
#使用断言来确保我要的数据是正确的
#当程序运行到某个节点的时候,就断定某个变量的值必然是什么,或者是对象必然拥有某个属性等。
# 简单点来说的话,就是断定是什么东西就必然是什么东西,如果不是,就抛出异常。
assert(w.shape == (dim,1)) #w的维度是(dim,1)
assert(isinstance(b,float) or isinstance(b,int)) #b的类型是float或者是int
return(w,b)
def propagate(w,b,X,Y):
"""
实现前向和后向传播的成本函数及其梯度
参数:
w - 权重,大小不等的数组(num_px * num_px * 3,1)
b - 偏差,一个标量
X - 矩阵类型为(num_px * num_px * 3,训练数量)
Y - 真正的“标签”矢量(如果非猫则为0,如果是猫则为1),矩阵维度为(1,训练数据数量)
返回:
cost - 逻辑回归的负对数似然成本
dw - 相对于w的损失梯度,因此与w相同的形状
db - 相对于b的损失梯度,因此与b形状相同
"""
m = X.shape[1]
#正向传播
A = sigmoid(np.dot(w.T,X)+b) #计算激活值,请参考公式2
cost = (-1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A))) #计算成本,请参考公式3和4
#反向传播
dw = (1 / m) * np.dot(X,(A - Y).T) #偏导
#np.dot:如果处理的是一维数组,则得到的是两数组的內积,如果是二维数组(矩阵)之间的运算,则得到的是矩阵积
db = (1 / m) * np.sum(A - Y) #偏导
#使用断言确保我的数据是正确
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost) #squeeze 函数:从数组的形状中删除单维度条目,即把shape中为1的维度去掉
assert(cost.shape == ())
#创建一个字典,把dw和db保存起来
grads = {"dw":dw,"db":db}
return (grads,cost)
#测试一下propagate
print("------测试propagate------")
#初始化一些参数
w,b,X,Y = np.array([[1],[2]]),2,np.array([[1,2],[3,4]]),np.array([[1,0]])
grads,cost=propagate(w,b,X,Y)
print("dw = " + str(grads["dw"]))
print("db = " + str(grads["db"]))
print("cost = " + str(cost))
def optimize(w,b,X,Y,num_iterations,learning_rate,print_cost=False):
"""
此函数通过运行梯度下降算法来优化w和b
参数:
w - 权重,大小不等的数组(num_px * num_px * 3,1)
b - 偏差,一个标量
X - 维度为(num_px *num_px * 3,1)
Y - 真正的“标签”矢量(如果非猫则为0,如果是猫则为1),矩阵维度为(1,训练数据的数量)
num_iterations - 优化循环的迭代次数
learning_rate - 梯度下降更新规则的学习率
print_cost - 每100步打印一次损失值
返回:
params - 包含权重w和偏差b的字典
grads - 包含权重和偏差相对于成本函数的梯度的字典
成本 - 优化期间计算的所有成本列表,将用于绘制学习曲线。
提示:
我们需要写下两个步骤并遍历它们:
1)计算当前参数的成本和梯度,使用propagate()。
2)使用w和b的梯度下降法则更新参数。
"""
costs = []
for i in range(num_iterations):
grads,cost = propagate(w,b,X,Y)
dw = grads["dw"]
db = grads["db"]
w = w - learning_rate * dw
b = b - learning_rate * db
#记录成本
if i % 100 == 0:
costs.append(cost)
#打印成本数据
if (print_cost) and (i % 100 == 0):
print("迭代的次数:%i,误差值:%f" % (i,cost))
params = {"w":w,"b":b}
grads = {"dw":dw,"db":db}
return (params,grads,costs)
#测试optimize
print("------测试optimize------")
w,b,X,Y = np.array([[1],[2]]),2,np.array([[1,2],[3,4]]),np.array([[1,0]])
params,grads,costs = optimize(w,b,X,Y,num_iterations=100,learning_rate=0.009,print_cost=False)
print ("w = " + str(params["w"]))
print ("b = " + str(params["b"]))
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
def predict(w,b,X):
"""
使用学习逻辑回归参数logistic (w,b)预测标签是0还是1,
参数:
w - 权重,大小不等的数组(num_px * num_px * 3,1)
b - 偏差,一个标量
X - 维度为(num_px * num_px * 3,训练数据的数量)的数据
返回:
Y_prediction - 包含X中所有图片的所有预测【0 | 1】的一个numpy数组(向量)
"""
m = X.shape[1] #图片的数量
"""
shape函数是numpy.core.fromnumeric中的函数,它的功能是读取矩阵的长度,
比如shape[0]就是读取矩阵第一维度的长度。
shape的输入参数可以是一个整数(表示维度),也可以是一个矩阵。
"""
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0],1) #reshape函数:改变数组的维数
#计预测猫在图片中出现的概率
A = sigmoid(np.dot(w.T,X) + b)
for i in range(A.shape[1]):
#将概率a[0,i]转换为实际预测p[0,i]
Y_prediction[0,i] = 1 if A[0,1] > 0.5 else 0
#使用断言
assert(Y_prediction.shape == (1,m))
return Y_prediction
#测试predict
print("------测试predict------")
w,b,X,Y = np.array([[1],[2]]),2,np.array([[1,2],[3,4]]),np.array([[1,0]])
print("predictions = " + str(predict(w,b,X)))
def model(X_train,Y_train,X_test,Y_test,num_iterations=2000,learning_rate=0.5,print_cost=False):
"""
通过调用之前实现的函数来构建逻辑回归模型
参数:
X_train - numpy的数组,维度为(num_px * num_px * 3,m_train)的训练集
Y_train - numpy的数组,维度为(1,m_train)(矢量)的训练标签集
X_test - numpy的数组,维度为(num_px * num_px * 3,m_test)的测试集
Y_test - numpy的数组,维度为(1,m_test)的(向量)的测试标签集
num_iterations - 表示用于优化参数的迭代次数的超参数
learning_rate - 表示optimize()更新规则中使用的学习速率的超参数
print_cost - 设置为true以每100次迭代打印成本
返回:
d - 包含有关模型信息的字典。
"""
w,b = initialize_with_zeros(X_train.shape[0])
parameters,grads,costs = optimize(w,b,X_train,Y_train,num_iterations,learning_rate,print_cost)
#从字典“参数”中检索参数w和b
w,b = parameters["w"],parameters["b"]
#预测测试/训练集的例子
Y_prediction_test = predict(w,b,X_test)
Y_prediction_train = predict(w,b,X_train)
#打印训练后的准确性
print("训练集准确性:",format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100),"%") #mean()函数功能:求取均值
print("测试集准确性:",format(100 - np.mean(np.abs(Y_prediction_test - Y_test))*100),"%") #abs() 函数返回数字的绝对值
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
print("------测试model------")
#这里加载的是真实的数据,请参见上面的代码部分
d = model(train_set_x,train_set_y,test_set_x,test_set_y,num_iterations=2000,learning_rate=0.005,print_cost=True)
#绘制图
costs = np.squeeze(d['costs'])
"""
squeeze()函数的用法:
在机器学习和深度学习中,通常算法的结果是可以表示向量的数组(即包含两对或以上的方括号形式[[]]),
如果直接利用这个数组进行画图可能显示界面为空(见后面的示例)。我们可以利用squeeze()函数将表示向量
的数组转换为秩为1的数组,这样利用matplotlib库函数画图时,就可以正常的显示结果了。
"""
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations(per hundreds)')
plt.title("Learning rate = " + str(d["learning_rate"]))
plt.show()
learning_rates = [0.01,0.001,0.0001]
models = {}
for i in learning_rates:
print("learning rate is:"+str(i))
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(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) #loc:图例所有figure位置;shadow:控制是否在图例后面画一个阴影
#设置图例legend背景颜色
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()
运行结果: