拟合y=w*x
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]
#定义模型 y = w*x
def forward(x):
return x*w
#定义损失函数 loss = (w*x-y)*(w*x-y)
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): #以0.1为单位,生成0到4的数据
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.title('Loss&w')
plt.show()
作业题:
参考代码:作业题
画图参考:matplotlib教程
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#这里设函数为y=3x+2
x_data = [1.0,2.0,3.0]
y_data = [5.0,8.0,11.0]
def forward(x):
return x * w + b
def loss(x,y):
y_pred = forward(x)
return (y_pred-y)*(y_pred-y)
mse_list = []
W=np.arange(0.0,4.1,0.1)
B=np.arange(0.0,4.1,0.1)
[w,b]=np.meshgrid(W,B)
l_sum = 0
for x_val, y_val in zip(x_data, y_data):
y_pred_val = forward(x_val)
print(y_pred_val)
loss_val = loss(x_val, y_val)
l_sum += loss_val
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(w, b, l_sum/3,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
plt.show()
画图结果: