• 山东大学人工智能导论实验三 Logistic回归分类器识别猫


    目录

    【实验目标】

    【实验内容】

    【数据集介绍】

    1.datasets/train_catvnoncat.h5

    2.datasets/ test_catvnoncat.h5

    3.lr_utils.py中有加载数据集的函数

    【代码要求】

    定义模型结构

    初始化模型的参数

    循环

    计算当前损失(前向传播)

    计算当前梯度(反向传播)

    更新参数(梯度下降)

    【文档要求】

    1.尝试不同的学习率(至少三种),观察不同学习率下随着迭代次数的增加损失值的变化

     2.分析不同的学习率对模型准确率的影响及原因,如何选择合适的学习率。


    【实验目标】

    1. 基于作业二的拓展,进一步理解神经网络的思想
    2. 理解逻辑回归实际上是一个非常简单的神经网络

    【实验内容】

    建立Logistic回归分类器用来识别猫。参考1 参考2

    【数据集介绍】

    1.datasets/train_catvnoncat.h5

    保存的是训练集里面的图像数据(本训练集有209张64x64的图像)及对应的分类值(0或1,0表示不是猫,1表示是猫)

    2.datasets/ test_catvnoncat.h5

    保存的是测试集里面的图像数据(本训练集有50张64x64的图像)及保存的是以bytes类型保存的两个字符串数据,数据为:[b’non-cat’ b’cat’]。

    3.lr_utils.py中有加载数据集的函数

    【代码要求】

    1. 定义模型结构

    2. 初始化模型的参数

    3. 循环

    • 计算当前损失(前向传播)

    • 计算当前梯度(反向传播)

    • 更新参数(梯度下降)

    1. import numpy as np
    2. import matplotlib.pyplot as plt
    3. import h5py
    4. from lr_utils import load_dataset
    5. train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
    6. m_train = train_set_y.shape[1]
    7. m_test = test_set_y.shape[1]
    8. num_px = train_set_x_orig.shape[1]
    9. print("训练集的数量: m_train = " + str(m_train))
    10. print("测试集的数量 : m_test = " + str(m_test))
    11. print("每张图片的宽/高 : num_px = " + str(num_px))
    12. print("每张图片的大小 : (" + str(num_px) + ", " + str(num_px) + ", 3)")
    13. print("训练集_图片的维数 : " + str(train_set_x_orig.shape))
    14. print("训练集_标签的维数 : " + str(train_set_y.shape))
    15. print("测试集_图片的维数: " + str(test_set_x_orig.shape))
    16. print("测试集_标签的维数: " + str(test_set_y.shape))
    17. # 将训练集的维度降低并转置。
    18. train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
    19. # 将测试集的维度降低并转置。
    20. test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
    21. print("训练集降维最后的维度: " + str(train_set_x_flatten.shape))
    22. print("训练集_标签的维数 : " + str(train_set_y.shape))
    23. print("测试集降维之后的维度: " + str(test_set_x_flatten.shape))
    24. print("测试集_标签的维数 : " + str(test_set_y.shape))
    25. index = 11
    26. plt.imshow(train_set_x_orig[index])
    27. print("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode(
    28. "utf-8") + "' picture.")
    29. train_set_x = train_set_x_flatten / 255
    30. test_set_x = test_set_x_flatten / 255
    31. def sigmoid(z):
    32. s = 1 / (1 + np.exp(-z))
    33. return s
    34. def initialize_with_zeros(dim):
    35. w = np.zeros(shape=(dim, 1))
    36. b = 0
    37. # 使用断言来确保我要的数据是正确的
    38. assert (w.shape == (dim, 1)) # w的维度是(dim,1)
    39. assert (isinstance(b, float) or isinstance(b, int)) # b的类型是float或者是int
    40. return (w, b)
    41. def propagate(w, b, X, Y):
    42. m = X.shape[1]
    43. # 正向传播
    44. A = sigmoid(np.dot(w.T, X) + b)
    45. cost = (- 1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A)))
    46. # 反向传播
    47. dw = (1 / m) * np.dot(X, (A - Y).T)
    48. db = (1 / m) * np.sum(A - Y)
    49. # 使用断言确保我的数据是正确的
    50. assert (dw.shape == w.shape)
    51. assert (db.dtype == float)
    52. cost = np.squeeze(cost)
    53. assert (cost.shape == ())
    54. # 创建一个字典,把dw和db保存起来。
    55. grads = {
    56. "dw": dw,
    57. "db": db
    58. }
    59. return (grads, cost)
    60. def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False):
    61. costs = []
    62. for i in range(num_iterations):
    63. grads, cost = propagate(w, b, X, Y)
    64. dw = grads["dw"]
    65. db = grads["db"]
    66. w = w - learning_rate * dw
    67. b = b - learning_rate * db
    68. # 记录成本
    69. if i % 100 == 0:
    70. costs.append(cost)
    71. # 打印成本
    72. if (print_cost) and (i % 100 == 0):
    73. print("迭代的次数: %i , 误差值: %f" % (i, cost))
    74. params = {
    75. "w": w,
    76. "b": b}
    77. grads = {
    78. "dw": dw,
    79. "db": db}
    80. return (params, grads, costs)
    81. def predict(w, b, X):
    82. m = X.shape[1] # 图片的数量
    83. Y_prediction = np.zeros((1, m))
    84. w = w.reshape(X.shape[0], 1)
    85. # 计预测猫在图片中出现的概率
    86. A = sigmoid(np.dot(w.T, X) + b)
    87. for i in range(A.shape[1]):
    88. # 将概率a [0,i]转换为实际预测p [0,i]
    89. Y_prediction[0, i] = 1 if A[0, i] > 0.5 else 0
    90. # 使用断言
    91. assert (Y_prediction.shape == (1, m))
    92. return Y_prediction
    93. def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):
    94. w, b = initialize_with_zeros(X_train.shape[0])
    95. parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
    96. # 从字典“参数”中检索参数w和b
    97. w, b = parameters["w"], parameters["b"]
    98. # 预测测试/训练集的例子
    99. Y_prediction_test = predict(w, b, X_test)
    100. Y_prediction_train = predict(w, b, X_train)
    101. # 打印训练后的准确性
    102. print("训练集准确性:", format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100), "%")
    103. print("测试集准确性:", format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100), "%")
    104. d = {
    105. "costs": costs,
    106. "Y_prediction_test": Y_prediction_test,
    107. "Y_prediciton_train": Y_prediction_train,
    108. "w": w,
    109. "b": b,
    110. "learning_rate": learning_rate,
    111. "num_iterations": num_iterations}
    112. return d
    113. d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations=2000, learning_rate=0.005, print_cost=True)
    114. # 绘制图
    115. costs = np.squeeze(d['costs'])
    116. plt.plot(costs)
    117. plt.ylabel('cost')
    118. plt.xlabel('iterations (per hundreds)')
    119. plt.title("Learning rate =" + str(d["learning_rate"]))
    120. plt.show()
    121. learning_rates = [1, 0.01, 0.006, 0.0003, 0.001, 0.0006]
    122. models = {}
    123. for i in learning_rates:
    124. print("learning rate is: " + str(i))
    125. models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations=1500, learning_rate=i,
    126. print_cost=False)
    127. print('\n' + "-------------------------------------------------------" + '\n')
    128. for i in learning_rates:
    129. plt.plot(np.squeeze(models[str(i)]["costs"]), label=str(models[str(i)]["learning_rate"]))
    130. plt.ylabel('cost')
    131. plt.xlabel('iterations')
    132. legend = plt.legend(loc='upper center', shadow=True)
    133. frame = legend.get_frame()
    134. frame.set_facecolor('0.90')
    135. plt.show()

    【文档要求】

    1.尝试不同的学习率(至少三种),观察不同学习率下随着迭代次数的增加损失值的变化

    请粘贴不同学习率下损失的变化曲线图像:

    这里我首先打印了一下训练集的内容:

     

    接着对模型进行训练,并打印不同学习率下损失的变化曲线图像:

        在这里我分析了五种学习率,分别是0.01, 0.006, 0.0003, 0.001, 0.0006,可以看到学习率过低或者过高对于模型的拟合效果都存在一定的影响。当学习率过大则导致模型不收敛,过小则导致模型收敛特别慢或者无法学习。

     2.分析不同的学习率对模型准确率的影响及原因,如何选择合适的学习率。

    一般在分析选取最优学习率时,可以先采用多个学习率粗略范围的学习率作为尝试,在同一张图上可以看到对应某个区间之间的学习率work best,然后在这个区间内进行较精确的调参,再观察其学习率,是一个不断缩小范围的过程,并且位置不同,对应的合适步长也不同,具体可以使用余弦退火的方式改变学习率的大小,或者以非常低的学习率运行训练,并在每次迭代中线性增加它。当损失功能开始急剧增加时,应停止训练。记录每次迭代的学习速率和损失,最后找到一个合理的学习率。

    初学人工智能导论,可能存在错误之处,还请各位不吝赐教。

    受于文本原因,本文相关实验工程无法展示出来,现已将资源上传,可自行下载。

    山东大学人工智能导论实验3工程文件-Logistic回归分类器识别猫-机器学习文档类资源-CSDN下载山东大学人工智能导论实验3工程文件-Logistic回归分类器识别猫详解博客地址:https://更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/m0_52316372/85913095

  • 相关阅读:
    M4Singer CUDA error: no kernel image is available for execution on the device
    Python之并发编程介绍
    面试机器学习你一定会遇到的知识点汇总
    2022辽宁省数学建模B题原创成品
    Selenium安装WebDriver(含116/117/118/119)
    Dapr学习(2)之Rancher2.63(k8s&k3s)环境安装Dapr
    C++/Qt音视频通话开发MetaRTC源码解读,视频推流和拉流
    适合开发者使用的6款浏览器,开发者工具很实用
    【初阶数据结构】——限定性线性表:栈 和 队列详解(C描述)
    自动安装系统-桌面
  • 原文地址:https://blog.csdn.net/m0_52316372/article/details/125626670