给出python实现逻辑斯蒂回归的代码,不能调用sklearn的库,并将结果可视化
时间: 2024-06-03 10:10:09 浏览: 82
逻辑回归算法及Python代码实现,ipynb格式
5星 · 资源好评率100%
我可以为您提供python实现逻辑斯蒂回归的示例代码如下:
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def loss(h, y):
return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()
def logistic_regression(X, y, lr=0.01, num_iter=100000):
m, n = X.shape
X = np.hstack((np.ones((m, 1)), X))
theta = np.zeros(n+1)
for i in range(num_iter):
z = np.dot(X, theta)
h = sigmoid(z)
grad = np.dot(X.T, (h - y)) / m
theta -= lr * grad
return theta
# 生成一些随机的点
np.random.seed(0)
x1 = np.random.normal(2, 1, 100)
y1 = np.random.normal(2, 1, 100)
x2 = np.random.normal(-2, 1, 100)
y2 = np.random.normal(-2, 1, 100)
X = np.vstack((np.hstack((x1, x2)), np.hstack((y1, y2)))).T
y = np.hstack((np.zeros(100), np.ones(100)))
# 拟合逻辑斯蒂回归
theta = logistic_regression(X, y)
# 绘制结果
plt.scatter(x1, y1, c='r', marker='o')
plt.scatter(x2, y2, c='b', marker='x')
x_plot = np.linspace(-5, 5, 100)
y_plot = -(theta[0] + theta[1] * x_plot) / theta[2]
plt.plot(x_plot, y_plot, 'g')
plt.show()
请您注意,这只是简单的示例代码,实际应用中需要考虑更多的细节问题。
阅读全文