##Uncomment it the "glmnet" package is never previously installed
##install.packages("glmnet");
library(glmnet);
n<-2000;
x<-matrix(rnorm(n*20),n,20);
##The usual two-class logistic regression
##y2<-sample(1:2,n,replace=TRUE);
##myglm2<-glmnet(x,y2,family="binomial");
##summary(myglm2);
##Four-class multiple logistic regression
y4<-sample(1:4,n,replace=TRUE);
##To split the data into training and test set
idx<-sample(1:n,floor(n/2),replace=FALSE);
xtr<-x[idx,]; ytr<-y4[idx];
xts<-x[-idx,]; yts<-y4[-idx];
##Fit the multiple logistic regression model
myglm4<-glmnet(xtr,ytr,family="multinomial");
##Apply the trained model to the test set
mypred4<-predict(myglm4,newx=xts,type="response",s=0.01);
posteriprob<-mypred4[,,1];
yhat<-matrix(1,nrow(xts),1);
for(i in 1:nrow(xts))
{
yhat[i]<-which.max(posteriprob[i,]);
}
acc<-sum(yhat==yts)/nrow(xts);
cat("Accuracy on the test set is", acc, "\n");