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. 模型不能自动捕捉特征之间的交互作用,需要手动进行特征工程。
相关推荐
码上淘金3 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo4 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552874 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
懵逼的小黑子4 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
Y3174295 小时前
Python Day23 学习
python·学习
Ai尚研修-贾莲5 小时前
Python语言在地球科学交叉领域中的应用——从数据可视化到常见数据分析方法的使用【实例操作】
python·信息可视化·数据分析·地球科学
IT古董6 小时前
【漫话机器学习系列】249.Word2Vec自然语言训练模型
机器学习·自然语言处理·word2vec
qq_508576096 小时前
if __name__ == ‘__main__‘
python
学地理的小胖砸6 小时前
【Python 基础语法】
开发语言·python
程序员小远6 小时前
自动化测试与功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例