在numpy的frompyfunc和矢量之间的区别

在numpy的frompyfunc和矢量之间的区别

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

问题描述

之间有什么和frompyfunc在numpy的?

似乎都非常相似。什么是一个典型的用例为他们每个人的?

修改:作为JoshAdel表明,该类矢量好像是在 frompyfunc 。 (见the来源)。现在还不清楚我是否 frompyfunc 可能有一个不属于矢量 ...

解决方案

由于JoshAdel指出,矢量包裹 frompyfunc 。矢量增加了额外的功能:


  • 将由原来的函数的文档字符串

  • 允许您排除规则广播的参数。

  • 返回正确的DTYPE,而不是DTYPE数组对象=

编辑:一些简要的比较测试后,我发现,矢量是(〜50%)比 frompyfunc显著慢对于大数组。如果性能是至关重要的应用程序,您的基准用例第一位。

`

 >>>一个= numpy.indices((3,3))。总和(0)>>>打印,a.dtype
[0 1 2]
 [1 2 3]
 [2 3 4]] INT32>>>高清函数f(x,y)的:
    返回2次X​​加Y
    返回2 * X + Y>>> f_vectorize = numpy.vectorize(F)>>> f_frompyfunc = numpy.frompyfunc(F,2,1)
>>> f_vectorize .__ doc__会给出
返回2次X​​加Y'>>> f_frompyfunc .__ doc__会给出
F(矢量)(X1,X2 [,超时])\\ n \\ ndynamic ufunc基于Python函数>>> f_vectorize(一,2)
阵列([[2,4,6]
       [4,6,8],
       [6,8,10]])>>> f_frompyfunc(一,2)
阵列([[2,4,6]
       [4,6,8],
       [6,8,10],DTYPE =对象)

`

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和矢量之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 09:57