代码之家  ›  专栏  ›  技术社区  ›  buzoherbert

多类别抽样

  •  0
  • buzoherbert  · 技术社区  · 8 年前

    我使用线性回归来处理一个包含许多分类变量的数据集,每个分类变量包含几个类别,其中一个类别中最多有45个类别。

    我以这种方式对数据进行采样:

    ## 70% of the sample size
    smp_size <- floor(0.7 * nrow(plot_data))
    ## set the seed to make your partition reproductible
    set.seed(888)
    train_ind <- sample(seq_len(nrow(plot_data)), size = smp_size)
    
    train <- plot_data[train_ind, ]
    test <- plot_data[-train_ind, ]
    

    然后我把模型做成这样:

    linear_model = lm(train$dependent_variable~., data = train)
    

    问题是,每当我尝试预测和使用测试集时,训练集都包含一些训练集没有的类别。

    pred_data = predict(linear_model, newdata = test)
    

    这给了我以下错误:

    Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
      factor origin has new levels someCategory1, SomeCategory2
    

    是否有办法确保所有类别都在列车和测试集中,或者是否有解决方法?

    1 回复  |  直到 8 年前
        1
  •  0
  •   buzoherbert    8 年前

    最后,我在测试集上以新的级别删除了观察结果。我知道它有局限性,OSR2失去了可靠性,但它完成了这项工作:

    test = na.omit(remove_missing_levels (fit=linear_model, test_data=test));
    

    我找到了remove\u missing\u levels函数 here .

    它需要此库:

    install.packages("magrittr");
    library(magrittr);