题目一:模型:y = w * b 如图, 求w
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]
#存放权值、损失值画图
w_list = []
l_list = []
for w in np.arange(0.0, 4.1, 0.01):
l = 0
for x, y in zip(x_data, y_data):
y_pred = x*w; #模型为: y=w*x 求w
l += (y_pred-y)*(y_pred-y)
print("loss:", l)
#l.backward() 注:这里是遍历的权值 根本不需要反向传播更新权值了,最重要的这样没有该属性
w_list.append(w)
l_list.append(l)
plt.plot(w_list, l_list)
plt.xlabel('w')
plt.ylabel('loss')
plt.show()
结果:肉眼可见loss最小时w为2
题目二:改上述模型为y = w * x + b
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]
w_list = []
mse_list = []
b_list = []
for w in np.arange(0.0, 4.1, 0.01):
for b in np.arange(0.0, 2.1, 0.01):
l_sum = 0
for x_val, y_val in zip(x_data, y_data):
y_pred = x_val * w + b
l_sum += (y_pred - y_val)*(y_pred - y_val)
w_list.append(w)
mse_list.append(l_sum/3)
b_list.append(b)
fig = plt.figure() # 定义新的三维坐标轴
ax3 = Axes3D(fig)
ax3.plot(w_list, b_list, mse_list)
ax3.set_xlabel('w')
ax3.set_ylabel('b')
ax3.set_zlabel('loss')
plt.show()
tips:仅供自己看 ,画出来的图奇奇怪怪,,,老师画出来好像不是这样的,等我画的出来的再改!!!!(右边为老师画出来的)