逻辑回归二分类实例完整代码
时间: 2024-05-25 18:09:01 浏览: 18
逻辑回归是一种二分类算法,它的主要思想是通过一个函数将输入映射为输出,函数的值域在0到1之间,表示概率。下面是一个逻辑回归的二分类实例完整代码:
```
import numpy as np
import matplotlib.pyplot as plt
# 构造数据
np.random.seed(0)
X = np.random.randn(100, 2)
Y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0)
# 定义sigmoid函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 定义代价函数
def cost_function(theta, X, Y):
m = len(Y)
h = sigmoid(X @ theta)
J = -1/m * (Y.T @ np.log(h) + (1-Y).T @ np.log(1-h))
grad = 1/m * X.T @ (h - Y)
return J, grad
# 梯度下降求解
def gradient_descent(X, Y, alpha=0.01, iterations=1000):
m, n = X.shape
theta = np.zeros((n, 1))
J_history = []
for i in range(iterations):
J, grad = cost_function(theta, X, Y)
theta = theta - alpha * grad
J_history.append(J.item())
return theta, J_history
# 特征缩放
mu = np.mean(X, axis=0)
sigma = np.std(X, axis=0)
X = (X - mu) / sigma
# 添加偏置项
X = np.hstack((np.ones((len(Y), 1)), X))
# 训练模型
theta, J_history = gradient_descent(X, Y)
# 绘制代价函数随迭代次数的变化曲线
plt.plot(np.arange(len(J_history)), J_history)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.show()
# 绘制决策边界
plt.scatter(X[:, 1][Y==0], X[:, 2][Y==0], marker='o', label='Class 0')
plt.scatter(X[:, 1][Y==1], X[:, 2][Y==1], marker='x', label='Class 1')
x_min, x_max = X[:, 1].min(), X[:, 1].max()
y_min, y_max = X[:, 2].min(), X[:, 2].max()
xx, yy = np.meshgrid(np.linspace(x_min, x_max), np.linspace(y_min, y_max))
Z = sigmoid(np.c_[np.ones((xx.ravel().shape, 1)), xx.ravel(), yy.ravel()].dot(theta))
Z = Z.reshape(xx.shape)
plt.contour(xx, yy, Z, levels=[0.5])
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.show()
```
这段代码使用了梯度下降算法求解逻辑回归模型,并用matplotlib绘制了代价函数随迭代次数的变化曲线和决策边界。如果您对这段代码有任何问题,可以继续提问。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)