利用python读入本地iris数据集,完成k-means聚类,分析其聚类效果
时间: 2024-06-09 08:06:50 浏览: 14
好的,首先需要安装一些Python的库。可以使用以下命令安装:
```
pip install numpy pandas matplotlib scikit-learn
```
然后,我们可以按照以下步骤读取iris数据集并进行k-means聚类:
1. 导入库并读取数据集
```python
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
```
2. 标准化数据
```python
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_features = scaler.fit_transform(df)
```
3. 使用KMeans进行聚类
```python
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=3)
kmeans.fit(scaled_features)
```
4. 分析聚类结果
```python
df['cluster'] = kmeans.labels_
# 绘制聚类结果
import matplotlib.pyplot as plt
plt.scatter(df['sepal length (cm)'], df['sepal width (cm)'], c=df['cluster'])
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.title('KMeans Clustering')
plt.show()
```
结果图如下所示:
![KMeans Clustering Result](https://i.imgur.com/Bh6aEiV.png)
从图中可以看出,KMeans将数据分为了3个簇,聚类效果较好。
相关推荐
![m](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)