首页 > 解决方案 > 线性回归预测:没有适用于“预测”的方法应用于“data.Frame”类的对象

问题描述

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

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”类的对象

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

有人有想法吗?

标签: rdataframemachine-learninglinear-regression

解决方案


那是因为你使用了:

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


推荐阅读