在R语言中,逻辑回归可以使用glm函数(广义线性模型)来拟合。以下是一个简单的逻辑回归的例子:

数据准备
# 使用内置数据集iris,只使用前两类(setosa和versicolor)作为二分类问题
data(iris)
iris_binary <- subset(iris, Species %in% c("setosa", "versicolor"))

运行逻辑回归
# 运行逻辑回归,以Species(setosa/versicolor)为二元因变量,以Sepal.Length和Sepal.Width为自变量
model <- glm(Species ~ Sepal.Length + Sepal.Width, data = iris_binary, family = "binomial")

# 显示回归结果
summary(model)

在上述代码中,Species是二元分类的因变量,而Sepal.Length和Sepal.Width是自变量。glm函数用于拟合逻辑回归模型。family = "binomial"表示使用二项分布。

绘制逻辑回归曲线
# 安装并加载ggplot2包
install.packages("ggplot2")
library(ggplot2)

# 绘制逻辑回归曲线
ggplot(iris_binary, aes(x = Sepal.Length, y = as.numeric(Species) - 1)) +
  geom_point(aes(color = Species)) +
  geom_smooth(method = "glm", method.args = list(family = "binomial"), se = FALSE, col = "blue") +
  labs(title = "Logistic Regression Curve", x = "Sepal Length", y = "Probability (setosa)")

上述代码中,使用ggplot2包绘制了散点图和逻辑回归曲线。




转载请注明出处:http://www.pingtaimeng.com/article/detail/6419/R语言