R에서 확률 적 하강 기울기를 가진 로지스틱 회귀를 프로그래밍하려고합니다. 예를 들어 Andrew Ng가 "ex2data1.txt"라는 예를 따라했습니다.Stochastic 그래디언트 강하를 이용한 로지스틱 회귀 프로그래밍 R
요점은 알고리즘이 제대로 작동하지만 추정치가 예상 한 것과 정확히 일치하지 않는다는 것입니다. 그래서이 문제를 해결하기 위해 전체 알고리즘을 변경하려고했습니다. 그러나, 그것은 거의 불가능했습니다. 이 문제를 일으키는 오류를 감지 할 수 없었습니다. 따라서 누군가가 예제를 확인하고 왜 thetas가 정확하게 계산되지 않는지를 알 수 있다면 매우 유용 할 것입니다. 정말 감사.
프로그래밍에 관해서는 또는에 구현 된 함수를 사용하고 있지 않습니다. 난 그냥 합계 및 subtractions 루프에서 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
내 쎄타 내가 다른 잉의 예를 세트에 대한 R의 솔루션을 구현 한
Intercept: 0.4624024
x[,2]: 1.3650234
대신 안녕하세요! 귀하의 답변을 주셔서 감사합니다,하지만 난 그냥 합계와 subtractions 루프를 사용하여 hadoop 코드를 사용하고 싶습니다 및 매트릭스 계산법 또는 이미 "R"에서 "sum", "sqrt", " 최적화 "등. – user3488416