xcssgzs commited on
Commit
a21c7ff
1 Parent(s): 60a0de6

Upload 3 files

Browse files
Files changed (3) hide show
  1. efficientNetV2.pth +3 -0
  2. model.py +377 -0
  3. script.py +90 -0
efficientNetV2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1013db4ed47636273955a4c81242df3318315688754e30720e2e54be29a2347e
3
+ size 90752533
model.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from functools import partial
3
+ from typing import Callable, Optional
4
+
5
+ import torch.nn as nn
6
+ import torch
7
+ from torch import Tensor
8
+
9
+
10
+ def drop_path(x, drop_prob: float = 0., training: bool = False):
11
+ """
12
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
13
+ "Deep Networks with Stochastic Depth", https://arxiv.org/pdf/1603.09382.pdf
14
+
15
+ This function is taken from the rwightman.
16
+ It can be seen here:
17
+ https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py#L140
18
+ """
19
+ if drop_prob == 0. or not training:
20
+ return x
21
+ keep_prob = 1 - drop_prob
22
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
23
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
24
+ random_tensor.floor_() # binarize
25
+ output = x.div(keep_prob) * random_tensor
26
+ return output
27
+
28
+
29
+ class DropPath(nn.Module):
30
+ """
31
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
32
+ "Deep Networks with Stochastic Depth", https://arxiv.org/pdf/1603.09382.pdf
33
+ """
34
+ def __init__(self, drop_prob=None):
35
+ super(DropPath, self).__init__()
36
+ self.drop_prob = drop_prob
37
+
38
+ def forward(self, x):
39
+ return drop_path(x, self.drop_prob, self.training)
40
+
41
+
42
+ class ConvBNAct(nn.Module):
43
+ def __init__(self,
44
+ in_planes: int,
45
+ out_planes: int,
46
+ kernel_size: int = 3,
47
+ stride: int = 1,
48
+ groups: int = 1,
49
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
50
+ activation_layer: Optional[Callable[..., nn.Module]] = None):
51
+ super(ConvBNAct, self).__init__()
52
+
53
+ padding = (kernel_size - 1) // 2
54
+ if norm_layer is None:
55
+ norm_layer = nn.BatchNorm2d
56
+ if activation_layer is None:
57
+ activation_layer = nn.SiLU # alias Swish (torch>=1.7)
58
+
59
+ self.conv = nn.Conv2d(in_channels=in_planes,
60
+ out_channels=out_planes,
61
+ kernel_size=kernel_size,
62
+ stride=stride,
63
+ padding=padding,
64
+ groups=groups,
65
+ bias=False)
66
+
67
+ self.bn = norm_layer(out_planes)
68
+ self.act = activation_layer()
69
+
70
+ def forward(self, x):
71
+ result = self.conv(x)
72
+ result = self.bn(result)
73
+ result = self.act(result)
74
+
75
+ return result
76
+
77
+
78
+ class SqueezeExcite(nn.Module):
79
+ def __init__(self,
80
+ input_c: int, # block input channel
81
+ expand_c: int, # block expand channel
82
+ se_ratio: float = 0.25):
83
+ super(SqueezeExcite, self).__init__()
84
+ squeeze_c = int(input_c * se_ratio)
85
+ self.conv_reduce = nn.Conv2d(expand_c, squeeze_c, 1)
86
+ self.act1 = nn.SiLU() # alias Swish
87
+ self.conv_expand = nn.Conv2d(squeeze_c, expand_c, 1)
88
+ self.act2 = nn.Sigmoid()
89
+
90
+ def forward(self, x: Tensor) -> Tensor:
91
+ scale = x.mean((2, 3), keepdim=True)
92
+ scale = self.conv_reduce(scale)
93
+ scale = self.act1(scale)
94
+ scale = self.conv_expand(scale)
95
+ scale = self.act2(scale)
96
+ return scale * x
97
+
98
+
99
+ class MBConv(nn.Module):
100
+ def __init__(self,
101
+ kernel_size: int,
102
+ input_c: int,
103
+ out_c: int,
104
+ expand_ratio: int,
105
+ stride: int,
106
+ se_ratio: float,
107
+ drop_rate: float,
108
+ norm_layer: Callable[..., nn.Module]):
109
+ super(MBConv, self).__init__()
110
+
111
+ if stride not in [1, 2]:
112
+ raise ValueError("illegal stride value.")
113
+
114
+ self.has_shortcut = (stride == 1 and input_c == out_c)
115
+
116
+ activation_layer = nn.SiLU # alias Swish
117
+ expanded_c = input_c * expand_ratio
118
+
119
+ # 在EfficientNetV2中,MBConv中不存在expansion=1的情况所以conv_pw肯定存在
120
+ assert expand_ratio != 1
121
+ # Point-wise expansion
122
+ self.expand_conv = ConvBNAct(input_c,
123
+ expanded_c,
124
+ kernel_size=1,
125
+ norm_layer=norm_layer,
126
+ activation_layer=activation_layer)
127
+
128
+ # Depth-wise convolution
129
+ self.dwconv = ConvBNAct(expanded_c,
130
+ expanded_c,
131
+ kernel_size=kernel_size,
132
+ stride=stride,
133
+ groups=expanded_c,
134
+ norm_layer=norm_layer,
135
+ activation_layer=activation_layer)
136
+
137
+ self.se = SqueezeExcite(input_c, expanded_c, se_ratio) if se_ratio > 0 else nn.Identity()
138
+
139
+ # Point-wise linear projection
140
+ self.project_conv = ConvBNAct(expanded_c,
141
+ out_planes=out_c,
142
+ kernel_size=1,
143
+ norm_layer=norm_layer,
144
+ activation_layer=nn.Identity) # 注意这里没有激活函数,所有传入Identity
145
+
146
+ self.out_channels = out_c
147
+
148
+ # 只有在使用shortcut连接时才使用dropout层
149
+ self.drop_rate = drop_rate
150
+ if self.has_shortcut and drop_rate > 0:
151
+ self.dropout = DropPath(drop_rate)
152
+
153
+ def forward(self, x: Tensor) -> Tensor:
154
+ result = self.expand_conv(x)
155
+ result = self.dwconv(result)
156
+ result = self.se(result)
157
+ result = self.project_conv(result)
158
+
159
+ if self.has_shortcut:
160
+ if self.drop_rate > 0:
161
+ result = self.dropout(result)
162
+ result += x
163
+
164
+ return result
165
+
166
+
167
+ class FusedMBConv(nn.Module):
168
+ def __init__(self,
169
+ kernel_size: int,
170
+ input_c: int,
171
+ out_c: int,
172
+ expand_ratio: int,
173
+ stride: int,
174
+ se_ratio: float,
175
+ drop_rate: float,
176
+ norm_layer: Callable[..., nn.Module]):
177
+ super(FusedMBConv, self).__init__()
178
+
179
+ assert stride in [1, 2]
180
+ assert se_ratio == 0
181
+
182
+ self.has_shortcut = stride == 1 and input_c == out_c
183
+ self.drop_rate = drop_rate
184
+
185
+ self.has_expansion = expand_ratio != 1
186
+
187
+ activation_layer = nn.SiLU # alias Swish
188
+ expanded_c = input_c * expand_ratio
189
+
190
+ # 只有当expand ratio不等于1时才有expand conv
191
+ if self.has_expansion:
192
+ # Expansion convolution
193
+ self.expand_conv = ConvBNAct(input_c,
194
+ expanded_c,
195
+ kernel_size=kernel_size,
196
+ stride=stride,
197
+ norm_layer=norm_layer,
198
+ activation_layer=activation_layer)
199
+
200
+ self.project_conv = ConvBNAct(expanded_c,
201
+ out_c,
202
+ kernel_size=1,
203
+ norm_layer=norm_layer,
204
+ activation_layer=nn.Identity) # 注意没有激活函数
205
+ else:
206
+ # 当只有project_conv时的情况
207
+ self.project_conv = ConvBNAct(input_c,
208
+ out_c,
209
+ kernel_size=kernel_size,
210
+ stride=stride,
211
+ norm_layer=norm_layer,
212
+ activation_layer=activation_layer) # 注意有激活函数
213
+
214
+ self.out_channels = out_c
215
+
216
+ # 只有在使用shortcut连接时才使用dropout层
217
+ self.drop_rate = drop_rate
218
+ if self.has_shortcut and drop_rate > 0:
219
+ self.dropout = DropPath(drop_rate)
220
+
221
+ def forward(self, x: Tensor) -> Tensor:
222
+ if self.has_expansion:
223
+ result = self.expand_conv(x)
224
+ result = self.project_conv(result)
225
+ else:
226
+ result = self.project_conv(x)
227
+
228
+ if self.has_shortcut:
229
+ if self.drop_rate > 0:
230
+ result = self.dropout(result)
231
+
232
+ result += x
233
+
234
+ return result
235
+
236
+
237
+ class EfficientNetV2(nn.Module):
238
+ def __init__(self,
239
+ model_cnf: list,
240
+ num_classes: int = 1000,
241
+ num_features: int = 1280,
242
+ dropout_rate: float = 0.2,
243
+ drop_connect_rate: float = 0.2):
244
+ super(EfficientNetV2, self).__init__()
245
+
246
+ for cnf in model_cnf:
247
+ assert len(cnf) == 8
248
+
249
+ norm_layer = partial(nn.BatchNorm2d, eps=1e-3, momentum=0.1)
250
+
251
+ stem_filter_num = model_cnf[0][4]
252
+
253
+ self.stem = ConvBNAct(3,
254
+ stem_filter_num,
255
+ kernel_size=3,
256
+ stride=2,
257
+ norm_layer=norm_layer) # 激活函数默认是SiLU
258
+
259
+ total_blocks = sum([i[0] for i in model_cnf])
260
+ block_id = 0
261
+ blocks = []
262
+ for cnf in model_cnf:
263
+ repeats = cnf[0]
264
+ op = FusedMBConv if cnf[-2] == 0 else MBConv
265
+ for i in range(repeats):
266
+ blocks.append(op(kernel_size=cnf[1],
267
+ input_c=cnf[4] if i == 0 else cnf[5],
268
+ out_c=cnf[5],
269
+ expand_ratio=cnf[3],
270
+ stride=cnf[2] if i == 0 else 1,
271
+ se_ratio=cnf[-1],
272
+ drop_rate=drop_connect_rate * block_id / total_blocks,
273
+ norm_layer=norm_layer))
274
+ block_id += 1
275
+ self.blocks = nn.Sequential(*blocks)
276
+
277
+ head_input_c = model_cnf[-1][-3]
278
+ head = OrderedDict()
279
+
280
+ head.update({"project_conv": ConvBNAct(head_input_c,
281
+ num_features,
282
+ kernel_size=1,
283
+ norm_layer=norm_layer)}) # 激活函数默认是SiLU
284
+
285
+ head.update({"avgpool": nn.AdaptiveAvgPool2d(1)})
286
+ head.update({"flatten": nn.Flatten()})
287
+
288
+ if dropout_rate > 0:
289
+ head.update({"dropout": nn.Dropout(p=dropout_rate, inplace=True)})
290
+ head.update({"classifier": nn.Linear(num_features, num_classes)})
291
+
292
+ self.head = nn.Sequential(head)
293
+
294
+ # initial weights
295
+ for m in self.modules():
296
+ if isinstance(m, nn.Conv2d):
297
+ nn.init.kaiming_normal_(m.weight, mode="fan_out")
298
+ if m.bias is not None:
299
+ nn.init.zeros_(m.bias)
300
+ elif isinstance(m, nn.BatchNorm2d):
301
+ nn.init.ones_(m.weight)
302
+ nn.init.zeros_(m.bias)
303
+ elif isinstance(m, nn.Linear):
304
+ nn.init.normal_(m.weight, 0, 0.01)
305
+ nn.init.zeros_(m.bias)
306
+
307
+ def forward(self, x: Tensor) -> Tensor:
308
+ x = self.stem(x)
309
+ x = self.blocks(x)
310
+ x = self.head(x)
311
+
312
+ return x
313
+
314
+
315
+ def efficientnetv2_s(num_classes: int = 1000):
316
+ """
317
+ EfficientNetV2
318
+ https://arxiv.org/abs/2104.00298
319
+ """
320
+ # train_size: 300, eval_size: 384
321
+
322
+ # repeat, kernel, stride, expansion, in_c, out_c, operator, se_ratio
323
+ model_config = [[2, 3, 1, 1, 24, 24, 0, 0],
324
+ [4, 3, 2, 4, 24, 48, 0, 0],
325
+ [4, 3, 2, 4, 48, 64, 0, 0],
326
+ [6, 3, 2, 4, 64, 128, 1, 0.25],
327
+ [9, 3, 1, 6, 128, 160, 1, 0.25],
328
+ [15, 3, 2, 6, 160, 256, 1, 0.25]]
329
+
330
+ model = EfficientNetV2(model_cnf=model_config,
331
+ num_classes=num_classes,
332
+ dropout_rate=0.2)
333
+ return model
334
+
335
+
336
+ def efficientnetv2_m(num_classes: int = 1000):
337
+ """
338
+ EfficientNetV2
339
+ https://arxiv.org/abs/2104.00298
340
+ """
341
+ # train_size: 384, eval_size: 480
342
+
343
+ # repeat, kernel, stride, expansion, in_c, out_c, operator, se_ratio
344
+ model_config = [[3, 3, 1, 1, 24, 24, 0, 0],
345
+ [5, 3, 2, 4, 24, 48, 0, 0],
346
+ [5, 3, 2, 4, 48, 80, 0, 0],
347
+ [7, 3, 2, 4, 80, 160, 1, 0.25],
348
+ [14, 3, 1, 6, 160, 176, 1, 0.25],
349
+ [18, 3, 2, 6, 176, 304, 1, 0.25],
350
+ [5, 3, 1, 6, 304, 512, 1, 0.25]]
351
+
352
+ model = EfficientNetV2(model_cnf=model_config,
353
+ num_classes=num_classes,
354
+ dropout_rate=0.3)
355
+ return model
356
+
357
+
358
+ def efficientnetv2_l(num_classes: int = 1000):
359
+ """
360
+ EfficientNetV2
361
+ https://arxiv.org/abs/2104.00298
362
+ """
363
+ # train_size: 384, eval_size: 480
364
+
365
+ # repeat, kernel, stride, expansion, in_c, out_c, operator, se_ratio
366
+ model_config = [[4, 3, 1, 1, 32, 32, 0, 0],
367
+ [7, 3, 2, 4, 32, 64, 0, 0],
368
+ [7, 3, 2, 4, 64, 96, 0, 0],
369
+ [10, 3, 2, 4, 96, 192, 1, 0.25],
370
+ [19, 3, 1, 6, 192, 224, 1, 0.25],
371
+ [25, 3, 2, 6, 224, 384, 1, 0.25],
372
+ [7, 3, 1, 6, 384, 640, 1, 0.25]]
373
+
374
+ model = EfficientNetV2(model_cnf=model_config,
375
+ num_classes=num_classes,
376
+ dropout_rate=0.4)
377
+ return model
script.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import torch
4
+ from PIL import Image
5
+ from torchvision import transforms
6
+
7
+ from model import efficientnetv2_s as create_model
8
+
9
+
10
+ def predict(test_metadata, root_path='/tmp/data/private_testset', output_csv_path='./submission.csv'):
11
+
12
+ img_size = {"s": [384, 384], # train_size, val_size
13
+ "m": [384, 480],
14
+ "l": [384, 480]}
15
+ num_model = "s"
16
+
17
+ data_transform = transforms.Compose(
18
+ [transforms.Resize(img_size[num_model][1]),
19
+ transforms.CenterCrop(img_size[num_model][1]),
20
+ transforms.ToTensor(),
21
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
22
+
23
+ id_list = test_metadata['observation_id'].tolist()
24
+ img_name_list = test_metadata['filename'].tolist()
25
+ print(os.path.abspath(os.path.dirname(__file__)))
26
+
27
+ id2classId = dict()
28
+ id2prob = dict()
29
+ prob_list = list()
30
+ classId_list = list()
31
+
32
+ for img_name in img_name_list:
33
+ img_path = os.path.join(root_path, img_name)
34
+ assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path)
35
+ img = Image.open(img_path).convert('RGB')
36
+ img = data_transform(img)
37
+ img = torch.unsqueeze(img, dim=0)
38
+
39
+ with torch.no_grad():
40
+ # predict class
41
+ output = model(img.to(device)).cpu()
42
+ predict = torch.softmax(output, dim=1)
43
+ probs, classesId = torch.max(predict, dim=1)
44
+ prob = probs.data.numpy().tolist()[0]
45
+ classesId = classesId.data.numpy().tolist()[0]
46
+ prob_list.append(prob)
47
+ classId_list.append(classesId)
48
+
49
+ for i, id in enumerate(id_list):
50
+ if id not in id2classId.keys():
51
+ id2classId[id] = classId_list[i]
52
+ id2prob[id] = prob_list[i]
53
+ else:
54
+ if prob_list[i] > id2prob[id]:
55
+ id2classId[id] = classId_list[i]
56
+ id2prob[id] = prob_list[i]
57
+ classes = list()
58
+ for id in id_list:
59
+ classes.append(str(id2classId[id]))
60
+ test_metadata["class_id"] = classes
61
+
62
+ user_pred_df = test_metadata.drop_duplicates("observation_id", keep="first")
63
+ user_pred_df[["observation_id", "class_id"]].to_csv(output_csv_path, index=None)
64
+
65
+
66
+ if __name__ == '__main__':
67
+ import zipfile
68
+
69
+ with zipfile.ZipFile("/tmp/data/private_testset.zip", 'r') as zip_ref:
70
+ zip_ref.extractall("/tmp/data")
71
+ root_path = '/tmp/data/private_testset'
72
+
73
+ # root_path = "../../data_set/flower_data/val/n1"
74
+
75
+ # json_file = open(json_path, "r")
76
+ # index2class = json.load(json_file)
77
+
78
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
79
+ # create model
80
+ model = create_model(num_classes=1784).to(device)
81
+
82
+ # load model weights
83
+ model_weight_path = "./efficientNetV2.pth"
84
+ model.load_state_dict(torch.load(model_weight_path, map_location=device))
85
+ model.eval()
86
+
87
+ metadata_file_path = "./SnakeCLEF2024_TestMetadata.csv"
88
+ # metadata_file_path = "./test1.csv"
89
+ test_metadata = pd.read_csv(metadata_file_path)
90
+ predict(test_metadata, root_path)