ResNet18实现

image.png

因为本人GPU显存不够就可怜的2G 实在hold不住ResNet 的参数量只好将 残差模块只弄两个卷积核,而且batch_size也修改为1只进行代码测试 - 。 -,听说COLAB上有免费的16G GPU使用下次在运行,由于GPU会进行并行运算这个计算出的显存与实际使用的显存也有点差距。

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import pickle
# 数据加载
def load(file):
    with open(file, 'rb') as fo:
        dict = pickle.load(fo, encoding='bytes')
    return dict
fil_1 = 'E:\Download\DigitalImage\cifar-10-batches-py\data_batch_1'
fil_2 = 'E:\Download\DigitalImage\cifar-10-batches-py\data_batch_2'
fil_3 = 'E:\Download\DigitalImage\cifar-10-batches-py\data_batch_3'
fil_4 = 'E:\Download\DigitalImage\cifar-10-batches-py\data_batch_4'
fil_5 = 'E:\Download\DigitalImage\cifar-10-batches-py\data_batch_5'
fil_6 = 'E:\Download\DigitalImage\cifar-10-batches-py\\test_batch_1'

path = [fil_1,fil_2,fil_3,fil_4,fil_5,fil_6]
train_data = []
test_data = []
for i in range(len(path)):
    if i != len(path)-1:
        datas = load(path[i])
        a = datas[b'data'].reshape(10000,3,32,32)
        train_data.append((torch.FloatTensor(a),torch.LongTensor(datas[b'labels'])))
        print()
    else:
        datas = load(path[i])
        test_data = [(torch.FloatTensor(datas[b'data'].reshape(10000,3,32,32)),torch.LongTensor(datas[b'labels']))]





# 残差块定义
class ResBlock(nn.Module):
    
    
    def __init__(self,in_channel,out_channel,stri):
        super(ResBlock,self).__init__()
        self.cov1 = nn.Conv2d(in_channel,out_channel,kernel_size = 3,stride = stri,padding = 1)
        self.bn1 = nn.BatchNorm2d(out_channel)
        self.cov2 = nn.Conv2d(out_channel,out_channel,kernel_size = 3,stride = 1,padding = 1)
        self.bn2 = nn.BatchNorm2d(out_channel)
        # 恒等映射保证和输出维度一致
        self.identity = nn.Sequential(
             nn.Conv2d(in_channel,out_channel,kernel_size = 1,stride =stri,padding = 0),
             nn.BatchNorm2d(out_channel)
            )
    def forward(self,x):
        out = F.relu(self.cov1(x))
        out = self.bn1(out)
        out = F.relu(self.cov2(out))
        out = self.bn2(out)
        #out = F.relu(self.cov2(out))
        #out = self.bn2(out)
        #out = F.relu(self.cov2(out))
        #out = self.bn2(out)
        #print(self.identity(x).shape,out.shape)
        out = self.identity(x) + out
        out = F.relu(out)
        return out
#测试代码输入伪图片
x = torch.randn(2,3,32,32)
a = ResBlock(3,64,2)
print(a(x).shape)
torch.Size([2, 64, 16, 16])
# 残差块网络连接
class Flatten(nn.Module):
    def __init__(self):
        super(Flatten,self).__init__()
        
    def forward(self,input):
        return input.view(input.size(0),-1)

class Resnet18(nn.Module):
    
    def __init__(self):
        super(Resnet18,self).__init__()
        
        self.model = nn.Sequential(
            nn.Conv2d(3,64,kernel_size = 3,stride = 1,padding = 1),
            nn.BatchNorm2d(64),
            ResBlock(64,128,stri = 2),
            ResBlock(128,256,stri = 2),
            ResBlock(256,512,stri = 2),
            ResBlock(512,1024,stri = 2),
            nn.AvgPool2d(2),
            Flatten(),
            nn.Linear(1024,10)
        ) 
   
    def forward(self,x):
        return self.model(x)
#测试代码
x = torch.randn(2,3,32,32)
c = Resnet18()
print(c(x).shape)
torch.Size([2, 10])
epochs = 10
device = torch.device('cuda:0')
ResNet18 = Resnet18().to(device)
optimizer = optim.SGD(ResNet18.parameters(),lr = 0.01)
loss_fun = nn.CrossEntropyLoss().to(device)
def Run():
    for epoch in range(epochs):
        ResNet18.train()
        for index,(data,label) in enumerate(train_data):
            for i in range(100):
                datas = data[i:(i+1),:,:,:].to(device)
                #print(datas.shape)
                labels = label[i:(i+1)].to(device)
                #print(labels.shape)
                logits = ResNet18(datas)
                loss = loss_fun(logits,labels)
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
            print('epoch:{}\t batch:{}\t loss:{}'.format(epoch,index,loss.item()))
        ResNet18.eval()
        loss = 0
        correct = 0
        AVGloss = 0
        for index,(data,label) in enumerate(test_data):
            for i in range(100):
                datas = data[i:i+1,:,:,:].to(device)
                labels = label[i:i+1].to(device)
                logits = ResNet18(datas)
                loss += loss_fun(logits,labels)
                predict = logits.argmax(dim=1)
                correct += predict.eq(labels).float().sum().item()
            loss /= 100.
            print('epochs:{} \t accuracy:{}%\t test_date_AVGloss:{} '.format(epoch,100.*correct/100,loss.item()))
Run()
epoch:0  batch:0     loss:1.193771243095398
epoch:0  batch:1     loss:0.6211187839508057
epoch:0  batch:2     loss:2.3206470012664795
epoch:0  batch:3     loss:1.0057952404022217
epoch:0  batch:4     loss:1.6052329540252686
epochs:0     accuracy:7.0%   test_date_AVGloss:4.08225154876709 
epoch:1  batch:0     loss:1.168436050415039
epoch:1  batch:1     loss:0.6469242572784424
epoch:1  batch:2     loss:1.9090821743011475
epoch:1  batch:3     loss:0.8259971141815186
epoch:1  batch:4     loss:1.482107400894165
epochs:1     accuracy:7.0%   test_date_AVGloss:4.174167633056641 
epoch:2  batch:0     loss:1.1068801879882812
epoch:2  batch:1     loss:0.5857620239257812
epoch:2  batch:2     loss:1.4080276489257812
epoch:2  batch:3     loss:0.6490111351013184
epoch:2  batch:4     loss:1.3858662843704224
epochs:2     accuracy:7.0%   test_date_AVGloss:4.06494140625 
epoch:3  batch:0     loss:0.7395391464233398
epoch:3  batch:1     loss:0.5753352642059326
epoch:3  batch:2     loss:1.252335786819458
epoch:3  batch:3     loss:0.41171860694885254
epoch:3  batch:4     loss:1.258840560913086
epochs:3     accuracy:10.0%  test_date_AVGloss:3.6299731731414795 
epoch:4  batch:0     loss:0.5887634754180908
epoch:4  batch:1     loss:0.5793724060058594
epoch:4  batch:2     loss:1.1198831796646118
epoch:4  batch:3     loss:0.300403356552124
epoch:4  batch:4     loss:0.7450690269470215
epochs:4     accuracy:14.0%  test_date_AVGloss:3.8890163898468018 
epoch:5  batch:0     loss:0.24598288536071777
epoch:5  batch:1     loss:0.16252756118774414
epoch:5  batch:2     loss:0.6145534515380859
epoch:5  batch:3     loss:0.1928553581237793
epoch:5  batch:4     loss:0.20372629165649414
epochs:5     accuracy:18.0%  test_date_AVGloss:3.09653377532959 
epoch:6  batch:0     loss:0.07158946990966797
epoch:6  batch:1     loss:0.2547154426574707
epoch:6  batch:2     loss:0.2163069248199463
epoch:6  batch:3     loss:0.1844019889831543
epoch:6  batch:4     loss:0.12868928909301758
epochs:6     accuracy:23.0%  test_date_AVGloss:2.7130041122436523 
epoch:7  batch:0     loss:0.04795646667480469
epoch:7  batch:1     loss:0.053249359130859375
epoch:7  batch:2     loss:0.02186727523803711
epoch:7  batch:3     loss:0.032016754150390625
epoch:7  batch:4     loss:0.02663278579711914
epochs:7     accuracy:23.0%  test_date_AVGloss:2.557596445083618 
epoch:8  batch:0     loss:0.03522920608520508
epoch:8  batch:1     loss:0.03684282302856445
epoch:8  batch:2     loss:0.014127731323242188
epoch:8  batch:3     loss:0.018548965454101562
epoch:8  batch:4     loss:0.019474029541015625
epochs:8     accuracy:21.0%  test_date_AVGloss:2.537302255630493 
epoch:9  batch:0     loss:0.01775217056274414
epoch:9  batch:1     loss:0.023839473724365234
epoch:9  batch:2     loss:0.011283397674560547
epoch:9  batch:3     loss:0.014598846435546875
epoch:9  batch:4     loss:0.014908790588378906
epochs:9     accuracy:25.0%  test_date_AVGloss:2.5501718521118164 
print(len(test_data))
1
# 参数字节数
byte = (9*(3*64+64*64+64*128+128*128+128*256+256*256+256*512+512*512+512*1024+1024*1024)+1024*10)*4
# SGD
sgd_byte = byte
# 保存梯度字节数
print(byte)
grad = byte
# 输入输出显存
put = (3*32*32+32*32*64+64*16*16+128*8*8+256*4*4+512*2*2+1024)*4
print((byte*3+put)/1000000)
75397888
226.595072

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345

推荐阅读更多精彩内容