python鸢尾花数据集聚类分析
时间: 2023-11-06 14:08:08 浏览: 41
好的,针对您的问题,我可以给您提供以下步骤:
1. 导入数据集和必要的库
2. 数据预处理
3. 聚类分析
4. 可视化结果
下面是详细的步骤:
1. 导入数据集和必要的库
首先,我们需要导入数据集和必要的库。在这里,我们将使用sklearn库中的鸢尾花数据集。
```python
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
2. 数据预处理
接下来,我们需要对数据进行预处理。我们将使用pandas库将数据集转换为DataFrame对象,并删除不必要的列。
```python
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df.head()
```
输出结果:
```
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
```
```python
df.drop(['sepal length (cm)', 'sepal width (cm)'], axis=1, inplace=True)
df.head()
```
输出结果:
```
petal length (cm) petal width (cm)
0 1.4 0.2
1 1.4 0.2
2 1.3 0.2
3 1.5 0.2
4 1.4 0.2
```
3. 聚类分析
现在,我们可以使用KMeans算法对数据进行聚类分析。在这里,我们将使用sklearn库中的KMeans算法。
```python
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=3)
kmeans.fit(df)
```
输出结果:
```
KMeans(n_clusters=3)
```
4. 可视化结果
最后,我们可以使用matplotlib库将聚类结果可视化。
```python
plt.scatter(df['petal length (cm)'], df['petal width (cm)'], c=kmeans.labels_)
plt.xlabel('Petal Length')
plt.ylabel('Petal Width')
plt.title('K-Means Clustering Results')
plt.show()
```
输出结果:
![image](https://img-blog.csdn.net/20180530163412909?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmdsZV9jaGF0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/80)