[英]How to use predict with multinom() with intercept in R?
我已經在R中運行了multinom()函數,但是當我嘗試對一個新樣本進行預測時,它會不斷出現錯誤。
這是代碼:
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)
這是錯誤:
Error in predict.multinom(res4, newdata = nd) :
NAs are not allowed in subscripted assignments
我認為這與分析中包含的截距有關,但與新的預測輸入無關。 我嘗試通過合並包含名為1的1x1數據幀(設置為incept)(在summary()中調用)來手動設置它,但仍然會出現相同的錯誤。
#add intercept manually to prediction row
intercept<-data.frame(1)
names(intercept)[1]<-"Intercept"
nd<-merge(intercept,nd)
問題在於您如何指定模型:您不能將R函數混入這樣的公式中。 嘗試這個:
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.