[英]Using CARET together with GAM (“gamSpline” method) in R Poisson Regression
我正在尝试使用插入符号包来调整gam模型的'df'参数,以进行同类群组分析。
带有以下数据:
cohort = 1:60
age = 1:26
grid = data.frame(expand.grid(age = age, cohort = cohort))
size = data.frame(cohort = cohort, N = sample(100:150,length(cohort), replace = TRUE))
df = merge(grid, size, by = "cohort")
log_k = -3 + log(df$N) - 0.5*log(df$age) + df$cohort*(df$cohort-30)*(df$cohort-50)/20000 + runif(nrow(df),min = 0, max = 0.5)
df$conversion = rpois(nrow(df),exp(log_k))
数据说明 :同类群组是潜在客户的到达时间。 N是当时到达的潜在客户数。 转化是指那些“转化”(购买了某些东西)的潜在客户的数量。 年龄是发生转化的同类群组的年龄(从到达起花费的时间)。 对于给定的同类群组,随着年龄的增长,转化次数会减少。 该效应遵循幂定律。 但是,每个同类群组的总转化率也会随着时间(同类群组数量)而缓慢变化。 因此,我需要模型中时间变量的平滑样条。
我可以从gam包中安装一个gam模型
library(gam)
fit = gam(conversion ~ log(N) + log(age) + s(cohort, df = 4), data = df, family = poisson)
fit
> Call:
> gam(formula = conversion ~ log(N) + log(age) + s(cohort, df = 4),
> family = poisson, data = df)
> Degrees of Freedom: 1559 total; 1553 Residual
> Residual Deviance: 1869.943
但是如果我尝试使用CARET套件训练模型
library(caret)
fitControl = trainControl(verboseIter = TRUE)
fit.crt = train(conversion ~ log(N) + log(age) + s(cohort,df),
data = df, method = "gamSpline",
trControl = fitControl, tune.length = 3, family = poisson)
我收到此错误:
+ Resample01: df=1
model fit failed for Resample01: df=1 Error in as.matrix(x) : object 'N' not found
- Resample01: df=1
+ Resample01: df=2
model fit failed for Resample01: df=2 Error in as.matrix(x) : object 'N' not found .....
请问有人知道我在做什么错吗?
谢谢
您的代码有两件事。
train
功能可能会有些乏味,具体取决于您使用的方法(您已经注意到)。 在method = "gamSpline"
的情况下, train
函数将平滑项添加到公式中的每个独立项 。 因此它将变量转换为s(log(N), df)
, s(log(age) df)
和s(s(cohort, df), df)
。 等待s(s(cohort, df), df)
确实没有道理。 因此,您必须将s(cohort, df)
更改为cohort
。
我不确定为什么,但是当您在公式中放置函数(例如log
)时,使用method = "gamSpline"
的train
不喜欢它。 我认为这是由于该方法已经将s()
函数应用于您的变量。 可以通过将日志更早地应用于变量来解决此问题。 例如df$N <- log(df$N)
或logN <- log(df$N)
并使用logN
作为变量。 当然, age
也一样。
我的猜测是,您不希望此方法根据您提供的代码将平滑项应用于所有自变量。 我不确定这是否可能,以及如何做到。
希望这可以帮助。
编辑:如果您想要比我在第2点提供的解决方案更优雅的解决方案,请确保阅读@topepo的注释。 如果我正确理解,此建议还允许您将s()
函数应用于所需的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.