gpt4 book ai didi

python - 用于多项式展开的 2d numpy.power

转载 作者:太空狗 更新时间:2023-10-30 01:23:35 25 4
gpt4 key购买 nike

我正在尝试编写一个将 2d-ndarray 映射到 2d-ndarray 的函数。输入数组的行可以独立处理,输入行和输出行之间应该是一一对应的。对于输入的每一行,应计算该行给定阶数的多项式展开(有关示例,请参见文档字符串)。当前的实现工作;然而,它需要在“powerMatrix”)中对行进行显式循环和重复行。是否可以通过一次调用 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

最佳答案

基本思想是将与计算无关的维度(在您的例子中,维度 0,行数)“移开”到更高维度,然后自动广播。

我不确定你的 cartesian方法正在做,但这里有一个使用 np.indices 的解决方案在 X 上生成索引元组矩阵:

import numpy as np
def polynomial_features(x, order):
x = np.asarray(x).T[np.newaxis]
n = x.shape[1]
power_matrix = np.tile(np.arange(order + 1), (n, 1)).T[..., np.newaxis]
X = np.power(x, power_matrix)
I = np.indices((order + 1, ) * n).reshape((n, (order + 1) ** n)).T
F = np.product(np.diagonal(X[I], 0, 1, 2), axis=2)
return F.T

关于python - 用于多项式展开的 2d numpy.power,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11723779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com