如何为 flexclust::distEuclidean 指定参数 centers?
How to specify argument `centers` for `flexclust::distEuclidean`?
我想使用 flexclust::distEuclidean
,但我不确定应该如何指定 centers
。 ?distance
.
的文档中没有给出示例
所以我查看了这个函数的源码(结果很短):
function (x, centers)
{
if (ncol(x) != ncol(centers))
stop(sQuote("x"), " and ", sQuote("centers"), " must have the same number of columns")
z <- matrix(0, nrow = nrow(x), ncol = nrow(centers))
for (k in 1:nrow(centers)) {
z[, k] <- sqrt(colSums((t(x) - centers[k, ])^2))
}
z
}
<environment: namespace:flexclust>
如果 p
是我数据中的一些特征,k
是聚类的数量,那么 centers
应该是一个 k x p
矩阵,即连续的质心应该排成一排?
实际上,它必须是这样的,因为这个函数首先检查是否ncol(x) = ncol(centers)
。但是我们有
z[, k] <- sqrt(colSums((t(x) - centers[k, ])^2))
t(x) - centers[k,]
是如何工作的? t(x)
是 p x n
矩阵,centers[k, ]
是 1 x p
向量,因此维度不匹配...
t(x)
is a p x n
matrix and centers[k, ]
is 1 x p
vector, so dimension don't match...
不,centers[k, ]
只是一个没有维度的向量。在t(x) - centers[k, ]
中,R中的recycling rule将适用。
如果你这样做 t(x) - centers[k, ,drop = FALSE]
,你会得到预期的失败。
一个简单的例子让你消化:
x <- matrix(1:6, nrow = 3)
y <- x
x - y[, 1] ## yeah!
x - y[, 1, drop = FALSE] ## oops!
我想使用 flexclust::distEuclidean
,但我不确定应该如何指定 centers
。 ?distance
.
所以我查看了这个函数的源码(结果很短):
function (x, centers)
{
if (ncol(x) != ncol(centers))
stop(sQuote("x"), " and ", sQuote("centers"), " must have the same number of columns")
z <- matrix(0, nrow = nrow(x), ncol = nrow(centers))
for (k in 1:nrow(centers)) {
z[, k] <- sqrt(colSums((t(x) - centers[k, ])^2))
}
z
}
<environment: namespace:flexclust>
如果 p
是我数据中的一些特征,k
是聚类的数量,那么 centers
应该是一个 k x p
矩阵,即连续的质心应该排成一排?
实际上,它必须是这样的,因为这个函数首先检查是否ncol(x) = ncol(centers)
。但是我们有
z[, k] <- sqrt(colSums((t(x) - centers[k, ])^2))
t(x) - centers[k,]
是如何工作的? t(x)
是 p x n
矩阵,centers[k, ]
是 1 x p
向量,因此维度不匹配...
t(x)
is ap x n
matrix andcenters[k, ]
is1 x p
vector, so dimension don't match...
不,centers[k, ]
只是一个没有维度的向量。在t(x) - centers[k, ]
中,R中的recycling rule将适用。
如果你这样做 t(x) - centers[k, ,drop = FALSE]
,你会得到预期的失败。
一个简单的例子让你消化:
x <- matrix(1:6, nrow = 3)
y <- x
x - y[, 1] ## yeah!
x - y[, 1, drop = FALSE] ## oops!