Pytorch线性模型实现——up主:刘二大人《PyTorch深度学习实践》
教程: https://www.bilibili.com/video/BV1Y7411d7Ys?p=2&vd_source=715b347a0d6cb8aa3822e5a102f366fe
数据集:
x
d
a
t
a
=
[
1.0
,
2.0
,
3.0
]
y
d
a
t
a
=
[
2.0
,
4.0
,
6.0
]
x_{data} = [1.0, 2.0, 3.0] \\y_{data} = [2.0, 4.0, 6.0]
xdata=[1.0,2.0,3.0]ydata=[2.0,4.0,6.0]
参数:
w
l
i
s
t
=
[
0.0
,
4.0
,
0.1
]
b
l
i
s
t
=
[
−
2.0
,
2.1
,
0.1
]
w_{list} = [0.0, 4.0, 0.1]\\b_{list} = [-2.0, 2.1, 0.1]
wlist=[0.0,4.0,0.1]blist=[−2.0,2.1,0.1]
模型:
y
=
w
∗
x
+
b
y = w*x+b
y=w∗x+b
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
def forward(x, y, w, b):
#矩阵计算 x为标量;w,b为矩阵
return x * w + b
#定义损失函数
def loss(y_pred, y):
return (y_pred - y) **2
w_list = np.arange(0.0, 4.0, 0.1)
b_list = np.arange(-2.0, 2.1, 0.1)
w, b = np.meshgrid(w_list, b_list)
mse = np.zeros(w.shape)
for x,y in zip(x_data, y_data):
y_pred = forward(x, y, w, b)
mse += loss(y_pred, y)
mse /= len(x_data)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
plt.xlabel(r'w', fontsize=20, color='cyan')
plt.ylabel(r'b', fontsize=20, color='cyan')
ax.plot_surface(w, b, mse, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
plt.show()