Need help translating this code in R to python. It is a logistic regression algo
ID: 3588238 • Letter: N
Question
Need help translating this code in R to python. It is a logistic regression algorithm.
rm(list=ls());
h <- function(a,b,t){
return (1/(1+(exp(-(t*a+b)))))
}
t=rbind(as.matrix(rnorm(50,5,1.5),nrow=50,ncol=1),as.matrix(rnorm(50,-1,1.5),nrow=50,ncol=1))
y=rbind(matrix(1,nrow=50,ncol=1),matrix(0,nrow=50,ncol=1))
a=0;b=0;tau=0.05
plot(x <- seq(-10, 10, length.out = 10^3),y=h(a,b,x),xlab='x',type='l',col='black', xlim=c(-10, 10), ylim=c(-0.3, 1.3))
lines(x=seq(0, 0, length.out = 10^3),y=seq(-2, 2, length.out = 10^3))
symbols(t[1:50],y[1:50], circles=matrix(1,nrow=nrow(t)/2,ncol=1), inches=0.03, ann=F, bg="salmon", fg=NULL, add=TRUE)
symbols(t[51:100],y[51:100], circles=matrix(1,nrow=nrow(t)/2,ncol=1), inches=0.03, ann=F, bg="lightskyblue", fg=NULL, add=TRUE)
i=0;
#Training
while(TRUE) {
pre_a=a;pre_b=b;
da=as.numeric(t((y-h(pre_a,pre_b,t)))%*%t)
a=pre_a + da*tau ;
db = as.numeric(sum(y-h(pre_a,pre_b,t))) ;
b=pre_b + db*tau ;
if (abs(pre_a-a)<0.01 && abs(pre_b-b)<0.01)
break;
i=i+1; print(i)
Sys.sleep(0.5)
lines(x <- seq(-10, 10, length.out = 10^3),y=h(a,b,x),lwd=0.3)
}
lines(x <- seq(-10, 10, length.out = 10^3),y=h(a,b,x),col='red',lwd=2)
print(a)
print(b)
Explanation / Answer
rm(list=ls());
h <- function(a,b,t){
return (1/(1+(exp(-(t*a+b)))))
}
t=rbind(as.matrix(rnorm(50,5,1.5),nrow=50,ncol=1),as.matrix(rnorm(50,-1,1.5),nrow=50,ncol=1))
y=rbind(matrix(1,nrow=50,ncol=1),matrix(0,nrow=50,ncol=1))
a=0;b=0;tau=0.05
plot(x <- seq(-10, 10, length.out = 10^3),y=h(a,b,x),xlab='x',type='l',col='black', xlim=c(-10, 10), ylim=c(-0.3, 1.3))
lines(x=seq(0, 0, length.out = 10^3),y=seq(-2, 2, length.out = 10^3))
symbols(t[1:50],y[1:50], circles=matrix(1,nrow=nrow(t)/2,ncol=1), inches=0.03, ann=F, bg="salmon", fg=NULL, add=TRUE)
symbols(t[51:100],y[51:100], circles=matrix(1,nrow=nrow(t)/2,ncol=1), inches=0.03, ann=F, bg="lightskyblue", fg=NULL, add=TRUE)
i=0;
#Training
while(TRUE) {
pre_a=a;pre_b=b;
da=as.numeric(t((y-h(pre_a,pre_b,t)))%*%t)
a=pre_a + da*tau ;
db = as.numeric(sum(y-h(pre_a,pre_b,t))) ;
b=pre_b + db*tau ;
if (abs(pre_a-a)<0.01 && abs(pre_b-b)<0.01)
break;
i=i+1; print(i)
Sys.sleep(0.5)
lines(x <- seq(-10, 10, length.out = 10^3),y=h(a,b,x),lwd=0.3)
}
lines(x <- seq(-10, 10, length.out = 10^3),y=h(a,b,x),col='red',lwd=2)