[英]"NAs introduced by coercion" Error when using tree function
我一直在使用 KNN 算法對事件進行分類,但這並沒有導致分類的高精度。 一些同事告訴我,R 中的tree ()
函數(來自tree
包)可以幫助解決這個問題。
這是我的數據示例。 我正在嘗試根據前兩列"ACTIVITY_X"
和"ACTIVITY_Y"
的值對不同的事件進行分類(我有 8 類不同的事件):
> print(dataset)
ACTIVITY_X ACTIVITY_Y Event
1: 19 21 Vigilance
2: 20 14 Vigilance
3: 34 35 Vigilance
4: 18 5 Vigilance
5: 23 27 Vigilance
---
426: 9 25 Vigilance
427: 0 0 Head-up
428: 0 0 Head-up
429: 3 3 Head-up
430: 0 0 Vigilance
理想情況下,我想在不同類別(平視、警戒等)之間找到不同的閾值,當"Event"
數據不可用且我只有"ACTIVITY_X"
和"ACTIVITY_Y"
數據時,這應該有助於對它們進行分類。 我想我應該使用tree()
函數:
xtree <- tree(Head-up~ACTIVITY_X+ACTIVITY_Y,data=dataset)
plot(xtree)
title("Head_up")
text(xtree)
xtree <- tree(Vigilance~ACTIVITY_X+ACTIVITY_Y,data=dataset)
plot(xtree)
title("Vigilance")
text(xtree)
etc..
但是,我在運行分析時遇到了不同的錯誤,主要是"NAs introduced by coercion"
。 當我使用rpart()
函數時,這些錯誤是不存在的,該函數也是一種分類算法。
> xtree <- tree(Vigilance~ACTIVITY_X+ACTIVITY_Y,data=dataset)
Warning message:
In tree(Vigilance ~ ACTIVITY_X + ACTIVITY_Y, data = dataset) :
NAs introduced by coercion
> plot(xtree)
Error in plot.tree(xtree) : cannot plot singlenode tree
> title("Vigilance")
Error in title("Vigilance") : plot.new has not been called yet
> text(xtree)
Error in text.tree(xtree) : cannot plot singlenode tree
任何幫助,將不勝感激。 我對 R 很陌生,所以我希望其他用戶仍然對這個問題感興趣。
我有點不確定我的數據結構是否與您的相同,但錯誤對我來說是相同的:
Binary | X1 | X2
No | 6.3 | 8.3
Yes | 7.2 | 9.8
Yes | 5.0 | 3.8
x = tree(Binary ~ . , data)
強制引入的 NA
對我來說,這個錯誤是因為數據集中的“二進制”變量的格式是“字符”而不是所需的“因子”格式
class(data$Binary)
"character"
data$Binary = as.factor(data$Binary)
class(data$Binary)
"factor"
在此轉換后,運行 tree 函數不再出現錯誤。
是的,將變量從其他類(如二進制、字符等)更改為因子,謝謝..!!!
> class(train_data$saleCAT)
[1]“性格”
data$saleCAT <- as.factor(data_cat)
> class(train_data$saleCAT)
[1] “因素”
關於這個主題的評論有點舊,但我認為舊版本的 R 在分配時會自動分配因子,我認為這會更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.