逻辑回归算法python实现
时间: 2023-12-21 16:31:26 浏览: 94
以下是使用原生Python实现逻辑回归算法的示例:
```python
import numpy as np
class LogisticRegression:
def __init__(self, learning_rate=0.01, n_iterations=1000):
self.learning_rate = learning_rate
self.n_iterations = n_iterations
self.weights = None
self.bias = None
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(self.n_iterations):
model = np.dot(X, self.weights) + self.bias
predictions = self.sigmoid(model)
dw = (1 / n_samples) * np.dot(X.T, (predictions - y))
db = (1 / n_samples) * np.sum(predictions - y)
self.weights -= self.learning_rate * dw
self.bias -= self.learning_rate * db
def predict(self, X):
model = np.dot(X, self.weights) + self.bias
predictions = self.sigmoid(model)
return [1 if i > 0.5 else 0 for i in predictions]
```
这是一个简单的逻辑回归算法的Python实现示例,包括了模型的训练和预测方法。
阅读全文