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. 模型不能自动捕捉特征之间的交互作用,需要手动进行特征工程。
相关推荐
用户0332126663674 分钟前
如何使用 Python 将 JSON 转换为 Excel
python·excel
小小张说故事8 分钟前
Python 的切片到底切了什么:拆开 slice 对象、负步长和 __getitem__
python
Rocky Ding*13 分钟前
【三年面试五年模拟】2026-11-05_月之暗面大模型算法岗一面、二面面经全解析
论文阅读·人工智能·深度学习·机器学习·aigc·强化学习·ai-native
在所不辞兄1 小时前
【人工智能驱动的电催化研究-05】条件、循环与数据检查
人工智能·深度学习·神经网络·机器学习·有限元·电化学·电催化
Godspeed Zhao11 小时前
从零开始学AI25——无监督学习之层次聚类
学习·机器学习·聚类
用户9562562542915 小时前
跟做:Firecrawl 单页转 Markdown 再丢进沙箱总结
python·api
威哥爱编程16 小时前
模拟面试智能体开发实战 02:回答等半分钟,谁还愿意练?把服务端和流式输出搭起来
python·agent·harmonyos
威哥爱编程16 小时前
模拟面试智能体开发实战 01:面试挂了都不知道挂在哪?用 Python 给自己造一个随叫随到的 AI 面试官
python·agent·harmonyos
2601_9679801116 小时前
Python行情API量化 02:顺序拉 20 要 2 秒?并发批量把时间压到 0.5 秒
python·api·限流·并发·量化