第2讲 linear_model 源代码
B站 刘二大人 PyTorch深度学习实践——线性模型
numpy学习 Numpy数据计算从入门到实战
zip用法 python中zip()函数的用法
import numpy as np
import matplotlib.pyplot as plt
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]```
def forward(w,x):
return w * x
def loss(x, y, w):
y_pred = forward(w, x)
return (y_pred - y) ** 2
w_list = []
mse_list = []
for w in np.arange(0.0, 4.1, 0.1):
print("w:",w)
loss_sum = 0
for x, y in zip(x_data, y_data):
y_pred = forward(w, x)
loss_val = loss(x, y, w)
loss_sum += loss_val
print("\t", x, y, y_pred, loss_val)
print("MSE", loss_sum / 3)
w_list.append(w)
mse_list.append(loss_sum / 3)
plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()
作业:
实现线性模型(y=wx+b)并输出loss的3D图像。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
W = np.arange(0.0, 4.1, 0.1)
B = np.arange(-2.0, 2.1, 0.1)
w, b = np.meshgrid(W, B)
def forward(x):
return w * x + b
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
mse_lst = []
l_sum = 0.
for x, y in zip(x_data, y_data):
y_pred = forward(x)
loss_val = loss(x, y)
l_sum += loss_val
mse_lst.append(l_sum/3)
# 定义figure
fig = plt.figure(figsize=(10,10), dpi=300)
# 将figure变为3d
ax = Axes3D(fig)
# 绘图,rstride:行之间的跨度 cstride:列之间的跨度
surf = ax.plot_surface(w, b, np.array(mse_lst[0]), rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
# Customize the z axis.
ax.set_zlim(0, 40)
# 设置坐标轴标签
ax.set_xlabel("w")
ax.set_ylabel("b")
ax.set_zlabel("loss")
ax.text(0.2, 2, 43, "Cost Value", color='red')
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()