CodeLibrary/03_pycharm_python_coursework_20240427/Kmeans.py
JRNitre 2092240e04 计算机专业前沿作业 Python
Date: 20240427
Design by JRNitre
2024-04-27 20:40:24 +08:00

24 lines
628 B
Python

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_blobs
from sklearn import metrics
n_samples = 1500
x, y = make_blobs(n_samples=n_samples, centers=4, random_state=170)
x = StandardScaler().fit_transform(x)
KMeans = KMeans(n_clusters=4, n_init='auto', random_state=170)
KMeans.fit(x)
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.scatter(x[:, 0], x[:, 1], c='r')
plt.title("Before clustering")
plt.subplot(122)
plt.scatter(x[:, 0], x[:, 1], c=KMeans.labels_)
plt.title("After clustering")
plt.show()