2016-05-01 11 views
2

私はさまざまな条件の下で細胞の透過性に適した関数を見つけようとしています。一定の透過性を仮定すると、実験データに適合させることができ、Sklearns PolynomialFeaturesLinearModelthis postで説明されているように)を使用して、条件と透過性との間の相関を決定することができる。しかし、透過率は一定ではなく、今はプロセス条件の関数として透過率をモデルに適合させようとしています。 sklearnのPolynomialFeatureモジュールは使い方がとてもいいです。いくつかのデータにScipyフィッティング多項式モデル

scipyまたはnumpy内に同等の機能がありますが、手作業で関数全体を記述することなく、多項式モデル(相互作用項など、a*x[0]*x[1]など)をさまざまな順序で作成できますか?

numpyの標準多項式クラスは、対話項をサポートしていないようです。

答えて

1

私はあなたの必要とする機能を正確に認識していませんが、itertoolsnumpyの組み合わせで実現できます。

予測変数がn_featuresの場合、基本的に、長さがn_featuresのすべてのベクトルを生成する必要があります。これらのエントリは、負でない整数であり、指定された順序になります。それぞれの新しいフィーチャー列は、これらのベクトルを使用して指定された順序で合計するコンポーネント単位の累乗です。

たとえば、order = 3n_features = 2の場合、新機能の1つは、それぞれの電力に昇格された古い機能、[2,1]になります。私は任意の順序と機能の数のためのいくつかのコードを書いた。私はベクトルの生成をorderからthis postに変更しました。

>>> 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が明示的に多項式マップを計算することなく、正確にこの効果を達成することを言及する必要があります:

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 

は、ここではいくつかの使用例です。もちろん、これにはプロと矛盾がありますが、私があなたがまだ持っていなければそれを考慮する必要があると言いました。

+0

チャームのように機能します – Moritz

関連する問題