forked from shawn233/DPDataSharing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dpn_auto.py
188 lines (167 loc) · 6.81 KB
/
dpn_auto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
'''Dual Path Networks in PyTorch.'''
import torch
import torchvision
import matplotlib.pyplot as plt
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
import torch.optim as optim
import torch.nn as nn
from auto_cifar import autoencoder
from torchvision.utils import save_image
import torchvision.transforms as transforms
##load data
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,download=True, transform=transform)
testloader=torch.utils.data.DataLoader(testset, batch_size=64,shuffle=False, num_workers=2)
classes=('plane','car','bird','cat','deer','dog','frog','horse','ship','truck')
##functions to show an image
def to_img(x):
x = 0.5 * (x + 1)
x = x.clamp(0, 1)
x = x.view(x.size(0), 3, 32, 32)
return x
##function to calculate accuracy
def accuracy(label,output):
_,prediction=torch.max(output.data,1)
return (prediction==label).sum()
##model definition
autoencoder=autoencoder().cuda()
criterion_auto=nn.MSELoss().cuda()
optimizer_auto=optim.Adam(autoencoder.parameters(),lr=0.01)
#dpn92
class Bottleneck(nn.Module):
def __init__(self, last_planes, in_planes, out_planes, dense_depth, stride, first_layer):
super(Bottleneck, self).__init__()
self.out_planes = out_planes
self.dense_depth = dense_depth
self.conv1 = nn.Conv2d(last_planes, in_planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv2 = nn.Conv2d(in_planes, in_planes, kernel_size=3, stride=stride, padding=1, groups=32, bias=False)
self.bn2 = nn.BatchNorm2d(in_planes)
self.conv3 = nn.Conv2d(in_planes, out_planes+dense_depth, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(out_planes+dense_depth)
self.shortcut = nn.Sequential()
if first_layer:
self.shortcut = nn.Sequential(
nn.Conv2d(last_planes, out_planes+dense_depth, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_planes+dense_depth)
)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = F.relu(self.bn2(self.conv2(out)))
out = self.bn3(self.conv3(out))
x = self.shortcut(x)
d = self.out_planes
out = torch.cat([x[:,:d,:,:]+out[:,:d,:,:], x[:,d:,:,:], out[:,d:,:,:]], 1)
out = F.relu(out)
return out
class DPN(nn.Module):
def __init__(self, cfg):
super(DPN, self).__init__()
in_planes, out_planes = cfg['in_planes'], cfg['out_planes']
num_blocks, dense_depth = cfg['num_blocks'], cfg['dense_depth']
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.last_planes = 64
self.layer1 = self._make_layer(in_planes[0], out_planes[0], num_blocks[0], dense_depth[0], stride=1)
self.layer2 = self._make_layer(in_planes[1], out_planes[1], num_blocks[1], dense_depth[1], stride=2)
self.layer3 = self._make_layer(in_planes[2], out_planes[2], num_blocks[2], dense_depth[2], stride=2)
self.layer4 = self._make_layer(in_planes[3], out_planes[3], num_blocks[3], dense_depth[3], stride=2)
self.linear = nn.Linear(out_planes[3]+(num_blocks[3]+1)*dense_depth[3], 10)
def _make_layer(self, in_planes, out_planes, num_blocks, dense_depth, stride):
strides = [stride] + [1]*(num_blocks-1)
layers = []
for i,stride in enumerate(strides):
layers.append(Bottleneck(self.last_planes, in_planes, out_planes, dense_depth, stride, i==0))
self.last_planes = out_planes + (i+2) * dense_depth
return nn.Sequential(*layers)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = F.avg_pool2d(out, 4)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
def DPN26():
cfg = {
'in_planes': (96,192,384,768),
'out_planes': (256,512,1024,2048),
'num_blocks': (2,2,2,2),
'dense_depth': (16,32,24,128)
}
return DPN(cfg)
def DPN92():
cfg = {
'in_planes': (96,192,384,768),
'out_planes': (256,512,1024,2048),
'num_blocks': (3,4,20,3),
'dense_depth': (16,32,24,128)
}
return DPN(cfg)
dpn=DPN92().cuda()
criterion=nn.CrossEntropyLoss().cuda()
optimizer=optim.Adam(dpn.parameters(),lr=0.01,weight_decay=1e-5)
##training auto-encoder
for epoch in range(0):
for i, data in enumerate(trainloader,0):
inputs,labels=data
inputs,labels=Variable(inputs),Variable(labels)
optimizer_auto.zero_grad()
output=autoencoder(inputs.cuda())
loss=criterion_auto(output,inputs)
loss.backward()
optimizer_auto.step()
if i %100==0:
print("epoch:{}, iter:{}, loss:{}".format(epoch,i,loss.data[0]))
print("finished autoencoder training")
##training dpn
for epoch in range(0):
for i,data in enumerate(trainloader,0):
image,label=data
image,label=Variable(image),Variable(label)
newinputs=autoencoder.encoder(image.cuda())
output=dpn(newinputs)
loss=criterion(output,label.cuda())
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i%100==0):
print("Epoch:{}, Round:{}, loss:{}".format(epoch,i,loss.data[0]))
testdata=iter(testloader)
image,label=testdata.next()
image=Variable(image)
newinputs=autoencoder.encoder(image.cuda())
output=dpn(newinputs.cuda())
num=accuracy(label.cuda(),output)
print("Epoch:{} ends, Accuracy:{}%".format(epoch,100*num/float(label.size(0))))
##evaluation
total=0.0
correct=0.0
for data in testloader:
image,label=data
newinputs=autoencoder.encoder(image.cuda())
output=dpn(newinputs)
correct+=accuracy(label.cuda(),output)
total+=label.size(0)
print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
##more detailed evaluation
class_correct=list(0. for i in range(10))
class_total=list(0. for i in range(10))
for data in testloader:
images,labels=data
newinput=autoencoder.encoder(Variable(images).cuda())
outputs=dpn(newinput)
_,predicted=torch.max(outputs.data,1)
c=(predicted==labels).squeeze()
for i in range(4):
label=labels[i]
class_correct[label]+=c[i]
class_total[label]+=1
for i in range(10):
print('Accuracy of %5s : %2d %%' % (classes[i], 100 * class_correct[i] / class_total[i]))