Skip to content

Commit 2c079bf

Browse files
authored
Merge pull request #482 from Open-Deep-ML/Q143
fix format for Q 143
2 parents 52e6105 + 19ee131 commit 2c079bf

File tree

8 files changed

+242
-38
lines changed

8 files changed

+242
-38
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Implement the Instance Normalization operation for 4D tensors (B, C, H, W) using NumPy. For each instance in the batch and each channel, normalize the spatial dimensions (height and width) by subtracting the mean and dividing by the standard deviation, then apply a learned scale (gamma) and shift (beta).
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"input": "import numpy as np\nB, C, H, W = 2, 2, 2, 2\nnp.random.seed(42)\nX = np.random.randn(B, C, H, W)\ngamma = np.ones(C)\nbeta = np.zeros(C)\nout = instance_normalization(X, gamma, beta)\nprint(np.round(out, 8))",
3+
"output": "[[[[-0.08841405 -0.50250083]\n [ 0.01004046 0.58087442]]\n\n [[-0.43833369 -0.43832346]\n [ 0.69114093 0.18551622]]]\n\n [[[-0.17259136 0.51115219]\n [-0.16849938 -0.17006144]]\n\n [[ 0.73955155 -0.55463639]\n [-0.44152783 0.25661268]]]]",
4+
"reasoning": "The function normalizes each instance and channel across (H, W), then applies the gamma and beta scaling/shifting parameters. This matches standard InstanceNorm behavior."
5+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
## Understanding Instance Normalization
2+
3+
Instance Normalization (IN) is a normalization technique primarily used in image generation and style transfer tasks. Unlike Batch Normalization or Group Normalization, Instance Normalization normalizes each individual sample (or instance) separately, across its spatial dimensions. This is particularly effective in applications like style transfer, where normalization is needed per image to preserve the content while allowing different styles to be applied.
4+
5+
### Concepts
6+
7+
Instance Normalization operates on the principle of normalizing each individual sample independently. This helps to remove the style information from the images, leaving only the content. By normalizing each instance, the method allows the model to focus on the content of the image rather than the variations between images in a batch.
8+
9+
The process of Instance Normalization consists of the following steps:
10+
11+
1. **Compute the Mean and Variance for Each Instance:** For each instance (image), compute the mean and variance across its spatial dimensions.
12+
2. **Normalize the Inputs:** Normalize each instance using the computed mean and variance.
13+
3. **Apply Scale and Shift:** After normalization, apply a learned scale (gamma) and shift (beta) to restore the model's ability to represent the data's original distribution.
14+
15+
### Structure of Instance Normalization for BCHW Input
16+
17+
For an input tensor with the shape **BCHW** , where:
18+
- **B**: batch size,
19+
- **C**: number of channels,
20+
- **H**: height,
21+
- **W**: width,
22+
Instance Normalization operates on the spatial dimensions (height and width) of each instance (image) separately.
23+
24+
#### 1. Mean and Variance Calculation for Each Instance
25+
26+
- For each individual instance in the batch (for each **b** in **B**), the **mean** $\mu_b$ and **variance** $\sigma_b^2$ are computed across the spatial dimensions (height and width), but **independently for each channel**.
27+
28+
$$
29+
\mu_b = \frac{1}{H \cdot W} \sum_{h=1}^{H} \sum_{w=1}^{W} x_{b,c,h,w}
30+
$$
31+
32+
$$
33+
\sigma_b^2 = \frac{1}{H \cdot W} \sum_{h=1}^{H} \sum_{w=1}^{W} (x_{b,c,h,w} - \mu_b)^2
34+
$$
35+
36+
Where:
37+
- $x_{b,c,h,w}$ is the activation at batch index $b$, channel $c$, height $h$, and width $w$.
38+
- $H$ and $W$ are the spatial dimensions (height and width).
39+
40+
#### 2. Normalization
41+
42+
Once the mean $\mu_b$ and variance $\sigma_b^2$ have been computed for each instance, the next step is to **normalize** the input for each instance across the spatial dimensions (height and width), for each channel:
43+
44+
$$
45+
\hat{x}_{b,c,h,w} = \frac{x_{b,c,h,w} - \mu_b}{\sqrt{\sigma_b^2 + \epsilon}}
46+
$$
47+
48+
Where:
49+
- $\hat{x}_{b,c,h,w}$ is the normalized activation for the input at batch index $b$, channel index $c$, height $h$, and width $w$.
50+
- $\epsilon$ is a small constant added to the variance for numerical stability.
51+
52+
#### 3. Scale and Shift
53+
54+
After normalization, the next step is to apply a **scale** ($\gamma_c$) and **shift** ($\beta_c$) to the normalized activations for each channel. These learned parameters allow the model to adjust the output distribution for each channel:
55+
56+
$$
57+
y_{b,c,h,w} = \gamma_c \hat{x}_{b,c,h,w} + \beta_c
58+
$$
59+
60+
Where:
61+
- $\gamma_c$ is the scaling factor for channel $c$.
62+
- $\beta_c$ is the shifting factor for channel $c$.
63+
64+
#### 4. Training and Inference
65+
66+
- **During Training**: The mean and variance are computed for each instance in the mini-batch and used for normalization.
67+
- **During Inference**: The model uses the running averages of the statistics (mean and variance) computed during training to ensure consistent behavior in production.
68+
69+
### Key Points
70+
71+
- **Instance-wise Normalization**: Instance Normalization normalizes each image independently, across its spatial dimensions (height and width) and across the channels.
72+
73+
- **Style Transfer**: This normalization technique is widely used in **style transfer** tasks, where each image must be normalized independently to allow for style information to be adjusted without affecting the content.
74+
75+
- **Batch Independence**: Instance Normalization does not depend on the batch size, as normalization is applied per instance, making it suitable for tasks where per-image normalization is critical.
76+
77+
- **Numerical Stability**: A small constant $\epsilon$ is added to the variance to avoid numerical instability when dividing by the square root of the variance.
78+
79+
- **Improved Training in Style-Related Tasks**: Instance Normalization helps to remove unwanted style-related variability across different images, allowing for better performance in tasks like style transfer, where the goal is to separate content and style information.
80+
81+
### Why Normalize Over Instances?
82+
83+
- **Content Preservation**: By normalizing each image individually, Instance Normalization allows the model to preserve the content of the images while adjusting the style. This makes it ideal for style transfer and other image manipulation tasks.
84+
85+
- **Batch Independence**: Unlike Batch Normalization, which requires large batch sizes to compute statistics, Instance Normalization normalizes each image independently, making it suitable for tasks where the batch size is small or varies.
86+
87+
- **Reducing Style Variability**: Instance Normalization removes the variability in style information across a batch, allowing for a consistent representation of content across different images.
88+
89+
In summary, Instance Normalization is effective for image-based tasks like style transfer, where the goal is to normalize each image independently to preserve its content while allowing style modifications.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"id": "143",
3+
"title": "Instance Normalization (IN) Implementation",
4+
"difficulty": "medium",
5+
"category": "Deep Learning",
6+
"video": "",
7+
"likes": "0",
8+
"dislikes": "0",
9+
"contributor": [
10+
{
11+
"profile_link": "https://github.com/nzomi",
12+
"name": "nzomi"
13+
}
14+
]
15+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import numpy as np
2+
3+
def instance_normalization(X: np.ndarray, gamma: np.ndarray, beta: np.ndarray, epsilon: float = 1e-5) -> np.ndarray:
4+
# Reshape gamma, beta for broadcasting: (1, C, 1, 1)
5+
gamma = gamma.reshape(1, -1, 1, 1)
6+
beta = beta.reshape(1, -1, 1, 1)
7+
mean = np.mean(X, axis=(2, 3), keepdims=True)
8+
var = np.var(X, axis=(2, 3), keepdims=True)
9+
X_norm = (X - mean) / np.sqrt(var + epsilon)
10+
return gamma * X_norm + beta
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import numpy as np
2+
3+
def instance_normalization(X: np.ndarray, gamma: np.ndarray, beta: np.ndarray, epsilon: float = 1e-5) -> np.ndarray:
4+
"""
5+
Perform Instance Normalization over a 4D tensor X of shape (B, C, H, W).
6+
gamma: scale parameter of shape (C,)
7+
beta: shift parameter of shape (C,)
8+
epsilon: small value for numerical stability
9+
Returns: normalized array of same shape as X
10+
"""
11+
# TODO: Implement Instance Normalization
12+
pass
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[
2+
{
3+
"test": "import numpy as np\nB, C, H, W = 2, 2, 2, 2\nnp.random.seed(42)\nX = np.random.randn(B, C, H, W)\ngamma = np.ones(C)\nbeta = np.zeros(C)\nout = instance_normalization(X, gamma, beta)\nprint(np.round(out[1][1], 4))",
4+
"expected_output": "[[ 1.4005, -1.0503] [-0.8361, 0.486 ]]"
5+
},
6+
{
7+
"test": "import numpy as np\nB, C, H, W = 2, 2, 2, 2\nnp.random.seed(101)\nX = np.random.randn(B, C, H, W)\ngamma = np.ones(C)\nbeta = np.zeros(C)\nout = instance_normalization(X, gamma, beta)\nprint(np.round(out[1][0], 4))",
8+
"expected_output": "[[-1.537, 0.9811], [ 0.7882, -0.2323]]"
9+
},
10+
{
11+
"test": "import numpy as np\nB, C, H, W = 2, 2, 2, 2\nnp.random.seed(101)\nX = np.random.randn(B, C, H, W)\ngamma = np.ones(C) * 0.5\nbeta = np.ones(C)\nout = instance_normalization(X, gamma, beta)\nprint(np.round(out[0][0], 4))",
12+
"expected_output": "[[1.8542, 0.6861], [0.8434, 0.6163]]"
13+
}
14+
]

0 commit comments

Comments
 (0)