import torch
import torch.nn.functional as F
# 神经网络的类
class Net(torch.nn.Module):
def __init__(self):
super().__init__()
# 两个卷积层
self.conv1=torch.nn.Conv2d(1,10,kernel_size=5)
self.conv2=torch.nn.Conv2d(10,20,kernel_size=5)
self.pooling=torch.nn.MaxPool2d(2)# 池化层
self.fc=torch.nn.Linear(320,10)# 线性变换层
def forward(self,x):
batch_size=x.size(0) #input的第一个维度
x=F.relu(self.pooling(self.conv1(x))) #relu非线性函数 激活函数
x=F.relu(self.pooling(self.conv2(x)))
x=x.view(batch_size,-1)
x=self.fc(x) #线性全连接网络
return x
model=Net()
#如果显卡可用则转移到显卡上面进行运算
device=torch.device("cuda:0"if torch.cuda.is_available() else "cpu")
model.to(device)
#从CPU转换到显卡,只需将网络和输入输出转移到显卡上即可
def train(epoch):
running_loss=0.0
for batch_idx,data in enumerate(train_loader,0):
inputs,target=data
inputs,target=inputs.to(device),target.to(device)
optimizer.zero_grad() #权重清零
outputs=model(inputs)
loss=criterion(outputs,target)
loss.backward()
optimizer.step()#更新
running_loss+=loss.item()
if batch.idx%300==299:
print('[%d,%5d] loss:%.3f' %(epoch+1,batch_idx+1,running_loss/300))
running_loss=0.0
def test():
correct=0
total=0
with torch.no_grad():
for data in test_loader:
inputs,target=data
outputs=model(inputs)
_,predict=torch.max(output.data,dim=1) #维度1 对应行 取出一行中最大值及其下标
total+=target.size(0) #总的样本大小
correct+=(predict==target).sum().item()
print('猜对的比率是:%d %%'%(100*correct/total))
以上代码不是很完整,只是体现大致思路。
梯度消失和梯度爆炸
import torch
import torch.nn.functional as F
#网状卷积神经网络
class InceptionA(torch.nn.Module):
def __init__(self,in_channels):
super().__init__()
self.branch1x1=torch.nn.Conv2d(in_channels,16,kernel_size=1)
self.branch5x5_1=torch.nn.Conv2d(in_channels,16,kernel_size=1)
self.branch5x5_2=torch.nn.Conv2d(16,24,kernel_size=5,podding=2)
self.branch3x3_1=torch.nn.Conv2d(in_channels,16,kernel_size=1)
self.branch3x3_2=torch.nn.COnv2d(16,24,kernel_size=3,podding=1)
self.branch3x3_3=torch.nn.Conv2d(24,24,kernel_size=3,podding=1)
self.branch_pool=torch.nn.Conv2d(in_channels,24,kernel_size=1)
def forward(self,x):
branch1x1=self.branch1x1(x)
branch5x5=self.branch5x5_1(x)
branch5x5=self.branch5x5_2(branch5x5)
branch3x3=self.branch3x3_1(x)
branch3x3=self.branch3x3_2(branch3x3)
branch3x3=self.branch3x3_3(branch3x3)
branch_pool=F.avg_pool2d(x,kernel_size=3,stride=1,padding=1)
branch_pool=self.branch_pool(branch_pool)
outputs=[branch1x1,branch5x5,branch3x3,branch_pool]
return torch.cat(outputs,dim=1) #在行的维度上将所有的数据进行连接
class Net(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1=torch.nn.Conv2d(1,10,kernel_size=5)
self.conv2=torch.nn.Conv2d(88,20,kernel_size=5)
self.incep1=InceptionA(in_channels=10)
self.incep2=InceptionA(in_channels=20)
self.mp=torch.nn.MaxPool2d(2) #最大池化层 长和宽都变为原来的一半
self.fc=torch.nn.Linear(1408,10)
def forward(self,x):
in_size=x.size(0)
x=F.relu(self.mp(self.conv1(x)))
x=self.incep1(x)
x=F.relu(self.mp(self.conv2(x)))
x=self.incep2(x)
x=x.view(in_size,-1)
x=self.fc(x)
return x
|