简体   繁体   English

如何在带有R的拦截的multinom()中使用预测?

[英]How to use predict with multinom() with intercept in R?

I have run the multinom() function in R, but when I try to predict on a new sample, it keeps giving an error. 我已经在R中运行了multinom()函数,但是当我尝试对一个新样本进行预测时,它会不断出现错误。

this is the code: 这是代码:

library(nnet)
dta=data.frame(replicate(10,runif(10)))
names(dta)=c('y',paste0('x',1:9))
res4 <- multinom(y ~ as.matrix(dta[2:10]) , data=dta)
#make new data to predict
nd<-0.1*dta[1,2:10]
pred<-predict(res4, newdata=nd)

and this is the error: 这是错误:

Error in predict.multinom(res4, newdata = nd) : 
  NAs are not allowed in subscripted assignments

I think it has to do with the intercept being included in the analysis, but not in the new prediction input. 我认为这与分析中包含的截距有关,但与新的预测输入无关。 I tried to set it manually by merging a 1x1 data frame containing a 1 named "Intercept" (as it is called in the summary()), but it still gives the same error. 我尝试通过合并包含名为1的1x1数据帧(设置为incept)(在summary()中调用)来手动设置它,但仍然会出现相同的错误。

#add intercept manually to prediction row
intercept<-data.frame(1)
names(intercept)[1]<-"Intercept"
nd<-merge(intercept,nd)

The problem is with how you specified your model: you can't mix R functions into formulas like that. 问题在于您如何指定模型:您不能将R函数混入这样的公式中。 Try this: 尝试这个:

res4 <- multinom(y ~ . , data=dta) # You could also specify explicitly: y~x1+x2+x3...
#make new data to predict
nd<-0.1*dta[1,2:10]
predict(res4, newdata=nd)
# [1] 0.971794712357223
# 10 Levels: 0.201776991132647 0.211950202938169 0.223103292752057 0.225121688563377 0.372682225191966 0.612373929005116 ... 0.971794712357223

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM