Python画K-means算法聚类后的日负荷曲线图

Python版本:Python3.6.2


一、K-Means算法


K-Means算法是聚类算法中最简单的,python中可以直接调用Kmeans()函数,其中参数n_clusters,指定要聚成几类。

代码:
# -*- coding: utf-8 -*-
"""
@Time    : 2018/1/22 21:53
@Author  : Sunflower
@FileName: cluster_kmeans.py
@Software: PyCharm
@Blog    :http://blog.csdn.net/sunflower_kris/article/
"""

import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

filename = 'D:\sunfl\sunflower\study\Jupyter Notebook/file1_728_sort.csv'

res = np.loadtxt(fname=filename,dtype=str,delimiter=',',skiprows=1,usecols=2)
#print(res)
data = [] #一维数组

for i in range(len(res)):
    tt = eval(res[i])
    data.append(float(tt))
#print(data)  #所有用户的电量数据都放在一维数组里

count_row = round(len(data)/48)
data = np.array(data).reshape(count_row,48)  #48维数据,904个样本

estimator =KMeans(n_clusters=5)   #构造一个聚类数为5的聚类器
estimator.fit(data)   #聚类
label_pred = estimator.labels_  #获取聚类标签
centroids = estimator.cluster_centers_ #获取聚类中心
print(label_pred)

for i in range(len(label_pred)):
    if label_pred[i] == 0:
        x = [i for i in range(48)]
        plt.plot(x, data[i], '#e24fff')
    if label_pred[i] == 1:
        x = [i for i in range(48)]
        plt.plot(x, data[i], 'g')
    if label_pred[i] == 2:
        x = [i for i in range(48)]
        plt.plot(x, data[i], 'r')
    if label_pred[i] == 3:
        x = [i for i in range(48)]
        plt.plot(x, data[i], 'k')
    if label_pred[i] == 4:
        x = [i for i in range(48)]
        plt.plot(x, data[i], 'c')
plt.show()
Python画K-means算法聚类后的日负荷曲线图_第1张图片

你可能感兴趣的:(用电行为分析)