Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Implementing an ML Algorithm

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Implementing an ML Algorithm. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Darwill needs a deterministic clustering routine for grouping audience feature vectors before campaign analysis. Implement k-means without external machine learning libraries.

Given n points in d dimensions and k initial centroids, repeatedly assign each point to its nearest centroid and recompute each centroid as the coordinate-wise mean of its assigned points.

Use squared Euclidean distance. If a point is equally close to multiple centroids, assign it to the centroid with the smallest index. If a centroid receives no points during an iteration, retain its previous coordinates. Stop when the largest squared centroid movement is at most tolerance², or when max_iterations is reached. Finally, assign every point using the returned centroids.

Return a dictionary with centroids, a list of final centroid vectors, and assignments, a list containing each point's centroid index.

Formal Specification

Implement k_means(points, initial_centroids, max_iterations, tolerance). points and initial_centroids are nonempty lists of equal-dimensional numeric vectors. initial_centroids contains k vectors. Return {"centroids": list[list[float]], "assignments": list[int]}.

Constraints

  • 1 <= n <= 10^4, where n is the number of points
  • 1 <= k <= min(n, 100)
  • 1 <= d <= 50, where d is the vector dimension
  • 1 <= max_iterations <= 1,000
  • tolerance >= 0
  • All vectors have the same dimension
  • All coordinates are finite numeric values

Function Signature

def k_means(points, initial_centroids, max_iterations, tolerance):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output