<jupyter_start><jupyter_text>Task 4*** Here is my solution to Task 4 of the Tasks Assessment. The author is <NAME> (<EMAIL>)  Task: Apply k-means clustering to Fisher’s famous Iris data set.***<jupyter_code>import numpy as np
import matplotlib.pyplot as plt

# KMeans
import sklearn.cluster as skcl

# Import the iris data set
from sklearn.datasets import load_iris
# Output the iris data set
x = load_iris().data[:, :]
x
# Plot the data set
plt.plot(x[:,0], x[:,1], 'x')
# Set limits
plt.xlim([4, 8.5])
plt.ylim([1.5, 5])
# Perform kmeans fitting
kmeans = skcl.KMeans(n_clusters=3, random_state=0).fit(x)
# The labels of each point
kmeans.labels_
# Plot the data set
plt.plot(x[kmeans.labels_ == 0][:,0], x[kmeans.labels_ == 0][:,1], 'gx')
plt.plot(x[kmeans.labels_ == 1][:,0], x[kmeans.labels_ == 1][:,1], 'rx')
plt.plot(x[kmeans.labels_ == 2][:,0], x[kmeans.labels_ == 2][:,1], 'bx')
# Set limits
plt.xlim([4, 8.5])
plt.ylim([1.5, 5])
# Predict the cluster for three points
y = np.array([[5, 4, 5, 4], [6, 3, 1, 3], [7, 3, 2, 3]])
predictions = kmeans.predict(y)
predictions
# Plot the data set
plt.plot(x[kmeans.labels_ == 0][:,0], x[kmeans.labels_ == 0][:,1], 'gx')
plt.plot(x[kmeans.labels_ == 1][:,0], x[kmeans.labels_ == 1][:,1], 'rx')
plt.plot(x[kmeans.labels_ == 2][:,0], x[kmeans.labels_ == 2][:,1], 'bx')
# Plot predictions
plt.plot(y[predictions == 0][:,0], y[predictions == 0][:,1], 'ro')
plt.plot(y[predictions == 1][:,0], y[predictions == 1][:,1], 'bo')
plt.plot(y[predictions == 2][:,0], y[predictions == 2][:,1], 'go')
# Set limits
plt.xlim([4, 8.5])
plt.ylim([1.5, 5])
# The coordinates of cluster centers
center = kmeans.cluster_centers_
center
# Plot the data set
plt.plot(x[kmeans.labels_ == 0][:,0], x[kmeans.labels_ == 0][:,1], 'gx')
plt.plot(x[kmeans.labels_ == 1][:,0], x[kmeans.labels_ == 1][:,1], 'rx')
plt.plot(x[kmeans.labels_ == 2][:,0], x[kmeans.labels_ == 2][:,1], 'bx')
# Plot predictions
plt.plot(y[predictions == 0][:,0], y[predictions == 0][:,1], 'ro')
plt.plot(y[predictions == 1][:,0], y[predictions == 1][:,1], 'bo')
plt.plot(y[predictions == 2][:,0], y[predictions == 2][:,1], 'go')
# Plot centers of clusters
plt.plot(center[:,0], center[:,1], 'k.')
# Set limits
plt.xlim([4, 8.5])
plt.ylim([1.5, 5])<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup