多项式模型对某些d的Scipy拟合

2024-04-23 09:10:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我确实试图在不同的条件下找到一个合适的细胞通透性函数。如果假设磁导率为常数,我可以将其与实验数据相匹配,并使用Sklearns PolynomialFeaturesLinearModel(如this post中所述),以确定条件和渗透率之间的相关性。然而,渗透率不是常数,现在我尝试用渗透率作为工艺条件的函数来拟合我的模型。sklearn的PolynomialFeature模块非常好用。在

在scipy或numpy中是否有一个等价函数,它允许我创建一个可变顺序的多项式模型(包括交互项,例如a*x[0]*x[1]等),而不需要手工编写整个函数?在

numpy中的标准多项式类似乎不支持交互项。在


Tags: 数据函数模型numpy常数this条件post
1条回答
网友
1楼 · 发布于 2024-04-23 09:10:06

我不知道这样一个函数能完全满足您的需要,但是您可以使用itertools和{}的组合来实现它。在

如果有n_features预测器变量,则必须生成所有长度为n_features的向量,这些向量的条目是非负整数,并按指定的顺序求和。每一个新的特征列都是使用这些向量的分量幂,这些向量的和为给定的顺序。在

例如,如果order = 3n_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

下面是一些用法示例:

^{pr2}$

最后,我要提到的是,SVM polynomial kernel在没有显式计算多项式映射的情况下就可以达到这种效果。当然有赞成和反对的意见,但我想我应该提一下,让你考虑一下,如果你还没有。在

相关问题 更多 >