Advance-Ali
commited on
Delete modeling.py
Browse files- modeling.py +0 -53
modeling.py
DELETED
@@ -1,53 +0,0 @@
|
|
1 |
-
from torch import nn
|
2 |
-
from torchvision import models
|
3 |
-
from torch.nn import *
|
4 |
-
import torch
|
5 |
-
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
6 |
-
|
7 |
-
class CustomResNet18(nn.Module):
|
8 |
-
|
9 |
-
def get_out_channels(self,module):
|
10 |
-
"""تابعی برای یافتن تعداد کانالهای خروجی از لایههای کانولوشن و BatchNorm"""
|
11 |
-
if isinstance(module, nn.Conv2d):
|
12 |
-
return module.out_channels
|
13 |
-
elif isinstance(module, nn.BatchNorm2d):
|
14 |
-
return module.num_features
|
15 |
-
elif isinstance(module, nn.Linear):
|
16 |
-
return module.out_features
|
17 |
-
return None
|
18 |
-
|
19 |
-
def replace_relu_with_prelu_and_dropout(self,module, inplace=True):
|
20 |
-
for name, child in module.named_children():
|
21 |
-
# بازگشتی به لایههای زیرین
|
22 |
-
self.replace_relu_with_prelu_and_dropout(child, inplace)
|
23 |
-
|
24 |
-
if isinstance(child, nn.ReLU): # شناسایی لایه ReLU
|
25 |
-
# یافتن تعداد کانالهای خروجی از ماژول قبلی
|
26 |
-
out_channels = None
|
27 |
-
for prev_name, prev_child in module.named_children():
|
28 |
-
if prev_name == name:
|
29 |
-
break
|
30 |
-
out_channels = self.get_out_channels(prev_child) or out_channels
|
31 |
-
|
32 |
-
if out_channels is None:
|
33 |
-
raise ValueError(f"Cannot determine `out_channels` for {child}. Please check the model structure.")
|
34 |
-
|
35 |
-
# ایجاد PReLU و Dropout2d
|
36 |
-
prelu = PReLU(device=device, num_parameters=out_channels) # استفاده از تعداد کانالهای خروجی
|
37 |
-
dropout = nn.Dropout2d(p=0.2) # مقدار p تنظیم شده
|
38 |
-
|
39 |
-
# جایگزینی ReLU با Sequential شامل PReLU و Dropout
|
40 |
-
setattr(module, name, nn.Sequential(prelu, dropout).to(device))
|
41 |
-
def __init__(self):
|
42 |
-
super(CustomResNet18,self)
|
43 |
-
self.model = models.resnet18(weights = models.ResNet18_Weights.IMAGENET1K_V1).train(True).to(device)
|
44 |
-
self.replace_relu_with_prelu_and_dropout(self.model)
|
45 |
-
# print(model.fc.in_features)
|
46 |
-
|
47 |
-
|
48 |
-
number = self.model.fc.in_features
|
49 |
-
module = []
|
50 |
-
# استفاده از حلقه while برای تقسیم بر 2 تا رسیدن به عدد 8
|
51 |
-
|
52 |
-
module.append(LazyLinear(7))
|
53 |
-
self.model.fc = Sequential(*module).to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|