python实现对数几率回归
时间: 2023-07-18 17:28:29 浏览: 123
对数几率回归(Logistic Regression)是一种常用的分类算法,可以用于二分类和多分类任务。下面是Python实现对数几率回归的示例代码:
```python
import numpy as np
class LogisticRegression:
def __init__(self, learning_rate=0.01, num_iterations=100000, fit_intercept=True, verbose=False):
self.learning_rate = learning_rate
self.num_iterations = num_iterations
self.fit_intercept = fit_intercept
self.verbose = verbose
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 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_iterations):
z = np.dot(X, self.theta)
h = self.__sigmoid(z)
gradient = np.dot(X.T, (h - y)) / y.size
self.theta -= self.learning_rate * gradient
if self.verbose and i % 10000 == 0:
z = np.dot(X, self.theta)
h = self.__sigmoid(z)
print(f'loss: {self.__loss(h, y)} \t')
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
```
以上代码使用了NumPy库,其中fit()方法用于拟合模型,predict_prob()方法用于预测样本属于正类的概率,predict()方法用于预测样本的类别。需要注意的是,在使用对数几率回归之前应该对数据进行标准化处理,以避免数值计算上的不稳定性。
阅读全文