logistic回归python,画出拟合结果函数和数学
时间: 2023-05-31 13:04:40 浏览: 61
公式
Logistic回归是一种分类算法,用于将输入变量映射到离散的输出变量。它使用sigmoid函数将输入变量转换为概率值,并通过最大化似然函数来拟合模型。
数学公式:
sigmoid函数:
$$sigmoid(z) = \frac{1}{1 + e^{-z}}$$
预测函数:
$$h_{\theta}(x) = sigmoid(\theta^Tx) = \frac{1}{1 + e^{-\theta^Tx}}$$
代价函数:
$$J(\theta) = -\frac{1}{m}\sum_{i=1}^{m}[y^{(i)}log(h_{\theta}(x^{(i)})) + (1 - y^{(i)})log(1 - h_{\theta}(x^{(i)}))]$$
梯度下降算法:
$$\theta_j := \theta_j - \alpha\frac{\partial J(\theta)}{\partial \theta_j}$$
画出拟合结果函数:
```python
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def plot_fit(theta, X, y):
plt.scatter(X[:, 1], y, marker='o', c='r')
x1_min, x1_max = X[:, 1].min(), X[:, 1].max()
x1 = np.linspace(x1_min, x1_max, 100)
x2 = (-1 / theta[2]) * (theta[1] * x1 + theta[0])
plt.plot(x1, x2, label='Decision Boundary')
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
plt.legend()
plt.show()
```
其中,theta为模型参数,X为输入数据矩阵,y为标签矩阵。
使用该函数可以将模型的拟合结果可视化出来。
参考资料:
1. 机器学习实战(第二版)
2. https://blog.csdn.net/qq_19707729/article/details/78429515