我确实在尝试为不同条件下的细胞渗透性找到合适的函数。如果我假设恒定渗透率,我可以将其拟合到实验数据并使用 Sklearns PolynomialFeatures 和 LinearModel(如 this post 中所述)以确定相关性在条件和渗透率之间。然而,渗透率不是恒定的,现在我尝试用作为过程条件函数的渗透率来拟合我的模型。 sklearn 的 PolynomialFeature 模块非常好用。
在 scipy 或 numpy 中是否有一个等效函数允许我创建一个多项式模型(包括交互项,例如 a*x[0]*x[1] 等)而无需手动编写整个函数?
numpy 中的标准多项式类似乎不支持交互项。
请您参考如下方法:
我不知道有这样一个函数可以完全满足您的需要,但是您可以结合使用 itertools 和 numpy 来实现它。
如果您有 n_features 预测变量,您基本上必须生成长度为 n_features 的所有向量,其条目为非负整数并按指定顺序求和。每个新的特征列都是使用这些向量的分量幂,这些向量求和为给定的顺序。
例如,如果 order = 3 和 n_features = 2,其中一个新特征将旧特征提升到各自的幂,[2 ,1]。我在下面为任意顺序和功能数量编写了一些代码。我修改了从 this post 求和为 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 polynomial kernel无需显式计算多项式映射即可达到此效果。这当然有利也有弊,但我认为我应该提及它以供您考虑,如果您还没有考虑的话。
