我正在尝试使用 R 中的随机梯度下降来构建我自己的逻辑回归函数,但是我现在所拥有的使权重无限制地增长,因此永远不会停止:
# Logistic regression
# Takes training example vector, output vector, learn rate scalar, and convergence delta limit scalar
my_logr <- function(training_examples,training_outputs,learn_rate,conv_lim) {
# Initialize gradient vector
gradient <- as.vector(rep(0,NCOL(training_examples)))
# Difference between weights
del_weights <- as.matrix(1)
# Weights
weights <- as.matrix(runif(NCOL(training_examples)))
weights_old <- as.matrix(rep(0,NCOL(training_examples)))
# Compute gradient
while(norm(del_weights) > conv_lim) {
for (k in 1:NROW(training_examples)) {
gradient <- gradient + 1/NROW(training_examples)*
((t(training_outputs[k]*training_examples[k,]
/(1+exp(training_outputs[k]*t(weights)%*%as.numeric(training_examples[k,]))))))
}
# Update weights
weights <- weights_old - learn_rate*gradient
del_weights <- as.matrix(weights_old - weights)
weights_old <- weights
print(weights)
}
return(weights)
}
该功能可以使用以下代码进行测试:
data(iris) # Iris data already present in R
# 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}}
random_sample <- sample(1:NROW(iris),50)
weights_a <- my_logr(iris_a[random_sample,1:4],iris_a$Species[random_sample],1,.1)
我用Abu-Mostafa's仔细检查了我的算法,如下所示:
- 初始化权重向量
- 对于每个时间步计算梯度:
gradient <- -1/N * sum_{1 to N} (training_answer_n * training_Vector_n / (1 + exp(training_answer_n * dot(weight,training_vector_n))))
weight_new <- weight - learn_rate*gradient
- 重复直到重量增量足够小
我在这里错过了什么吗?