【发布时间】:2017-01-01 09:17:36
【问题描述】:
我认为逻辑回归可以用于回归(获取 0 和 1 之间的数字,例如使用逻辑回归来预测 0 和 1 之间的概率)和分类。问题是,似乎在我们提供了训练数据和目标之后,逻辑回归可以自动判断我们是在做回归还是在做分类?
例如,在下面的示例代码中,逻辑回归发现我们只需要输出为0, 1, 2 的三个类别之一,而不是0 和2 之间的任何数字?只是好奇逻辑回归如何自动判断它是在做回归(输出是连续范围)还是分类(输出是离散)问题?
http://scikit-learn.org/stable/auto_examples/linear_model/plot_iris_logistic.html
print(__doc__)
# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, datasets
# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features.
Y = iris.target
h = .02 # step size in the mesh
logreg = linear_model.LogisticRegression(C=1e5)
# we create an instance of Neighbours Classifier and fit the data.
logreg.fit(X, Y)
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1, figsize=(4, 3))
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())
plt.show()
【问题讨论】:
-
I think logistic regression could be used for both regression [...] and classification- 原则上是的,但是如果人们说逻辑回归,他们总是指分类算法(是的,这很奇怪)。回归案例是generalized linear models的一个特例,带有 logit 链接功能。 -
@cel,很好的赶上和投票。如果我希望逻辑回归输出值在 0 和 1 之间,我应该怎么做?假设 0 表示人们没有购买东西,1 表示人们购买了东西,我想使用逻辑回归预测购买的概率。在我的例子中,目标只有值 0 和 1,但我想预测一个介于 0 和 1 之间的浮点数的概率。
-
@LinMa 使用 logreg.predict_proba() scikit-learn.org/stable/modules/generated/…
-
谢谢@joc,投票。我认为 sigmoid 函数输出 0 到 1 之间的连续值,但 scikit 中的逻辑回归默认输出 0 或 1 用于分类问题。只是好奇 scikit learn 如何自动计算并将输出归一化为 0 或 1,是否有阈值 scikit learn 逻辑回归利用底层?谢谢。
标签: python python-2.7 machine-learning scikit-learn logistic-regression