【问题标题】:How to use the vectorize numpy function in python2.7?python2.7中如何使用vectorize numpy函数?
【发布时间】:2017-01-23 06:30:26
【问题描述】:

我在 ipython 中尝试了以下代码:我想使用矢量化并给出函数 prox(x,tau)。但是 lambda 中的第一个值总是出现两次。

In [32]: a = np.array([[ 1., 2.],[ 3., 4.]])
In [33]: def prox(x, tau):
    ...:     print x, tau
    ...:     if x >= tau:
    ...:         print "first"
    ...:         return x-tau
    ...:     if -tau <= x and x <= tau:
    ...:         print "second"
    ...:         return 0.0
    ...:     if x <= -tau:
    ...:         print "third"
    ...:         return x+tau

In [34]: b = np.vectorize(lambda x: prox(x, 2))(a[:,1:])
In [35]: b 
2.0 2
first
2.0 2
first
4.0 2
first

为什么在第 35 行两次打印相同的值? 2.0 2

【问题讨论】:

    标签: python-2.7 numpy


    【解决方案1】:

    如果您不指定otypes,则vectorize 使用第一个值执行测试计算,并使用它来确定它返回的数组的dtype。因此对第一项进行双重评价。

    通常,额外的计算并不重要。但小心点。如果初始计算返回一个整数(例如标量 0),则返回的数组也将是整数,在后续计算中会丢失任何浮点值。

    有关更多详细信息,请查看vectorize 的文档。

    vectorize is indeterminate - 意外的整数 otype 产生的错误。我在其他 SO 问题中看到过这个错误。

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 2021-05-02
      • 2016-09-01
      • 2020-12-24
      • 2020-06-09
      • 2011-10-09
      相关资源
      最近更新 更多