【问题标题】:Unable to get R-squared for test dataset无法获得测试数据集的 R 平方
【发布时间】:2018-12-17 08:42:19
【问题描述】:

我正在尝试学习一些关于不同类型的回归的知识,并且正在通过下面的代码示例进行破解。

library(magrittr)
library(dplyr)


# Polynomial degree 1
df=read.csv("C:\\path_here\\auto_mpg.csv",stringsAsFactors = FALSE) # Data from UCI
df1 <- as.data.frame(sapply(df,as.numeric))

# Select key columns
df2 <- df1 %>% select(cylinder,displacement,horsepower,weight,acceleration,year,mpg)
df3 <- df2[complete.cases(df2),]


smp_size <- floor(0.75 * nrow(df3))
# Split as train and test sets
train_ind <- sample(seq_len(nrow(df3)), size = smp_size)

train <- mtcars[train_ind, ]
test <- mtcars[-train_ind, ]


Rsquared <- function (x, y) cor(x, y) ^ 2


# Fit a model of degree 1
fit <- lm(mpg~. ,data=train)
rsquared1 <-Rsquared(fit,test$mpg)
sprintf("R-squared for Polynomial regression of degree 1 (auto_mpg.csv)  is : %f", rsquared1)

我收到此错误:

'Error in cor(x, y) : 'x' must be numeric'

我从这里获得了代码示例(1.2b 和 1.3a)。

https://gigadom.wordpress.com/2017/10/06/practical-machine-learning-with-r-and-python-part-1/

原始数据可在此处获得。

https://raw.githubusercontent.com/tvganesh/MachineLearning-RandPython/master/auto_mpg.csv

【问题讨论】:

    标签: r machine-learning regression linear-regression


    【解决方案1】:

    就在几分钟前,我对Function to calculate R2 (R-squared) in R 投了赞成票。现在我猜是你送的,谢谢。

    Rsquare 函数需要两个向量,但您传入了一个模型对象 fit(它是一个列表)和一个向量 test$mpg。我猜你想要predict(fit, newdata = test) 作为它的第一个参数。

    【讨论】:

    • 是的,我投了赞成票。好吧,你的建议有效,但解释结果很热?这些不能是 R 平方值。这些数字太高了!
    • 没错!我看到了这个:马自达 RX4 Wag = 20.20765 & Valiant = 19.38514 & 13.44487。
    • 嗯,'predict(fit, newdata = test)' 究竟是做什么的?
    • 啊!现在它是有道理的!好的,谢谢你的一切!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 2023-01-21
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 2020-03-23
    相关资源
    最近更新 更多