【问题标题】:Error in model.frame.default(formula = mpg01 ~ ., data = list(cylinders = c(8, : variable lengths differ (found for 'cylinders')model.frame.default 中的错误(公式 = mpg01 ~ .,数据 = 列表(圆柱体 = c(8,:可变长度不同(为“圆柱体”找到))
【发布时间】:2021-06-24 11:28:53
【问题描述】:

我不确定如何修复代码中的长度错误。一切运行顺利,直到我运行 svm.tune。请指教!

library(ISLR)
attach(Auto)
n <- nrow(Auto)
mpg01 <- rep(0, length(mpg))
mpg01[mpg > median(mpg)] <- 1
mpg01 <- as.factor(mpg01)
Auto <- data.frame(Auto, mpg01)
Auto$mpg = NULL

set.seed(1)
train <- sample(1:n, 0.8*n)
x.train <- Auto[train,-9]
x.test <- Auto[-train,-9]
y.train <- Auto$mpg01[train]
y.test <- Auto$mpg01[-train]

library(e1071)
RNGkind(sample.kind = "Rounding")
set.seed(1)
svm.tune <- tune(method=svm, 
                 mpg01~., data = x.train,
                 kernel = "linear",
                 ranges = list(cost = c(0.01,0.1,1,5,10)))

【问题讨论】:

    标签: r svm


    【解决方案1】:

    习惯上data 也包含响应变量,因此不要将训练和测试拆分为 x 和 y,而是将训练全部保存在一个数据帧中,将测试保存在一个数据帧中。

    xy.train <- Auto[train,]
    xy.test <- Auto[-train,]
    
    library(e1071)
    #RNGkind(sample.kind = "Rounding")
    set.seed(1)
    svm.tune <- tune(method=svm, 
                     mpg01~., data = xy.train,
                     kernel = "linear",
                     ranges = list(cost = c(0.01,0.1,1,5,10)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多