本文将通过Python逻辑回归梯度下降法,对于逻辑回归的原理、实现方法和应用进行详细阐述。
一、逻辑回归原理
逻辑回归是一种常用的分类算法,其原理可以用线性回归模型来描述,将线性回归的预测结果通过一个sigmoid函数映射到[0,1]之间,从而得到预测概率值,最终将概率值大于等于0.5的归为一类,小于0.5的归为另一类。
在逻辑回归中,用到的损失函数是对数损失函数,其形式如下:
def loss_function(theta,X,y): h_theta = sigmoid(np.dot(X,theta)) return np.mean(-(y*np.log(h_theta) + (1-y)*np.log(1-h_theta)))
其中,theta为模型的参数,X为特征矩阵,y为标签,sigmoid函数如下:
def sigmoid(x): return 1 / (1 + np.exp(-x))
二、梯度下降法
逻辑回归模型的训练需要优化模型的参数,常用的方法是梯度下降法。梯度下降法是一种常用的优化算法,其思想是在参数空间中找到一个使得损失函数最小的方向,沿着这个方向进行参数更新。
对于逻辑回归中的对数损失函数,其梯度可以表示为:
def gradient(theta,X,y): h_theta = sigmoid(np.dot(X,theta)) return np.dot(X.T,(h_theta-y))/y.size
其中,X为特征矩阵,y为标签,theta为模型参数。
下面是梯度下降法的实现:
def gradient_descent(theta,X,y,alpha,num_iters): for i in range(num_iters): theta -= alpha*gradient(theta,X,y) return theta
其中,alpha是学习率,num_iters是迭代次数。
三、应用实例
逻辑回归可以应用于二分类问题,下面以一个二分类问题为例,来演示应用逻辑回归的过程。数据来源于Kaggle上的一个肝癌患者预测数据集。
首先,导入数据集,进行数据探索和清理。
import pandas as pd import numpy as np data = pd.read_csv('liver.csv') data.head() data.dropna(inplace=True) data.describe()
接下来,将数据集分割为训练集和测试集,将标签y与特征X分离。
from sklearn.model_selection import train_test_split X = data.drop(['Liver_disease'],axis=1) y = data['Liver_disease'] X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
然后,对于训练集进行特征标准化。
from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test)
接着,使用梯度下降法进行模型训练,并计算在测试集上的准确率。
theta = np.zeros(X_train_scaled.shape[1]) alpha = 0.01 num_iters = 1000 theta = gradient_descent(theta,X_train_scaled,y_train,alpha,num_iters) def predict(theta,X): return np.round(sigmoid(np.dot(X,theta))) predictions = predict(theta,X_test_scaled) accuracy = np.mean(predictions==y_test)*100 print("准确率:",accuracy)
最终的准确率为70.5%。
四、总结
本文介绍了Python逻辑回归梯度下降法的原理、实现方法和应用实例,逻辑回归是一种常用的分类算法,在许多领域中都有广泛的应用。