如何在二维numpy数组/矩阵中应用每个元素的函数/映射值? [英] How to apply a function / map values of each element in a 2d numpy array/matrix?
问题描述
给出以下numpy矩阵:
Given the following numpy matrix:
import numpy as np
mymatrix = mymatrix = np.matrix('-1 0 1; -2 0 2; -4 0 4')
matrix([[-1, 0, 1],
[-2, 0, 2],
[-4, 0, 4]])
和以下功能(S形/物流):
and the following function (sigmoid/logistic):
import math
def myfunc(z):
return 1/(1+math.exp(-z))
我想获得一个新的numpy数组/矩阵,其中每个元素都是将myfunc
函数应用于原始矩阵中相应元素的结果.
I want to get a new numpy array/matrix where each element is the result of applying the myfunc
function to the corresponding element in the original matrix.
map(myfunc, mymatrix)
失败,因为它尝试将myfunc应用于行,而不是应用于每个元素.我尝试使用numpy.apply_along_axis
和numpy.apply_over_axis
,但是它们也意在将函数应用于行或列,而不是逐个元素地应用.
the map(myfunc, mymatrix)
fails because it tries to apply myfunc to the rows not to each element. I tried to use numpy.apply_along_axis
and numpy.apply_over_axis
but they are meant also to apply the function to rows or columns and not on a element by element basis.
那么如何将myfunc(z)
应用于myarray
的每个元素以获得:
So how can apply myfunc(z)
to each element of myarray
to get:
matrix([[ 0.26894142, 0.5 , 0.73105858],
[ 0.11920292, 0.5 , 0.88079708],
[ 0.01798621, 0.5 , 0.98201379]])
推荐答案
显然,将函数应用于元素的方法是将函数转换为向量化版本,该向量化版本将数组作为输入,并将数组作为输出.
Apparently the way to apply a function to elements is to convert your function into a vectorized version that takes arrays as input and return arrays as output.
您可以使用numpy.vectorize
轻松地将函数转换为矢量化形式,如下所示:
You can easily convert your function to vectorized form using numpy.vectorize
as follows:
myfunc_vec = np.vectorize(myfunc)
result = myfunc_vec(mymatrix)
或一次性使用:
np.vectorize(myfunc)(mymatrix)
如@Divakar所指出的那样,如果可以从头开始编写一个已经矢量化的函数(使用numpy构建的
As pointed out by @Divakar, it's better (performance-wise) if you can write an already vectorized function from scratch (using numpy built ufuncs without using numpy.vectorize
) like so:
def my_vectorized_func(m):
return 1/(1+np.exp(-m)) # np.exp() is a built-in ufunc
myvectorized_func(mymatrix)
由于 numpy.exp
已经向量化(不是math.exp
),整个表达式1/(1+np.exp(-m))
将被向量化(并且更快地将我的原始函数应用于每个元素).
Since numpy.exp
is already vectorized (and math.exp
wasn't) the whole expression 1/(1+np.exp(-m))
will be vectorized (and faster that applying my original function to each element).
以下完整示例产生了所需的输出:
The following complete example produced the required output:
import numpy as np
mymatrix = mymatrix = np.matrix('-1 0 1; -2 0 2; -4 0 4')
import math
def myfunc(z):
return 1/(1+math.exp(-z))
np.vectorize(myfunc)(mymatrix) # ok, but slow
def my_vectorized_func(m):
return 1/(1+np.exp(-m))
my_vectorized_func(mymatrix) # faster using numpy built-in ufuncs
这篇关于如何在二维numpy数组/矩阵中应用每个元素的函数/映射值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!