Sklearn.KMeans():获取类质心标签和对数据集的引用

时间:2014-12-16 12:38:44

标签: python date svm k-means pca

Sci-Kit学习Kmeans和PCA降维

我有一个数据集,2M行7列,不同的家庭功耗测量值和每次测量的日期。

  • 日期,
  • Global_active_power,
  • Global_reactive_power,
  • 电压,
  • Global_intensity,
  • Sub_metering_1,
  • Sub_metering_2,
  • Sub_metering_3

我将数据集放入pandas数据框,选择除日期列之外的所有列,然后执行交叉验证拆分。

import pandas as pd
from sklearn.cross_validation import train_test_split

data = pd.read_csv('household_power_consumption.txt', delimiter=';')
power_consumption = data.iloc[0:, 2:9].dropna()
pc_toarray = power_consumption.values
hpc_fit, hpc_fit1 = train_test_split(pc_toarray, train_size=.01)
power_consumption.head()

power table

我使用K-means分类,然后通过PCA降维来显示。

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

hpc = PCA(n_components=2).fit_transform(hpc_fit)
k_means = KMeans()
k_means.fit(hpc)

x_min, x_max = hpc[:, 0].min() - 5, hpc[:, 0].max() - 1
y_min, y_max = hpc[:, 1].min(), hpc[:, 1].max() + 5
xx, yy = np.meshgrid(np.arange(x_min, x_max, .02), np.arange(y_min, y_max, .02))
Z = k_means.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
          extent=(xx.min(), xx.max(), yy.min(), yy.max()),
          cmap=plt.cm.Paired,
          aspect='auto', origin='lower')

plt.plot(hpc[:, 0], hpc[:, 1], 'k.', markersize=4)
centroids = k_means.cluster_centers_
inert = k_means.inertia_
plt.scatter(centroids[:, 0], centroids[:, 1],
           marker='x', s=169, linewidths=3,
           color='w', zorder=8)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()

PCA output

现在我想知道哪一行属于给定的类,然后哪个日期属于给定的类。

  • 有没有办法将图表上的点与我的索引相关联 数据集,在PCA之后?
  • 我不知道的一些方法?
  • 或者我的方法是否存在根本缺陷?
  • 有什么建议吗?

我是这个领域的新手,我正在尝试阅读大量代码,这是我已经记录过的几个例子的汇编。

我的目标是对数据进行分类,然后获取属于某个类的日期。

谢谢

1 个答案:

答案 0 :(得分:8)

KMeans()。预测(X)..docs here


预测X中每个样本所属的最近集群。

在矢量量化文献中,cluster_centers_被称为代码簿,而predict返回的每个值都是代码簿中最接近的代码的索引。

Parameters: (New data to predict)

X : {array-like, sparse matrix}, shape = [n_samples, n_features]

Returns: (Index of the cluster each sample belongs to)  

labels : array, shape [n_samples,]

我提交的代码存在的问题是使用

train_test_split()

返回数据集中的两个随机行数组,有效地破坏了数据集顺序,使得很难将从KMeans分类返回的标签与数据集中的连续日期相关联。


以下是一个例子:

import pandas as pd
import numpy as np
from sklearn.cluster import KMeans

#read data into pandas dataframe
df = pd.read_csv('household_power_consumption.txt', delimiter=';')

Raw Dataset head

#convert merge date and time colums and convert to datetime objects
df['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
df.set_index(pd.DatetimeIndex(df['Datetime'],inplace=True))
df.drop(['Date','Time'], axis=1, inplace=True)

#put last column first
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df = df[cols]
df = df.dropna()

preprocessed dates

#convert dataframe to data array and removes date column not to be processed, 
sliced = df.iloc[0:, 1:8].dropna()
hpc = sliced.values

k_means = KMeans()
k_means.fit(hpc)

# array of indexes corresponding to classes around centroids, in the order of your dataset
classified_data = k_means.labels_

#copy dataframe (may be memory intensive but just for illustration)
df_processed = df.copy()
df_processed['Cluster Class'] = pd.Series(classified_data, index=df_processed.index)

Finished


  • 现在,您可以在右侧看到与您的数据集匹配的结果。
  • 现在它被分类了,由你来推导意义。
  • 从开始到结束,这只是一个很好的整体示例。
  • 显示结果,查看PCA或根据班级制作其他图表。
相关问题