首页 文章

使用具有重要性/ varImp函数的随机森林和因子变量进行特征选择

提问于
浏览
1

为了构建分类模型,我试图从数据集中选择最重要的功能 .
我的数据包含混合属性(数字和分类) . 我计划在应用Random forest从数据中选择要素后,在R中应用 (importance or varImp) 函数,以提高模型的准确性 .

我的问题是: Can I apply Random forest directly on the data without transformation step or I have to convert categorical attributes into binary (0,1)

我已经在一个数值数据集上应用了具有重要性/ varImp函数的随机森林,该模型工作正常,但我不确定混合数据 .

2 回答

  • 1

    是的,可以在R中包含变量重要性度量和分类/回归的阶乘(偶数有序)变量 .

    看到这个可重复的例子:

    library(randomForest)
    
    df <- iris
    df$Petal.Width <- as.factor(df$Petal.Width)
    str(df)
    # 'data.frame': 150 obs. of  5 variables:
    # $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
    # $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
    # $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
    # $ Petal.Width : Factor w/ 22 levels "0.1","0.2","0.3",..: 2 2 2 2 2 4 3 2 2 1 ...
    # $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
    
    rfmodel <- randomForest(x = df[,1:4], 
                            y = df$Species, 
                            importance = T)
    importance(rfmodel)
    #                 setosa versicolor virginica MeanDecreaseAccuracy MeanDecreaseGini
    # Sepal.Length 11.266441   8.036164 13.480521            15.940870        14.152530
    # Sepal.Width   6.394913   4.071819  5.076422             7.869699         2.880664
    # Petal.Length 43.532850  39.802356 46.246262            60.663778        53.622069
    # Petal.Width  14.272307  24.389310 19.109018            26.923048        28.617028
    
  • 0

    如果您使用randomForrest包中的randomForrest函数,则不必将每个值的独立分类变量转换为单独的列 .

    虽然,您需要确保依赖(预测)变量是一个因子(用于分类)或数字(用于回归) .

相关问题