【问题标题】:Assign class labels using nearest neighbor classifier in R使用 R 中的最近邻分类器分配类标签
【发布时间】:2016-10-19 01:49:19
【问题描述】:

我不知道从哪里开始。我的任务是使用 R 中内置的 IRIS 数据集:

编写一段 R 代码,使用最近邻分类器 (NN)[1] 为每个 OBSERVATIONS(四维)分配一个类标签。使用 Part A 作为参考数据库(观察和分类标签),使用 Part B 作为测试集。假设您不知道 B 部分的类标签,对于 B 部分的每个观测值,找到离 A 部分最近的观测值,并将其类标签分配给 A 部分的观测值。

计算并返回每类准确度(每类正确分类的观察数除以观察总数)。

我为第一部分编写的代码非常简单:

newData = iris

evenRows.A <- newData[seq(2, nrow(newData), 2),]  #SELECT EVEN ROWS

oddRows.B <- newData[seq(1, nrow(newData), 2),]   #SELECT ODD ROWS. This is the testing set

任何关于类标签的帮助都将不胜感激。

编辑:格式化的 R 代码

【问题讨论】:

    标签: r classification


    【解决方案1】:
        newData = iris
        evenRows.A <- newData[seq(2, nrow(newData), 2),]  #SELECT EVEN ROWS
        oddRows.B <- newData[seq(1, nrow(newData), 2),]   #SELECT ODD ROWS. This is the testing set
    
    normalize <- function(x){return((x-min(x))/(max(x)-min(x)))}       #Define a function to normalize the data
        evenRows.train<- as.data.frame(normalize(evenRows.A[,c(1,2,3,4)]))  #Apply normalization to part A, the reference data
        oddRows.test<- as.data.frame(normalize(oddRows.B[,c(1,2,3,4)]))    #Apply normalization to part B, the test data
        evenRows.train.target<-evenRows.A[,5]
    
        require(class)  #load required classes for nearest neighbor modelling
        sqrt(150)
        #rule of thumb: pick k= sqrt(observations), rounded to nearest odd integer. In this case, 12.247 --> k = 13
    
        model1<-knn(train=evenRows.train, test=oddRows.test, cl=evenRows.train.target, k=13)
        model1
    
        #Display confusion matrix of results, to quantify correct versus incorrect classification
    
        table(oddRows.test.target, model1) 
    

    我尝试应用 k 最近邻分类,并在最后将结果显示为混淆矩阵。你们能告诉我这对于我发布的问题是否明智?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      相关资源
      最近更新 更多