-
Notifications
You must be signed in to change notification settings - Fork 0
/
targetmodel.py
executable file
·73 lines (60 loc) · 2.03 KB
/
targetmodel.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
import torch.nn as nn
from PIL import Image
from torch.utils.data import Dataset
import numpy as np
from transform_file import cut
root = '/home/wang/Dataset/Caltech256/'
# root = '/media/this/02ff0572-4aa8-47c6-975d-16c3b8062013/Caltech256/'
def default_loader(path):
return Image.open(path).convert('RGB')
class MyDataset(Dataset):
def __init__(self, txt, transform=None, pert=np.zeros(1), loader=default_loader):
fh = open(txt, 'r')
imgs = []
for line in fh:
line = line.strip()
words = line.split()
imgs.append((words[0], int(words[1])))
self.imgs = imgs
self.transform = transform
self.loader = loader
self.pert = pert
def __getitem__(self, index):
'''
return Tensor with v
'''
fn, label = self.imgs[index]
img = Image.fromarray(np.clip(cut(self.loader(fn))+self.pert, 0, 255).astype(np.uint8))
if self.transform is not None:
img = self.transform(img)
return img, label
def __len__(self):
return len(self.imgs)
class ResNet_ft(nn.Module):
def __init__(self, model):
super(ResNet_ft, self).__init__()
self.resnet_layer = nn.Sequential(*list(model.children())[:-1])
self.Linear_layer = nn.Linear(2048, 257)
def forward(self, x):
x = self.resnet_layer(x)
x = x.view(x.size(0), -1)
x = self.Linear_layer(x)
return x
class VGG_ft(nn.Module):
def __init__(self, model):
super(VGG_ft, self).__init__()
self.feature_layer = nn.Sequential(*list(model.children())[:-1])
self.classifier_layer = nn.Sequential(
nn.Linear(25088, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 257),
)
def forward(self, x):
x = self.feature_layer(x)
x = x.view(x.size(0), -1)
x = self.classifier_layer(x)
return x