机器学习算法:逻辑回归| Python 和 R 代码实现
逻辑回归
不要被它的名字所迷惑!它是一种分类算法而不是回归算法。它用于根据给定的一组自变量估计离散值(二进制值,如 0/1、是/否、真/假)。简而言之,它通过将数据拟合到 logit 函数来预测事件的概率。这就是为什么它也被称为logit回归。由于它预测概率,因此其输出值介于 0 和 1 之间(如预期)。
我们通过一个简单的例子再次理解一下。
假设你的朋友给你一个难题要你解决。只有两种结局场景——要么解决,要么不解决。现在想象一下,给你不同的谜题/测验来了解你擅长什么科目。研究结果是这样的——如果给你一道十年级的三角函数题,你有 70% 的机会解决它。另一方面,如果是5级历史问题,得到答案的概率只有30%。这就是逻辑回归为您提供的。
从数学角度来看,结果的对数赔率被建模为预测变量的线性组合。
odds= p/ (1-p) = probability of event occurrence / probability of not event occurrence
ln(odds) = ln(p/(1-p))
logit(p) = ln(p/(1-p)) = b0+b1X1+b2X2+b3X3....+bkXk
P 是感兴趣对象存在的概率。它选择最大化观察样本值的概率的参数,而不是最小化误差平方和(如普通回归)。
现在你可能会问,为什么要写日记?为简单起见,我们将其视为复制阶跃函数的最佳数学方法之一。我可以详细说明,但这将违背本文的目的。
Python 代码
#Import Library
from sklearn.linear_model import LogisticRegression
#Assumed you have, X (predictor) and Y (target) for training data set and x_test(predictor) of test_dataset
# Create logistic regression object
model = LogisticRegression()
# Train the model using the training sets and check score
model.fit(X, y)
model.score(X, y)
#Equation coefficient and Intercept
print('Coefficient: \n', model.coef_)
print('Intercept: \n', model.intercept_)
#Predict Output
predicted= model.predict(x_test)
R 语言代码
x <- cbind(x_train,y_train)
# Train the model using the training sets and check score
logistic <- glm(y_train ~ ., data = x,family='binomial')
summary(logistic)
#Predict Output
predicted= predict(logistic,x_test)
此外,您还可以尝试许多不同的步骤来改进模型:
- 包含交互项
- 删除特征
- 使用正则化技术非线性模型
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
code前端网