網(wǎng)站首頁 編程語言 正文
1. 簡單的線性回歸
函數(shù)自帶的例子(R 中鍵入?lm
),lm(y ~ x)
回歸y=kx + b
, lm( y ~ x -1 )
省略b,不對截距進(jìn)行估計
:
require(graphics) ## Annette Dobson (1990) "An Introduction to Generalized Linear Models". ## Page 9: Plant Weight Data. ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) group <- gl(2, 10, 20, labels = c("Ctl","Trt")) weight <- c(ctl, trt) lm.D9 <- lm(weight ~ group) lm.D90 <- lm(weight ~ group - 1) # omitting intercept anova(lm.D9) summary(lm.D90) opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0)) plot(lm.D9, las = 1) # Residuals, Fitted, ... par(opar)
使用R中自帶的mtcars數(shù)據(jù),可以得到截距和斜率,也可以得到解釋率R-square:
require(ggplot2) library(dplyr) #加載dplyr包 library(ggpmisc) #加載ggpmisc包 library(ggpubr) require(gridExtra) model=lm(mtcars$wt ~ mtcars$mpg) model ## 輸出: Call: lm(formula = mtcars$wt ~ mtcars$mpg) Coefficients: (Intercept) mtcars$mpg 6.047 -0.141 ``` ```handlebars summary(model) ## 輸出: Call: lm(formula = mtcars$wt ~ mtcars$mpg) Residuals: Min 1Q Median 3Q Max -0.652 -0.349 -0.138 0.319 1.368 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 6.0473 0.3087 19.59 < 2e-16 *** mtcars$mpg -0.1409 0.0147 -9.56 1.3e-10 *** --- Signif. codes: 0 ‘***' 0.001 ‘**' 0.01 ‘*' 0.05 ‘.' 0.1 ‘ ' 1 Residual standard error: 0.494 on 30 degrees of freedom Multiple R-squared: 0.753, Adjusted R-squared: 0.745 F-statistic: 91.4 on 1 and 30 DF, p-value: 1.29e-10
提取回歸R-square值:
通過summary提取: ## 上面的例子 ## mtcars例子 model=lm(mtcars$wt ~ mtcars$mpg) res=summary(model) str(res) ## 提取各個值: res$r.squared res$coefficients res$adj.r.squared ## df 矯正后的結(jié)果 res$coefficients[1,1] res$coefficients[2,1]
使用默認(rèn)的plot繪制回歸散點(diǎn):
plot(mtcars$mpg, mtcars$wt, pch=20,cex=2) abline(model,col="red",lwd=2)
計算Confidence interval(95%):
test=mtcars[c("mpg","wt")] head(test) colnames(test)=c("x","y") model = lm(y ~ x, test) test$predicted = predict( object = model, newdata = test) test$CI = predict( object = model, newdata = test, se.fit = TRUE )$se.fit * qt(1 - (1-0.95)/2, nrow(test)) test$predicted = predict( object = model, newdata = test) test$CI_u=test$predicted+test$CI test$CI_l=test$predicted-test$CI plot(mtcars$mpg, mtcars$wt, pch=20,cex=1) ## have replicated x values abline(model,col="red",lwd=2) lines(x=test$x,y=test$CI_u,col="blue") lines(x=test$x,y=test$CI_l,col="blue")
上面的圖藍(lán)線有點(diǎn)奇怪,簡單繪制最初的plot:
plot(mtcars$mpg, mtcars$wt, pch=20,cex=1,type="b") ## have replicated x values
實(shí)際上面的計算方法沒問題,但是數(shù)據(jù)不合適,因?yàn)閿?shù)據(jù)x含有重復(fù)值,所以要考慮這個。
2. 使用ggplot2展示
ggplot2例子:
p <- ggplot(df, aes(x=yreal, y=ypred)) + geom_point(color = "grey20",size = 1, alpha = 0.8) #回歸線 #添加回歸曲線 p2 <- p + geom_smooth(formula = y ~ x, color = "red", fill = "blue", method = "lm",se = T, level=0.95) + theme_bw() + stat_poly_eq( aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~')), formula = y ~ x, parse = TRUE,color="blue", size = 5, #公式字體大小 label.x = 0.05, #位置 ,0-1之間的比例 label.y = 0.95) + labs(title="test",x="Real Value (Huang Huaihai 1777)" , y="Predicted Value (Correlation: 0.5029)") p2
ggplot版本的手動計算:
require(ggplot2) library(dplyr) #加載dplyr包 library(ggpmisc) #加載ggpmisc包 library(ggpubr) require(gridExtra) ggplot(data=df, aes(x=yreal, y=ypred)) + geom_smooth(formula = y ~ x, color = "blue", fill = "grey10", method = "lm") + geom_point() + stat_regline_equation(label.x=0.1, label.y=-1.5) + stat_cor(aes(label=..rr.label..), label.x=0.1, label.y=-2) test=df head(test) colnames(test)=c("x","y") model = lm(y ~ x, test) test$predicted = predict( object = model, newdata = test) test$CI = predict( object = model, newdata = test, se.fit = TRUE )$se.fit * qt(1 - (1-0.95)/2, nrow(test)) ggplot(test) + aes(x = x, y = y) + geom_point(size = 1,colour="grey40") + geom_smooth(formula =y ~ x,method = "lm", fullrange = TRUE, color = "black") + geom_line(aes(y = predicted + CI), color = "blue") + # upper geom_line(aes(y = predicted - CI), color = "red") + # lower theme_classic()
參考:
https://stackoverflow.com/questions/23519224/extract-r-square-value-with-r-in-linear-models (提取R2)
https://blog.csdn.net/LeaningR/article/details/118971000 (提取R2等)
https://stackoverflow.com/questions/45742987/how-is-level-used-to-generate-the-confidence-interval-in-geom-smooth (添加lm線)
https://zhuanlan.zhihu.com/p/131604431 (知乎)
原文鏈接:https://blog.csdn.net/cfc424/article/details/126712889
相關(guān)推薦
- 2022-01-17 url傳參 中文出現(xiàn)亂碼問題 解決方案
- 2022-10-14 cannot find symbol[ERROR] package sun.misc
- 2022-02-11 SQL中ISNULL函數(shù)使用介紹_數(shù)據(jù)庫其它
- 2022-04-01 mybatis if 并且判斷列表是否為空
- 2022-09-19 Nginx配置Tcp負(fù)載均衡的方法_nginx
- 2022-03-20 C語言數(shù)學(xué)公式來實(shí)現(xiàn)土味表白_C 語言
- 2022-11-10 ASP.NET?MVC使用Quartz.NET執(zhí)行定時任務(wù)_實(shí)用技巧
- 2022-06-28 ASP.NET一次性對GridView批量更新多行數(shù)據(jù)_實(shí)用技巧
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支