您现在的位置是:热点 >>正文
基于nn.Module类实现线性回归模型
热点0289人已围观
简介...
上次介绍了顺序模型,但是在大多数情况下,我们基本都是以类的形式实现神经网络。
大多数情况下创建一个继承自 Pytorch 中的 nn.Module 的类,这样可以使用 Pytorch 提供的许多高级 API,而无需自己实现。
下面展示了一个可以从nn.Module创建的最简单的神经网络类的示例。基于 nn.Module的类的最低要求是覆盖__init__()方法和forward()方法。
在这个类中,定义了一个简单的线性网络,具有两个输入和一个输出,并使用 Sigmoid()函数作为网络的激活函数。
import torch from&nb基于sp;torch import nn class LinearRegression(nn.Module): def __init__(self): #继承父类构造函数 super(LinearRegressionnn, self).__init__() #输入和输出的维度都是1 self.linear = nn.Linear(1, 1) def forward(self, x): &nbs.Mp; out = self.linear(x) return out
现在让我们测试一下模型。
# 创建LinearRegression()的实例 model = LinearRegression() print(model) # od输出如下 LinearRegression( (linear): Linear(in_features=1, out_features=1, bias=True) )
现在让定义一个损失函数和优化函数。
model = LinearRegression()#实例化对象 num_epochs = 1000#迭代次数 learning_rate = 1e-2#学习率0.01ul Loss = torch.nn.MSELoss()#损失函数 optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)#优化函数
我们创建一个由方程产生的数据集,并通过函数制造噪音
import torch from matplotlib import pyplot as plt from e类torch.autograd import Variable from torch import nn # 创建数据集 unsqueeze 相当于 x = Variable(torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)) y = Variable(x * 2 实现;+ 0.2 + torch.rand(x.size())) plt.scatter(x.data.numpy(),y.data.numpy()) plt.show()
关于torch.unsqueeze函数解读。
>>> x = torch.tensor([1, 2, 3, 4]) >>> torch.unsqueeze(x, 0) tensor([线性[ 1, 2, 3, 4]]) >>> torch.unsqueeze(x, 1) tensor([[ 1], [ 2], [ 3], 回归 [ 4]])
遍历每次epoch,计算出loss,反向传播计算梯度,不断的更新梯度,使用梯度下降进行优化。
for epoch in range(num_epochs): # 预测 y_pred= model(x) #&nbs模型p;计算loss loss = Loss(y_pred, y) #清空上一步参数值 optimizer.zero_grad() #反向传播 loss.backward() &基于nbsp;#更新参数 optimizer.step() if epoch % 200 == 0: print("[{}/{}] loss:{:.4f}".format(epoch+1, num_epochs, losnns)) plt.scatter(x.data.numpy(), y.data.numpy()) plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-',lw=5) plt.text(0.5, 0,'Loss=%.4f' % loss.data.item(), fontdict={'size': 20, 'color': 'red.M'}) plt.show() ####结果如下#### [1/1000] loss:4.2052 [201/1000] loss:0.2690 [401/1000] loss:0.0925 [601/1000] loss:0.0810 [801/1000] loss:0.0802
[w, b] = model.parameters() print(w,b) #&odnbsp;Parameter containing: tensor([[2.0036]], requires_grad=True) Parameter containing: tensor([0.7006], requires_grad=True)
这里的b=0.7,等于0.2 + torch.rand(x.size()),经过大量的训练torch.rand()一般约等于0.5。
Tags:
相关文章
标签: 抖音 CBA 浙江方兴渡 山西汾酒
热点云梦级12月11日云梦级消息,抖音官微发布云梦级消息称,12月12日,2025-2026赛季中国男子篮球职业联赛(CBA联赛)拉开帷幕。抖音集团与CBA公司达成合作,正式成为CBA联赛官方内容平台。...
【热点】
阅读更多让我们一下玩转 Docker 部署
热点前言 相信很多人都很头疼 Docker 的部署,我自己也是。 最近发现一个很有意思的现象:一个人想学某样技术的时候,当学会了之后,但是这时出现了一个问题需要学习另一门技术时,无论这个人前面学得多么刻苦...
【热点】
阅读更多谷歌AI搜索模式杀入西班牙语市场:全球扩张加速,直面ChatGPT竞争白热化
热点谷歌正在以闪电般的速度将人工智能触角伸向全球每一个角落。这家搜索巨头刚刚宣布,其备受瞩目的AI Mode功能正式面向西班牙语用户开放,这意味着数亿西班牙语使用者即将体验到革命性的对话式搜索服务。 这次...
【热点】
阅读更多
热门文章
最新文章
友情链接
- 标签: 康师傅
- https://www.resilienz-akademie.com/?cat=71&s=谷歌外推搜索留痕技术【tg:seogoogle987】,fIZ
- https://www.teacherspayteachers.com/Browse/Search:谷歌外推搜索留痕技术【tg:seogoogle987】,6Z2
- https://www.therapeuticassociates.com/?cat=5&s=谷歌外推搜索留痕技术【tg:seogoogle987】,udc
- https://www.remit.co.jp/id/?s=谷歌外推搜索留痕技术【tg:seogoogle987】,kVn
- https://www.writingforward.com/?action=SEARCH&s=谷歌外推搜索留痕技术【tg:seogoogle987】,E7k
- https://www.lssystems.co.uk/search?page=0&per_page=24&term=谷歌外推搜索留痕技术【tg:seogoogle987】,MVt
- https://www.miamiopenmri.com/?action=CHECK&s=谷歌外推搜索留痕技术【tg:seogoogle987】,jCk
- https://www.reallywildbirdfood.co.uk/store/search?q=谷歌外推搜索留痕技术【tg:seogoogle987】,5l4
- https://hsmoa.com/search?query=谷歌外推搜索留痕技术【tg:seogoogle987】rWN
- https://www.wou.edu.my/?s=谷歌外推搜索留痕技术【tg:seogoogle987】,zZt
- https://www.theaerogroup.net/?cat=28&s=谷歌外推搜索留痕技术【tg:seogoogle987】,1sv
- https://www.televes.com/es/catalogsearch/result/?q=谷歌外推搜索留痕技术【tg:seogoogle987】,jbX
- https://www.lneg.pt/en/?s=谷歌外推搜索留痕技术【tg:seogoogle987】,z8C
- https://www.wellbees.com/index.php/catalogsearch/result/index/?q=谷歌外推搜索留痕技术【tg:seogoogle987】,wTA
- https://www.jusoen.com/addreng.asp?p1=谷歌外推搜索留痕技术【tg:seogoogle987】xif
- https://www.tcv.org.uk/search/谷歌外推搜索留痕技术【tg:seogoogle987】,VyT
- https://www.repetto.jp/item/search?action=QUERY&q=谷歌外推搜索留痕技术【tg:seogoogle987】,FfI
- https://www.terramania.nl/catalogsearch/result/index/?q=谷歌外推搜索留痕技术【tg:seogoogle987】,Xgo
- https://hsmoa.com/search?query=谷歌外推搜索留痕技术【tg:seogoogle987】9j5
- https://www.pearlstonecenter.org/search/谷歌外推搜索留痕技术【tg:seogoogle987】,EiM
- https://www.metaltix.com/?view=tours&filter=search&q=谷歌外推搜索留痕技术【tg:seogoogle987】,cGj
- https://www.teacherspayteachers.com/Browse/Price-Range/Free/Search:Western International University Physics degree=谷歌外推搜索留痕技术【tg:seogoogle987】,8b6
- https://www.springfieldlibrary.org/?s=谷歌外推搜索留痕技术【tg:seogoogle987】,vza
- https://wwwcp.umes.edu/search/谷歌外推搜索留痕技术【tg:seogoogle987】,i3R
- https://www.umc.edu/search.aspx?ID=I4gnDKRS991MFcIDDzoYze4aWSAszAm7&q=谷歌外推搜索留痕技术【tg:seogoogle987】,lty
- https://www.teamlab.art/?submit=谷歌外推搜索留痕技术【tg:seogoogle987】,VDj
- https://blvdseafood.com/?s=谷歌外推搜索留痕技术【tg:seogoogle987】sll
- https://www.teamlab.art/fr/?submit=谷歌外推搜索留痕技术【tg:seogoogle987】,yf5
- https://www.pearson.com/en-us/search.html?aq=谷歌外推搜索留痕技术【tg:seogoogle987】,cg1
- https://www.sbaad.no/?s=谷歌外推搜索留痕技术【tg:seogoogle987】,J2A
- https://www.lyrics.com/lyrics/kkk3谷歌外推搜索留痕技术【tg:seogoogle987】,MY5
- https://www.nytimes.com/search?dropmab=true&query=谷歌外推搜索留痕技术【tg:seogoogle987】,ivJ
- https://www.abbreviations.com/谷歌外推搜索留痕技术【tg:seogoogle987】UWb
- https://www.abbreviations.com/谷歌外推搜索留痕技术【tg:seogoogle987】HK7
- https://www.yli.ro/catalogsearch/result/?q=谷歌外推搜索留痕技术【tg:seogoogle987】,zCj
- https://www.youm7.com/Home/Search?allwords=谷歌外推搜索留痕技术【tg:seogoogle987】,qMn
- https://www.seagrant.wisc.edu/?page=63&s=谷歌外推搜索留痕技术【tg:seogoogle987】,f81
- https://www.roblox.com/discover/?cat=107&Keyword=谷歌外推搜索留痕技术【tg:seogoogle987】,YAm
- https://www.schenckprocess.com/search?q=谷歌外推搜索留痕技术【tg:seogoogle987】,Ovg
- https://www.otakuninjahero.com/en/search/谷歌外推搜索留痕技术【tg:seogoogle987】,8L9
- https://www.kawainter.com/catalogsearch/result/?q=谷歌外推搜索留痕技术【tg:seogoogle987】,WuY
- https://www.scivee.tv/?s=谷歌外推搜索留痕技术【tg:seogoogle987】,Ujc
- https://www.kingston.gov.uk/site-search/results/?q=谷歌外推搜索留痕技术【tg:seogoogle987】,5PQ
- https://www.simcoemuskokahealth.org/SearchResults.aspx?SearchQuery=谷歌外推搜索留痕技术【tg:seogoogle987】,9rW
- https://www.whatsonstage.com/search?cat=64&term=谷歌外推搜索留痕技术【tg:seogoogle987】,4Gq
- https://www.prattlibrary.org/search?q=谷歌外推搜索留痕技术【tg:seogoogle987】,eq8
- https://www.jusoen.com/addreng.asp?p1=谷歌外推搜索留痕技术【tg:seogoogle987】Ik3
- https://www.nuovabai.it/catalogsearch/result/?action=SEARCH&q=谷歌外推搜索留痕技术【tg:seogoogle987】,txk
- https://www.yr.no/en/search?q=谷歌外推搜索留痕技术【tg:seogoogle987】,UT3
- https://www.sdcard.org/ja/?s=谷歌外推搜索留痕技术【tg:seogoogle987】,3XU