numpy中frompyfunc和vectorize的区别 [英] Difference between frompyfunc and vectorize in numpy

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

问题描述

vectorizefrompyfunc?

两者看起来非常相似.它们各自的典型用例是什么?

编辑:正如 JoshAdel 所指出的,vectorize 类似乎是建立在 frompyfunc 之上的.(请参阅来源).我仍然不清楚 frompyfunc 是否可能有任何 vectorize...

未涵盖的用例

解决方案

正如 JoshAdel 所指出的,vectorize 包装了 frompyfunc.Vectorize 添加了额外的功能:

  • 从原始函数复制文档字符串
  • 允许您从广播规则中排除参数.
  • 返回一个包含正确 dtype 的数组,而不是 dtype=object

经过一些简短的基准测试后,我发现对于大型数组,vectorize 明显比 frompyfunc 慢(约 50%).如果性能对您的应用程序至关重要,请先对您的用例进行基准测试.

`

<预><代码>>>>a = numpy.indices((3,3)).sum(0)>>>打印一个, a.dtype[[0 1 2][1 2 3][2 3 4]] int32>>>定义 f(x,y):"""返回 x 加 y 的 2 次"""返回 2*x+y>>>f_vectorize = numpy.vectorize(f)>>>f_frompyfunc = numpy.frompyfunc(f, 2, 1)>>>f_vectorize.__doc__'返回 x 加 y 的 2 次'>>>f_frompyfunc.__doc__'f (vectorized)(x1, x2[, out])\n\n基于python函数的动态ufunc'>>>f_vectorize(a,2)数组([[ 2, 4, 6],[ 4, 6, 8],[ 6, 8, 10]])>>>f_frompyfunc(a,2)数组([[2, 4, 6],[4, 6, 8],[6, 8, 10]], dtype=object)

`

What is the difference between vectorize and frompyfunc in numpy?

Both seem very similar. What is a typical use case for each of them?

Edit: As JoshAdel indicates, the class vectorize seems to be built upon frompyfunc. (see the source). It is still unclear to me whether frompyfunc may have any use case that is not covered by vectorize...

解决方案

As JoshAdel points out, vectorize wraps frompyfunc. Vectorize adds extra features:

  • Copies the docstring from the original function
  • Allows you to exclude an argument from broadcasting rules.
  • Returns an array of the correct dtype instead of dtype=object

Edit: After some brief benchmarking, I find that vectorize is significantly slower (~50%) than frompyfunc for large arrays. If performance is critical in your application, benchmark your use-case first.

`

>>> a = numpy.indices((3,3)).sum(0)

>>> print a, a.dtype
[[0 1 2]
 [1 2 3]
 [2 3 4]] int32

>>> def f(x,y):
    """Returns 2 times x plus y"""
    return 2*x+y

>>> f_vectorize = numpy.vectorize(f)

>>> f_frompyfunc = numpy.frompyfunc(f, 2, 1)
>>> f_vectorize.__doc__
'Returns 2 times x plus y'

>>> f_frompyfunc.__doc__
'f (vectorized)(x1, x2[, out])\n\ndynamic ufunc based on a python function'

>>> f_vectorize(a,2)
array([[ 2,  4,  6],
       [ 4,  6,  8],
       [ 6,  8, 10]])

>>> f_frompyfunc(a,2)
array([[2, 4, 6],
       [4, 6, 8],
       [6, 8, 10]], dtype=object)

`

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

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