首页 > 其他分享 >CNN --Inception Module

CNN --Inception Module

时间:2023-09-26 18:56:05浏览次数:32  
标签:__ nn -- self torch transform Module CNN size

Smiling & Weeping

 

                  ---- 祝你想我

                    在平静的湖面

                   不止在失控的雪山之前

说明:Inception Module

1. 卷积核超参数选择困难,自动找到卷积的最佳组合

2. 1x1卷积核,不同通道的信息融合。使用1x1卷积核可以调节通道数量,可以显著降低计算量

3. Inception Module由四个分支组成,要分清哪些是在init里定义的,那些是在forward里调用的。4个分支在dim=1(channels)上进行concatenate

 

  1 import torch
  2 import torch.nn as nn
  3 from torchvision import transforms
  4 from torchvision import datasets
  5 from torch.utils.data import DataLoader
  6 import torch.nn.functional as F
  7 import torch.optim as optim
  8 import matplotlib.pyplot as plt
  9 
 10 batch_size = 64
 11 # 归一化,均值和方差
 12 transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
 13 
 14 train_dataset = datasets.MNIST(root='../dataset/mnist', train=True, download=True, transform=transform)
 15 train_loader = DataLoader(train_dataset, shuffle=True,batch_size=batch_size)
 16 test_dataset = datasets.MNIST(root='../dataset/mnist', train=False, download=True, transform=transform)
 17 test_loader = DataLoader(test_dataset, shuffle=True, batch_size=batch_size)
 18 
 19 # design model using class
 20 class InceptionA(nn.Module):
 21     def __init__(self, in_channels):
 22         super(InceptionA, self).__init__()
 23         self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1)
 24         
 25         self.branch5x5_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
 26         self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2)
 27         
 28         self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
 29         self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1)
 30         self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1)
 31         
 32         self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1)
 33         
 34     def forward(self, x):
 35         branch1x1 = self.branch1x1(x)
 36         
 37         branch5x5 = self.branch5x5_1(x)
 38         branch5x5 = self.branch5x5_2(branch5x5)
 39         
 40         branch3x3 = self.branch3x3_1(x)
 41         branch3x3 = self.branch3x3_2(branch3x3)
 42         branch3x3 = self.branch3x3_3(branch3x3)
 43         
 44         branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
 45         branch_pool = self.branch_pool(branch_pool)
 46         
 47         outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
 48         return torch.cat(outputs, dim=1)
 49 
 50 class Net(nn.Module):
 51     def __init__(self):
 52         super(Net, self).__init__()
 53         self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
 54         self.conv2 = nn.Conv2d(88, 20, kernel_size=5) # 88=24*3+16
 55         
 56         self.incep1 = InceptionA(in_channels=10) # conv1 中的10对应
 57         self.incep2 = InceptionA(in_channels=20) # conv2 中的20对应
 58         
 59         self.mp = nn.MaxPool2d(2)
 60         self.fc = nn.Linear(1408, 10)
 61         
 62     def forward(self, x):
 63         in_size = x.size(0)
 64         x = F.relu(self.mp(self.conv1(x)))
 65         x = self.incep1(x)
 66         x = F.relu(self.mp(self.conv2(x)))
 67         x = self.incep2(x)
 68         x = x.view(in_size, -1)
 69         x = self.fc(x)
 70         
 71         return x 
 72 
 73 model = Net()
 74 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 75 model.to(device)
 76 
 77 # 定义优化器 和 损失
 78 criterion = torch.nn.CrossEntropyLoss()
 79 optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
 80 # print(model.parameters())
 81 
 82 def train(epoch):
 83     run_loss = 0.0
 84     for batch_idx, data in enumerate(train_loader, 0):
 85         inputs, target = data
 86         inputs, target = inputs.to(device), target.to(device)
 87         optimizer.zero_grad()
 88         
 89         outputs = model(inputs)
 90         loss = criterion(outputs, target)
 91         loss.backward()
 92         optimizer.step()
 93         
 94         run_loss += loss.item()
 95         if batch_idx%300 == 299:
 96             print('[%d %5d] loss: %.3f' % (epoch+1, batch_idx+1, run_loss/300))
 97             run_loss = 0.0
 98 
 99 def test():
100     correct = 0
101     total = 0
102     with torch.no_grad():
103         for data in test_loader:
104             images, labels = data
105             images, labels = images.to(device), labels.to(device)
106             outputs = model(images)
107             _, prediction = torch.max(outputs.data, dim=1)
108             total += labels.size(0)
109             correct += (prediction == labels).sum().item()
110     print('accuracy on test set: %d %%' % (100*correct/total))
111     return correct/total
112         
113 epoch_list = []
114 acc_list = []
115 for epoch in range(10):
116     train(epoch)
117     acc = test()
118     epoch_list.append(epoch)
119     acc_list.append(acc)
120     
121 plt.plot(epoch_list, acc_list)
122 plt.ylabel('accuracy')
123 plt.xlabel('epoch')
124 plt.show()
125 
126 class DatasetSubmissionMNIST(torch.utils.data.Dataset):
127     def __init__(self, file_path, transform=None):
128         self.data = pd.read_csv(file_path)
129         self.transform = transform
130         
131     def __len__(self):
132         return len(self.data)
133     
134     def __getitem__(self, index):
135         image = self.data.iloc[index].values.astype(np.uint8).reshape((28, 28, 1))
136 
137         
138         if self.transform is not None:
139             image = self.transform(image)
140             
141         return image
142 
143 transform = transforms.Compose([
144     transforms.ToPILImage(),
145     transforms.ToTensor(),
146     transforms.Normalize(mean=(0.5,), std=(0.5,))
147 ])
148 
149 submissionset = DatasetSubmissionMNIST('/kaggle/input/digit-recognizer/test.csv', transform=transform)
150 submissionloader = torch.utils.data.DataLoader(submissionset, batch_size=batch_size, shuffle=False)
151 
152 submission = [['ImageId', 'Label']]
153 
154 with torch.no_grad():
155     model.eval()
156     image_id = 1
157 
158     for images in submissionloader:
159         images = images.cuda()
160         log_ps = model(images)
161         ps = torch.exp(log_ps)
162         top_p, top_class = ps.topk(1, dim=1)
163         
164         for prediction in top_class:
165             submission.append([image_id, prediction.item()])
166             image_id += 1
167             
168 print(len(submission) - 1)
169 import csv
170 
171 with open('submission.csv', 'w') as submissionFile:
172     writer = csv.writer(submissionFile)
173     writer.writerows(submission)
174     
175 print('Submission Complete!')
176 # submission.to_csv('/kaggle/working/submission.csv', index=False)

文章到此结束,我们下次再见

-- 大地的芳香来自每一株野草的献祭

 

标签:__,nn,--,self,torch,transform,Module,CNN,size
From: https://www.cnblogs.com/smiling-weeping-zhr/p/17730921.html

相关文章

  • 9.25 周一总结
    try{Filefile=newFile("wrong.txt");if(file.exists())file.delete();try{//创建新(空)文件(原文件不存在时,才会创建成功)file.createNewFile();}catch(Exceptione){e.printStackTrace();}FileWriterwriter=newFileWriter("wrong.txt",true);......
  • 2023021885
    2023021885杨少雄swordnewnew的主页-博客园(cnblogs.com)开朗数据库,HTML滑板,摩托车前端工程师希望大家玩的开心,在这次的合作中相互学习,相互进步......
  • bfs (9/26)
    bfs可用于权值相同为1的时候求最短路问题#include<iostream>#include<algorithm>#include<cstring>#include<queue>usingnamespacestd;constintN=110;typedefpair<int,int>PII;queue<PII>q;inta[N][N],f[N][N];intn,m;intbfs()......
  • 游客必读
    退役之前,在cnblog里发表一下自己对竞赛一些事宜的看法吧。你可以理解为闲话。如果您是其他地方的OIer,看个乐子就好;如果您是本校或者附近的OIer,希望你也可以以乐观的心态将竞赛这条路坚持下去;如果您是老师,请不要见怪,我可以保证我说的没有一句是气话。我知道我们作为学生资......
  • Codeforces Round 899 (Div. 2)
    赛后四题B题直接枚举不存在的元素即可C题的trick有点像之前abc的某道题,对于奇数位置它一定可以贡献,对于偶数位置,如果它有数选了,那么它就能够贡献。\(f[i]\)表示到前i个且至少选了一个的最大答案。#include<cstdio>#include<algorithm>#include<cstring>#include<cmath>#de......
  • B3637 最长上升子序列
    B3637最长上升子序列dp模板题以样例124134作为说明每个数都是自己的一个子序列,所以全部初始化为1从1-n开始循环,定下来当前要计算的数i再从1-i开始循环,判断i的最长上升子序列,定为j如果i比j要大,则说明是上升的,此时的长度为i的长度与j的长度+1的最......
  • Go每日一库之24:gjson
    简介之前我们介绍过gojsonq,可以方便地从一个JSON串中读取值。同时它也支持各种查询、汇总统计等功能。今天我们再介绍一个类似的库gjson。在上一篇文章Go每日一库之buntdb中我们介绍过JSON索引,内部实现其实就是使用gjson这个库。gjson实际上是get+json的缩写,用于读取JSO......
  • os.path:Python操作和处理文件路径
    前言os.path是平台独立的文件名管理库,使用该库能够很方便来处理多个平台上的文件。即使程序不打算在平台之间移值,也应当使用os.path库来完成可靠的文件名解析。本篇博文将详细介绍os.path库的用法。解析路径的基本用法os.path中的第一组函数可以用来将表示文件名的字符串解析......
  • P1111 修复公路
    并查集模板题只要按时间从小到达排序,然后加入并查集中即可,维护最大值。如果并查集的数量等于n,则直接退出即可。点击查看代码#include<bits/stdc++.h>usingnamespacestd;constintN=1e5+10;structnode{ intu,v,t; booloperator<(constnode&a)const{ re......
  • 实现function
    实现function需要先声明templateclassmyfunction;下面做特例化template<typenameR,typename...A> 需要#include<iostream>#include<functional>usingnamespacestd;template<typenameSignature>classmyfunction;template<typenameR,typena......