我正在尝试将KMeans(scikitlearn)应用于以下提到的数据。 . 在
我已经看到了足够多的例子,其中Float64值显示在集群中。我想知道的是,在df[[Description]]列上是否可以进行集群,以x和y轴作为经度和纬度。在
我的代码是这样的。在
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
from sklearn.preprocessing import LabelEncoder
import pandas as pd
matplotlib.style.use('ggplot')
df = pd.read_csv('df.csv')
encoder =LabelEncoder()
Longitude = encoder.fit_transform(df.Longitude)
Latitude= df[df.columns[19]].values #(latitude)
x=np.array([Longitude, Latitude]).T
est = KMeans(3)
est.fit(df[['Longitude', 'Latitude', 'Description']])
但我在这条线上得到的错误是
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () ----> 1 est.fit(df[['Longitude', 'Latitude', 'Description']])
c:\users\magiri\appdata\local\programs\python\python35-32\lib\site-packages\sklearn\cluster\k_means_.py in fit(self, X, y) 878 """ 879 random_state = check_random_state(self.random_state) --> 880 X = self._check_fit_data(X) 881 882 self.cluster_centers_, self.labels_, self.inertia_, self.n_iter_ = \
c:\users\magiri\appdata\local\programs\python\python35-32\lib\site-packages\sklearn\cluster\k_means_.py in _check_fit_data(self, X) 852 def _check_fit_data(self, X): 853 """Verify that the number of samples given is larger than k""" --> 854 X = check_array(X, accept_sparse='csr', dtype=[np.float64, np.float32]) 855 if X.shape[0] < self.n_clusters: 856 raise ValueError("n_samples=%d should be >= n_clusters=%d" % (
c:\users\magiri\appdata\local\programs\python\python35-32\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 380 force_all_finite) 381 else: --> 382 array = np.array(array, dtype=dtype, order=order, copy=copy) 383 384 if ensure_2d:
ValueError: could not convert string to float: 'GAME/DICE'
所以,我想知道的是数据框说明以经纬度为基准的聚类。我知道Description列有字符串值,这就是我得到错误的原因。有没有什么我可以避免这个错误,并可以看到集群的描述列。在
K均值算法只适用于数值数据。您可以将
LabelEncoder
应用于“Description”字段,将其转换为类id同时将
LabelEncoder
应用于经度/格度并不是最佳的,因为这样就失去了两点之间有多近的概念。相反,您应该在K-means之前对数据应用StandardScaler
,以规范化不同字段的相对权重。在我已经成功地使用kmodes和kprototype对分类数据进行了聚类。这里有一个python实现:https://github.com/nicodv/kmodes。Kmodes允许对分类数据进行聚类,kprototype可以对分类数据和数值数据进行聚类(kmeans和Kmodes的混合)。github页面的示例用法
kmode只是基于点之间的公共类别进行聚类。kprototype的距离度量的简化摘要是
^{pr2}$其中}是两点的数值,}是范畴值。
a_num
和{a_cat
和{gamma
是类别差异与数值距离的成本加权。默认值为数值特征标准偏差的一半(=0.5,如果事先将数值特征标准化)。在相关问题 更多 >
编程相关推荐