【问题标题】:Error in colMeans(x, na.rm = TRUE) : 'x' must be numeric in KNN classificationcolMeans(x, na.rm = TRUE) 中的错误:“x”在 KNN 分类中必须是数字
【发布时间】:2018-05-23 14:08:46
【问题描述】:

我有以下代码尝试在分类模型中使用 knn:

library(dplyr)
library(e1071)
library(ggplot2)
library(nnet)
library(DMwR)
library(rpart.plot)
library(class)

dat         <- read.csv("C:/Users/Ze/Desktop/HallowSet/train.csv",header = T,stringsAsFactors = F)

needToSolve <- read.csv("C:/Users/Ze/Desktop/HallowSet/test.csv",header = T,stringsAsFactors = F)

dat$color <- factor(dat$color)
dat$type  <- factor(dat$type)

sp    <- sample(1:nrow(dat),0.7*nrow(dat))
train <- dat[sp,]
test  <- dat[-sp,]
full  <- rbind(train,test)



pre <-kNN(type ~ .,train ,test,k=3,norm=TRUE,type='class')

但是当代码到达下一行时,我得到一个 colMeans(x, na.rm = TRUE) : 'x' must be numeric,我不知道为什么会发生这种情况以及如何解决它,有人可以告诉我它? 提前谢谢。

str(完整):

'data.frame':   259 obs. of  12 variables:
$ id           : int  62 699 23 172 701 70 809 393 465 839 ...
$ bone_length  : num  0.304 0.417 0.585 0.498 0.477 ...
$ rotting_flesh: num  0.267 0.625 0.593 0.374 0.479 ...
$ hair_length  : num  0.527 0.329 0.681 0.58 0.404 ...
$ has_soul     : num  0.387 0.28 0.936 0.512 0.545 ...
$ color        : Factor w/ 6 levels "black","blood",..: 4 2 4 4 3 5 6 4 6 2 ...
$ type         : Factor w/ 3 levels "Ghost","Ghoul",..: 3 1 2 3 2 1 1 2 1 3 ...
$ bone_flesh   : num  0.0812 0.2608 0.3467 0.1866 0.2282 ...
$ bone_hair    : num  0.16 0.137 0.398 0.289 0.192 ...
$ bone_soul    : num  0.118 0.117 0.547 0.255 0.26 ...
$ flesh_hair   : num  0.141 0.205 0.404 0.217 0.193 ...
$ flesh_soul   : num  0.103 0.175 0.555 0.192 0.261 ...

【问题讨论】:

    标签: r runtime-error knn


    【解决方案1】:

    “颜色”是一个因素。 kNN 只接受数字输入。您可以将 Color 变量转换为数值变量,或者完全删除 Color。

    dat$color = as.numeric(dat$color)
    

    【讨论】:

    • 那么这意味着 knn 在将其用作因子的意义上不适用于分类变量?
    • 它没有。 knn 适用于数字差异,而不是分类或文本。
    • 那么如果我想将它与文本值一起使用,我需要删除文本列,对吗?
    • 是的。您还应该从模型中删除“id”,因为这会扭曲您的结果。
    猜你喜欢
    • 2020-12-19
    • 2019-10-04
    • 2017-10-25
    • 2020-06-18
    • 2023-03-28
    • 2018-01-27
    • 2018-01-17
    • 2021-02-14
    • 1970-01-01
    相关资源
    最近更新 更多