Certainly! Below is the code formatted as a Jupyter Notebook. You can copy and paste this into a Jupyter Notebook cell to run it.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Functional K-Means Clustering Algorithm"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.datasets import load_iris\n",
"\n",
"def euclidean_distance(a, b):\n",
" return np.linalg.norm(a - b)\n",
"\n",
"def assign_clusters(data, centroids):\n",
" return np.argmin(np.array([[euclidean_distance(data_point, centroid) for centroid in centroids] for data_point in data]), axis=1)\n",
"\n",
"def update_centroids(data, labels, k):\n",
" return np.array([data[labels == i].mean(axis=0) for i in range(k)])\n",
"\n",
"def k_means(data, k, max_iters=100):\n",
" # Randomly initialize centroids\n",
" initial_indices = np.random.choice(data.shape[0], k, replace=False)\n",
" centroids = data[initial_indices]\n",
" \n",
" for _ in range(max_iters):\n",
" labels = assign_clusters(data, centroids)\n",
" new_centroids = update_centroids(data, labels, k)\n",
" \n",
" # Check for convergence\n",
" if np.allclose(centroids, new_centroids):\n",
" break\n",
" \n",
" centroids = new_centroids\n",
" \n",
" return centroids, labels\n",
"\n",
"# Load the Iris dataset\n",
"iris = load_iris()\n",
"data = iris.data\n",
"\n",
"# Run k-means clustering\n",
"k = 3 # There are 3 classes of iris\n",
"centroids, labels = k_means(data, k)\n",
"\n",
"# Plot the results\n",
"plt.figure(figsize=(10, 6))\n",
"plt.scatter(data[:, 0], data[:, 1], c=labels, s=50, cmap='viridis')\n",
"plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, alpha=0.75, marker='X')\n",
"plt.xlabel(iris.feature_names[0])\n",
"plt.ylabel(iris.feature_names[1])\n",
"plt.title(\"K-Means Clustering on Iris Dataset\")\n",
"plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
To use this in a Jupyter Notebook, simply create a new notebook, paste the above JSON into a cell, and run it. This will execute the k-means clustering algorithm on the Iris dataset and display the resulting clusters.