Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Multi dimension logistic regression. Need to translate this R code to python. rm

ID: 3588244 • Letter: M

Question

Multi dimension logistic regression. Need to translate this R code to python.

rm(list=ls());
h <- function(w,X){
return (1/(1+(exp(-( X%*%w )) )))
}


data=read.table('iris.data',sep=',')
X=cbind(as.matrix(data[1:100,-ncol(data)]),matrix(1,nrow=100,ncol=1))
testX=X[1,]
trainX=X[-1,]
y=rbind(matrix(0,nrow=50,ncol=1),matrix(1,nrow=50,ncol=1))
testy=y[1,]
trainy=y[-1,]

tau=0.01
#Training
w=matrix(0,nrow=ncol(trainX),ncol=1)


while(TRUE) {
pre_w=w
for(j in 1:ncol(trainX)){
pre_wj=w[j]
dwj=as.numeric(t((trainy-h(w,trainX)))%*%trainX[,j])
w[j]=w[j] + dwj*tau ;  
}
if (abs(t(pre_w)%*%pre_w - t(w)%*%w)<0.001)
break;
}


print(h(w,testX))
print(testy)

Explanation / Answer

rm(list=ls());
h <- function(w,X){
return (1/(1+(exp(-( X%*%w )) )))
}


data=read.table('iris.data',sep=',')
X=cbind(as.matrix(data[1:100,-ncol(data)]),matrix(1,nrow=100,ncol=1))
testX=X[1,]
trainX=X[-1,]
y=rbind(matrix(0,nrow=50,ncol=1),matrix(1,nrow=50,ncol=1))
testy=y[1,]
trainy=y[-1,]

tau=0.01
#Training
w=matrix(0,nrow=ncol(trainX),ncol=1)


while(TRUE) {
pre_w=w
for(j in 1:ncol(trainX)){
pre_wj=w[j]
dwj=as.numeric(t((trainy-h(w,trainX)))%*%trainX[,j])
w[j]=w[j] + dwj*tau ;  
}
if (abs(t(pre_w)%*%pre_w - t(w)%*%w)<0.001)
break;
}


print(h(w,testX))
print(testy)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote