(刘二大人)PyTorch深度学习实践-线性模型作业

1.3D绘图参考

(刘二大人)PyTorch深度学习实践-线性模型作业_第1张图片

2.代码实现

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator

#w = 2,b=0,设置数据
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]

W = np.arange(0.0,4.1,0.1)
B = np.arange(-2.0,2.1,0.1)

[w,b] = np.meshgrid(W,B)


def forward(x):
    return w*x+b

def loss(x,y):
    y_pred = forward(x)
    return  (y_pred-y)**2

sum_loss = 0
mse_list = []
for x_val,y_val in zip(x_data,y_data):
    y_pred = forward(x_val)
    loss_val = loss(x_val,y_val)
    sum_loss +=loss_val
    print('\t',x_val,y_val,y_pred,loss_val)


#进行构图实现
fig,ax = plt.subplots(subplot_kw={"projection":"3d"})

surf = ax.plot_surface(w,b,sum_loss/3,cmap=cm.coolwarm,linewidth =0,antialiased = False)

ax.set_zlim(0.0,40.0)
ax.set_xlabel("w")
ax.set_ylabel('b')
ax.set_title("Cost Value")
ax.zaxis.set_major_locator(LinearLocator(10))#设置网格大小
ax.zaxis.set_major_formatter('{x:.01f}')#设置z轴的数字格式,保留多少小数

fig.colorbar(surf,shrink=0.6,aspect =10)#设置彩虹条
plt.show()

 3.图像展示

(刘二大人)PyTorch深度学习实践-线性模型作业_第2张图片

 

你可能感兴趣的:(PyTorch,pytorch,人工智能,python)