从零开始 Python 中的 K 均值
K Means in Python from Scratch
我有一个 k-means 算法的 python 代码。
我很难理解它的作用。
像 C = X[numpy.random.choice(X.shape[0], k, replace=False), :]
这样的行让我很困惑。
有人可以解释这段代码的实际作用吗?
谢谢
def k_means(data, k, num_of_features):
# Make a matrix out of the data
X = data.as_matrix()
# Get k random points from the data
C = X[numpy.random.choice(X.shape[0], k, replace=False), :]
# Remove the last col
C = [C[j][:-1] for j in range(len(C))]
# Turn it into a numpy array
C = numpy.asarray(C)
# To store the value of centroids when it updates
C_old = numpy.zeros(C.shape)
# Make an array that will assign clusters to each point
clusters = numpy.zeros(len(X))
# Error func. - Distance between new centroids and old centroids
error = dist(C, C_old, None)
# Loop will run till the error becomes zero of 5 tries
tries = 0
while error != 0 and tries < 1:
# Assigning each value to its closest cluster
for i in range(len(X)):
# Get closest cluster in terms of distance
clusters[i] = dist1(X[i][:-1], C)
# Storing the old centroid values
C_old = deepcopy(C)
# Finding the new centroids by taking the average value
for i in range(k):
# Get all of the points that match the cluster you are on
points = [X[j][:-1] for j in range(len(X)) if clusters[j] == i]
# If there were no points assigned to cluster, put at origin
if not points:
C[i][:] = numpy.zeros(C[i].shape)
else:
# Get the average of all the points and put that centroid there
C[i] = numpy.mean(points, axis=0)
# Erro is the distance between where the centroids use to be and where they are now
error = dist(C, C_old, None)
# Increase tries
tries += 1
return sil_coefficient(X,clusters,k)
(扩展答案,稍后格式化)
X 是数据,作为矩阵。
使用 [] 表示法,我们从矩阵中获取切片或 selecting 单个元素。您可能想要查看 numpy 数组索引。 https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
numpy.random.choice selects k 个元素从数据矩阵第一维的大小中随机抽取,无需放回。
请注意,在索引中,使用 [] 语法,我们看到我们有两个条目。 numpy.random.choice 和“:”。
“:”表示我们正在沿该轴获取所有内容。
因此,X[numpy.random.choice(X.shape[0], k, replace=False), :] 意味着我们 select 沿第一个轴的元素并取每个元素沿着共享第一个索引的第二个。实际上,我们是 select 矩阵的随机行。
(评论很好地解释了这段代码,我建议您阅读 numpy indexing an list comprehensions 以进一步阐明)。
C[C[j][:-1] for j in range(len(c))]
"C[" 之后的部分使用列表理解来 select 矩阵 C 的部分。
C[j]表示矩阵C的行。
我们使用 [:-1] 来占据,但不包括该行的最后一个元素。我们对矩阵 C 中的每一行执行此操作。这将删除矩阵的最后一列。
C = numpy.asarray(C)。这会将矩阵转换为 numpy 数组,因此我们可以用它做特殊的 numpy 事情。
C_old = numpy.zeros(C.shape)。这将创建一个零矩阵,稍后填充,其大小与 C 相同。我们正在初始化此数组以稍后填充。
簇 = numpy.zeros(len(x))。这将创建一个零向量,其维度与矩阵 X 中的行数相同。稍后将填充此向量。我们正在初始化此数组以供稍后填充。
error = dist(C, C_old, None).取两个矩阵之间的距离。我相信这个函数将在您的脚本的其他地方定义。
尝试 = 0。将轮胎计数器设置为 0。
while...在此条件为真时执行此块。
for i in [0...(X - 1 中的行数)]:
clusters[i] = dist1(X[i][:-1], C);把X的第i行最靠近哪个簇放在簇的第i个位置。
C_old = deepcopy(C) - 创建 C 的新副本。不要只是移动指针。
对于每个(0..平均值 - 1):
points = [X[j][:-1] for j in range(len(X)) if clusters[j] == i]。这是一个列表理解。创建 X 行的列表,包含除最后一个条目以外的所有行,但仅包含属于第 j 个簇的行。
如果不点。如果没有任何东西属于一个集群。
C[i][:] = numpy.zeros(C[i].shape)。创建一个零向量,稍后填充,并将此向量用作簇矩阵 C.
的第 i 行
其他:
C[i] = np.mean(点,轴=0)。将簇矩阵 C 的第 i 行指定为簇中的平均点。我们对行求和(轴 = 0)。这是我们更新我们的集群。
我有一个 k-means 算法的 python 代码。
我很难理解它的作用。
像 C = X[numpy.random.choice(X.shape[0], k, replace=False), :]
这样的行让我很困惑。
有人可以解释这段代码的实际作用吗? 谢谢
def k_means(data, k, num_of_features):
# Make a matrix out of the data
X = data.as_matrix()
# Get k random points from the data
C = X[numpy.random.choice(X.shape[0], k, replace=False), :]
# Remove the last col
C = [C[j][:-1] for j in range(len(C))]
# Turn it into a numpy array
C = numpy.asarray(C)
# To store the value of centroids when it updates
C_old = numpy.zeros(C.shape)
# Make an array that will assign clusters to each point
clusters = numpy.zeros(len(X))
# Error func. - Distance between new centroids and old centroids
error = dist(C, C_old, None)
# Loop will run till the error becomes zero of 5 tries
tries = 0
while error != 0 and tries < 1:
# Assigning each value to its closest cluster
for i in range(len(X)):
# Get closest cluster in terms of distance
clusters[i] = dist1(X[i][:-1], C)
# Storing the old centroid values
C_old = deepcopy(C)
# Finding the new centroids by taking the average value
for i in range(k):
# Get all of the points that match the cluster you are on
points = [X[j][:-1] for j in range(len(X)) if clusters[j] == i]
# If there were no points assigned to cluster, put at origin
if not points:
C[i][:] = numpy.zeros(C[i].shape)
else:
# Get the average of all the points and put that centroid there
C[i] = numpy.mean(points, axis=0)
# Erro is the distance between where the centroids use to be and where they are now
error = dist(C, C_old, None)
# Increase tries
tries += 1
return sil_coefficient(X,clusters,k)
(扩展答案,稍后格式化) X 是数据,作为矩阵。 使用 [] 表示法,我们从矩阵中获取切片或 selecting 单个元素。您可能想要查看 numpy 数组索引。 https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html numpy.random.choice selects k 个元素从数据矩阵第一维的大小中随机抽取,无需放回。 请注意,在索引中,使用 [] 语法,我们看到我们有两个条目。 numpy.random.choice 和“:”。 “:”表示我们正在沿该轴获取所有内容。
因此,X[numpy.random.choice(X.shape[0], k, replace=False), :] 意味着我们 select 沿第一个轴的元素并取每个元素沿着共享第一个索引的第二个。实际上,我们是 select 矩阵的随机行。
(评论很好地解释了这段代码,我建议您阅读 numpy indexing an list comprehensions 以进一步阐明)。
C[C[j][:-1] for j in range(len(c))] "C[" 之后的部分使用列表理解来 select 矩阵 C 的部分。
C[j]表示矩阵C的行。 我们使用 [:-1] 来占据,但不包括该行的最后一个元素。我们对矩阵 C 中的每一行执行此操作。这将删除矩阵的最后一列。
C = numpy.asarray(C)。这会将矩阵转换为 numpy 数组,因此我们可以用它做特殊的 numpy 事情。
C_old = numpy.zeros(C.shape)。这将创建一个零矩阵,稍后填充,其大小与 C 相同。我们正在初始化此数组以稍后填充。
簇 = numpy.zeros(len(x))。这将创建一个零向量,其维度与矩阵 X 中的行数相同。稍后将填充此向量。我们正在初始化此数组以供稍后填充。
error = dist(C, C_old, None).取两个矩阵之间的距离。我相信这个函数将在您的脚本的其他地方定义。
尝试 = 0。将轮胎计数器设置为 0。
while...在此条件为真时执行此块。
for i in [0...(X - 1 中的行数)]:
clusters[i] = dist1(X[i][:-1], C);把X的第i行最靠近哪个簇放在簇的第i个位置。
C_old = deepcopy(C) - 创建 C 的新副本。不要只是移动指针。
对于每个(0..平均值 - 1):
points = [X[j][:-1] for j in range(len(X)) if clusters[j] == i]。这是一个列表理解。创建 X 行的列表,包含除最后一个条目以外的所有行,但仅包含属于第 j 个簇的行。
如果不点。如果没有任何东西属于一个集群。
C[i][:] = numpy.zeros(C[i].shape)。创建一个零向量,稍后填充,并将此向量用作簇矩阵 C.
的第 i 行其他:
C[i] = np.mean(点,轴=0)。将簇矩阵 C 的第 i 行指定为簇中的平均点。我们对行求和(轴 = 0)。这是我们更新我们的集群。