题目要求:构建一个单结点的神经网络,能够识别64*64的cat图片。其中训练集在train_catvnoncat中,测试集在test_catvnoncat中。
所需资源和包:
链接: https://pan.baidu.com/s/1pslul3qqeU2QvKptTtEOhQ 提取码: 348w
解答:
一:前提准备
1:首先数据是以.h5的形式进行存储,熟悉h5的操作
#测试H5的属性
f = h5py.File('./test_catvnoncat.h5','r')
f.keys() #可以查看所有的主键
print([key for key in f.keys()])
print('first, we get values of x:', f['list_classes'][:])#
print('****************************************************\n')
print('then, we get values of y:', f['test_set_x'][:])
print('****************************************************\n')
print('then, we get values of y:', f['test_set_y'][:])
print(f['test_set_x'][:].shape)
print(f['test_set_y'][:].shape)
2:从数据集从挑选一张图片进行展示
#展示图片
train_dataset = h5py.File('./train_catvnoncat.h5', "r")#matlab文件
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
index = 24
plt.imshow(train_set_x_orig[index])
plt.show()
print("this is picture")
3:查看数据集的维度等信息
#测试图片的数量
train_dataset = h5py.File('./train_catvnoncat.h5', "r")#matlab文件
train_set_x = np.array(train_dataset["train_set_x"][:]) # your train set features
train_set_y = np.array(train_dataset["train_set_y"][:]) # your train set labels
test_dataset = h5py.File('./test_catvnoncat.h5', "r")
test_set_x = np.array(test_dataset["test_set_x"][:]) # your test set features
test_set_y = np.array(test_dataset["test_set_y"][:]) # your test set labels
#shape表示所有维,shape[i]表示第i维
m_train = train_set_x.shape[0] #训练集里图片的数量。
m_test = test_set_x.shape[0] #测试集里图片的数量。
num_px = train_set_x.shape[1] #训练、测试集里面的图片的宽度和高度(均为64x64)。
#现在看一看我们加载的东西的具体情况
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.shape))#(209, 64, 64, 3)的四维矩阵
print ("训练集_标签的维数 : " + str(train_set_y.shape))#(209,)的一维矩阵
print ("测试集_图片的维数: " + str(test_set_x.shape))#(50, 64, 64, 3)的四维矩阵
print ("测试集_标签的维数: " + str(test_set_y.shape))#(50,)的一维矩阵
4:将数据进行降低维读处理并转置,之后进行压缩
#将训练集的维度降低并转置。
train_set_x_flatten = train_set_x.reshape(train_set_x.shape[0],-1).T
train_set_y_flatten = train_set_y.reshape((1, train_set_y.shape[0]))
#将测试集的维度降低并转置。
test_set_x_flatten = test_set_x.reshape(test_set_x.shape[0], -1).T
test_set_y_flatten= test_set_y.reshape((1, test_set_y.shape[0]))
print ("训练集降维最后的维度: " + str(train_set_x_flatten.shape))
print ("训练集_标签的维数 : " + str(train_set_y_flatten.shape))
print ("测试集降维之后的维度: " + str(test_set_x_flatten.shape))
print ("测试集_标签的维数 : " + str(test_set_y_flatten.shape))
#标准化数据
train_set_x = train_set_x_flatten / 255
test_set_x = test_set_x_flatten / 255
二:训练过程
顾名思义,训练神经网络即是通过训练集得到最能够使得代价函数降到最小的W与B的集合
神经网络的训练分为:
propagate:前向传播和计算代价函数
optimize:反向传播和计算准确率
predict:预测函数,利用训练好的模型进行预测
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]#训练集降维最后的维度: (12288, 209)
#正向传播
A = sigmoid(np.dot(w.T,X) + b) #计算激活值,请参考公式2。 A(1,209)
cost = (- 1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A))) #计算成本,请参考公式3和4。
#Y(1,209) A(1 209) 矩阵*为对应位置相乘,np.dot为矩阵乘法
#反向传播
dw = (1 / m) * np.dot(X, (A - Y).T) #请参考视频中的偏导公式 (12288, 209) (209,1) 12288,1
db = (1 / m) * np.sum(A - Y) #请参考视频中的偏导公式。1,209
#使用断言确保我的数据是正确的
assert(dw.shape == w.shape)
assert(db.dtype == float)
#cost = np.squeeze(cost) #删除一个单维度
#assert(cost.shape == ())
#创建一个字典,把dw和db保存起来。
grads = {
"dw": dw,
"db": db
}
return (grads , 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,训练数据的数量)的数组。
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)
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] #图片的数量(12880,209)
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0],1)
#计预测猫在图片中出现的概率
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,i] > 0.5 else 0
#使用断言
assert(Y_prediction.shape == (1,m))
return Y_prediction
三:正式运行
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) ,"%")
print("测试集准确性:" , format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100) ,"%")
d = {
"costs" : costs,
"Y_prediction_test" : Y_prediction_test,
"Y_prediciton_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'])
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)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()
四:利用训练的模型预测本地图片
利用训练的模型预测本地图片:
步骤1:首先将一张图片利用“画图”工具转化成64*64像素的图片
步骤2:将图片导入IDE,执行代码
import matplotlib.image as mpimg
from package.preparetion import train_set_x, train_set_y
from package.code import model
cat=mpimg.imread('1.jpg')
cat=cat.reshape(-1,1)
print(cat.shape[0])
print(cat.shape[1])
d = model(train_set_x, train_set_y, cat, 0, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
参考资源:CSDN博主「何宽」
原文链接:https://blog.csdn.net/u013733326/article/details/79639509