R中的简单对数回归模型

机器算法验证 r 回归 非线性回归 曲线拟合 非线性
2022-04-13 23:46:54

我正在尝试拟合回归模型,因为图中显示关系是对数。

在此处输入图像描述

我试着用

lm(logData$x ~ logData$b3, data = logData) 

但它不起作用,因为它适合线性模型。

我也尝试使用

model = nls(logData$x ~ logData$b3) 

但它给了我错误。

所以,我需要做的是拟合简单的对数回归,并在散点图上绘制回归曲线。

1个回答

在我看来,在执行线性回归模型之前转换数据是一个很好的策略,因为您的数据显示出良好的对数关系:

> #generating the data
> n=500
> x <- 1:n
> set.seed(10)
> y <- 1*log(x)-6+rnorm(n)
> 
> #plot the data
> plot(y~x)
> 
> #fit log model
> fit <- lm(y~log(x))
> #Results of the model
> summary(fit)

Call:
lm(formula = y ~ log(x))

Residuals:
     Min       1Q   Median       3Q      Max 
-3.06157 -0.69437 -0.00174  0.76330  2.63033 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  -6.4699     0.2471  -26.19   <2e-16 ***
log(x)        1.0879     0.0465   23.39   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.014 on 498 degrees of freedom
Multiple R-squared:  0.5236,    Adjusted R-squared:  0.5226 
F-statistic: 547.3 on 1 and 498 DF,  p-value: < 2.2e-16

>
> coef(fit)
(Intercept)      log(x) 
  -6.469869    1.087886 
> 
> #plot 
> x=seq(from=1,to=n,length.out=1000)
> y=predict(fit,newdata=list(x=seq(from=1,to=n,length.out=1000)),
+           interval="confidence")
> matlines(x,y,lwd=2)

前面代码的结果: 在此处输入图像描述