Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Cross-Validation Code Example

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

Your question is Cross-Validation Code Example. 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

Oxy production sensor data may contain multiple equipment conditions, and model evaluation should measure performance across representative subsets. Implement stratified k-fold cross-validation without using machine learning libraries.

Given feature vectors X, class labels y, and an integer k, divide the samples into k folds while preserving each class's distribution as evenly as possible. For each fold, train a nearest-centroid classifier on the other folds, predict the held-out samples, and report each fold's accuracy and the mean accuracy.

Formal Specification

Implement cross_validate(X, y, k). X is a list of numeric feature vectors, y is a list of hashable labels with one label per row, and k is the number of folds. Return a dictionary with fold_accuracies, a list of rounded accuracies in fold order, and mean_accuracy, the rounded average. Round every accuracy to six decimal places.

A class centroid is the coordinate-wise mean of its training vectors. Classify a validation vector using the class centroid with the smallest squared Euclidean distance. If distances tie, choose the class that first appeared in y.

Constraints

  • 2 <= len(X) <= 10^4
  • len(X) == len(y)
  • 1 <= len(X[i]) <= 50
  • All feature vectors have the same dimension
  • 2 <= k <= 10
  • Every class appears at least k times
  • Feature values are finite numbers

Function Signature

def cross_validate(X, y, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output