K均值聚类:更新每个聚类的中心点并选择颜色的功能。

问题描述 投票:0回答:1

这是我正在经历的一个关于K Means Clustering的例子的节选。谁能帮我理解一下最后两行是怎么回事,好吗?

具体来说

  1. 什么是... class_of_points = compare_to_first_center > compare_to_second_center 在做什么?是否只是返回一个布尔值?
  2. 另外,在下一行中,什么是 colors_map[class_of_points + 1 - 1] 在做什么?

先谢谢各位了。

import random # library for random number generation
import numpy as np # library for vectorized computation
import pandas as pd # library to process data as dataframes

import matplotlib.pyplot as plt

from sklearn.cluster import KMeans 
from sklearn.datasets.samples_generator import make_blobs

# data
x1 = [-4.9, -3.5, 0, -4.5, -3, -1, -1.2, -4.5, -1.5, -4.5, -1, -2, -2.5, -2, -1.5, 4, 1.8, 2, 2.5, 3, 4, 2.25, 1, 0, 1, 2.5, 5, 2.8, 2, 2]
x2 = [-3.5, -4, -3.5, -3, -2.9, -3, -2.6, -2.1, 0, -0.5, -0.8, -0.8, -1.5, -1.75, -1.75, 0, 0.8, 0.9, 1, 1, 1, 1.75, 2, 2.5, 2.5, 2.5, 2.5, 3, 6, 6.5]

#Define a function that updates the centroid of each cluster

colors_map = np.array(['b', 'r'])
def assign_members(x1, x2, centers):

    compare_to_first_center = np.sqrt(np.square(np.array(x1) - centers[0][0]) + np.square(np.array(x2) - centers[0][1]))
    compare_to_second_center = np.sqrt(np.square(np.array(x1) - centers[1][0]) + np.square(np.array(x2) - centers[1][1]))
    class_of_points = compare_to_first_center > compare_to_second_center
    colors = colors_map[class_of_points + 1 - 1]
    return colors, class_of_points

python matplotlib scikit-learn cluster-analysis k-means
1个回答
0
投票

compare_to_first_center 是所有点到 centers[0] 和类似。compare_to_second_center 是所有点到 centers[1]. 现在.., class_of_points 是一个与你的点相同大小的布尔数组,表示每个点是否更接近于 center[0]centers[1]. 如果 class_of_points[i]True, point[i] 在您的数据中更接近于 centers[0].

colors = colors_map[class_of_points + 1 - 1] 分配颜色 br 到点。b 如果他们接近 centers[1]r 对于 centers[0]. 请注意,为了将布尔掩码转换为 class_of_points 到索引数组,它们加1和减1,这样输出就会转换为 False 作为 0True 为1,从而使它们成为指数。一个例子是。

np.array([True, False, True])+1-1 

[1, 0, 1]

或者,你可以简单地将其替换为。

colors = colors_map[class_of_points + 0]

0
投票

似乎有两个中心点的列表。这段代码将计算每一个点到每一个中心点的欧氏距离,并将蓝色分配给那些更接近中心点的中心点。centers[0][:] 和红色的点更接近中心点,在 centers[1][:].

def assign_members(x1, x2, centers):

    # In the following two lines, the eucledean distances are being calculated
    compare_to_first_center = np.sqrt(np.square(np.array(x1) - centers[0][0]) + np.square(np.array(x2) - centers[0][1]))
    compare_to_second_center = np.sqrt(np.square(np.array(x1) - centers[1][0]) + np.square(np.array(x2) - centers[1][1]))

    # Check which center is closer to each point
    # So class_of_points is a binary arary specifies the class number
    class_of_points = compare_to_first_center > compare_to_second_center

    # Depending on the class number (i.e. 0 or 1) it chooses the colour (blue or red)
    colors = colors_map[class_of_points + 1 - 1]
    return colors, class_of_points
© www.soinside.com 2019 - 2024. All rights reserved.