使用numpy fromfunction [英] Use of numpy fromfunction

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

问题描述

im试图使用fromfunction创建一个5x5矩阵,其高斯值为mu = 3和sig = 2,这是我的尝试:

im trying to use fromfunction to create a 5x5 matrix with gaussian values of mu=3 and sig=2, this is my attempt :

from random import gauss
import numpy as np
np.fromfunction(lambda i,j: gauss(3,2), (5, 5))

这是结果:5.365244570434782

this is the result : 5.365244570434782

据我从 docs 所了解的应该可以用,但是我得到的是标量而不是5x5矩阵...为什么?以及如何解决这个问题?

as i understand from the docs this should have worked, but i am getting a scalar instead of 5x5 matrix... why? and how to fix this?

推荐答案

numpy.fromfunction文档极具误导性. fromfunction并不会重复调用函数并从结果中构建数组,而是实际上仅对传递它的函数进行一次调用.在该调用中,它将多个索引数组而不是单个索引传递给您的函数.

The numpy.fromfunction docs are extremely misleading. Instead of calling your function repeatedly and building an array from the results, fromfunction actually only makes one call to the function you pass it. In that one call, it passes a number of index arrays to your function, instead of individual indices.

剥离文档字符串,实现如下:

Stripping out the docstring, the implementation is as follows:

def fromfunction(function, shape, **kwargs):
    dtype = kwargs.pop('dtype', float)
    args = indices(shape, dtype=dtype)
    return function(*args,**kwargs)

这意味着除非广播您的函数,否则numpy.fromfunction不会像文档所说的那样执行任何操作.

That means unless your function broadcasts, numpy.fromfunction doesn't do anything like what the docs say it does.

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

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