使用K-means算法将市场中的宠物根据价格、品种等特征进行聚类,发现不同类型宠物的市场需求和价格趋势。相关Python代码
时间: 2024-01-22 07:17:55 浏览: 28
以下是使用K-means算法将宠物根据价格和品种进行聚类的Python代码示例:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# 读取数据
data = pd.read_csv('pet_data.csv')
# 数据预处理
X = data[['price', 'breed']].values
breed_dict = {'Dog': 0, 'Cat': 1} # 将品种转换为数字
X[:, 1] = np.array([breed_dict[breed] for breed in X[:, 1]])
# 使用K-means算法进行聚类
kmeans = KMeans(n_clusters=3, init='k-means++', random_state=42)
kmeans.fit(X)
# 可视化聚类结果
plt.scatter(X[kmeans.labels_ == 0, 0], X[kmeans.labels_ == 0, 1], s=100, c='red', label='Cluster 1')
plt.scatter(X[kmeans.labels_ == 1, 0], X[kmeans.labels_ == 1, 1], s=100, c='blue', label='Cluster 2')
plt.scatter(X[kmeans.labels_ == 2, 0], X[kmeans.labels_ == 2, 1], s=100, c='green', label='Cluster 3')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='yellow', label='Centroids')
plt.title('Pet Clusters')
plt.xlabel('Price')
plt.ylabel('Breed')
plt.legend()
plt.show()
```
其中,`pet_data.csv`是包含宠物价格和品种数据的CSV文件。 `n_clusters`参数指定了聚类的数量,`init`参数指定了初始化聚类中心的策略,`random_state`参数是为了保证结果的可重复性。执行代码后,会显示出聚类结果的可视化图形。
相关推荐
![](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)
![](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)