我有以下data.table,其中每個唯一的x
值與唯一的y
值相關聯。於是我強迫一個x
價值NA
第k近鄰鍛鍊的目的:knnImpute使用分類變量與插入符號包
dt <- data.table(x = rep(c(1:4), 3),
y = rep(c("Brandon", "Erica", "Karyna", "Alex"), 3))
dt[3, 1] <- NA
print(dt)
# x y
#1: 1 Brandon
#2: 2 Erica
#3: NA Karyna
#4: 4 Alex
#5: 1 Brandon
#6: 2 Erica
#7: 3 Karyna
#8: 4 Alex
#9: 1 Brandon
#10: 2 Erica
#11: 3 Karyna
#12: 4 Alex
參考第一答案this question,我創建了一個二元矩陣出dt$y
像這樣:
dt.a <- model.matrix(~ y -1 , data = dt)
dt2 <- cbind(dt[, -2, with = FALSE], dt.a)
print(dt2)
# x yAlex yBrandon yErica yKaryna
#1: 1 0 1 0 0
#2: 2 0 0 1 0
#3: NA 0 0 0 1
#4: 4 1 0 0 0
#5: 1 0 1 0 0
#6: 2 0 0 1 0
#7: 3 0 0 0 1
#8: 4 1 0 0 0
#9: 1 0 1 0 0
#10: 2 0 0 1 0
#11: 3 0 0 0 1
#12: 4 1 0 0 0
使用caret
包的preProcess
函數中的knnImpute
方法,我期望dt3[1, 3]
下面的中心和縮放輸出等於第7和第12行,但它不會。事實上,它看起來是幾乎相等的行7的負值和12
preobj <- preProcess(dt2, method = "knnImpute")
dt3 <- predict(preobj, dt2)
print(dt3)
# x yAlex yBrandon yErica yKaryna
#1: -1.19857753 -0.5527708 1.6583124 -0.5527708 -0.5527708
#2: -0.37455548 -0.5527708 -0.5527708 1.6583124 -0.5527708
#3: -0.04494666 -0.5527708 -0.5527708 -0.5527708 1.6583124
#4: 1.27348863 1.6583124 -0.5527708 -0.5527708 -0.5527708
#5: -1.19857753 -0.5527708 1.6583124 -0.5527708 -0.5527708
#6: -0.37455548 -0.5527708 -0.5527708 1.6583124 -0.5527708
#7: 0.44946657 -0.5527708 -0.5527708 -0.5527708 1.6583124
#8: 1.27348863 1.6583124 -0.5527708 -0.5527708 -0.5527708
#9: -1.19857753 -0.5527708 1.6583124 -0.5527708 -0.5527708
#10: -0.37455548 -0.5527708 -0.5527708 1.6583124 -0.5527708
#11: 0.44946657 -0.5527708 -0.5527708 -0.5527708 1.6583124
#12: 1.27348863 1.6583124 -0.5527708 -0.5527708 -0.5527708
不應該dt3$x
的第3行的行相等7和11?如果是這樣,我需要在腳本中更改哪些內容?如果不是,爲什麼?
很好的解釋。對於我的具體情況,我在'preProcess'函數中做了'k = 2',它給了我期望看到的東西。然後,我重新創建了我的'dt'表,並在'preProcess'函數中重複了11次重複並使用'k = 10',並且現在仍然可以得到相同的答案。 – bshelt141