pytorch實(shí)現(xiàn)線性回歸代碼練習(xí)實(shí)例,供大家參考,具體內(nèi)容如下
歡迎大家指正,希望可以通過小的練習(xí)提升對(duì)于pytorch的掌握
# 隨機(jī)初始化一個(gè)二維數(shù)據(jù)集,使用朋友torch訓(xùn)練一個(gè)回歸模型 import numpy as np import random import matplotlib.pyplot as plt x = np.arange(20) y = np.array([5*x[i] + random.randint(1,20) for i in range(len(x))]) # random.randint(參數(shù)1,參數(shù)2)函數(shù)返回參數(shù)1和參數(shù)2之間的任意整數(shù) print('-'*50) # 打印數(shù)據(jù)集 print(x) print(y) import torch x_train = torch.from_numpy(x).float() y_train = torch.from_numpy(y).float() # model class LinearRegression(torch.nn.Module): def __init__(self): super(LinearRegression, self).__init__() # 輸入與輸出都是一維的 self.linear = torch.nn.Linear(1,1) def forward(self,x): return self.linear(x) # 新建模型,誤差函數(shù),優(yōu)化器 model = LinearRegression() criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(),0.001) # 開始訓(xùn)練 num_epoch = 20 for i in range(num_epoch): input_data = x_train.unsqueeze(1) target = y_train.unsqueeze(1) # unsqueeze(1)在第二維增加一個(gè)維度 out = model(input_data) loss = criterion(out,target) optimizer.zero_grad() loss.backward() optimizer.step() print("Eopch:[{}/{},loss:[{:.4f}]".format(i+1,num_epoch,loss.item())) if ((i+1)%2 == 0): predict = model(input_data) plt.plot(x_train.data.numpy(),predict.squeeze(1).data.numpy(),"r") loss = criterion(predict,target) plt.title("Loss:{:.4f}".format(loss.item())) plt.xlabel("X") plt.ylabel("Y") plt.scatter(x_train,y_train) plt.show()
實(shí)驗(yàn)結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
標(biāo)簽:衡水 湖州 江蘇 駐馬店 股票 畢節(jié) 呼和浩特 中山
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《pytorch實(shí)現(xiàn)線性回歸》,本文關(guān)鍵詞 pytorch,實(shí)現(xiàn),線性,回歸,pytorch,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。