模型显著性检验
相关系数实现代码
x=c(1,2,3,4,5)
y = c(1,1.5,3,4.5,5)
n=5
xy=data.frame(x,y)
cor=cor.test(x,y)
plot(x,y)
x.mean=mean(x)
y.mean=mean(y)
Sxy=sum((x-x.mean)*(y-y.mean)/(n-1))
Sx=sqrt(sum((x-x.mean)^2)/(n-1))
Sy=sqrt(sum((y-y.mean)^2)/(n-1))
rxy=Sxy/(Sx*Sy)
> rxy
[1] 0.9838699
rxy接近于1,说明x,y具有较强的线性关系
协方差检验相关系数
> cor.test(x,y)
Pearson's product-moment correlation
data: x and y
t = 9.5263, df = 3, p-value = 0.002453
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
0.7699298 0.9989834
sample estimates:
cor
0.9838699
相关系数和rxy相同,p值小于0.05也能说明x,y具有较强的线性关系
回归方程模型:
y(x)=a+bx
残差平方和函数
若要模型最优,即残差平方和最小。
对残差平方和函数求偏导,在偏导函数等于0时,残差平方和最小
解得:
代码
> b=Sxy/(Sx)^2
> b
[1] 1.1
> a=y.mean-b*x.mean
> a
[1] -0.3
R语言lm函数线性拟合
> x.lm<-lm(y~x)
> x.lm
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
-0.3 1.1
拟合图像
b=Sxy/(Sx)^2
a=y.mean-b*x.mean
f=function(x){
a+b*x
}
curve(f,from=0,to=6,col="blue",add=T)
x.lm<-lm(y~x)
abline(x.lm,col="red")
蓝线与红线重合,手动拟合符合预期
模型的参数的置信区间
x=c(1,2,3,4,5)
y = c(1,1.5,3,4.5,5)
xy=data.frame(x=x,y=y)
model <- lm(xy$y ~ x )
> confint(model, level=0.95)
2.5 % 97.5 %
(Intercept) -1.5187841 0.9187841
x 0.7325228 1.4674772
plot(x,y)
pre=predict(model,xy,interval='confidence',level=0.99)
lines(x,pre[,1],col='green',lwd=3)
lines(x,pre[,2],col='black',lwd=1)
lines(x,pre[,3],col='black',lwd=1)