Logistic Regression 逻辑回归算法例子,python代码实现

来源:互联网 发布:电梯卡软件下载 编辑:程序博客网 时间:2024/05/16 22:02

转载自原文

逻辑回归 Logistic Regression

虽然名字叫做逻辑回归 Logistic regression ,但它是一种分类算法。对于文本处理方便,逻辑回归是一种非常强大的分类器。它主要通过在逻辑函数上执行回归来实现,正如其名字。

逻辑回归的一个小例子

如下图,红色表示分类1,蓝色表示分类为0.但是对于特征,横坐标上有一个区间既可以分到1也可以分到0。遇到这种情况,最好能用概率来表示分到某一类的可能性,而不是用离散的方式来表示0或1。 逻辑回归示例

在数学上,向来都是很难设定模型的边界,像本例中的0和1。但是我们可以经过一些处理,使得分类的概率值落在0和1之间。

如果一个数据有0.9的可能性是属于分类1的,我们可以认为其有9:1的可能性将该数据分类为1。如果另一个数据有0.5的可能性分类为1,则认为有1:1的可能性将数据的分类为1。这种odd的表达方式的范围是0到无穷大。如果将odd加上log,取对数。则可以将odd的范围映射到0和1 之间。这样就实现了将离散的分类值转换成连续的概率值的映射。

逻辑回归曲线

取对数之后的曲线:

逻辑回归对数曲线

逻辑回归python代码

使用 scipy.stats的norm.rvs产生随机数,参数loc表示平均数,scale表示标准差,size是样本量

np.hstack合并两个数组

import osfrom data import CHART_DIRimport numpy as npfrom scipy.stats import normfrom matplotlib import pyplotnp.random.seed(3)num_per_class = 40#生成样本X = np.hstack((norm.rvs(2, size=num_per_class, scale=2),              norm.rvs(8, size=num_per_class, scale=3)))y = np.hstack((np.zeros(num_per_class),               np.ones(num_per_class)))def lr_model(clf, X):    return 1.0 / (1.0 + np.exp(-(clf.intercept_ + clf.coef_ * X)))from sklearn.linear_model import LogisticRegressionlogclf = LogisticRegression()print(logclf)logclf.fit(X.reshape(num_per_class * 2, 1), y)print(np.exp(logclf.intercept_), np.exp(logclf.coef_.ravel()))print("P(x=-1)=%.2f\tP(x=7)=%.2f" %      (lr_model(logclf, -1), lr_model(logclf, 7)))X_test = np.arange(-5, 20, 0.1)pyplot.figure(figsize=(10, 4))pyplot.xlim((-5, 20))pyplot.scatter(X, y, c=y)pyplot.xlabel("feature value")pyplot.ylabel("class")pyplot.grid(True, linestyle='-', color='0.75')pyplot.savefig(    os.path.join(CHART_DIR, "log_reg_example_data.png"), bbox_inches="tight")def lin_model(clf, X):    return clf.intercept_ + clf.coef_ * Xfrom sklearn.linear_model import LinearRegressionclf = LinearRegression()print(clf)clf.fit(X.reshape(num_per_class * 2, 1), y)X_odds = np.arange(0, 1, 0.001)pyplot.figure(figsize=(10, 4))pyplot.subplot(1, 2, 1)pyplot.scatter(X, y, c=y)pyplot.plot(X_test, lin_model(clf, X_test))pyplot.xlabel("feature value")pyplot.ylabel("class")pyplot.title("linear fit on original data")pyplot.grid(True, linestyle='-', color='0.75')X_ext = np.hstack((X, norm.rvs(20, size=100, scale=5)))y_ext = np.hstack((y, np.ones(100)))clf = LinearRegression()clf.fit(X_ext.reshape(num_per_class * 2 + 100, 1), y_ext)pyplot.subplot(1, 2, 2)pyplot.scatter(X_ext, y_ext, c=y_ext)pyplot.plot(X_ext, lin_model(clf, X_ext))pyplot.xlabel("feature value")pyplot.ylabel("class")pyplot.title("linear fit on additional data")pyplot.grid(True, linestyle='-', color='0.75')pyplot.savefig(    os.path.join(CHART_DIR, "log_reg_log_linear_fit.png"), bbox_inches="tight")pyplot.figure(figsize=(10, 4))pyplot.xlim((-5, 20))pyplot.scatter(X, y, c=y)pyplot.plot(X_test, lr_model(logclf, X_test).ravel())pyplot.plot(X_test, np.ones(X_test.shape[0]) * 0.5, "--")pyplot.xlabel("feature value")pyplot.ylabel("class")pyplot.grid(True, linestyle='-', color='0.75')pyplot.savefig(    os.path.join(CHART_DIR, "log_reg_example_fitted.png"), bbox_inches="tight")X = np.arange(0, 1, 0.001)pyplot.figure(figsize=(10, 4))pyplot.subplot(1, 2, 1)pyplot.xlim((0, 1))pyplot.ylim((0, 10))pyplot.plot(X, X / (1 - X))pyplot.xlabel("P")pyplot.ylabel("odds = P / (1-P)")pyplot.grid(True, linestyle='-', color='0.75')pyplot.subplot(1, 2, 2)pyplot.xlim((0, 1))pyplot.plot(X, np.log(X / (1 - X)))pyplot.xlabel("P")pyplot.ylabel("log(odds) = log(P / (1-P))")pyplot.grid(True, linestyle='-', color='0.75')pyplot.savefig(    os.path.join(CHART_DIR, "log_reg_log_odds.png"), bbox_inches="tight")

0 0
原创粉丝点击