R语言学习:实际工作用到的R包,如何增进tidyverse技能,GLM模型,tidymodels包学习
2021年第48周。
这一周R语言学习,记录如下。
01
我实际工作用到的R包
我用R语言做数据科学工作,解决金融科技领域的精准营销和智能风控的问题。
我实际工作用到的R包,主要用于做以下事情。
1)数据导入和导出
2)数据整洁
3)数据处理
4)数据可视化
5)函数式编程
6)数据建模
7)数据报告
# 我实际工作中常用的R包
# 第一种方式:加载工作所需的R包
# 1 数据导入R包
library(RODBC)
library(readr)
library(readxl)
library(xlsx)
library(openxlsx)
library(haven)
# 2 数据整洁包
library(tidyr)
# 3 数据处理包
library(dplyr)
library(data.table)
# 4 数据可视化包
library(ggplot2)
library(ggthemes)
library(patchwork)
# 5 函数实编程包
library(purrr)
# 6 数据建模包
library(caret)
library(scorecard)
# 7 数据报告包
library(rmarkdown)
# 或者
# 第二种方式:加载工作所需R包
library(pacman)
p_load(
tidyverse,
RODBC,
readxl,
xlsx,
openxlsx,
haven,
data.table,
ggthemes,
patchwork,
caret,
scorecard,
rmarkdown
)
你会发现,我的R语言学习周记里面,会经常记录tidyverse包的知识和技能。因为我每天都要使用这个包,tidyverse包可以帮助我高效工作。
02
如何增进tidyverse技能?
我从如下三个方面来增进自己的tidyverse技能。
1 阅读优质的tidyverse资料
2 每天用tidyverse做数据科学工作
3 坚持代码学习法
我分享一些优质的tidyverse资料
1 tidyverse官网
https://www.tidyverse.org/
2 R4DS书籍
https://r4ds.had.co.nz/
3 R4DS习题解答
https://brshallo.github.io/r4ds_solutions/
我创建了R4DS群,也欢迎大家加入,可以扫描文末的二维码,备注:R4DS,添加我微信,邀请你入群,一起学用R语言做数据科学。
代码学习范例
library(tidyverse)
library(palmerpenguins)
library(skimr)
data(package = 'palmerpenguins')
# 数据EDA
skim(penguins)
skim(penguins_raw)
penguins %>%
slice_head(n = 5)
# 字体设置
# 使用showtext包
library(showtext)
font_add_google("Lobster Two", "lobstertwo")
font_add_google("Roboto", "roboto")
font_add_google("Poppins", "poppins")
showtext_auto()
# 主题设置
theme_set(theme_bw())
theme_update(
legend.text = element_text(size=9, family = "roboto"),
legend.title = element_text(face="bold", size=12, family = "roboto"),
legend.position = c(1,0),
legend.justification = c(1, 0),
text = element_text(family = "lobstertwo", size = 8, color = "black"),
plot.title = element_text(family = "lobstertwo", size = 20,
face = "bold", color="#2a475e"),
plot.subtitle = element_text(family = "lobstertwo", size = 15,
face = "bold", color="#1b2838"),
plot.caption = element_text(size = 10),
plot.title.position = "plot",
#plot.caption.position = "plot",
axis.text = element_text(size = 10, color = "black"),
axis.title = element_text(size=12),
axis.ticks = element_blank(),
axis.line = element_line(colour = "grey50"),
rect = element_blank(),
panel.grid = element_line(color = "#b4aea9"),
panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank(),
#panel.grid.major.x = element_line(linetype="dashed"),
#panel.grid.major.y = element_blank(),
panel.grid.major.y = element_line(linetype="dashed"),
plot.background = element_rect(fill = '#fbf9f4', color = '#fbf9f4')
)
# 删除含有缺失值的样例
penguins_comp <- penguins %>%
drop_na()
# 散点图可视化
penguins_comp %>%
ggplot(aes(x=flipper_length_mm, y=bill_length_mm)) +
geom_point(aes(color=species, shape=species), size=2, alpha=0.8) +
scale_color_manual(values = c("#386cb0","#fdb462","#7fc97f")) +
labs(
title = "Palmer Penguins Data Visualization",
subtitle = "Scatter plot of flipper lenth vs bill length",
x = "flip length (mm)",
y = "bill length (mm)"
)
# 多图合并
# 使用patchwork包
library(patchwork)
p1 <- penguins_comp %>%
ggplot(aes(x=flipper_length_mm, y=bill_length_mm)) +
geom_point(aes(color=species, shape=species), size=2, alpha=0.8) +
scale_color_manual(values = c("#386cb0","#fdb462","#7fc97f")) +
labs(x = "flip length (mm)",
y = "bill length (mm)")
p2 <- penguins_comp %>%
ggplot(aes(x=bill_length_mm, y=bill_depth_mm)) +
geom_point(aes(color=species, shape=species), size=2, alpha=0.8) +
scale_color_manual(values = c("#386cb0","#fdb462","#7fc97f")) +
labs(x = "bill length (mm)",
y = "bill depth (mm)")
p1 + p2 +
plot_layout(guides = "collect") +
plot_annotation(
title = "Palmer Penguins Data Visualization",
subtitle = "Scatter plots, left: flip length vs bill lengtt;
right: bill length vs bill depth") &
theme(legend.position = "bottom",
legend.justification = "center")
p3 <- penguins_comp %>%
ggplot(aes(x = sex, fill = species)) +
geom_bar(alpha = 0.8,width=0.6, show.legend = FALSE) +
scale_fill_manual(values = c("#386cb0","#fdb462","#7fc97f")) +
facet_wrap(~species, ncol = 3) +
theme(strip.text = element_text(size=12, face="bold"))
(p1 + p2) / p3 +
plot_layout(guides = "collect") +
plot_annotation(
title = "Palmer Penguins Data Visualization") &
theme(legend.position = "bottom",
legend.justification = "center")
结果图
03
广义线性模型GLM
广义线性模型建立的3个基础
思考题:
1 证明高斯分布是一种指数分布
2 证明伯努利分布是一种指数分布
3 证明线性回归是GLM的一种应用
4 证明逻辑回归是GLM的一种应用
线性回归用于的解决的问题:
逻辑回归用于解决的问题:
GLM的一个简短介绍视频,来自youtube。
GLM模型,R语言使用glm()函数设计和构建。可以通过help(glm)查看详细的文档。
逻辑回归模型和泊松回归模型参考代码
# 1 Logistic Regression
# where F is a binary factor and
# x1-x3 are continuous predictors
fit <- glm(F~x1+x2+x3,data=mydata,family=binomial())
summary(fit) # display results
confint(fit) # 95% CI for the coefficients
exp(coef(fit)) # exponentiated coefficients
exp(confint(fit)) # 95% CI for exponentiated coefficients
predict(fit, type="response") # predicted values
residuals(fit, type="deviance") # residuals
#2 Poisson Regression
# where count is a count and
# x1-x3 are continuous predictors
fit <- glm(count ~ x1+x2+x3, data=mydata, family=poisson())
summary(fit) # display results
学习资料:
1https://www.youtube.com/watch?v=hKpMXZrRgLg
2https://www.statmethods.net/advstats/glm.html
04
我创建的3个R语言项目
项目一:Tidyverse学习项目,以R4DS书籍为基础,并广泛阅读其它相关材料,收录和总结Tidyverse包的知识和技能。
https://github.com/wangluqing/Tidyverse_Study_Project
项目二:Shiny学习项目,以Mastering Shiny书籍为基础,并学习其它相关材料,记录了Shiny包做Web应用开发的知识和技能。
https://github.com/wangluqing/Shiny_Study_Project
项目三:R语言学习项目,其目的是帮助更多人学用R语言。我会录制R语言学习视频,总结和分享R语言的知识和技能。
https://github.com/wangluqing/R_Study_Project
R语言学习系列视频
第3集 RStudio如何通过git和github做版本控制?
05
书籍阅读:Hands-On Programming with R
这本书会教你如何用R语言编程,并配置了一系列可以实操的例子。
书籍阅读的在线网址:
https://rstudio-education.github.io/hopr/
你在学习R语言编程的过程中,有什么问题,欢迎扫描文末的二维码,备注:姓名-R语言群,我会邀请你进群,一起学习和讨论。
06
Tidymodels包学习和应用
第1集:认识Tidymodels包
1 Tidymodels包是什么?
它是一个基于Tidyverse包设计原则而用来做数据建模和机器学习的集合包。
2 Tidymodels包安装和加载?
# tidymodels包的安装和加载
if(!require("tidymodels")) {
install.packages("tidymodels")
library("tidymodels")
}
3 Tidymodels包生态?
Tidymodels包生态由许多包组合而成,关注下面这些包。
这些包分别可以做什么呢?
-
rsample包-数据集划分
-
recipes包-数据预处理以做数据准备
-
parsnip包-指定和拟合数据模型
-
yardstick和tune包-模型性能评价
-
workflows包-设计建模工作流
-
tune和dials包-模型优化(模型调参)
-
broom包-让模型的结果更有可读性
tidymodels的常用函数
4 tidymodels数据建模实例
# 第1步:数据划分 rsample包
set.seed(1234)
# 默认75%做训练,25%做测试
split_iris <- initial_split(iris, prop = 2 / 3)
split_iris
str(split_iris)
# 获取训练集和测试集
training_iris <- training(split_iris)
head(training_iris)
testing_iris <-testing(split_iris)
head(testing_iris)
# 第2步:数据集做预处理
first_recipe <- recipe(training_iris) %>%
recipes::update_role(Sepal.Length, new_role = "outcome") %>%
recipes::update_role(Sepal.Width, new_role = "predictor") %>%
recipes::update_role(Species, new_role = "predictor")
first_recipe
summary(first_recipe)
# 使用step系列函数集做相应的处理
first_recipe <- first_recipe %>%
step_dummy(Species, one_hot = TRUE)
first_recipe
summary(first_recipe)
prepped_rec <- prep(first_recipe, verbose = TRUE, retain = TRUE )
summary(prepped_rec)
names(prepped_rec)
prepped_rec$var_info
preproc_train <- recipes::bake(prepped_rec, new_data = NULL)
glimpse(preproc_train)
baked_test_pm <- recipes::bake(prepped_rec, new_data = testing_iris)
glimpse(baked_test_pm)
# 第3步 数据建模
# 设计线性模型
Lin_reg_model <- parsnip::linear_reg()
Lin_reg_model <-
Lin_reg_model %>%
parsnip::set_engine("lm") %>%
parsnip::set_mode("regression")
Lin_reg_model
iris_reg_wflow <-workflows::workflow() %>%
workflows::add_recipe(first_recipe) %>%
workflows::add_model(Lin_reg_model)
iris_reg_wflow
iris_reg_wflow_fit <- parsnip::fit(iris_reg_wflow, data = training_iris)
iris_reg_wflow_fit
# 第4步 模型评价
wf_fit <- iris_reg_wflow_fit %>%
pull_workflow_fit()
head(wf_fit$fit$fitted.values)
predict(iris_reg_wflow_fit, new_data = training_iris)
wf_fitted_values <-
broom::augment(wf_fit$fit, data = preproc_train) %>%
select(Sepal.Length, .fitted:.std.resid)
head(wf_fitted_values)
# 计算rmse指标值
yardstick::rmse(wf_fitted_values,
truth = Sepal.Length,
estimate = .fitted)
# 测试集上面做评估
predict(iris_reg_wflow_fit, new_data = testing_iris)
test_wf_fitted_values <- data.frame(
true_label = testing_iris$Sepal.Length,
pred_result = predict(iris_reg_wflow_fit, new_data = testing_iris)$.pred
)
yardstick::rmse(test_wf_fitted_values,
truth = true_label,
estimate = pred_result)
# 数据可视化
library(patchwork)
# 训练集
p1 <- wf_fitted_values %>%
ggplot(aes(x = Sepal.Length, y = .fitted)) +
geom_point() +
geom_smooth(method = "lm") +
labs( x = "True Sepal Length", y = "Predicted Sepal Length") +
theme_classic() +
ggtitle("训练集可视化")
# 测试集
p2 <- test_wf_fitted_values %>%
ggplot(aes(x = true_label, y = pred_result)) +
geom_point() +
geom_smooth(method = "lm") +
labs( x = "True Sepal Length", y = "Predicted Sepal Length") +
theme_classic() +
ggtitle("测试集可视化")
p1 + p2
我创建了R语言群,添加我的微信,备注:姓名-入群,我邀请你进群,一起学习R语言。
如果你想学习数据科学与人工智能,请关注下方公众号~
如果你想找数据工作,请关注下方公众号~
R语言学习专辑:
如果觉得本文不错,就顺手帮我转发到朋友圈和微信群哦,谢谢。
请关注“恒诺新知”微信公众号,感谢“R语言“,”数据那些事儿“,”老俊俊的生信笔记“,”冷🈚️思“,“珞珈R”,“生信星球”的支持!