Rで確率的下降勾配を使用してロジスティック回帰をプログラムしようとしています。たとえば、「ex2data1.txt」という名前のAndrew Ngの例に従いました。
要点は、アルゴリズムが適切に機能するということですが、thetas の推定は私が期待したものとまったく同じではありません。そこで、この問題を解決するためにアルゴリズム全体を変更しようとしました。しかし、それは私にはほとんど不可能でした。この問題の原因となっているエラーを検出できませんでした。したがって、誰かが例をチェックして、シータが正しく計算されない理由を教えてくれると非常に便利です。ほんとうにありがとう。
プログラミングに関しては、Rや行列計算で実装されている関数は使用していません。Hadoopでコードを使用したいため、ループで合計と減算を使用しているだけで、行列計算や、「sum」、「sqrt」などのRですでにプログラムされている関数さえ使用できません
確率的勾配降下法は次のとおりです。
Loop {
for i = 1 to m, {
θj := θj + α(y(i) - hθ(x(i)))(xj)(i)
}
}`
そしてロジスティック回帰:
私のコードは次のとおりです。
data1 <- read.table("~/ex2data1.txt", sep = ",")
names(data1) <- c("Exam1", "Exam2", "Admit")
# Sample the data for stochastic gradient decent
ss<-data1[sample(nrow(data1),size=nrow(data1),replace=FALSE),]
x <- with(ss, matrix(cbind(1, Exam1), nrow = nrow(ss)))
y <- c(ss$Admit)
m <- nrow(x)
# startup parameters
iterations<-1
j<-vector()
alpha<-0.05
theta<-c(0,0)
#My loop
while(iterations<=10){
coste<-c(0,0)
suma<-0
for(i in 1:m){
# h<-1/(1+exp(-Q*x)
h<-1/(1+exp((-theta)*x[i,]))
#Cost(hQ(x),y)=y(i)*log(hQ(x))+(1-y(i))*log(1-hQ(x))
cost<-((y[i]*log(h))+((1-y[i])*log(1-h)))
#sum(cost) i=1 to m
suma<-suma+cost
#Diferences=(hQ(x(i))-y(i))*x(i)
difference<-(h-y[i])*x[i,]
#sum the differences
coste<-coste+difference
#calculation thetas and upgrade = Qj:= Qj - alpha* sum((h-y[i])*x[i,]*x(i))
theta[1]<-(theta[1]-alpha*1/m*(coste[1]))
theta[2]<-(theta[2]-alpha*1/m*(coste[2]))
}
#J(Q)=(-1/m)* sum ( y(i)*log(hQ(x))+(1-y(i))*log(1-hQ(x)))
j[iterations]<-(-1/m)*suma
iterations=iterations+1
}
#If I compare my thetas with R glm
Call: glm(formula = y ~ x[, 2], family = binomial("logit"), data = data1)
Coefficients:
Intercept:-4.71816
x[, 2] :0.08091
私のシータ
Intercept: 0.4624024
x[,2]: 1.3650234