Bird
Raised Fist0

Implement Data Augmentation - Flip, Crop, Normalize

CODINGbeginnerInterview freq: medium
Choose your preparation mode6 modes available
▶
Execution Trace
Step 1/4
Original Image

The image is loaded with dimensions 32x32x3.

🎯 Understanding the initial state of the image is crucial for applying transformations.
import cv2
image = cv2.imread('image.jpg')
print(image.shape)  # Output: (32, 32, 3)
Horizontal Flip

The image is flipped horizontally, maintaining dimensions 32x32x3.

🎯 Flipping is a common augmentation to increase dataset diversity.
flipped_image = cv2.flip(image, 1)
print(flipped_image.shape)  # Output: (32, 32, 3)
Crop

The image is cropped to 28x28x3, focusing on the center.

🎯 Cropping helps in focusing on the main object and reducing noise.
cropped_image = flipped_image[2:30, 2:30]
print(cropped_image.shape)  # Output: (28, 28, 3)
Normalize

Pixel values are normalized to the range [0, 1].

🎯 Normalization ensures consistent input scale for the model.
normalized_image = cropped_image / 255.0
print(normalized_image.min(), normalized_image.max())  # Output: 0.0, 1.0
📊
Diagram
Diagram
┌───────────────────────────────┐
│   Original Image (32x32x3)   │
└────────────┬──────────────────┘
             │
┌────────────▼────────────┐
│      Horizontal Flip    │
│   Flipped Image (32x32x3) │
└────────────┬────────────┘
             │
┌────────────▼────────────┐
│          Crop          │
│   Cropped Image (28x28x3) │
└────────────┬────────────┘
             │
┌────────────▼────────────┐
│       Normalize        │
│ Normalized Image (28x28x3) │
└─────────────────────────┘
  • Original Image: The input image before augmentation
  • Horizontal Flip: Flipping the image along the vertical axis
  • Crop: Cropping the image to a smaller size
  • Normalize: Scaling pixel values to a standard range
🔑
Key Moments
▲
Q: Why is horizontal flipping used in data augmentation?
A: Horizontal flipping increases dataset diversity by creating mirror images, which helps the model generalize better.
Q: What is the purpose of cropping in image preprocessing?
A: Cropping focuses on the central part of the image, reducing noise and potentially irrelevant background information.
Q: How does normalization affect the training process?
A: Normalization scales pixel values to a consistent range, improving convergence speed and model performance.

This diagram illustrates the process of data augmentation for image preprocessing, including horizontal flipping, cropping, and normalization. Each step modifies the image to enhance model training by increasing data diversity and ensuring consistent input scales. Understanding these transformations is crucial for preparing robust datasets that improve model generalization and performance.

Primary Focus

✓ Data augmentation techniques for image preprocessing

Practice

(1/5)
1. What does the following Python code output when implementing logistic regression with a sigmoid activation function?
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

z = np.array([0, 2, -2])
output = sigmoid(z)
print(output)
easy
A. [0.5, 0.88, 0.12]
B. [0.5, 0.88, 0.11]
C. [0.5, 0.87, 0.12]
D. [0.5, 0.86, 0.12]

Solution

  1. Step 1: Calculate sigmoid for each element

    Sigmoid function is applied element-wise: sigmoid(0) = 0.5, sigmoid(2) ≈ 0.88, sigmoid(-2) ≈ 0.12.
  2. Step 2: Check precision of calculations

    Common mistake is rounding errors. Correct values are [0.5, 0.880797, 0.119203], rounded to [0.5, 0.88, 0.12].
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sigmoid(0)=0.5, Sigmoid(2)≈0.88, Sigmoid(-2)≈0.12 [OK]
Hint: Sigmoid(0)=0.5, Sigmoid(2)≈0.88, Sigmoid(-2)≈0.12 [OK]
Common Mistakes:
2. What is the time complexity of a single update step in Mini-Batch SGD with Momentum for a model with n parameters?
easy
A. O(n)
B. O(n log n)
C. O(n^2)
D. O(1)

Solution

  1. Step 1: Identify operations involved

    Each update step involves computing the gradient and updating the velocity and parameters, all of which are linear operations with respect to the number of parameters.
  2. Step 2: Determine the complexity

    Since each operation is linear, the overall complexity is O(n).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Each parameter update is linear in complexity [OK]
Hint: Each parameter update is linear in complexity [OK]
Common Mistakes:
3. In a decision tree, how would you handle a dataset with continuous features?
medium
A. Ignore continuous features.
B. Use one-hot encoding for continuous features.
C. Discretize continuous features into bins.
D. Use continuous features directly without modification.

Solution

  1. Step 1: Consider handling continuous features

    Discretizing into bins allows decision trees to handle continuous data effectively.
  2. Step 2: Eliminate wrong options

    One-hot encoding (A) is for categorical data; ignoring (C) loses information; using directly (D) can lead to overfitting.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Continuous? Discretize into bins [OK]
Hint: Continuous? Discretize into bins [OK]
Common Mistakes:
4. In the context of implementing linear regression with gradient descent, how would you handle a dataset with missing values?
medium
A. Impute missing values using the mean of each feature.
B. Ignore missing values during training.
C. Replace missing values with zeros.
D. Remove any samples with missing values.

Solution

  1. Step 1: Consider impact of missing values

    Ignoring or zero-filling can bias results; removing samples reduces data.
  2. Step 2: Choose appropriate imputation

    Mean imputation is a common strategy that maintains dataset size and reduces bias.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Mean imputation balances bias and data retention. [OK]
Hint: Mean imputation balances bias and data retention. [OK]
Common Mistakes:
5. In the following learned positional encoding implementation, the model is not learning as expected. What is the most likely cause?
import torch
import torch.nn as nn

class LearnedPositionalEncoding(nn.Module):
    def __init__(self, max_len, d_model):
        super().__init__()
        self.positional_encoding = nn.Parameter(torch.zeros(max_len, d_model))

    def forward(self, x):
        return x + self.positional_encoding[:x.size(1), :]

model = LearnedPositionalEncoding(100, 512)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
medium
A. The positional encoding is not initialized properly.
B. The learning rate is too low.
C. The optimizer is not suitable for this task.
D. The positional encoding is not being updated.

Solution

  1. Step 1: Identify the initialization issue

    The positional encoding is initialized to zeros, which may not provide a useful starting point for learning.
  2. Step 2: Eliminate wrong options

    The learning rate is too low. is incorrect because the learning rate is standard. The optimizer is not suitable for this task. is incorrect because Adam is generally suitable. The positional encoding is not being updated. is incorrect because the parameter is part of the model and should be updated.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Check initialization of learned parameters. [OK]
Hint: Check initialization of learned parameters. [OK]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard