import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# Create an empty array to store the data points
X = np.empty((0, 2))
plt.figure()
plt.ion() # Turn on interactive mode
# Create an empty scatter plot
scatter = plt.scatter([], [], marker='o', facecolors='none', edgecolors='black', s=80)
# Set initial plot limits and labels
x_min, x_max = 0, 10
y_min, y_max = 0, 10
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.title('Real-time Clustering')
plt.xticks(())
plt.yticks(())
num_clusters = 1 # Set the desired number of clusters (updated to 1)
kmeans = KMeans(init='k-means++', n_clusters=num_clusters, n_init=10)
while True:
# Generate a random data point
new_point = np.random.rand(1, 2) * 10
# Add the new point to the data array
X = np.vstack([X, new_point])
# Perform clustering on the updated data
kmeans.fit(X)
# Clear the current plot
scatter.remove()
# Plot the updated data points
scatter = plt.scatter(X[:, 0], X[:, 1], marker='o', facecolors='none', edgecolors='black', s=80)
# Plot the cluster centers
cluster_centers = kmeans.cluster_centers_
plt.scatter(cluster_centers[:, 0], cluster_centers[:, 1], marker='o', s=210, linewidths=4, color='black',
zorder=12, facecolors='black')
# Update plot limits if necessary
x_min = min(x_min, new_point[0, 0]) - 1
x_max = max(x_max, new_point[0, 0]) + 1
y_min = min(y_min, new_point[0, 1]) - 1
y_max = max(y_max, new_point[0, 1]) + 1
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
# Update the plot
plt.pause(0.5)