[网络收集]form表单及网站开发中常用js表单取值方法,伊春网站优化,传奇购买域名做网站,建站哪家好 discuz实现 K-means 聚类从零开始涉及几个关键步骤#xff1a;初始化质心、将点分配给最近的质心、根据分配更新质心#xff0c;以及重复这个过程直到收敛。这里是一个基本的 Python 实现#xff1a;
K-means 算法步骤#xff1a;
初始化质心#xff1a;从数据点中随机选择 k …实现 K-means 聚类从零开始涉及几个关键步骤初始化质心、将点分配给最近的质心、根据分配更新质心以及重复这个过程直到收敛。这里是一个基本的 Python 实现
K-means 算法步骤
初始化质心从数据点中随机选择 k 个初始质心。将点分配给最近的质心对于数据集中的每个点找到最近的质心并将该点分配到那个簇中。更新质心重新计算作为每个簇中所有点的平均值的质心。重复重复步骤 2 和 3直到质心不再显著变化表明算法已经收敛。
import numpy as npdef initialize_centroids(points, k):从数据点中随机初始化质心。indices np.random.choice(points.shape[0], k, replaceFalse)return points[indices]def closest_centroid(points, centroids):返回一个数组包含每个点到最近质心的索引。distances np.sqrt(((points - centroids[:, np.newaxis])**2).sum(axis2))return np.argmin(distances, axis0)def update_centroids(points, closest, centroids):更新质心为每个簇分配的所有点的平均值。new_centroids np.array([points[closestk].mean(axis0) for k in range(centroids.shape[0])])return new_centroidsdef k_means(points, k, max_iters100):实现 K-means 算法。centroids initialize_centroids(points, k)for _ in range(max_iters):closest closest_centroid(points, centroids)new_centroids update_centroids(points, closest, centroids)# 检查收敛if np.all(centroids new_centroids):breakcentroids new_centroidsreturn centroids, closest# 示例用法
if __name__ __main__:# 生成一些数据例如在 2D 空间中的两个簇np.random.seed(42)cluster_1 np.random.normal(0, 1, (100, 2))cluster_2 np.random.normal(5, 1, (100, 2))points np.vstack((cluster_1, cluster_2))# 应用 K-meansk 2centroids, assignments k_means(points, k)print(质心:\n, centroids)K-means 算法的计算成本和时间成本主要依赖于几个因素数据点的数量、特征的维数、质心的数量k 值以及算法迭代次数。算法的时间复杂度通常表示为 O(n*k*i*d)其中 n 是数据点的数量k 是质心的数量i 是迭代次数d 是特征的维数。
计算成本和时间成本
数据点数量n数据点越多每次计算距离和更新质心的时间就越长。质心数量k质心越多计算每个数据点到每个质心的距离的成本就越高。迭代次数i算法需要更多的迭代次数来收敛到最终的簇分配特别是对于初始质心选择不理想或数据分布复杂的情况。特征的维数d维度越高计算距离就越复杂因此时间成本更高。
局限性
初始质心的选择K-means 的结果可能对初始质心的选择非常敏感不同的初始质心可能导致不同的最终簇划分。簇的形状和大小K-means 假设每个簇在所有方向上的方差都相同因此它最适合识别球形簇。对于非球形簇或大小差异很大的簇K-means 可能不会很有效。确定 k 值在实际应用中确定最佳的 k 值即簇的数量通常是一个挑战。局部最小值K-means 可能会收敛到局部最优解而不是全局最优解这意味着算法的结果可能不是最优的簇划分。
由于这些限制虽然 K-means 在许多情况下都是一个有用和高效的聚类方法但在应用时需要考虑数据的特性并可能需要尝试不同的初始质心或使用如 K-means 这样的方法来改进初始质心的选择。
绘制二维的K-means
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans# Generate synthetic two-dimensional data
X, y_true make_blobs(n_samples300, centers4, cluster_std0.60, random_state0)# Apply KMeans clustering
kmeans KMeans(n_clusters4)
kmeans.fit(X)
y_kmeans kmeans.predict(X)# Plot the data points
plt.scatter(X[:, 0], X[:, 1], s50, cy_kmeans, cmapviridis)# Plot the centroids
centers kmeans.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], cred, s200, alpha0.5)
plt.title(K-means Clustering)
plt.xlabel(Feature 1)
plt.ylabel(Feature 2)
plt.show()