Skip to content

Add a 3D plot to visualise the K-mean algorithm #12367

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion data_structures/arrays/sudoku_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,8 @@ def unitsolved(unit):

def from_file(filename, sep="\n"):
"Parse a file into a list of strings, separated by sep."
return open(filename).read().strip().split(sep) # noqa: SIM115
with open(filename) as file:
return file.read().strip().split(sep)


def random_puzzle(assignments=17):
Expand Down
22 changes: 21 additions & 1 deletion machine_learning/k_means_clust.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,13 @@
heterogeneity,
k
)
5. Transfers Dataframe into excel format it must have feature called
5. 3D Plot of the labeled data points with centroids.
plot_kmeans(
X,
centroids,
cluster_assignment
)
6. Transfers Dataframe into excel format it must have feature called
'Clust' with k means clustering numbers in it.
"""

Expand Down Expand Up @@ -126,6 +132,19 @@ def plot_heterogeneity(heterogeneity, k):
plt.show()


def plot_kmeans(data, centroids, cluster_assignment):
ax = plt.axes(projection="3d")
ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=cluster_assignment, cmap="viridis")
ax.scatter(
centroids[:, 0], centroids[:, 1], centroids[:, 2], c="red", s=100, marker="x"
)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title("3D K-Means Clustering Visualization")
plt.show()


def kmeans(
data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False
):
Expand Down Expand Up @@ -193,6 +212,7 @@ def kmeans(
verbose=True,
)
plot_heterogeneity(heterogeneity, k)
plot_kmeans(dataset["data"], centroids, cluster_assignment)


def report_generator(
Expand Down