python - Sklearn.KMeans() : Get class centroid labels and reference to a dataset

标签 python date svm k-means pca

Sci-Kit学习Kmeans和PCA降维

我有一个 200 万行 x 7 列的数据集,其中包含不同的家庭用电量测量值以及每个测量值的日期。

  • 日期,
  • Global_active_power,
  • Global_reactive_power,
  • 电压,
  • 全局强度,
  • 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 均值分类,然后使用 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之后?
  • 一些我不知道的方法?
  • 或者我的方法存在根本性缺陷?
  • 有什么建议吗?

我是这个领域的新手,正在尝试通读大量代码,这是我看到的几个示例的汇编。

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

谢谢

最佳答案

KMeans().predict(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


  • 现在您可以在右侧看到与您的数据集匹配的结果。
  • 既然它是 secret 的,接下来就看您的意思了。
  • 这只是从头到尾如何使用它的一个很好的整体示例。
  • 显示您的结果,查看 PCA 或根据类别制作其他图表。

关于python - Sklearn.KMeans() : Get class centroid labels and reference to a dataset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27504870/

相关文章:

python计数并附加到列表

java - 从句子java中获取日期、时间和整数值

SQL:访问查询唯一满足多个条件

Mysql STR_TO_DATE 在不同环境中给出不一致的结果

r - 使用SVM的Kaggle数字识别器(e1071): Error in predict. svm(ret,xhold,decision.values = TRUE):模型为空

machine-learning - LIBSVM 如何准备带有图像的训练数据集以进行 Logo 检测?

java - 如何在 Java 中使用 SVM

python - 在 python 中增长字典是否有有效的替代方法?

python - 使用 Google Colab 的 SSL 证书

python - 重新构建 Python 和 mod_wsgi