-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicBlock.py
More file actions
50 lines (38 loc) · 1.72 KB
/
basicBlock.py
File metadata and controls
50 lines (38 loc) · 1.72 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
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_channels, out_channels, stride=1):
super(BasicBlock, self).__init__()
# 첫 번째 합성곱 레이어 (3x3)
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
# 두 번째 합성곱 레이어 (3x3)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
# Shortcut (Skip Connection) 처리를 위한 downsample 레이어
# 입력(x)와 출력(F(x))의 차원이 다를 때 (stride가 1이 아니거나 채널이 변했을 때) 맞춰주는 역할
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != self.expansion * out_channels:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, self.expansion * out_channels, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels)
)
def forward(self, x):
# 1. 원본 입력 저장 (Skip Connection 처리를 위함)
identity = x
# 2. 주 경로 (Main Path) : F(x) 계산
out = self.conv1(x)
out = self.bn1(out)
out = F.relu(out)
out = self.conv2(out)
out = self.bn1(out)
# 3. 차원 맞추기 (필요한 경우 1x1 conv 적용)
identity = self.shortcut(identity)
# 4. Element-wise Addition (요소별 합)
# F(x) + x
out += identity
# 5. 최종 활성화 함수
out = F.relu(out)
return out