Katkat

Solve Seven Python Image and Data Tasks

Luma AIMachine Learning Engineer · Technical Screen

Last updated

This problem tests foundational proficiency in NumPy array manipulation, mathematical function implementation, and geometric logic, which are essential for low-level image processing tasks.

Problem Description

You are tasked with implementing a set of utility functions commonly used in machine learning data pipelines. Please provide Python implementations for the following tasks, preferably using NumPy where appropriate.

1. Center Crop

Given a 3D image array of shape (H, W, C) and target dimensions (new_H, new_W), return the center-cropped image. You may assume new_H <= H and new_W <= W.

def center_crop(image, new_H, new_W):
    # Return the cropped array

2. Stable Softmax

Implement the softmax function for a 1D array x. Ensure numerical stability by subtracting the maximum value from the input vector before exponentiation.

def stable_softmax(x):
    # Return the normalized probability distribution

3. Gaussian Kernel

Construct a 2D Gaussian kernel of size (k, k) with standard deviation sigma.

def get_gaussian_kernel(k, sigma):
    # Return a (k, k) kernel array normalized to sum to 1

4. Triangle Inequality Check

Given a list of side lengths, determine if they can form a valid non-degenerate triangle. A triangle is valid if the sum of any two sides is strictly greater than the third side.

def is_valid_triangle(sides):
    # Return True if valid, else False

Examples

  • Center Crop: An image (100, 100, 3) cropped to (50, 50) should return the central 50x50 patch.
  • Stable Softmax: [1000, 1001] should return [~0.2689, ~0.7311] rather than [nan, nan].
  • Triangle: is_valid_triangle([3, 4, 5]) returns True; is_valid_triangle([1, 1, 3]) returns False.

Constraints

  • Assume standard input types (lists, NumPy arrays).
  • For the Gaussian kernel, the center of the kernel should be at index (k-1)/2.
  • Ensure stable_softmax handles large inputs without overflow.

Hints

Hint 1

For center cropping, calculate the starting indices as `(H - new_H) // 2` and `(W - new_W) // 2`.

Hint 2

For the Gaussian kernel, use the formula `exp(-((x-center)**2 + (y-center)**2) / (2 * sigma**2))` and divide by the sum of all elements to ensure it represents a probability distribution.

Hint 3

To check the triangle inequality, sort the list of three sides first to verify only that the sum of the two smallest sides is greater than the largest side.

Follow-up questions

  • How would you optimize the Gaussian kernel generation if you needed to apply it to a batch of 10,000 images?
  • What are the implications of using float32 versus float64 when calculating the softmax of very small values?
  • How would you extend the `center_crop` function to handle batch dimensions `(B, H, W, C)` without explicit loops?