本节主要讲的是线性模型
涉及的主要代码有:
import torch
import matplotlib.pyplot as plt
import numpy as np
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
def forawrd(x):
return w * x
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
w_list = []
mse_list = []
for w in arange(0, 4, 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_lsit.append(w)
mse_list.append(l_sum/3)
plt.plot(w_list,mse_list)
plt.ylabel('mse')
plt.xlabel('w')
plt.show()
会得到如下的结果图:
从图中不难看出w=2.0时均方误差最小。
在课程最后布置了课后作业:
主要是用新的模型(添加了偏置b),并画出3D曲面图:
我所做的代码如下:
import torch
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
def forawrd(x):
return w * x + b
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
w_cor = np.arange(0, 4, 0.1)
b_cor = np.arange(-2, 2, 0.1)
w, b = np.meshgrid(w_cor, b_cor)
mse_list = []
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
mse_list.append(l_sum / 3)
fig = plt.figure()
ax = Axes3D(fig)
plt.xlabel('w')
plt.ylabel('b')
ax.plot_surface(w, b, l_sum / 3, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
plt.show()
得到3D曲面图如下:
对比课后作业中的图形几乎一样!!