您的位置:首页 > 理论基础 > 计算机网络

Pytorch搭建网络

2019-01-21 23:39 375 查看

用PyTorch搭建一个小网络

下面以计算两个数的和为例,x是输入数据,y是标签。
下面这比较简单的,是线性层,还没涉及卷积层,池化层等。

import torch
import torch.nn as nn

x = torch.Tensor([[0.2,0.4],[0.2,0.3],[0.3,0.4]])#数据
y = torch.Tensor([[0.6],[0.5],[0.7]])#标签 不需要求导

#定义网络
class MyNet(nn.Module):
def __init__(self):#类的构造函数
super(MyNet,self).__init__()#调用基类的构造函数
#定义网络层,不在一层层写了,用function包裹起来
self.fc = nn.Sequential(#容器
nn.Linear(2,4),
nn.ReLU(),
nn.Linear(4,4),#隐含层
nn.ReLU(),
nn.Linear(4,1)
)
self.opt = torch.optim.Adam(self.parameters())#优化器
self.mls = torch.nn.MSELoss()#损失函数

def forward(self,inputs):
return self.fc(inputs)

def train_model(self,x,y):#训练模型
out = self.forward(x)#网络输出
loss = self.mls(out,y)#损失
print('loss',loss)#输出误差
self.opt.zero_grad()#梯度是累加的,每次反向传播要归零
loss.backward()#反向传播
self.opt.step()#优化

def test(self,x):#测试
return self.forward(x)

#下面实例化一个网络
net = MyNet()
for i in range(10000):
net.train_model(x,y)

out = net.test(x)
print(out)

上面代码的运行结果:


多次训练之后得到结果。
如果用新的数据看看这个网络是不是学会了加法运算。例如用0.5+0.3
后面代码加上

x = torch.Tensor([[0.5,0.3]])
out = net.test(x)
print(out)

运行结果:

可以看到网络自己学习到了0.5+0.3 = 0.8。

搭建CNN网络

import torch
import torch.nn as nn

class MyCNN(nn.Module):
def __init__(self):
super(MyCNN,self).__init__()
#卷积层
self.cnn1 = nn.Sequential(
#例如 原图像是 3*128*128
#二维卷积
nn.Con2d(3,64,3,1,1), #parammeters:输入通道 输出通道 卷积核大小 步长stride 填充padding(与卷积核有关)
#卷积后得到 64*128*128
#池化 得到 64*64*64
nn.MaxPool2d(2),
nn.ReLU()
)
#卷积层
self.cnn2 = nn.Sequential(
# 64*64*64
nn.Con2d(64,128,3,1,1),
#卷积后得到 128*64*64
#池化 得到 128*32*32
nn.MaxPool2d(2),
nn.ReLU()
)
#全连接层
self.fc = nn.Sequential(#容器
nn.Linear(128*32*32,64),
nn.ReLU(),
nn.Linear(64,48),#隐含层
nn.ReLU(),
nn.Linear(48,10)
)

def forward(self,inputs):
out = self.con1(inputs)
out = self.con2(out)
out = out.view(out.size(0),-1)#展成一维
out = self.fc(out)
return out

cnn = MyCNN()
cnn.cuda()#网络放到GPU上

x = torch.Tensor([11,2])
x.cuda()#数据放到GPU上

x.cpu()#回到cpu

然而我的电脑跑不了CNN网络的。。。

【未完,待更新…】

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: