Numpy向量化2D阵列运算错误 [英] Numpy vectorized 2d array operation error
问题描述
我正在尝试将矢量化函数应用于numpy行的2-d数组,并且遇到了ValueError: setting an array element with a sequence.
I'm trying to apply a vectorized function over a 2-d array in numpy row-wise, and I'm encountering ValueError: setting an array element with a sequence.
import numpy as np
X = np.array([[0, 1], [2, 2], [3, 0]], dtype=float)
coeffs = np.array([1, 1], dtype=float)
np.apply_along_axis(
np.vectorize(lambda row: 1.0 / (1.0 + np.exp(-coeffs.dot(row)))),
0, X
)
我不完全知道如何解释此错误.如何设置具有序列的数组元素?
I don't totally know how to interpret this error. How am I setting an array element with a sequence?
当我在单行上测试lambda函数时,它可以工作并返回单个浮点数.某种程度上,它在此矢量化函数的范围内失败了,这使我相信该矢量化函数是错误的,或者我没有正确使用apply_along_axis
.
When I test the lambda function on a single row, it works and returns a single float. Somehow it's failing within the scope of this vectorized function, which leads me to believe that either the vectorized function is wrong or I'm not using apply_along_axis
correctly.
在这种情况下可以使用向量化函数吗?如果是这样,怎么办?向量化函数可以接受数组吗?还是我误解了文档?
Is it possible to use a vectorized function in this context? If so, how? Can a vectorized function take an array or am I misunderstanding the documentation?
推荐答案
您正在将X
的第二个轴与coeffs
的唯一轴相减.因此,您只需将np.dot(X,coeffs)
用作sum-reductions
.
You are sum-reducing the second axis of X
against the only axis of coeffs
. So, you could simply use np.dot(X,coeffs)
for sum-reductions
.
因此,矢量化解决方案应为-
Thus, a vectorized solution would be -
1.0 / (1.0 + np.exp(-X.dot(coeffs)))
样品运行-
In [227]: X = np.array([[0, 1], [2, 2], [3, 0]], dtype=float)
...: coeffs = np.array([1, 1], dtype=float)
...:
# Using list comprehension
In [228]: [1.0 / (1.0 + np.exp(-coeffs.dot(x))) for x in X]
Out[228]: [0.7310585786300049, 0.98201379003790845, 0.95257412682243336]
# Using proposed method
In [229]: 1.0 / (1.0 + np.exp(-X.dot(coeffs)))
Out[229]: array([ 0.73105858, 0.98201379, 0.95257413])
使用np.apply_along_axis
的正确方法是放下np.vectorize
并沿X
的第二个轴应用它,即X
-
The correct way to use np.apply_along_axis
would be to drop np.vectorize
and apply it along the second axis of X
, i.e. every row of X
-
np.apply_along_axis(lambda row: 1.0 / (1.0 + np.exp(-coeffs.dot(row))), 1,X)
这篇关于Numpy向量化2D阵列运算错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!