日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Pytorch高阶API示范——线性回归模型

發(fā)布時(shí)間:2023/11/29 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Pytorch高阶API示范——线性回归模型 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文與《20天吃透Pytorch》有所不同,《20天吃透Pytorch》中是繼承之前的模型進(jìn)行擬合,本文是單獨(dú)建立網(wǎng)絡(luò)進(jìn)行擬合。

代碼實(shí)現(xiàn):

import torch import numpy as np import matplotlib.pyplot as plt import pandas as pd from torch import nn import torch.nn.functional as F from torch.utils.data import Dataset,DataLoader,TensorDataset""" 1.準(zhǔn)備數(shù)據(jù) """ n=800 #樣本數(shù)量#生成測試用的數(shù)據(jù)集 X = 10*torch.rand([n,2])-5.0 #torch.rand是均勻分布 w0 = torch.tensor([[2.0],[-3.0]]) b0 = torch.tensor([10.0]) Y = X@w0 + b0 + torch.normal(0.0,2.0,size=[n,1]) ## @表示矩陣乘法,增加正態(tài)擾動#數(shù)據(jù)可視化 plt.figure(figsize= (12,5)) ax1 = plt.subplot(121) ax1.scatter(X[:,0],Y[:,0],c = 'b',label = 'samples') ax1.legend() #圖例 plt.xlabel("x1") plt.ylabel("y",rotation = 0) ax2 = plt.subplot(122) ax2.scatter(X[:,1],Y[:,0],c = 'g',label = 'samples') ax2.legend() plt.xlabel('x2') plt.ylabel('y',rotation = 0) plt.show()""" 構(gòu)建通道 """ds = TensorDataset(X,Y) ds_train,ds_valid = torch.utils.data.random_split(ds,[int (n*0.7),n-int(n*0.7)]) #選取總樣本的70%為訓(xùn)練數(shù)據(jù) dl_train = DataLoader(ds_train,batch_size=10,shuffle=True) dl_valid = DataLoader(ds_valid,batch_size=10,shuffle=True)""" 2.定義模型 """class LinearRegression(torch.nn.Module):def __init__(self):super(LinearRegression, self).__init__()self.fc = nn.Linear(2,1)def forward(self,x):x = self.fc(x)return xnet = LinearRegression() """ 3.訓(xùn)練模型 """ loss_func = torch.nn.MSELoss() optimizer= torch.optim.Adam(net.parameters(),lr = 0.01)eporchs = 10 log_step_freq = 20for eporch in range(1,eporchs+1):net.train()loss_sum = 0.0metric_sum = 0.0step = 1for step,(features,labels) in enumerate(dl_train,1):predictions = net(features)loss = loss_func(predictions,labels)optimizer.zero_grad()loss.backward()optimizer.step()w = net.state_dict()["fc.weight"]b = net.state_dict()["fc.bias"]print("step =", step, "loss = ", loss)print("w =", w)print("b =", b)loss_sum += loss.item()""" 結(jié)果可視化 """ w,b = net.state_dict()["fc.weight"],net.state_dict()["fc.bias"]plt.figure(figsize = (12,5)) ax1 = plt.subplot(121) ax1.scatter(X[:,0],Y[:,0], c = "b",label = "samples") ax1.plot(X[:,0],w[0,0]*X[:,0]+b[0],"-r",linewidth = 5.0,label = "model") ax1.legend() plt.xlabel("x1") plt.ylabel("y",rotation = 0)ax2 = plt.subplot(122) ax2.scatter(X[:,1],Y[:,0], c = "g",label = "samples") ax2.plot(X[:,1],w[0,1]*X[:,1]+b[0],"-r",linewidth = 5.0,label = "model") ax2.legend() plt.xlabel("x2") plt.ylabel("y",rotation = 0)plt.show()

結(jié)果展示:

數(shù)據(jù)部分:

線性回歸結(jié)果:

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結(jié)

以上是生活随笔為你收集整理的Pytorch高阶API示范——线性回归模型的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。