用python语言自编程实现逻辑回归算法
时间: 2023-11-10 20:16:01 浏览: 77
好的,以下是一个简单的 Python 实现逻辑回归算法的代码:
```python
import numpy as np
class LogisticRegression:
def __init__(self, learning_rate=0.01, iterations=1000):
self.learning_rate = learning_rate
self.iterations = iterations
self.weights = None
self.bias = None
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def fit(self, X, y):
m, n = X.shape
self.weights = np.zeros(n)
self.bias = 0
for i in range(self.iterations):
z = np.dot(X, self.weights) + self.bias
a = self.sigmoid(z)
dz = a - y
dw = np.dot(X.T, dz) / m
db = np.sum(dz) / m
self.weights -= self.learning_rate * dw
self.bias -= self.learning_rate * db
def predict(self, X):
z = np.dot(X, self.weights) + self.bias
a = self.sigmoid(z)
y_pred = np.round(a)
return y_pred
```
其中,sigmoid 函数用于将输入值映射到 0~1 的范围内,fit 函数用于训练模型,predict 函数用于预测结果。这里使用的是梯度下降算法来最小化损失函数,每次迭代更新权重和偏差,直到达到最大迭代次数或者损失函数的变化小于某个阈值。
阅读全文