【问题标题】:LinearRegression Predict: No applicable method for 'predict' applied to an object of class "data.Frame"线性回归预测:没有适用于“预测”的方法应用于“data.Frame”类的对象
【发布时间】:2020-02-16 11:15:15
【问题描述】:

我有我的数据(目前是虚拟数据):

data_for_prediction <- original_data[,c(1,3)]

如果您想重现问题,则以下内容足以解决此错误:

data_for_prediction <- data.frame(
  diff = c(1,2,3),
  f.mean_slope = c (1,2,3)
)

仅包含两行:“diff”(Y)和“f.mean_slope”(x)

然后我对整个事情进行采样:

set.seed(101)
trainingRowIndex <- sample(1:nrow(data_for_prediction), 0.8*nrow(data_for_prediction))
trainingData <- data_for_prediction[trainingRowIndex, ]  
testData  <- data_for_prediction[-trainingRowIndex, ]

然后我创建一个适合:

model_fit <- lm(diff ~ ., data = trainingData, method = "model.frame")

当我现在尝试预测某事时:

newdata <- data.frame(
  f.mean_slope = c(1,2,3)
)

distPred <- predict(model_fit, newdata) 

然后 R Studio 只返回错误消息:

UseMethod("predict") 中的错误:没有适用于“predict”的方法应用于“data.Frame”类的对象

这让我发疯了,因为我在互联网上搜索了大量类似问题的问题,但没有一个有效......

有人有想法吗?

【问题讨论】:

    标签: r dataframe machine-learning linear-regression


    【解决方案1】:

    那是因为你使用了:

    model_fit <- lm(diff ~ ., data = trainingData, method = "model.frame")
    class(model_fit)
    [1] "data.frame"
    

    上面给出了用于拟合数据的模型矩阵。

    你可以这样做:

    model_fit <- lm(diff ~ ., data = trainingData,model=TRUE)
    newdata <- data.frame(
      f.mean_slope = c(1,2,3)
    )
    
    distPred <- predict(model_fit, newdata) 
    

    并且模型矩阵可以在model_fit$model中找到

    【讨论】:

    • 很好的作品再次,但又一次......不是。我这样做是因为我有一些列,其中包含总体模拟值。因此,如果没有'method = "model.frame",我会得到一个'对比只能应用于具有 2 个或更多级别的因素'。有没有办法解决这两个问题?
    • 您能提供您的数据吗?您收到该错误是因为您的预测变量之一只有 1 个级别
    • 您的列日期导致了问题。里面有一个 1 值
    • 此外,您有一些列,其中每个条目都是一个级别,例如,f.autocorrelation.lag2.string_fd_sumv,您无法适应它.. 删除这些列
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多