cluster KMeans need preprocessing scale????

Out:

n_digits: 10,    n_samples 1797,         n_features 64
__________________________________________________________________________________
init            time    inertia homo    compl   v-meas  ARI     AMI     silhouette
k-means++       0.30s   69432   0.602   0.650   0.625   0.465   0.598   0.146
random          0.23s   69694   0.669   0.710   0.689   0.553   0.666   0.147
PCA-based       0.04s   70804   0.671   0.698   0.684   0.561   0.668   0.118
__________________________________________________________________________________

from:http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_digits.html#sphx-glr-auto-examples-cluster-plot-kmeans-digits-py

print(__doc__)

from time import time
import numpy as np
import matplotlib.pyplot as plt

from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale

np.random.seed(42)

digits = load_digits()
data = scale(digits.data)

n_samples, n_features = data.shape
n_digits = len(np.unique(digits.target))
labels = digits.target

sample_size = 300

print("n_digits: %d, \t n_samples %d, \t n_features %d"
      % (n_digits, n_samples, n_features))

print(82 * ‘_‘)
print(‘init\t\ttime\tinertia\thomo\tcompl\tv-meas\tARI\tAMI\tsilhouette‘)

def bench_k_means(estimator, name, data):
    t0 = time()
    estimator.fit(data)
    print(‘%-9s\t%.2fs\t%i\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f‘
          % (name, (time() - t0), estimator.inertia_,
             metrics.homogeneity_score(labels, estimator.labels_),
             metrics.completeness_score(labels, estimator.labels_),
             metrics.v_measure_score(labels, estimator.labels_),
             metrics.adjusted_rand_score(labels, estimator.labels_),
             metrics.adjusted_mutual_info_score(labels,  estimator.labels_),
             metrics.silhouette_score(data, estimator.labels_,
                                      metric=‘euclidean‘,
                                      sample_size=sample_size)))

bench_k_means(KMeans(init=‘k-means++‘, n_clusters=n_digits, n_init=10),
              name="k-means++", data=data)

bench_k_means(KMeans(init=‘random‘, n_clusters=n_digits, n_init=10),
              name="random", data=data)

# in this case the seeding of the centers is deterministic, hence we run the
# kmeans algorithm only once with n_init=1
pca = PCA(n_components=n_digits).fit(data)
bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1),
              name="PCA-based",
              data=data)
print(82 * ‘_‘)

# #############################################################################
# Visualize the results on PCA-reduced data

reduced_data = PCA(n_components=2).fit_transform(data)
kmeans = KMeans(init=‘k-means++‘, n_clusters=n_digits, n_init=10)
kmeans.fit(reduced_data)

# Step size of the mesh. Decrease to increase the quality of the VQ.
h = .02     # point in the mesh [x_min, x_max]x[y_min, y_max].

# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

# Obtain labels for each point in mesh. Use last trained model.
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
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(reduced_data[:, 0], reduced_data[:, 1], ‘k.‘, markersize=2)
# Plot the centroids as a white X
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1],
            marker=‘x‘, s=169, linewidths=3,
            color=‘w‘, zorder=10)
plt.title(‘K-means clustering on the digits dataset (PCA-reduced data)\n‘
          ‘Centroids are marked with white cross‘)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()

It depends on your data.

If you have attributes with a well-defined meaning. Say, latitude and longitude, then you should not scale your data, because this will cause distortion. (K-means might be a bad choice, too - you need something that can handle lat/lon naturally)

If you have mixed numerical data, where each attribute is something entirely different (say, shoe size and weight), has different units attached (lb, tons, m, kg ...) then these values aren‘t really comparable anyway; z-standardizing them is a best-practise to give equal weight to them.

If you have binary values, discrete attributes or categorial attributes, stay away from k-means. K-means needs to compute means, and the mean value is not meaningful on this kind of data.

from:https://stats.stackexchange.com/questions/89809/is-it-important-to-scale-data-before-clustering


Importance of Feature Scaling

Feature scaling though standardization (or Z-score normalization) can be an important preprocessing step for many machine learning algorithms. Standardization involves rescaling the features such that they have the properties of a standard normal distribution with a mean of zero and a standard deviation of one.

While many algorithms (such as SVM, K-nearest neighbors, and logistic regression) require features to be normalized, intuitively we can think of Principle Component Analysis (PCA) as being a prime example of when normalization is important. In PCA we are interested in the components that maximize the variance. If one component (e.g. human height) varies less than another (e.g. weight) because of their respective scales (meters vs. kilos), PCA might determine that the direction of maximal variance more closely corresponds with the ‘weight’ axis, if those features are not scaled. As a change in height of one meter can be considered much more important than the change in weight of one kilogram, this is clearly incorrect.

To illustrate this, PCA is performed comparing the use of data with StandardScaler applied, to unscaled data. The results are visualized and a clear difference noted. The 1st principal component in the unscaled set can be seen. It can be seen that feature #13 dominates the direction, being a whole two orders of magnitude above the other features. This is contrasted when observing the principal component for the scaled version of the data. In the scaled version, the orders of magnitude are roughly the same across all the features.

The dataset used is the Wine Dataset available at UCI. This dataset has continuous features that are heterogeneous in scale due to differing properties that they measure (i.e alcohol content, and malic acid).

The transformed data is then used to train a naive Bayes classifier, and a clear difference in prediction accuracies is observed wherein the dataset which is scaled before PCA vastly outperforms the unscaled version.

from:http://scikit-learn.org/stable/auto_examples/preprocessing/plot_scaling_importance.html

原文地址:https://www.cnblogs.com/bonelee/p/9084835.html

时间: 2024-11-08 21:21:22

cluster KMeans need preprocessing scale????的相关文章

聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用

4 用python实现K均值算法 x=np.random.randint(1,100,[20,1]) y=np.zeros(20) k=3 def initcenter(x,k): return x[:k] def nearest(kc,i): d = (abs(kc - i)) w = np.where(d ==np.min(d)) return w [0] [0] kc = initcenter(x,k) nearest(kc,14) for i in range(x.shape[0]):

RFM模型的变形LRFMC模型与K-means算法的有机结合

应用场景: 可以应用在不同行业的客户分类管理上,比如航空公司,传统的RFM模型不再适用,通过RFM模型的变形LRFMC模型实现客户价值分析:基于消费者数据的精细化营销 应用价值: LRFMC模型构建之后使用了经典的聚类算法-K-Means算法来对客户进行细分,而不是传统的来与参考值对比进行手工分类,使得准确率和效率得到了大大提升,从而实现客户价值分析,进行精准的价格和服务设置: 经常买机票的朋友不知道有没有发现,机票的价格通常“阴晴不定”.3个月前是一个价格,2个月1个月1周前又是另一个价格:有

sklearn数据预处理-scale

对数据按列属性进行scale处理后,每列的数据均值变成0,标准差变为1.可通过下面的例子加深理解: from sklearn import preprocessing import numpy as np 测试数据: X = np.array([[1., -1., 2.], [2., 0., 0.], [0., 1., -1.]]) 使用sklearn进行scale处理时,有两种方式可供选择. 方式1:直接使用preprocessing.scale()方法: X_scaled = preproc

二分Kmeans的java实现

刚刚研究了Kmeans.Kmeans是一种十分简单的聚类算法.可是他十分依赖于用户最初给定的k值.它无法发现随意形状和大小的簇.最适合于发现球状簇.他的时间复杂度为O(tkn).kmeans算法有两个核心点:计算距离的公式&推断迭代停止的条件.一般距採用欧式距离等能够随意.推断迭代停止的条件能够有: 1) 每一个簇的中心点不再变化则停止迭代 2)全部簇的点与这个簇的中心点的误差平方和(SSE)的全部簇的总和不再变化 3)设定人为的迭代次数.观察实验效果. 当初始簇心选择不好的时候聚类的效果会非常

preprocessing

二.标准化(Standardization),或者去除均值和方差进行缩放 公式为:(X-X_mean)/X_std 计算时对每个属性/每列分别进行. 将数据按其属性(按列进行)减去其均值,然后除以其方差.最后得到的结果是,对每个属性/每列来说所有数据都聚集在0附近,方差值为1. 首先说明下sklearn中preprocessing库里面的scale函数使用方法: sklearn.preprocessing.scale(X, axis=0, with_mean=True,with_std=True

scikit-learn学习之预处理(preprocessing)一

一.标准化,均值去除和按方差比例缩放 数据集的标准化:当个体特征太过或明显不遵从高斯正态分布时,标准化表现的效果较差.实际操作中,经常忽略特征数据的分布形状,移除每个特征均值,划分离散特征的标准差,从而等级化,进而实现数据中心化. scale 1 >>> from sklearn import preprocessing 2 >>> import numpy as np 3 >>> X = np.array([[1., -1., 2.], [2., 0

【Python数据挖掘课程】 三.Kmeans聚类代码实现、作业及优化

这篇文章直接给出上次关于Kmeans聚类的篮球远动员数据分析案例,同时介绍这次作业同学们完成的图例,最后介绍Matplotlib包绘图的优化知识.        前文推荐:       [Python数据挖掘课程]一.安装Python及爬虫入门介绍       [Python数据挖掘课程]二.Kmeans聚类数据分析及Anaconda介绍        希望这篇文章对你有所帮助,尤其是刚刚接触数据挖掘以及大数据的同学,同时准备尝试以案例为主的方式进行讲解.如果文章中存在不足或错误的地方,还请海涵

scikit-learn:4.3. Preprocessing data(standardi/normali/binari..zation、encoding、missing value)

参考:http://scikit-learn.org/stable/modules/preprocessing.html 主要讲述The sklearn.preprocessing package的utility function and transformer classes,包括standardization.normalization.binarization.encoding categorical features.process missing value. 1.Standardiz

NBA控卫聚类——K-Means详解

Dataset 在NBA的媒体报道,体育记者通常集中在少数几个球员.由于我们的数据科学的帽子,我们不禁感到一阵怀疑为什么这个球员与其他球员不一样.那么就使用数据科学进一步探索该这个问题. 本文的数据集nba_2013.csv是2013 - 2014赛季的NBA球员的表现. player – name of the player(名字) pos – the position of the player(位置) g – number of games the player was in(参赛场数)