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
| import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import shutil
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import cv2
from PIL import Image
from src.services.hcaptcha_challenger.solutions.elephant_solution import ElephantSolution
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels,
out_channels,
kernel_size=3,
stride=stride,
padding=1,
bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels,
out_channels,
kernel_size=3,
stride=1,
padding=1,
bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.downsample = nn.Sequential()
if stride != 1 or in_channels != out_channels:
self.downsample = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels))
def forward(self, x):
residual = x
out = self.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
out += self.downsample(residual)
out = self.relu(out)
return out
class Net(nn.Module):
def __init__(self, in_channels=3, num_classes=10):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 16, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(16)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.resblock1 = ResidualBlock(16, 32)
self.resblock2 = ResidualBlock(32, 64, stride=2)
self.avgpool = nn.AvgPool2d(kernel_size=7, stride=1)
self.fc = nn.Linear(256, num_classes)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.resblock1(x)
x = self.resblock2(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
# print(x.size())
x = self.fc(x)
return x
img_path = os.path.join('..', 'database', 'elephants_drawn_with_leaves')
img_transform = torchvision.transforms.Compose([
# torchvision.transforms.Grayscale(num_output_channels=1),
# torchvision.transforms.GaussianBlur(kernel_size=3),
torchvision.transforms.Resize((64, 64)),
torchvision.transforms.ToTensor(),
])
def train():
model = Net(3, 2)
model.train()
model.cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=0.005)
# focal loss
criterion = nn.CrossEntropyLoss()
print('model:', model)
data = torchvision.datasets.ImageFolder(img_path, transform=img_transform)
data_loader = torch.utils.data.DataLoader(data, batch_size=1, shuffle=True)
print(f'{len(data)} images')
epochs = 20
# train with focal loss
for epoch in range(epochs):
total_loss = 0
total_acc = 0
for i, (img, label) in enumerate(data_loader):
img = img.cuda()
label = label.cuda()
optimizer.zero_grad()
out = model(img)
loss = criterion(out, label)
loss.backward()
optimizer.step()
if (i + 1) % 10 == 0:
print(f'epoch: {epoch + 1}, iter: {i + 1}, loss: {loss.item():.4f}')
total_loss += loss.item()
total_acc += torch.sum(torch.argmax(out, dim=1) == label).item()
print(
f'epoch: {epoch + 1}, avg loss: {total_loss / len(data):.4f}, avg acc: {total_acc / len(data):.4f}'
)
torch.save(model.state_dict(), 'model.pth')
def test_single(model, img):
img = img_transform(img)
img = img.unsqueeze(0)
img = img.cuda()
out = model(img)
pred = torch.argmax(out, dim=1)
# print(f'pred: {pred.item()}')
if pred.item() == 0:
return 0
else:
return 1
def test():
model = Net(3, 2)
model.load_state_dict(torch.load('model.pth'))
model.eval()
torch.onnx.export(model,
torch.randn(1, 3, 64, 64),
'model.onnx',
verbose=True,
export_params=True)
model.cuda()
test_data_path = os.path.join('val-dataset')
imgs = os.listdir(test_data_path)
dir1 = os.path.join('val-dataset', 'elephant_drawn_with_leaves')
dir2 = os.path.join('val-dataset', 'house_drawn_with_leaves')
dir3 = os.path.join('val-dataset', 'without_leaves')
dirs = [dir1, dir2, dir3]
for dir in dirs:
if os.path.exists(dir):
shutil.rmtree(dir)
os.mkdir(dir)
es = ElephantSolution()
for img in imgs:
if os.path.isdir(os.path.join(test_data_path, img)):
continue
img_ = cv2.imread(os.path.join(test_data_path, img))
result = 2
if es._style_classification(img_):
result = test_single(model, Image.open(os.path.join(test_data_path, img)))
print(f'{img} is {result} save to {os.path.join(dirs[result], img)}')
cv2.imwrite(os.path.join(dirs[result], img), img_)
if __name__ == '__main__':
train()
test()
|