无法获得测试数据的R平方 [英] Unable to get R-squared for test dataset

查看:82
本文介绍了无法获得测试数据的R平方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习一些有关不同类型的回归的知识,并且通过下面的代码示例来破解自己的方式.

I am trying to learn a bit about different types of regression and I am hacking my way through the code sample below.

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).

I got the code samples from here (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

推荐答案

就在几分钟前,我对

Just a few minutes ago I got an upvote for Function to calculate R2 (R-squared) in R. Now I guess it is from you, thanks.

Rsquare函数需要两个向量,但是您已经传递了模型对象fit(这是一个列表)和一个向量test$mpg.我想你想在这里用predict(fit, newdata = test)作为第一个参数.

Rsquare function expects two vectors, but you've passed in a model object fit (which is a list) and a vector test$mpg. I guess you want predict(fit, newdata = test) for its first argument here.

这篇关于无法获得测试数据的R平方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆