【发布时间】:2020-12-29 17:52:33
【问题描述】:
我正在尝试执行以下循环:
-
将我的矩阵 X 的 n 行中的每一行与 X.prototype 矩阵进行比较。
-
找到 X.prototype 中与 X 的每一行最近的行。
-
如果两行具有相同的标签(y 和 y.prototype),则使值接近;否则,把它们放得更远。
我的代码:
for (i in (1:n)){
closest.row <- which.min(colSums((t(X.prototype) - X[i,])^2))
X.new.x1 <- ifelse(y.prototype[closest.row] == y[i],
X.prototype[closest.row,1]+(eta*(X[i,1]-X.prototype[closest.row,1])),
X.prototype[closest.row,1]-(eta*(X[i,1]-X.prototype[closest.row,1])))
X.new.x2<- ifelse(y.prototype[closest.row] == y[i],
X.prototype[closest.row,2]+(eta*(X[i,2]-X.prototype[closest.row,2])),
X.prototype[closest.row,2]-(eta*(X[i,2]-X.prototype[closest.row,2])))
X.new <- matrix(c(X.new.x1,X.new.x2),ncol=2)
plot(X.new.x2~X.new.x1)
print(X.new)
}
----------
set.seed(123) # Set seed for reproducibility
n <- 100
X <- cbind(x1 = runif(n, -1.5, 1.5),
x2 = runif(n, -1.5, 1.5)) # Generate random points
y <- as.integer(rowSums(X^2)<1) # Determine whether inside the circle#
idx <- sample(100, 10) # Mess up 10 class labels ...
y[idx] <- 1-y[idx] # ... by flipping the label
is <- c(sample(which(y==0),K), sample(which(y==1),K))
X.prototype <- X[is,]
y.prototype <- y[is] # Will be K times 0, followed by K times 1
K <- 10
eta <- 0.25
H <- 25
问题是结果以单个向量的形式出现,我无法将它们组合成一个 X.new 矩阵,用于新的预测并绘制它。
this is a link to how my output looks
This is how I'd like them to look
谢谢 S
【问题讨论】:
-
X.new的class是什么?
标签: r loops if-statement matrix