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