python

下面展示一些 内联代码片

```python
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import seaborn as sns

def loadData(filePath):
    data = pd.read_excel(filePath, header=0)
    cityName = data.iloc[:, 0].tolist()
    retData = data.iloc[:, 1:].values.tolist()
    return retData, cityName


if __name__=='__main__':
    filepath = r'C:\Users\l\Desktop\city.xls'
    data, cityName = loadData(filepath)  #利用loadData方法读取数据
    km = KMeans(n_clusters=4)              #创建实例
    label = km.fit_predict(data)          #调用KMeans() fit_predict()方法进行计算
    
    # 绘制散点图
    plt.scatter(data[:, 0], data[:, 1], c=label)
    plt.scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], marker='*', s=300, c='r')
    plt.title("City Expenses Clusters")
    plt.xlabel("Expense of First Category")
    plt.ylabel("Expense of Second Category")
    plt.show()
    
    # 绘制热力图
    df = pd.DataFrame(data)
    df['label'] = label
    df = df.groupby('label').mean()
    sns.heatmap(df, cmap='Reds', annot=True, fmt='.2f')
    plt.title("Average Expenses of Each Cluster")
    plt.show()
    
    expenses = np.sum(km.cluster_centers_, axis=1)  
    CityCluster = [[], [], [], []]      #将城市按label分成设定的簇,将每个簇的城市输出
    for i in range(len(cityName)):
        CityCluster[label[i

你可能感兴趣的:(深度学习)