- 四步走:
- Dataset
- Model
- Training
- Infering(拿到新data,推理出结果)
- loss是针对一条样本而言的,cost(例如mse)是针对training set而言的
- 在本节中,我们使用穷举法琼剧所有可能的模型参数(w),绘制出mse曲线,肉眼观察处最优的模型参数
课上代码说明:
- 函数forward(x)中,有一个变量w。这个变量w最终的值是从for循环中传入的,可视为全局变量
- Pyhton的zip函数
import numpy as np
import matplotlib.pyplot as plt
# prepare the dataset
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
# define the model
def forward(x):
return x * w
# define the loss function
def loss(x, y):
y_pred = forward(x)
return (y_pred-y) ** 2
# prepare two list to draw the graph
w_list = []
mse_list = []
# 穷举过程
# zip函数:将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
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)
# draw the graph
plt.plot(w_list,mse_list)
plt.ylabel("Loss")
plt.xlabel("w")
plt.show()
补充:课上还讲了在深度学习过程中使用到的Visdom可视化工具
课后作业代码:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# prepare dataset, y = 2x + 3
x_data = [1.0, 2.0, 3.0]
y_data = [5.0, 7.0, 9.0]
# 生成矩阵坐标
W, B = np.arange(0.0, 4.1, 0.1).round(1), np.arange(0.0, 4.1, 0.1).round(1)
w, b = np.meshgrid(W, B)
# defint the model
def forward(x):
return x * w + b
# loss
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
# 这里的运算都是矩阵运算
l_sum = 0
for x_val, y_val in zip(x_data, y_data):
loss_val = loss(x_val, y_val)
l_sum += loss_val
mse = l_sum/len(x_data)
# 绘图
## 定义figure
fig = plt.figure()
## 画3D图
ax = Axes3D(fig)
surf = ax.plot_surface(w, b, mse, rstride=1, cstride=1, cmap='rainbow')
## 设置下标
ax.set_xlabel('w')
ax.set_ylabel('b')
ax.set_zlabel('Loss')
## 设置颜色条
fig.colorbar(surf, shrink = 0.5, aspect = 5)
plt.show()
注意,相比于例题中显式枚举每一个w的值,这里直接进行了矩阵运算,最后得到的loss_val、l_sum、mse等都是矩阵
参考文献: