【问题标题】:How do we make a model in r using more than one row我们如何使用多行在 r 中制作模型
【发布时间】:2021-05-03 05:01:19
【问题描述】:

以下是我的 R 代码,用于创建模型,使用 R 编程从钻石数据集中预测钻石价格。在这里,我无法通过为每一行提供日志来创建模型。如果不使用日志,我会得到一个预测价格不正确的可怕模型。我还粘贴了显示的错误和数据集以供参考。

错误如下所示

> mod =(lm(log(price)~log(carat)+log(x)+log(y)+log(z),data=train))
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 
  NA/NaN/Inf in 'x'

此处附有数据集的链接: https://www.kaggle.com/shivam2503/diamonds

下面给出的是相同的代码

setwd ("C:/akash/study videos/virginia")
akash = read.csv("diamonds.csv")
#summary(akash)
ind = sample(2, nrow(akash),replace = TRUE , prob = c(0.8,0.2)) 
train = akash[ind==1,]
test = akash[ind==2,]
mod =(lm(log(price)~log(carat)+log(x)+log(y)+log(z),data=train))
summary(mod)
predicted = predict(mod,newdata = test)
mon = round(exp(predicted),0)
head(mon)
#head(test)
#View(akash)

【问题讨论】:

  • 您链接到的数据中没有z 变量,但您已在模型中包含了一个变量。这似乎不正确。

标签: r machine-learning diamond-problem


【解决方案1】:

您的模型失败,因为您的变量 x,y,z 的最小值为 0,因此当您对这些变量进行对数转换时,您将获得 -inf

lapply(c("x","y","z"),function(x)summary(log(diamonds[[x]])))

您可以尝试仅对结果进行对数转换,从转换中删除最小值,或者只是更改模型。

例如:这里我比较了 lm 的 RMSE(没有转换)、lmlog(price) 转换,以及来自包 ranger 的简单随机森林模型。我使用caret 来使用相同的模型接口(默认情况下carte::train 执行25 次引导重采样以选择给定模型的最佳参数,因此在此示例中,只有随机森林有一些调整参数)。

library(ggplot2)#for "diamonds" dataset
data("diamonds")
set.seed(5)
ind = sample(2, nrow(diamonds),replace = TRUE , prob = c(0.8,0.2)) 
train = diamonds[ind==1,]
test = diamonds[ind==2,]

library(caret)
rf <- train(price~carat+x+y+z,data=train,method="ranger")
lm <- train(price~carat+x+y+z,data=train,method="lm")
lm_log <- train(log(price)~carat+x+y+z,data=train,method="lm")

RMSE(predict(rf,test),test$price)/mean(test$price)*100
RMSE(predict(lm,test),test$price)/mean(test$price)*100
RMSE(exp(predict(lm_log,test)),test$price)/mean(test$price)*100

这给了我:

[1] 35.73012
[1] 40.2437
[1] 45.92143

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2021-05-07
    • 2020-10-03
    • 2023-02-09
    • 2016-03-07
    • 2015-08-21
    • 2020-10-31
    相关资源
    最近更新 更多