日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

PyTorch實現(xiàn)線性回歸詳細過程_python

作者:心?升明月 ? 更新時間: 2022-05-09 編程語言

一、實現(xiàn)步驟

1、準備數(shù)據(jù)

x_data = torch.tensor([[1.0],[2.0],[3.0]])
y_data = torch.tensor([[2.0],[4.0],[6.0]])

2、設計模型

class LinearModel(torch.nn.Module):
? ? def __init__(self):
? ? ? ? super(LinearModel,self).__init__()
? ? ? ? self.linear = torch.nn.Linear(1,1)
? ? ? ??
? ? def forward(self, x):
? ? ? ? y_pred = self.linear(x)
? ? ? ? return y_pred
? ? ? ??
model = LinearModel() ?

3、構造損失函數(shù)和優(yōu)化器

criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)

4、訓練過程

epoch_list = []
loss_list = []
w_list = []
b_list = []
for epoch in range(1000):
? ? y_pred = model(x_data)?? ??? ??? ??? ??? ? ?# 計算預測值
? ? loss = criterion(y_pred, y_data)?? ?# 計算損失
? ? print(epoch,loss)
? ??
? ? epoch_list.append(epoch)
? ? loss_list.append(loss.data.item())
? ? w_list.append(model.linear.weight.item())
? ? b_list.append(model.linear.bias.item())
? ??
? ? optimizer.zero_grad() ? # 梯度歸零
? ? loss.backward() ? ? ? ? # 反向傳播
? ? optimizer.step() ? ? ? ?# 更新

5、結果展示

展示最終的權重和偏置:

# 輸出權重和偏置
print('w = ',model.linear.weight.item())
print('b = ',model.linear.bias.item())

結果為:

w = ?1.9998501539230347
b = ?0.0003405189490877092

模型測試:

# 測試模型
x_test = torch.tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ',y_test.data)

y_pred = ?tensor([[7.9997]])

分別繪制損失值隨迭代次數(shù)變化的二維曲線圖和其隨權重與偏置變化的三維散點圖:

# 二維曲線圖
plt.plot(epoch_list,loss_list,'b')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()

# 三維散點圖
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(w_list,b_list,loss_list,c='r')
#設置坐標軸
ax.set_xlabel('weight')
ax.set_ylabel('bias')
ax.set_zlabel('loss')
plt.show()

結果如下圖所示:

?到此這篇關于PyTorch實現(xiàn)線性回歸詳細過程的文章就介紹到這了,更多相關PyTorch線性回歸內容請搜索AB教程網以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持AB教程網!

二、參考文獻

  • [1] https://www.bilibili.com/video/BV1Y7411d7Ys?p=5

原文鏈接:https://blog.csdn.net/weixin_43821559/article/details/123298468

欄目分類
最近更新