我正在研究机器学习,已经用Python编写了K均值算法的实现。它将二维数据组织成聚类。每个数据点还具有0或1的类值。
我对这个算法感到困惑的是,如何使用它来预测另一组没有0或1的二维数据的值,而是未知的。对于每个聚类,我应该对其中的点进行平均处理以得到0或1,如果一个未知点最接近该聚类,则该未知点采用平均值?或者有更聪明的方法吗?
谢谢!
我正在研究机器学习,已经用Python编写了K均值算法的实现。它将二维数据组织成聚类。每个数据点还具有0或1的类值。
我对这个算法感到困惑的是,如何使用它来预测另一组没有0或1的二维数据的值,而是未知的。对于每个聚类,我应该对其中的点进行平均处理以得到0或1,如果一个未知点最接近该聚类,则该未知点采用平均值?或者有更聪明的方法吗?
谢谢!
在k-means聚类算法中,要将一个新的数据点分配给一组已经创建好的聚类中的一个,你只需找到最接近该点的质心。
换句话说,对于原始数据集中的每个点进行迭代分配到k个聚类中所使用的步骤是相同的。唯一的区别是,在此计算中使用的质心是最终集合,即最后一次迭代时质心的值。
以下是一种python实现(使用NumPy):
>>> import numpy as NP
>>> # just made up values--based on your spec (2D data + 2 clusters)
>>> centroids
array([[54, 85],
[99, 78]])
>>> # randomly generate a new data point within the problem domain:
>>> new_data = NP.array([67, 78])
>>> # to assign a new data point to a cluster ID,
>>> # find its closest centroid:
>>> diff = centroids - new_data[0,:] # NumPy broadcasting
>>> diff
array([[-13, 7],
[ 32, 0]])
>>> dist = NP.sqrt(NP.sum(diff**2, axis=-1)) # Euclidean distance
>>> dist
array([ 14.76, 32. ])
>>> closest_centroid = centroids[NP.argmin(dist),]
>>> closest_centroid
array([54, 85])
def predict(data, centroids):
centroids, data = np.array(centroids), np.array(data)
distances = []
for unit in data:
for center in centroids:
distances.append(np.sum((unit - center) ** 2))
distances = np.reshape(distances, data.shape)
closest_centroid = [np.argmin(dist) for dist in distances]
print(closest_centroid)
def Labs( dataset,centroids ):
a = []
for i in range(len(dataset)):
d = []
for j in range(n):
dist = np.linalg.norm(dataset[(i),:]-centroids[(j),:])
d.append(dist)
assignment = np.argmin(d)
a.append(assignment)
return pd.DataFrame(np.array(a) + 1,columns =['Lab'])
希望它有所帮助。