建立logistic回归函数;
时间: 2023-06-27 19:01:09 浏览: 51
Logistic回归是一种用于分类问题的机器学习算法,其基本思想是根据输入特征的线性组合预测输出结果的概率,并将其映射到[0,1]的范围内。下面是简单的Python代码实现:
```python
import numpy as np
class LogisticRegression:
def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False):
self.lr = lr
self.num_iter = num_iter
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_iter):
z = np.dot(X, self.theta)
h = self.__sigmoid(z)
gradient = np.dot(X.T, (h - y)) / y.size
self.theta -= self.lr * 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
```
在这个代码中,我们定义了一个`LogisticRegression`的类,其中包括以下方法:
- `__init__` : 初始化函数,用于设置学习率,迭代次数,是否拟合截距和是否输出训练过程。
- `__add_intercept` : 添加拟合截距。
- `__sigmoid` : sigmoid函数,用于将线性组合的结果转化为概率值。
- `__loss` : 损失函数,用于计算模型预测值与真实值之间的误差。
- `fit` : 训练模型,使用梯度下降法更新模型参数。
- `predict_prob` : 预测概率值。
- `predict` : 预测结果。
使用时,我们可以先实例化一个`LogisticRegression`对象,然后调用`fit`方法进行训练,最后使用`predict`方法进行预测。例如:
```python
X = np.array([[1, 2], [3, 4], [5, 6]])
y = np.array([0, 1, 1])
model = LogisticRegression(lr=0.1, num_iter=300000)
model.fit(X, y)
print(model.predict(np.array([[1, 2], [3, 4], [5, 6]])))
```
输出结果为:
```
[False True True]
```
这表示模型预测第一个样本为负例,后两个样本为正例。