您的位置:首页 > 其它

103 保序回归 isotonic regression

2016-03-30 11:25 405 查看

1.关于isotonic regression

首先sklearn粘上原贡献者的博客Isotonic Regression http://fa.bianp.net/blog/2013/isotonic-regression/
及Wikipedia上的解释https://en.wikipedia.org/wiki/Isotonic_regression

这种回归,是这一种单调函数的回归,回归模型中后一个x一定比前一个x大,也就是有序,具体的数学公式在上面两个网址中都有。

保序回归并不需要制定的目标函数。

保序回归的应用之一就是用来做统计推断,比如药量和毒性的关系,一般认为毒性随着药量是不减或者递增的关系,借此可以来估计最大药量。

2.部分函数介绍

2.1 matplotlib.collection.linecollection http://matplotlib.org/api/collections_api.html#matplotlib.collections.LineCollection
主要功能是用直线将多个单元连接起来
主要介绍两个参数segments和zorder
segment可以是序列或者是numpy.array,本例中
segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]

代表 需要连接n条的线段

zorder是artists的绘图顺序,自己改改参数 就可以看出不同了,至于artists的含义,请看下面的网址 http://old.sebug.net/paper/books/scipydoc/matplotlib_intro.html#axes

2.2 sklearn.utils.check_random_state

赋予一个np.random.RandomState值
如果其参数为一个整数的话返回整数值,并赋值
如果已经设定了一个state,而且不是这个整数的话就返回错误
如果没有参数程序自己看着办,随随便便给个state

2.3
sklearn.isotonic.
IsotonicRegression

http://scikit-learn.org/stable/modules/generated/sklearn.isotonic.IsotonicRegression.html#sklearn.isotonic.IsotonicRegression

主要写下例子中用到的fit_transform
首先fit拟合数据,然后再进行transformer
这里的y_ = ir.fit_transform(x, y)等于y2=ir.fit(x,y) y3=y2.predict(x)

2.4 np.newaxis

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis

作用是在切片操作时创建一个新的维度,例如:x = np.arange(n)原本的shape是(100,);x[:,np.newaxis]就成了(100,1),很神奇的东西,一定要记下来噢

2.5
matplotlib.pyplot.
gca

gca=Get the current
Axes

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.gca

3.代码

# Author: Nelle Varoquaux <nelle.varoquaux@gmail.com>
#         Alexandre Gramfort <alexandre.gramfort@inria.fr>
# #copy by IKoala

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

from sklearn.linear_model import LinearRegression
from sklearn.isotonic import IsotonicRegression
from sklearn.utils import check_random_state

n = 100
x = np.arange(n)
rs = check_random_state(333)

y = rs.randint(-50, 50, size=(n,)) + 50. * np.log(1 + np.arange(n))

###############################################################################
# Fit IsotonicRegression and LinearRegression models
#分别用iR、LR拟合

ir = IsotonicRegression()

y_ = ir.fit_transform(x, y)

lr = LinearRegression()

lr.fit(x[:, np.newaxis], y)  # x needs to be 2d for LinearRegression

###############################################################################
# plot result

segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
lc = LineCollection(segments, zorder=0)
lc.set_array(np.ones(len(y)))#把它变成arange(100)看看啥效果噢
lc.set_linewidths(0.5 * np.ones(n))

fig = plt.figure()
plt.plot(x, y, 'r.', markersize=12)
plt.plot(x, y_, 'g.-', markersize=12)
plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-')
plt.gca().add_collection(lc)
plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right')
plt.title('Isotonic regression')
plt.show()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: