harbor run -t LiteCoder/kmeans-clustering-from-scratchharbor download LiteCoder/kmeans-clustering-from-scratchImplement a K-Means clustering algorithm from scratch in Python and apply it to synthetic 2D data. Evaluate performance across different K values and produce a structured JSON report.
numpy, matplotlib, scikit-learn (only for make_blobs and silhouette_score), jsonsklearn.cluster.KMeans). The core K-Means logic (initialization, assignment, update) must be implemented from scratch./app/solution.pypython /app/solution.py must produce all output files described below.Use sklearn.datasets.make_blobs to generate synthetic 2D data with these exact parameters:
n_samples=500centers=4cluster_std=1.0random_state=42The from-scratch K-Means must:
k, and max_iterations (default 300).random_state=42 (via numpy.random.seed) for reproducible centroid initialization.k data points from the dataset.max_iterations is reached.(k, 2)), and number of iterations until convergence./app/output.json — A JSON file containing the evaluation results with this exact structure:{
"data_info": {
"n_samples": 500,
"n_features": 2,
"true_centers": 4
},
"kmeans_results": [
{
"k": 2,
"silhouette_score": <float rounded to 4 decimal places>,
"iterations": <int>,
"centroids": [[<float>, <float>], ...]
},
{
"k": 3,
"silhouette_score": <float rounded to 4 decimal places>,
"iterations": <int>,
"centroids": [[<float>, <float>], ...]
},
{
"k": 4,
"silhouette_score": <float rounded to 4 decimal places>,
"iterations": <int>,
"centroids": [[<float>, <float>], ...]
},
{
"k": 5,
"silhouette_score": <float rounded to 4 decimal places>,
"iterations": <int>,
"centroids": [[<float>, <float>], ...]
}
],
"best_k": <int>,
"best_silhouette_score": <float rounded to 4 decimal places>
}
best_k: the K value (from 2, 3, 4, 5) that achieved the highest silhouette score.best_silhouette_score: the corresponding silhouette score./app/clusters_k4.png — Scatter plot of the clustering result for K=4. Each cluster should be shown in a different color, and centroids should be marked distinctly (e.g., with an "X" marker).
/app/elbow_plot.png — A line plot showing inertia (sum of squared distances of points to their assigned centroid) on the y-axis vs. K values (2, 3, 4, 5) on the x-axis.
/app/silhouette_comparison.png — A bar chart comparing silhouette scores for K values 2, 3, 4, 5.