下面我的python代码对一组数据执行非常简单的K-means聚类。存在的问题是我需要根据最接近的质心来改变数据点的颜色。任何人都可以帮助我做我应该做的事情吗?
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def calc_dist_euclidean(vec_1, vec_2):
distances = np.sqrt(((vec_1 - vec_2[:, np.newaxis]) ** 2).sum(axis=2))
dist_euclidean = np.argmin(distances, axis=0)
return dist_euclidean
def init_cent(dataset, k):
centroids = dataset.copy()
np.random.shuffle(centroids)
return centroids[:k]
def k_means(dataset, k):
centroids = init_cent(dataset, k)
distances = calc_dist_euclidean(dataset, centroids)
cluster_assigning = np.array([dataset[distances == k].mean(axis=0) for k in range(centroids.shape[0])])
return centroids, cluster_assigning
df = pd.read_csv('bristol_vacation_rentals_2016.csv')
dataset = df[['latitude', 'longitude']].values
k = 3
centroids, cluster_assigning = k_means(dataset, k)
plt.subplot(121)
plt.scatter(dataset[:, 0], dataset[:, 1], s=2)
plt.scatter(centroids[:, 0], centroids[:, 1], c='r', s=50)
plt.xlabel('latitude')
plt.ylabel('longitude')
plt.subplot(122)
plt.scatter(dataset[:, 0], dataset[:, 1], s=2)
plt.scatter(cluster_assigning[:, 0], cluster_assigning[:, 1], c='r', s=50)
plt.xlabel('latitude')
plt.ylabel('longitude')
plt.show()
答案 0 :(得分:0)
为了使其更容易,我将重用k_means()
函数中的变量def k_means(dataset, k):
centroids = init_cent(dataset, k)
distances = calc_dist_euclidean(dataset, centroids)
cluster_assigning = np.array([dataset[distances == k].mean(axis=0) for k in range(centroids.shape[0])])
return centroids, distances, cluster_assigning
,并将其返回:
colors
然后,您可以根据定义包含每种颜色的numpy数组colors[distances]
的相应群集绘制质心和数据点,并使用df = pd.read_csv('bristol_vacation_rentals_2016.csv')
dataset = df[['latitude', 'longitude']].values
k = 3
colors = np.array(['r', 'g', 'b'])
centroids, distances, cluster_assigning = k_means(dataset, k)
plt.subplot(121)
plt.scatter(dataset[:, 0], dataset[:, 1], c=colors[distances], s=2)
plt.scatter(centroids[:, 0], centroids[:, 1], c=colors, s=50)
plt.xlabel('latitude')
plt.ylabel('longitude')
plt.subplot(122)
plt.scatter(dataset[:, 0], dataset[:, 1], c=colors[distances], s=2)
plt.scatter(cluster_assigning[:, 0], cluster_assigning[:, 1], c=colors, s=50)
plt.xlabel('latitude')
plt.ylabel('longitude')
plt.show()
为每个数据点创建一个numpy颜色数组:< / p>
export PATH=/usr/local/cuda-9.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64\
${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}