用k-means写一段代码
时间: 2024-01-29 22:04:00 浏览: 79
K-Means代码
5星 · 资源好评率100%
Sure, here is an example code for k-means clustering in Python:
```python
from sklearn.cluster import KMeans
import numpy as np
# Generate some random data
X = np.random.rand(100, 2)
# Initialize the k-means model with 3 clusters
kmeans = KMeans(n_clusters=3)
# Fit the model to the data
kmeans.fit(X)
# Get the cluster labels for each data point
labels = kmeans.predict(X)
# Get the centroids of each cluster
centroids = kmeans.cluster_centers_
```
This code uses the `KMeans` class from the `sklearn.cluster` module to cluster some random data into 3 clusters. The `fit` method is used to train the model on the data, and the `predict` method is used to get the cluster labels for each data point. Finally, the `cluster_centers_` attribute is used to get the centroids of each cluster.
阅读全文