我确实试图为细胞在不同条件下的通透性找到一个合适的功能。如果假设渗透率恒定,则可以将其与实验数据相拟合,并与PolynomialFeatures和LinearModel (在这个职位中解释)一起使用,以确定条件与渗透率之间的相关性。然而,渗透率不是恒定的,现在我试着将我的模型与渗透率作为工艺条件的函数进行拟合。PolynomialFeature模块的滑雪是相当不错的使用。
在scipy或numpy中是否有一个等价的函数,它允许我创建一个多项式模型(包括交互项,如a*x[0]*x[1]等)有着不同的顺序而不用手工书写整个功能?
numpy中的标准多项式类似乎不支持交互项。
发布于 2016-05-02 15:14:28
我不知道这样一个函数能够完全满足您的需要,但是您可以使用itertools和numpy的组合来实现它。
如果您有n_features预测变量,则本质上必须生成长度为n_features的所有向量,其条目为非负整数,和为指定的顺序。每一个新的特征列都是使用这些向量和给定的顺序的分量幂。
例如,如果order = 3和n_features = 2,新特性之一将是旧功能提高到各自的权力,[2,1]。下面我已经为任意顺序和特性的数量编写了一些代码。我修改了从order到这个职位的向量的生成。
import itertools
import numpy as np
from scipy.special import binom
def polynomial_features_with_cross_terms(X, order):
"""
X: numpy ndarray
Matrix of shape, `(n_samples, n_features)`, to be transformed.
order: integer, default 2
Order of polynomial features to be computed.
returns: T, powers.
`T` is a matrix of shape, `(n_samples, n_poly_features)`.
Note that `n_poly_features` is equal to:
`n_features+order-1` Choose `n_features-1`
See: https://en.wikipedia.org\
/wiki/Stars_and_bars_%28combinatorics%29#Theorem_two
`powers` is a matrix of shape, `(n_features, n_poly_features)`.
Each column specifies the power by row of the respective feature,
in the respective column of `T`.
"""
n_samples, n_features = X.shape
n_poly_features = int(binom(n_features+order-1, n_features-1))
powers = np.zeros((n_features, n_poly_features))
T = np.zeros((n_samples, n_poly_features), dtype=X.dtype)
combos = itertools.combinations(range(n_features+order-1), n_features-1)
for i,c in enumerate(combos):
powers[:,i] = np.array([
b-a-1 for a,b in zip((-1,)+c, c+(n_features+order-1,))
])
T[:,i] = np.prod(np.power(X, powers[:,i]), axis=1)
return T, powers下面是一些示例用法:
>>> X = np.arange(-5,5).reshape(5,2)
>>> T,p = polynomial_features_with_cross_terms(X, order=3)
>>> print X
[[-5 -4]
[-3 -2]
[-1 0]
[ 1 2]
[ 3 4]]
>>> print p
[[ 0. 1. 2. 3.]
[ 3. 2. 1. 0.]]
>>> print T
[[ -64 -80 -100 -125]
[ -8 -12 -18 -27]
[ 0 0 0 -1]
[ 8 4 2 1]
[ 64 48 36 27]]最后,我要指出的是,在不显式计算多项式映射的情况下,SVM多项式核实现了这一效果。这当然有正反两方面的,但我想我应该提出来让你考虑一下,如果你还没有。
https://stackoverflow.com/questions/36971635
复制相似问题