5
我想寫一個函數,將2d-ndarray映射到2d-ndarray。輸入數組的行可以獨立處理,輸入行和輸出行之間應該有1對1的對應關係。對於輸入的每一行,應計算該行給定順序的多項式展開式(參見文檔字符串舉例)。目前的實施工作;但是它需要在「powerMatrix」中的行和行的重複上進行顯式循環)。是否可以通過一次性調用numpy.power來獲得相同的結果?順便說一句:結果行中條目的順序對我來說並不重要。2d numpy.power多項式展開
import numpy
def polynomialFeatures(x, order):
""" Generate polynomial features of given order for data x.
For each row of ndarray x, the polynomial expansions are computed, i.e
for row [x1, x2] and order 2, the following row of the result matrix is
computed: [1, x1, x1**2, x2, x1*x2, x1**2*x2, x2**2, x1*x2**2, x1**2*x2**2]
Parameters
----------
x : array-like
2-D array; for each of its rows, the polynomial features are created
order : int
The order of the polynomial features
Returns
-------
out : ndarray
2-D array of shape (x.shape[0], (order+1)**x.shape[1]) containing the
polynomial features computed for the rows of the array x
Examples
--------
>>> polynomialFeatures([[1, 2, 3], [-1, -2, -3]], 2)
array([[ 1 3 9 2 6 18 4 12 36 1 3 9 2 6 18 4 12
36 1 3 9 2 6 18 4 12 36]
[ 1 -3 9 -2 6 -18 4 -12 36 -1 3 -9 2 -6 18 -4 12
-36 1 -3 9 -2 6 -18 4 -12 36]])
"""
x = numpy.asarray(x)
# TODO: Avoid duplication of rows
powerMatrix = numpy.array([range(order+1)] * x.shape[1]).T
# TODO: Avoid explicit loop, and use numpy's broadcasting
F = []
for i in range(x.shape[0]):
X = numpy.power(x[i], powerMatrix).T
F.append(numpy.multiply.reduce(cartesian(X), axis=1))
return numpy.array(F)
print numpy.all(polynomialFeatures([[1, 2, 3], [-1, -2, -3]], 2) ==
numpy.array([[1, 3, 9, 2, 6, 18, 4, 12, 36, 1,
3, 9, 2, 6, 18, 4, 12, 36, 1, 3,
9, 2, 6, 18, 4, 12, 36],
[1, -3, 9, -2, 6, -18, 4, -12, 36, -1,
3, -9, 2, -6, 18, -4, 12, -36, 1, -3,
9, -2, 6, -18, 4, -12, 36]]))
感謝, 揚
編輯:缺少的功能笛卡爾在這裏定義:Using numpy to build an array of all combinations of two arrays
+1。 [刪除了我的一個愚蠢的評論 - 我已經通過'[1,2,3]'到你的函數而不是'[[1,2,3]]',這當然給出同樣愚蠢的結果。] – DSM 2012-07-30 20:02:54
謝謝很多,這樣做的工作:-) – frisbee 2012-07-31 09:14:11
這是一個非常優雅的解決方案!如果你不介意的話,我想在我正在處理的一個小項目中使用它:https://github.com/dreamwalkerrr/mledu。 (如果可以,將這個算法歸功於你鏈接到這個答案?)。另外,你能否讓我知道排除第0位權力的最佳方式是什麼? – dreamwalker 2013-11-21 15:40:17