logistic回归python实现代码
时间: 2023-09-24 07:06:19 浏览: 96
当然可以回答您的问题。以下是一个简单的 logistic 回归在 Python 中的实现代码:
```python
import numpy as np
class LogisticRegression:
def __init__(self, learning_rate=0.01, num_iterations=10000, fit_intercept=True):
self.learning_rate = learning_rate
self.num_iterations = num_iterations
self.fit_intercept = fit_intercept
def add_intercept(self, X_data):
intercept = np.ones((X_data.shape[0], 1))
return np.concatenate((intercept, X_data), axis=1)
def sigmoid_function(self, z):
return 1 / (1 + np.exp(-z))
def gradient_descent(self, X_data, y_data, theta):
m = len(y_data)
for i in range(self.num_iterations):
z = np.dot(X_data, theta)
h = self.sigmoid_function(z)
gradient = np.dot(X_data.T, (h - y_data)) / m
theta -= self.learning_rate * gradient
return theta
def fit(self, X_data, y_data):
if self.fit_intercept:
X_data = self.add_intercept(X_data)
self.theta = np.zeros(X_data.shape[1])
self.theta = self.gradient_descent(X_data, y_data, self.theta)
def predict_prob(self, X_data):
if self.fit_intercept:
X_data = self.add_intercept(X_data)
return self.sigmoid_function(np.dot(X_data, self.theta))
def predict(self, X_data, threshold=0.5):
return self.predict_prob(X_data) >= threshold
```
这里实现了一个 LogisticRegression 类,包含了常见的功能如梯度下降、sigmoid 函数等。可以通过调用类中的方法来进行训练和预测。
阅读全文