Logistic回归

Logistic回归模型:

适用于二分类或多分类问题,样本特征是数值型(否则需要转换为数值型)

策略:极大似然估计

算法:随机梯度 或 BFGS算法(改进的拟牛顿法)

线性回归表达式:

式子中;w为N个特征权重组成的向量,即;b是第i个样本对应的偏置常数。

Sigmoid函数:

对数概率

Logistic 回归模型:

构造似然函数:

Logistic回归优化:梯度下降,分别对权重w,偏置b求导数:

综上,可归纳Logistic回归的过程:

实例:鸢尾花数据集划分:

python 复制代码
class Logistic_Regression:
    
    def __init__(self):
        self.coef_ = None
        self.intercept_ = None
        self._theta = None
        
    def _sigmoid(self,t):
        return 1./(1.+np.exp(-t)) 
    
    def fit(self,X_train,y_train,eta = 0.01, n_iters =1e4):
        
        def J(theta,X_b,y):
            y_hat = self._sigmoid(X_b.dot(theta))
            try:
                return -np.sum(y*np.log(y_hat)  +(1-y)*np.log(1-y_hat)  )
            except:
                return float('inf')
        
        def dJ(theta,X_b,y):
            return X_b.T.dot(self._sigmoid(X_b.dot(theta))-y)
    
        def gradient_descent(initia_theta,X_b,y, eta,n_iters =1e4,epsilon =1e-8 ):
            theta = initia_theta
            cur_iter = 0

            while cur_iter < n_iters:
                gradient = dJ(theta,X_b, y)
                last_theta = theta
                theta = theta - eta * gradient

                if (abs(J(theta,X_b, y)-J(last_theta,X_b, y)) < epsilon):
                    break
                cur_iter += 1

            return theta

        X_b = np.hstack([np.ones(len(X_train)).reshape(-1,1),X_train])
        initia_theta = np.zeros(X_b.shape[1])
        self._theta = gradient_descent(initia_theta,X_b,y_train,eta,n_iters)
        
        self.intercept_ = self._theta[0]
        self.coef_ = self._theta[1:]
        
        return self
    
    def predict_proba(self,X_predict):
        X_b = np.hstack([np.ones(len(X_predict)).reshape(-1,1),X_predict])
        return self._sigmoid(X_b.dot(self._theta))
    
    def predict(self,X_predict):
        proba = self.predict_proba(X_predict)
        return np.array(proba >= 0.5,dtype = 'int')
    
    def score(self,X_test,y_test):
        y_predict = self.predict(X_test)
        return accuracy_score(y_test, y_predict)
    
    def __repr__(self):
        return "LogisticRegression()"

可视化划分:

python 复制代码
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target
X = X[y<2,:2]
y = y[y<2]
plot_decision_boundary(log_reg,X_test)
plt.scatter(X_test[y_test==0,0],X_test[y_test==0,1])
plt.scatter(X_test[y_test==1,0],X_test[y_test==1,1])
plt.show()

总结

**注意:**虽然 Logistic 回归的名字叫作回归,但其实它是一种分类方法!!!

优点

  1. 逻辑斯蒂回归模型基于简单的线性函数,易于理解和实现。
  2. Logistic 回归模型对一般的分类问题都可使用。
  3. Logistic 回归模型不仅可以预测出样本类别,还可以得到预测为某类别的近似概率,这在许多需要利用概率辅助决策的任务中比较实用。
  4. Logistic 回归模型中使用的对数损失函数是任意阶可导的凸函数,有很好的数学性质,可避免局部最小值问题。

缺点

  1. Logis ic 回归模型本质上还是种线性模型,只能做线性分类,不适合处理非线性的情况,一般需要结合较多的人工特征处理使用。
  2. Logistic 回归对正负样本的分布比较敏感,所以要注意样本的平衡性,即y=1的样本数不能太少。
  3. 模型不能自动捕捉特征之间的交互作用,需要手动进行特征工程。
相关推荐
大大dxy大大6 小时前
机器学习实现逻辑回归-癌症分类预测
机器学习·分类·逻辑回归
武子康6 小时前
AI研究-119 DeepSeek-OCR PyTorch FlashAttn 2.7.3 推理与部署 模型规模与资源详细分析
人工智能·深度学习·机器学习·ai·ocr·deepseek·deepseek-ocr
Mr_Xuhhh7 小时前
GUI自动化测试--自动化测试的意义和应用场景
python·集成测试
2301_764441337 小时前
水星热演化核幔耦合数值模拟
python·算法·数学建模
循环过三天7 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法
Q_Q5110082857 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
没有钱的钱仔9 小时前
机器学习笔记
人工智能·笔记·机器学习
SunnyDays10119 小时前
如何使用Python高效转换Excel到HTML
python·excel转html
Q_Q5110082859 小时前
python+django/flask的在线学习系统的设计与实现 积分兑换礼物
spring boot·python·django·flask·node.js·php
Q_Q51100828510 小时前
python+django/flask的车辆尾气检测排放系统-可视化大屏展示
spring boot·python·django·flask·node.js·php