用梯度下降算法实现Logistic回归的L1正则化和L2正则化python代码
时间: 2023-12-18 12:08:36 浏览: 150
下面是用梯度下降算法实现Logistic回归的L1正则化和L2正则化的Python代码:
```python
import numpy as np
class LogisticRegression:
def __init__(self, lr=0.1, num_iter=1000, fit_intercept=True, regularization=None, lambda_=0.1):
self.lr = lr
self.num_iter = num_iter
self.fit_intercept = fit_intercept
self.regularization = regularization
self.lambda_ = lambda_
def __add_intercept(self, X):
intercept = np.ones((X.shape[0], 1))
return np.concatenate((intercept, X), axis=1)
def __sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def __loss(self, h, y):
return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()
def __l1_regularization(self, w):
return self.lambda_ * np.abs(w[1:]).sum()
def __l2_regularization(self, w):
return self.lambda_ * np.sum(w[1:] ** 2)
def fit(self, X, y):
if self.fit_intercept:
X = self.__add_intercept(X)
self.theta = np.zeros(X.shape[1])
for i in range(self.num_iter):
z = np.dot(X, self.theta)
h = self.__sigmoid(z)
if self.regularization == 'l1':
# L1正则化
grad = np.dot(X.T, (h - y)) / y.size + self.lambda_ * np.sign(self.theta)
elif self.regularization == 'l2':
# L2正则化
grad = np.dot(X.T, (h - y)) / y.size + self.lambda_ * self.theta
else:
grad = np.dot(X.T, (h - y)) / y.size
self.theta -= self.lr * grad
def predict_prob(self, X):
if self.fit_intercept:
X = self.__add_intercept(X)
return self.__sigmoid(np.dot(X, self.theta))
def predict(self, X, threshold=0.5):
return self.predict_prob(X) >= threshold
```
其中,lr是学习率,num_iter是迭代次数,fit_intercept表示是否拟合截距,regularization表示正则化方法,lambda_是正则化系数。在fit方法中,通过判断regularization的取值,来实现L1正则化和L2正则化。在L1正则化中,使用np.sign函数计算符号函数,而在L2正则化中,直接对参数的平方和进行惩罚。在predict_prob方法中,对X进行截距拟合和sigmoid变换,返回预测概率。在predict方法中,对预测概率进行阈值处理,返回预测结果。
阅读全文