-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdrivingModel.py
More file actions
123 lines (96 loc) · 4.27 KB
/
drivingModel.py
File metadata and controls
123 lines (96 loc) · 4.27 KB
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
import torch
import torch.nn as nn
import torch.nn.functional as F
# -----------------------------
# BasicBlock (ResNet18/34)
# -----------------------------
class BasicBlock(nn.Module):
# BasicBlock는 채널 확장 없음
expansion = 1
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
super(BasicBlock, self).__init__()
# 첫 번째 3x3 conv
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
# 두 번째 3x3 conv
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
# identity(스킵) 변환기가 필요하면 전달
self.downsample = downsample
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
# 스킵 경로용 원본 입략
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
# 필요하면 identity를 downsample로 조정(1x1 conv + BN)
if self.downsample is not None:
identity = self.downsample(x)
# Element-wise Addition (요소별 합)
# F(x) + x
out += identity
out = self.relu(out)
return out
class DribingResNet(nn.Module):
def __init__(self, num_classes=3):
super(DribingResNet, self).__init__()
block = BasicBlock
# ResNet18
layers = [2, 2, 2, 2]
self.in_channels = 64
# 초기 입력 처리 (Initial Conv Layer)
# 보통 7x7 conv를 쓰지만 CIFAR-10 정도의 작은 이미지엔 3x3을 쓰기도 함
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
# 공간 해상도 감소, 모델의 연산량 감소
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# Residual Layers (4개의 스테이지)
# _make_layer 함수를 통해 블록을 반복해서 쌓음
self.layer1 = self._make_layer(block, 64, layers[0], stride=1)
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
# 최종 출력물 (Avrage Pooling + Fully Connected)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
# 파라미터들의 초기값을 설정
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, out_channels, blocks, stride):
downsample = None
if stride != 1 or self.in_channels != out_channels * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.in_channels, out_channels * block.expansion, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels * block.expansion),
)
layers = []
# 첫 블록: stride 가능 (downsample 포함)
layers.append(block(self.in_channels, out_channels, stride, downsample))
self.in_channels = out_channels * block.expansion
# 남은 블록들: stride=1 (feature map size 유지)
# 첫 블록은 상단에서 생성 했으니 반복문은 1부터 시작
for _ in range(1, blocks):
layers.append(block(self.in_channels, out_channels))
return nn.Sequential(*layers)
def forward(self, x):
# 초기 변환
out = F.relu(self.bn1(self.conv1(x)))
out = self.maxpool(out)
# Residual Blocks 통과
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
# 분류기
out = self.avgpool(out)
out = torch.flatten(out, 1)
out = self.fc(out)
return out