逻辑回归梯度下降代码实现
时间: 2023-11-21 22:56:02 浏览: 75
求解逻辑回归—-梯度下降
以下是逻辑回归梯度下降的Python代码实现:
```python
import numpy as np
def sigmoid(z):
"""
sigmoid函数
"""
return 1 / (1 + np.exp(-z))
def gradient_descent(X, y, theta, alpha, num_iters):
"""
梯度下降函数
"""
m = len(y)
for i in range(num_iters):
h = sigmoid(np.dot(X, theta))
theta = theta - (alpha / m) * np.dot(X.T, h - y)
return theta
# 测试
X = np.array([[1, 2, 3], [1, 3, 4], [1, 4, 5], [1, 5, 6]])
y = np.array([[0], [0], [1], [1]])
theta = np.zeros((3, 1))
alpha = 0.1
num_iters = 1000
theta = gradient_descent(X, y, theta, alpha, num_iters)
print(theta)
```
阅读全文