File size: 7,750 Bytes
e1b5e8e | 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 179 180 181 182 183 184 185 186 187 188 189 190 | import numpy as np
# ๋์ ์์ฑ์ ์ํ ํฌํผ (๊ฐ์ค์น๋ฅผ ์๋ฏธ)
def randn(*shape):
# Xavier/Glorot ์ด๊ธฐํ์ ์ ์ฌํ๊ฒ ์ค์ผ์ผ๋ง (์ดํด๋ฅผ ๋๊ธฐ ์ํจ)
return np.random.randn(*shape) * np.sqrt(2.0 / (shape[0] * np.prod(shape[2:])))
def randn_bias(*shape):
return np.zeros(shape)
class NumpyUNet:
def __init__(self, in_channels=1, out_classes=2):
"""
NumPy๋ก U-Net ๊ฐ์ค์น๋ฅผ ์ด๊ธฐํํฉ๋๋ค.
์ฌ๊ธฐ์๋ 2-Level U-Net์ ํ๋์ฝ๋ฉํฉ๋๋ค. (์: 64 -> 128 -> 256(๋ฐ๋ฅ) -> 128 -> 64)
"""
self.weights = {}
# --- ์ธ์ฝ๋ (Encoder) ๊ฐ์ค์น ---
# Level 1 (Input -> 64 filters)
self.weights['enc1_w1'] = randn(64, in_channels, 3, 3)
self.weights['enc1_b1'] = randn_bias(64)
self.weights['enc1_w2'] = randn(64, 64, 3, 3)
self.weights['enc1_b2'] = randn_bias(64)
# Level 2 (64 -> 128 filters)
self.weights['enc2_w1'] = randn(128, 64, 3, 3)
self.weights['enc2_b1'] = randn_bias(128)
self.weights['enc2_w2'] = randn(128, 128, 3, 3)
self.weights['enc2_b2'] = randn_bias(128)
# --- ๋ฐ๋ฅ (Bottleneck) ๊ฐ์ค์น ---
# (128 -> 256 filters)
self.weights['bottle_w1'] = randn(256, 128, 3, 3)
self.weights['bottle_b1'] = randn_bias(256)
self.weights['bottle_w2'] = randn(256, 256, 3, 3)
self.weights['bottle_b2'] = randn_bias(256)
# --- ๋์ฝ๋ (Decoder) ๊ฐ์ค์น ---
# Level 1 (Up-Conv 256 + Skip 128 = 384 -> 128 filters)
self.weights['dec1_w1'] = randn(128, 384, 3, 3)
self.weights['dec1_b1'] = randn_bias(128)
self.weights['dec1_w2'] = randn(128, 128, 3, 3)
self.weights['dec1_b2'] = randn_bias(128)
# Level 2 (Up-Conv 128 + Skip 64 = 192 -> 64 filters)
self.weights['dec2_w1'] = randn(64, 192, 3, 3)
self.weights['dec2_b1'] = randn_bias(64)
self.weights['dec2_w2'] = randn(64, 64, 3, 3)
self.weights['dec2_b2'] = randn_bias(64)
# --- ์ต์ข
1x1 Conv ---
self.weights['final_w'] = randn(out_classes, 64, 1, 1)
self.weights['final_b'] = randn_bias(out_classes)
# --- U-Net์ ํต์ฌ ์ฐ์ฐ๋ค ---
def _relu(self, x):
return np.maximum(0, x)
def _conv2d(self, x, kernel, bias, padding=1):
"""
NumPy๋ฅผ ์ฌ์ฉํ 'same' 2D ์ปจ๋ณผ๋ฃจ์
(stride=1)
x: (In_C, H, W)
kernel: (Out_C, In_C, K, K)
bias: (Out_C,)
"""
in_C, in_H, in_W = x.shape
out_C, _, K, _ = kernel.shape
# ํจ๋ฉ ์ ์ฉ ('same'์ ์ํด)
padded_x = np.pad(x, ((0, 0), (padding, padding), (padding, padding)), 'constant')
# ์ถ๋ ฅ ๋งต ์ด๊ธฐํ
out_H, out_W = in_H, in_W # 'same' ํจ๋ฉ์ด๋ฏ๋ก ํฌ๊ธฐ ๋์ผ
output = np.zeros((out_C, out_H, out_W))
# ์ปจ๋ณผ๋ฃจ์
์ฐ์ฐ (๋งค์ฐ ๋๋ฆฐ ์ด์ค ๋ฃจํ)
for k in range(out_C): # ์ถ๋ ฅ ์ฑ๋
for i in range(out_H): # ๋์ด
for j in range(out_W): # ๋๋น
# (In_C, K, K) ํฌ๊ธฐ์ ํจ์น๋ฅผ ์๋ผ๋
patch = padded_x[:, i:i+K, j:j+K]
# (Out_C[k], In_C, K, K) ์ปค๋๊ณผ ์์๋ณ ๊ณฑ์
ํ ํฉ์ฐ
output[k, i, j] = np.sum(patch * kernel[k]) + bias[k]
return output
def _max_pool2d(self, x, pool_size=2):
""" 2x2 Max Pooling """
in_C, in_H, in_W = x.shape
out_H = in_H // pool_size
out_W = in_W // pool_size
output = np.zeros((in_C, out_H, out_W))
for c in range(in_C):
for i in range(out_H):
for j in range(out_W):
patch = x[c, i*pool_size:(i+1)*pool_size, j*pool_size:(j+1)*pool_size]
output[c, i, j] = np.max(patch)
return output
def _upsample2d(self, x, scale=2):
"""
Transposed Conv ๋์ ๊ฐ๋จํ Nearest-neighbor ์
์ํ๋ง ๊ตฌํ
"""
# np.repeat๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ ํ๊ณผ ์ด์ 'scale'๋งํผ ๋ฐ๋ณต
return x.repeat(scale, axis=1).repeat(scale, axis=2)
def _conv_block(self, x, w1, b1, w2, b2):
""" (3x3 Conv + ReLU) * 2ํ ๋ฐ๋ณต ๋ธ๋ก """
x = self._conv2d(x, w1, b1, padding=1)
x = self._relu(x)
x = self._conv2d(x, w2, b2, padding=1)
x = self._relu(x)
return x
# --- U-Net ์์ ํ (Forward Pass) ---
def forward(self, x):
"""
U-Net ์ํคํ
์ฒ๋ฅผ ๋ฐ๋ผ ์์ ํ๋ฅผ ์ํํฉ๋๋ค.
x: (In_C, H, W)
"""
w = self.weights
skip_connections = []
print(f"Input: \t\t{x.shape}")
# === 1. ์ธ์ฝ๋ (์์ถ ๊ฒฝ๋ก) ===
# Level 1
e1 = self._conv_block(x, w['enc1_w1'], w['enc1_b1'], w['enc1_w2'], w['enc1_b2'])
p1 = self._max_pool2d(e1)
skip_connections.append(e1) # ์คํต ์ฐ๊ฒฐ์ ์ํด ์ ์ฅ
print(f"Encoder 1: \t{e1.shape} -> Pool: {p1.shape}")
# Level 2
e2 = self._conv_block(p1, w['enc2_w1'], w['enc2_b1'], w['enc2_w2'], w['enc2_b2'])
p2 = self._max_pool2d(e2)
skip_connections.append(e2) # ์คํต ์ฐ๊ฒฐ์ ์ํด ์ ์ฅ
print(f"Encoder 2: \t{e2.shape} -> Pool: {p2.shape}")
# === 2. ๋ฐ๋ฅ (Bottleneck) ===
b = self._conv_block(p2, w['bottle_w1'], w['bottle_b1'], w['bottle_w2'], w['bottle_b2'])
print(f"Bottleneck: \t{b.shape}")
# === 3. ๋์ฝ๋ (ํ์ฅ ๊ฒฝ๋ก) ===
skip_connections = skip_connections[::-1] # ์์ ๋ค์ง๊ธฐ (LIFO)
# Level 1
u1 = self._upsample2d(b)
s1 = skip_connections[0] # Encoder 2์ ์ถ๋ ฅ (e2)
c1 = np.concatenate((u1, s1), axis=0) # ์ฑ๋ ์ถ(axis=0)์ผ๋ก ๊ฒฐํฉ
d1 = self._conv_block(c1, w['dec1_w1'], w['dec1_b1'], w['dec1_w2'], w['dec1_b2'])
print(f"Decoder 1: \tUp: {u1.shape} + Skip: {s1.shape} = Concat: {c1.shape} -> Block: {d1.shape}")
# Level 2
u2 = self._upsample2d(d1)
s2 = skip_connections[1] # Encoder 1์ ์ถ๋ ฅ (e1)
c2 = np.concatenate((u2, s2), axis=0) # ๊ฒฐํฉ
d2 = self._conv_block(c2, w['dec2_w1'], w['dec2_b1'], w['dec2_w2'], w['dec2_b2'])
print(f"Decoder 2: \tUp: {u2.shape} + Skip: {s2.shape} = Concat: {c2.shape} -> Block: {d2.shape}")
# === 4. ์ต์ข
1x1 Conv ===
# 1x1 Conv๋ 3x3 Conv์ ๋์ผํ์ง๋ง K=1, padding=0์ ์ฌ์ฉ
output = self._conv2d(d2, w['final_w'], w['final_b'], padding=0)
print(f"Final 1x1 Conv: {output.shape}")
return output
# --- ์คํ ์์ ---
if __name__ == "__main__":
# (์ฑ๋, ๋์ด, ๋๋น) - ๋์ด/๋๋น๋ 2์ ๋ฐฐ์์ฌ์ผ ํจ
# (๋งค์ฐ ๋๋ฆฌ๋ฏ๋ก ์์ ์ด๋ฏธ์ง ์ฌ์ฉ)
dummy_image = np.random.randn(1, 32, 32)
# ๋ชจ๋ธ ์ด๊ธฐํ (์
๋ ฅ ์ฑ๋ 1, ์ถ๋ ฅ ํด๋์ค 2)
model = NumpyUNet(in_channels=1, out_classes=2)
print("--- U-Net Forward Pass Start ---")
# ์์ ํ ์คํ
output_map = model.forward(dummy_image)
print("--- U-Net Forward Pass End ---")
print(f"\n์ต์ข
์
๋ ฅ ์ด๋ฏธ์ง Shape: {dummy_image.shape}")
print(f"์ต์ข
์ถ๋ ฅ ๋งต Shape: {output_map.shape}")
# ์
๋ ฅ๊ณผ ์ถ๋ ฅ์ ๋์ด/๋๋น๊ฐ ๋์ผํ๊ณ ์ฑ๋ ์๋ง ๋ฐ๋ ๊ฒ์ ํ์ธ
assert dummy_image.shape[1:] == output_map.shape[1:]
assert output_map.shape[0] == 2 |