线性模型
课程
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=0for x_v,y_v in zip(x_data,y_data):loss_v=loss(x_v,y_v)l_sum+=loss_vprint(x_v,y_v,loss_v)l_sum/=3print("MSE=",l_sum)w_list.append(w)mse_list.append(l_sum)
plt.plot(w_list,mse_list)
plt.xlabel('w')
plt.ylabel('loss')
plt.show()
作业
代码
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#令y=2x+1
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=np.arange(0.0,4.0,0.1)
b_list=np.arange(-2.0,2.0,0.1)
mse_list=[]
for w in np.arange(0.0,4.0,0.1):for b in np.arange(-2.0,2.0,0.1):print("w=",w)print("b=",b)l_sum=0for x_v,y_v in zip(x_data,y_data):loss_v=loss(x_v,y_v)l_sum+=loss_vprint(x_v,y_v,loss_v)l_sum/=3print("MSE=",l_sum)mse_list.append(l_sum)
#将一维的数值转变为二维坐标点
w,b=np.meshgrid(w_list,b_list)
#调整形状并转置,以适应w,b的坐标
mse=np.array(mse_list)
mse=np.transpose(mse.reshape(40,40))
fig = plt.figure()
ax =fig.add_axes(Axes3D(fig))
ax.plot_surface(w,b,mse,cmap=plt.get_cmap('rainbow'))
plt.show()
结果