UP:B站-刘二大人
原视频链接:2.线性模型_哔哩哔哩_bilibili
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
x_data = [1.0, 2.0, 3.0]
y_data = [5.0, 8.0, 11.0] # y=3*x+2
def forward(x):
return x * w + b
def loss(x, y):
y_pred = forward(x)
return (y-y_pred) * (y-y_pred)
W = np.arange(0.0, 4.1, 0.1)
B = np.arange(0.0, 4.1, 0.1)
mse_list = []
'''
语法:x,y = meshgrid(a,b)
作用:输入两个一维数组,输出两个二维数组x,y。其中矩阵x的行向量是向量a的简单复制,而矩阵y的列向量是向量b的简单复制。
a = np.linspace(0,2,3) # a = [0, 1, 2]
b = np.linspace(0,2,3) # b = [0, 1, 2]
x, y = np.meshgrid(a,b)
print(x)
# [[ 0. 1. 2.]
# [ 0. 1. 2.]
# [ 0. 1. 2.]]
print(y)
# [[ 0. 0. 0.]
# [ 1. 1. 1.]
# [ 2. 2. 2.]]
>>> c = [0, 1, 2]
>>> d = [0, 1]
>>> np.meshgrid(c,d)
[array([[0, 1, 2],[0, 1, 2]]), array([[0, 0, 0],[1, 1, 1]])]
'''
w, b = np.meshgrid(W, B)
loss_sum = 0
for x_val, y_val in zip(x_data, y_data):
y_pred_val = forward(x_val)
loss_val = loss(x_val, y_val)
loss_sum += loss_val
print("mse=", loss_sum/len(x_data))
mse_list.append(loss_sum/len(x_data))
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(w, b, loss_sum/len(x_data), cmap='rainbow')
plt.show()