2017-08-28 42 views
1

類型使用內置虹膜數據集,我可以訓練一個模型,如:提取要素類/從插入符號火車對象

model <- train(Species~., data=iris, method='xgbTree') 

我可以提取特徵的名字,但是當我試圖讓他們的類,它返回的字符,因爲他們只是字符串。

model$coefnames 
## "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" 

lapply(model$coefnames, class) 
## "character" "character" "character" "character" 

但是,當您嘗試放入其他類型的變量以進行預測時,看起來好像插入符號知道預期的類型。

test<- data.frame(Sepal.Length=1, 
        Sepal.Width=2, 
        Petal.Length=3, 
        Petal.Width="x") # character instead of numeric 

predict(model, newdata=test) 
## Error: variable 'Petal.Width' was fitted with type "numeric" but type "factor" was supplied 

有沒有什麼辦法可以通過使用模型對象本身來提取用於訓練模型的特徵類型?我能得到的最接近的是使用dplyr函數type.convert,但是這需要知道輸入將是。我理想中的功能將操作是這樣的:

model_types(model$coefnames) 
## "numeric" "numeric" "numeric" "numeric" 

回答

1

此信息存儲爲模型的項的屬性

attr(terms(model), "dataClasses") 
#  Species Sepal.Length Sepal.Width Petal.Length Petal.Width 
#  "factor" "numeric" "numeric" "numeric" "numeric" 
+0

太感謝了,知道它是在那裏的地方。 – tjq