逻辑回归:二项式变量中的 x 和 y 训练数据误差(glm、glmnet 公式)

Logistic Regression: x and y training data errors in binomial variable (glm, glmnet formula)

我正在尝试对矩阵数据集 training/testing 执行逻辑回归。最终结果应该告诉我二项式变量的预测有多准确。 R 一直告诉我我需要一个 nx2 矩阵,但我不知道该怎么做,因为我的一个向量已经是一个二项式变量。这是代码

library(glmnet)
library(e1071)
require(caTools)


A=matrix(
  c(64830,18213,4677,24761,9845,17504,22137,12531,5842,28827,66161,18852,5581,27219,10159,17527,23402,11409,8115,31425,68426,18274,5513,25687,10971,14104,19604,13438,6011,30055,69716,18366,5735,26556,11733,16605,20644,15516,5750,31116,73128,18906,5759,28555,11951,19810,22086,17425,6152,28469,1,1,1,0,1,0,0,0,0,1),


nrow = 10,
ncol = 6,
byrow = FALSE)  #"bycol" does NOT exist
################### data set as vectors
a<-c(64830,18213,4677,24761,9845,17504,22137,12531,5842,28827)
b<-c(66161,18852,5581,27219,10159,17527,23402,11409,8115,31425)
c<-c(68426,18274,5513,25687,10971,14104,19604,13438,6011,30055)
d<-c(69716,18366,5735,26556,11733,16605,20644,15516,5750,31116)
e<-c(73128,18906,5759,28555,11951,19810,22086,17425,6152,28469)
f<-c(1,1,1,0,1,0,0,0,0,1)
######################

n<-nrow(A);
K<-ncol(A)-1;
x<-matrix(0,n,K);

for(i in 1:K){x[,i]<-A[,i];}
#A[,i] is 10long and x[,i] is 1long.
#A[,i:length(x[,i])]=x[,i]
y<-A[,K+1];
#training/test data split:
idx<-sample(1:n,floor(n/2),replace=FALSE);
xtr<-x[idx,]; ytr<-y[idx];
xts<-x[-idx,]; yts<-y[-idx];
#fit the logistic model to it
myglm<-glmnet(ytr,yts,family="binomial"); 
#Error in if (is.null(np) | (np[2] <= 1)) stop("x should be a matrix with 2 or more columns") : argument is of length zero

#apply traning data to test data
#glmnet(xtr,ytr,family="binomial")

mypred<-predict(myglm,newx=xts,type="response",s=0.01);
posteriprob<-mypred[,,1];
yhat<-matrix(1,nrow(xts),1);
for(i in 1:nrow(xts))
{
  yhat[i]<-which.max(posteriprob[i,]);
}

acc<-sum(yhat+2==yts)/nrow(xts);
cat("accuracy of test data:", acc, "\n");

在 for 循环之后,当我为逻辑公式调用 glmnet 时,我得到错误:

Error in if (is.null(np) | (np[2] <= 1)) stop("x should be a matrix with 2 or more columns") : argument is of length zero

问题是因为您将 ytr(一个数值向量)作为 x 变量。试试

myglm<-glmnet(xts,yts,family="binomial")

myglm<-glmnet(xtr,ytr,family="binomial")

两个代码似乎都有效。