numpy 的 fromfunction 的参数 [英] Parameters to numpy's fromfunction

查看:30
本文介绍了numpy 的 fromfunction 的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有理解 numpy 中的关键概念.

I haven't grokked the key concepts in numpy yet.

我想创建一个 3 维数组并用函数调用的结果填充每个单元格 - 即该函数将使用不同的索引多次调用并返回不同的值.

I would like to create a 3-dimensional array and populate each cell with the result of a function call - i.e. the function would be called many times with different indices and return different values.

注意:自撰写此问题以来,文档已更新为更清晰.

我可以用零(或空)创建它,然后用 for 循环覆盖每个值,但直接从函数填充它似乎更清晰.

I could create it with zeros (or empty), and then overwrite every value with a for loop, but it seems cleaner to populate it directly from the function.

fromfunction 听起来很完美.阅读文档 听起来该函数被调用一次每个单元格.

fromfunction sounds perfect. Reading the documentation it sounds like the function gets called once per cell.

但是当我真正尝试...

But when I actually try it...

from numpy import *

def sum_of_indices(x, y, z):
    # What type are X, Y and Z ? Expect int or duck-type equivalent.
    # Getting 3 individual arrays
    print "Value of X is:"
    print x

    print "Type of X is:", type(x)
    return x + y + z

a = fromfunction(sum_of_indices, (2, 2, 2))

我希望得到类似的东西:

I expect to get something like:

Value of X is:
0
Type of X is: int
Value of X is:
1
Type of X is: int

重复了 4 次.

我明白了:

Value of X is:
[[[ 0.  0.]
  [ 0.  0.]]

 [[ 1.  1.]
  [ 1.  1.]]]
[[[ 0.  0.]
  [ 1.  1.]]

 [[ 0.  0.]
  [ 1.  1.]]]
[[[ 0.  1.]
  [ 0.  1.]]

 [[ 0.  1.]
  [ 0.  1.]]]
Type of X is: <type 'numpy.ndarray'>

该函数只被调用一次,并且似乎返回整个数组作为结果.

The function is only called once, and seems to return the entire array as result.

基于对索引函数的多次调用来填充数组的正确方法是什么?

What is the correct way to populate an array based on multiple calls to a function of the indices?

推荐答案

文档在这方面非常具有误导性.就像你注意到的那样:numpy 不是执行 f(0,0), f(0,1), f(1,0), f(1,1),而是执行

The documentation is very misleading in that respect. It's just as you note: instead of performing f(0,0), f(0,1), f(1,0), f(1,1), numpy performs

f([[0., 0.], [0., 1.]], [[1., 0.], [1., 1.]])

当您尝试使用诸如lambda i: l[i] 之类的东西时,使用 ndarrays 而不是承诺的整数坐标非常令人沮丧,其中 l 是另一个数组或列表(尽管实际上,在 numpy 中可能有更好的方法来做到这一点).

Using ndarrays rather than the promised integer coordinates is quite frustrating when you try and use something likelambda i: l[i], where l is another array or list (though really, there are probably better ways to do this in numpy).

numpy vectorize 函数修复了这个问题.你在哪里

The numpy vectorize function fixes this. Where you have

m = fromfunction(f, shape)

尝试使用

g = vectorize(f)
m = fromfunction(g, shape)

这篇关于numpy 的 fromfunction 的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆