一、课堂代码
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(x):
return x*w
def loss(x,y):
y_pred = forward(x)
return(y_pred-y)*(y_pred-y)
w_list = []
mse_list = []
for w in np.arange(0.0, 4.1,0.1):
print('w=',w)
l_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)
l_sum += loss_val
print('\t',x_val,y_val,y_pred_val,loss_val)
print('MSE=',l_sum/3)
w_list.append(w)
mse_list.append(l_sum/3)
plt.plot(w_list,mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()
运行结果:
二、课后作业
(1)课后作业的线性模型为:y=x*w+b,包含w和b两个参数,因此最直接的想法就是利用双层for循环去遍历w和b的值,在每一次b值循环后将w、b、MSE的值保存至空数组,作为绘图的X、Y、Z值。我看了很多其他人分享的课后作业代码,结构更简洁,就是有点难理解。
(2)在此过程中遇到了一个错误“"ValueError: Argument Z must be 2-dimensional."”,这是因为最开始使用了np.meshgrid()函数将X,Y变成了二维数组,但Z未经处理还是一维,而ax.plot_surface(X,Y,Z,cmp="rainbow")要求X,Y,Z三个参数均为二维,因此提示错误。故需要改用ax.plot_trisurf(X, Y, Z,cmap="rainbow"),plot.trisurf()函数要求X,Y,Z均为一维,并将X, Y = np.meshgrid(X, Y)语句删掉即可。
plot.trisurf()函数参考链接:
python 画三维图像 曲面图和散点图_samoyan的博客-CSDN博客
np.meshgrid()函数:
3分钟理解np.meshgrid()_littlehaes的博客-CSDN博客_np.meshgrid()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
#假设y=2x+0
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
def forward(x):
return x*w+b
def loss(x,y):
y_pred = forward(x)
return(y_pred-y)*(y_pred-y)
w_list = []
b_list = []
mse_list = []
for w in np.arange(0.0, 4.1,0.1):
for b in np.arange(-2,2,0.1):
print('w=',w,',b=',b)
l_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)
l_sum += loss_val
print('\t',x_val,y_val,y_pred_val,loss_val)
print('MSE=',l_sum/3)
w_list.append(w)
b_list.append(b)
mse_list.append(l_sum/3)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = np.array(w_list)
Y = np.array(b_list)
#X, Y = np.meshgrid(X, Y)
print("X维度信息",X.shape)
print("Y维度信息",Y.shape)
Z = np.array(mse_list)
print("Z轴数据维度",Z.shape)
#ax.plot_surface(X, Y, Z,cmap="rainbow")
surf = ax.plot_trisurf(X, Y, Z,cmap="rainbow")
ax.set_xlabel('w', color='b')
ax.set_ylabel('b', color='g')
ax.set_zlabel('Loss', color='r')
#加上图例表
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.draw()
plt.show()
运行结果: