二元logistic回归 python代码案例
时间: 2023-10-12 16:16:42 浏览: 57
以下是一个简单的二元logistic回归的Python代码案例:
```
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
# 创建数据集
np.random.seed(0)
X = np.random.randn(100, 2)
y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0)
# 训练逻辑回归模型
clf = LogisticRegression()
clf.fit(X, y)
# 绘制决策边界
xx, yy = np.meshgrid(np.linspace(-3, 3, 500), np.linspace(-3, 3, 500))
Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
Z = Z.reshape(xx.shape)
plt.contour(xx, yy, Z, levels=[0.5], cmap="Greys", vmin=0, vmax=.6)
# 绘制数据点
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="bwr", edgecolors="k")
plt.axis("tight")
plt.show()
```
这个例子使用sklearn库中的LogisticRegression模型,创建了一个二元分类数据集,并绘制了决策边界。
相关问题
二元logistic回归python
二元logistic回归是一种常用的分类算法,它可以用来预测二元分类问题。在Python中,可以使用scikit-learn库中的LogisticRegression模型来实现二元logistic回归。该模型可以通过拟合训练数据来学习分类边界,并用于预测新的数据点的类别。在使用LogisticRegression模型时,需要注意选择合适的正则化参数和优化算法,以避免过拟合和提高模型的准确性。
Logistic回归python代码
Logistic回归的Python代码如下:
```python
import numpy as np
# 加载数据集
def loadDataSet():
dataMat = []
labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
labelMat.append(int(lineArr[2]))
return dataMat,labelMat
# Sigmoid函数
def sigmoid(inX):
return 1.0 / (1 + np.exp(-inX))
# 梯度上升算法
def gradAscent(dataMatIn, classLabels):
dataMatrix = np.mat(dataMatIn)
labelMat = np.mat(classLabels).transpose()
m, n = np.shape(dataMatrix)
alpha = 0.001
maxCycles = 500
weights = np.ones((n,1))
for k in range(maxCycles):
h = sigmoid(dataMatrix * weights)
error = labelMat - h
weights = weights + alpha * dataMatrix.transpose() * error
return weights
# 测试代码
dataMat,labelMat = loadDataSet()
weights = gradAscent(dataMat, labelMat)
print(weights)
```