python使用逻辑回归代码
时间: 2024-05-24 14:07:16 浏览: 101
python逻辑回归代码
以下是使用Python实现逻辑回归的代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def logistic_regression(x, label, learning_rate, num_iterations):
m, n = x.shape
x = np.hstack((np.ones((m, 1)), x))
omega = np.zeros(n + 1)
for i in range(num_iterations):
z = np.dot(x, omega)
h = sigmoid(z)
gradient = np.dot(x.T, (h - label)) / m
omega -= learning_rate * gradient
return omega
# 示例数据
x = np.array([[2, 3], [4, 1], [6, 7], [8, 5]])
label = np.array([0, 0, 1, 1])
# 调用逻辑回归函数
omega = logistic_regression(x, label, learning_rate=0.1, num_iterations=1000)
# 画出决策边界
x1 = np.linspace(0, 10, 100)
y1 = (-omega - omega * x1) / omega
plt.scatter(x[:, 0], x[:, 1], c=label)
plt.plot(x1, y1)
plt.show()
```
这段代码实现了逻辑回归算法,其中包括sigmoid函数的定义、梯度下降法的实现以及画出决策边界的代码[^1]。
阅读全文