Logistic函数

图中显示的是逻辑回归如何在这个综合数据集中使用logistic曲线将值分类为0或1,即第一类或第二类。

print(__doc__)


# Code source: Gael Varoquaux
# License: BSD 3 clause

import numpy as np
import matplotlib.pyplot as plt

from sklearn import linear_model
from scipy.special import expit

# General a toy dataset:s it's just a straight line with some Gaussian noise:
xmin, xmax = -55
n_samples = 100
np.random.seed(0)
X = np.random.normal(size=n_samples)
y = (X > 0).astype(np.float)
X[X > 0] *= 4
X += .3 * np.random.normal(size=n_samples)

X = X[:, np.newaxis]

# Fit the classifier
clf = linear_model.LogisticRegression(C=1e5)
clf.fit(X, y)

# and plot the result
plt.figure(1, figsize=(43))
plt.clf()
plt.scatter(X.ravel(), y, color='black', zorder=20)
X_test = np.linspace(-510300)

loss = expit(X_test * clf.coef_ + clf.intercept_).ravel()
plt.plot(X_test, loss, color='red', linewidth=3)

ols = linear_model.LinearRegression()
ols.fit(X, y)
plt.plot(X_test, ols.coef_ * X_test + ols.intercept_, linewidth=1)
plt.axhline(.5, color='.5')

plt.ylabel('y')
plt.xlabel('X')
plt.xticks(range(-510))
plt.yticks([00.51])
plt.ylim(-.251.25)
plt.xlim(-410)
plt.legend(('Logistic Regression Model''Linear Regression Model'),
           loc="lower right", fontsize='small')
plt.tight_layout()
plt.show()

脚本的总运行时间:(0分0.089秒)

Download Python source code: plot_logistic.py

Download Jupyter notebook: plot_logistic.ipynb