逻辑回归梯度下降算法python实战
时间: 2023-11-21 16:50:25 浏览: 115
求解逻辑回归—-梯度下降
逻辑回归是一种常用的分类算法,梯度下降是逻辑回归中常用的优化算法之一。下面是一个使用Python实现逻辑回归梯度下降算法的示例代码:
```python
import numpy as np
def sigmoid(z):
"""Sigmoid函数"""
return 1 / (1 + np.exp(-z))
def logistic_regression(X, y, num_iterations, learning_rate):
"""逻辑回归梯度下降算法"""
m, n = X.shape
theta = np.zeros(n)
for iteration in range(num_iterations):
z = np.dot(X, theta)
h = sigmoid(z)
gradient = np.dot(X.T, (h - y)) / m
theta -= learning_rate * gradient
return theta
# 使用示例数据进行训练
X = np.array([[1, 2], [3, 4], [5, 6]])
y = np.array([0, 0, 1])
num_iterations = 1000
learning_rate = 0.1
theta = logistic_regression(X, y, num_iterations, learning_rate)
print("训练得到的参数theta:", theta)
```
阅读全文