私はあなたの必要とする機能を正確に認識していませんが、itertools
とnumpy
の組み合わせで実現できます。
予測変数がn_features
の場合、基本的に、長さがn_features
のすべてのベクトルを生成する必要があります。これらのエントリは、負でない整数であり、指定された順序になります。それぞれの新しいフィーチャー列は、これらのベクトルを使用して指定された順序で合計するコンポーネント単位の累乗です。
たとえば、order = 3
とn_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
は、ここではいくつかの使用例です。もちろん、これにはプロと矛盾がありますが、私があなたがまだ持っていなければそれを考慮する必要があると言いました。
チャームのように機能します – Moritz