import numpy as np
import torch
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
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 pow(y_pred-y,2)
sum=0
W=np.arange(0,4.1,0.1)
B=np.arange(0,4.1,0.1)
[w,b]=np.meshgrid(W,B)
for x_val,y_val in zip(x_data,y_data):
y_pval=forward(x_val)
print(y_pval)
loss_val=loss(x_val,y_val)#由唯一的[w,b]确定唯一的loss_val
sum+=loss_val
fig=plt.figure()
ax=Axes3D(fig)
ax.plot_surface(w,b,sum/3)
plt.xlabel('w')
plt.ylabel('b')
plt.show()
pytorch练习1 3d图的绘制(线性回归)
于 2024-03-17 19:45:57 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)