我正在尝试在 R 中实现我自己的逻辑回归算法,但我似乎无法使矩阵乘法/点积运算符%*%
工作。我已经尝试了很多不同的东西。下面是可以在 R 环境中运行的代码:
weight_a <- c(rep(1,5))
random_sample <- sample(1:NROW(iris),50)
# Delta terms for each type (starts out nonzero)
del_a <- 1;
# Dataset for part a (first 50 vs. last 100)
iris_a <- iris
iris_a$Species <- as.integer(iris_a$Species)
# Convert list to binary class
for (i in 1:NROW(iris_a$Species)) {if (iris_a$Species[i] != "1") {iris_a$Species[i] <- -1}}
while(del_a > 0.01) {
# Compute gradient
for (k in 1:NROW(random_sample)) {
grade_a <- -1/NROW(random_sample) * sum(iris_a$Species[random_sample[k]]*iris_a[random_sample[k],1:4]
/(1+exp(iris_a$Species[random_sample[k]]*weight_a%*%iris_a[random_sample[k],1:4])))
}
}
关键部分是weight_a%*%iris_a[random_sample[k],1:4]
,它不起作用(翻译成英文,错误是“需要矩阵或向量”)。所以我尝试了其他一些事情:
# Trivial case works, gives 5
rep(1,5)%*%rep(1,5)
# Gives tensor product
rep(1,5)%*%as.matrix(iris_a[random_sample[k],1:4])
# Transpose doesn't work, gives row vector and result is an error ("Improper argument").
t(t(rep(1,5)))%*%as.matrix(iris_a[random_sample[k],1:4])
# Double transpose gives column vector, but result is tensor product again
t(t(rep(1,5)))%*%as.matrix(iris_a[random_sample[k],1:4])
# Matrix context gives tensor product again
as.matrix(rep(1,5))%*%as.matrix(iris_a[random_sample[k],1:4])
# Transposing the first argument to get a row vector gives an "Improper argument" error again
t(as.matrix(rep(1,5)))%*%as.matrix(iris_a[random_sample[k],1:4])
R 应该比这更聪明(并且比 MATLAB 更好)。假设我只是做错了,那么正确的方法是什么?(我推出了自己的循环函数,但是,呃......)