image.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.pngimage.png1、函数forward()中,有一个变量w。这个变量最终的值是从for循环中传入的。
    2、for循环中,使用了np.arange。若对numpy不太熟悉,传送门Numpy数据计算从入门到实战
    3、python中zip()函数的用法

    1. import numpy as np
    2. import matplotlib.pyplot as plt
    3. x_data = [1.0, 2.0, 3.0]
    4. y_data = [2.0, 4.0, 6.0]
    5. def forward(x):
    6. return x*w
    7. def loss(x, y):
    8. y_pred = forward(x)
    9. return (y_pred - y)**2
    10. # 穷举法
    11. w_list = []
    12. mse_list = []
    13. for w in np.arange(0.0, 4.1, 0.1):
    14. print("w=", w)
    15. l_sum = 0
    16. for x_val, y_val in zip(x_data, y_data):
    17. y_pred_val = forward(x_val)
    18. loss_val = loss(x_val, y_val)
    19. l_sum += loss_val
    20. print('\t', x_val, y_val, y_pred_val, loss_val)
    21. print('MSE=', l_sum/3)
    22. w_list.append(w)
    23. mse_list.append(l_sum/3)
    24. plt.plot(w_list,mse_list)
    25. plt.ylabel('Loss')
    26. plt.xlabel('w')
    27. plt.show()

    image.png

    1. # Numpy
    2. import numpy
    3. # For plotting
    4. import matplotlib.pyplot as plt
    5. from matplotlib import cm
    6. from mpl_toolkits.mplot3d import Axes3D
    7. x_data = [1.0, 2.0, 3.0]
    8. y_data = [2.0, 4.0, 6.0]
    9. def forward(w: numpy.ndarray, b: numpy.ndarray, x: float) -> numpy.ndarray:
    10. return w * x + b
    11. def loss(y_hat: numpy.ndarray, y: float) -> numpy.ndarray:
    12. return (y_hat - y) ** 2
    13. w_cor = numpy.arange(0.0, 4.0, 0.1)
    14. b_cor = numpy.arange(-2.0, 2.1, 0.1)
    15. # 此处直接使用矩阵进行计算
    16. w, b = numpy.meshgrid(w_cor, b_cor)
    17. mse = numpy.zeros(w.shape)
    18. for x, y in zip(x_data, y_data):
    19. _y = forward(w, b, x)
    20. mse += loss(_y, y)
    21. mse /= len(x_data)
    22. h = plt.contourf(w, b, mse)
    23. fig = plt.figure()
    24. ax = Axes3D(fig)
    25. plt.xlabel(r'w', fontsize=20, color='cyan')
    26. plt.ylabel(r'b', fontsize=20, color='cyan')
    27. ax.plot_surface(w, b, mse, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
    28. plt.show()

    image.png
    image.png