具体过程和代码如下所示:1.使用glmnet及predict函数进行预测:
fit1=glmnet(x_train,y_train,family="multinomial",type.multinomial = "grouped")
prefit.t<-predict(fit1,newx = x_test,type = "class",s=0)
2.提取theta系数,之后使用自己编写的L.predict函数进行预测:
预测函数公式:
L.predict<-function(x,theta,theta0,kl){ pred<-vector()
P<-matrix(NA,nrow=nrow(x),ncol = kl)
for(t in 1:nrow(x)){
for (i in 1:kl){
#先计算出klp,即kl类的概率总和
klp<-0
for(k in 1:kl){
klp<-klp+exp(theta0[k] + as.numeric(crossprod(x[t,],theta[k,])))
}
#第i类概率的取值Pi
P[t,i]<-exp(theta0+as.numeric(crossprod(x[t,],theta[i,])))/klp
}
pred[t]<-which(P[t,] == (max(P[t,])))
}
res<-list(P,pred)
return(res)
}
提取theta值:
theta<-list()
theta0<-vector()
for (i in 1:3){
theta[]<-coef(fit1,s=0)[][-1]
theta0<-coef(fit1,s=0)[][1]
}
theta1<-matrix(cbind(theta[[1]],theta[[2]],theta[[3]]),nrow=3)
pred_y<-L.predict(x_test,theta1,theta0,kl)