【问题标题】:NumPy vectorize() or dot() appears buggyNumPy vectorize() 或 dot() 出现错误
【发布时间】:2016-12-19 21:06:10
【问题描述】:

在下面的代码中,y1 和 y2 应该相等,但它们不是。 vectorize() 或 dot() 会不会有 bug?

import numpy as np
interval = np.arange(0, 30, 0.1)
y1 = [- 1.57 * max(0, x - 10) - 0.72 * max(0, 15 - x)
      - 1.09 * max(0, 20 - x) for x in interval]

def fun(x, pivot, truth):
    if truth: return max(0, x - pivot)
    else:     return max(0, pivot - x)

pivots = [10, 15, 20]
truths = [ 1,  0,  0]
coeffs = [-1.57, -0.72, -1.09]
y2 = [np.dot(np.vectorize(fun)(x, pivots, truths), coeffs) for x in interval]

import matplotlib.pyplot as plt
plt.plot(interval, y1, interval, y2)
plt.show()

y1 和 y2 的图表:

【问题讨论】:

    标签: numpy types vectorization


    【解决方案1】:

    我不确定这是否适用于你的情况,但vectorize 有一些技巧。

    如果您没有指定返回 dtype,它会通过测试计算来确定它 - 使用您的第一个案例。如果您的函数返回一个标量整数,如 0,则 vectorize 返回一个整数数组。因此,如果您期望浮点数,请确保指定返回 dtype

    另外 - vectorize 不是速度工具。这只是将广播应用于您的输入的一种便捷方式。它并不比显式循环输入更快。

    np.vectorize(fun, otypes=[float])
    

    删除步骤。

    ============

    试试这个:

    vfun = np.vectorize(fun, otypes=[float])
    X = vfun(interval[:,None], pivots, truths)
    print(X.shape)     # (300,3)
    y2 = np.dot(X, coeffs)
    print(y2.shape)    # (300,)
    

    更充分地利用了vectorize's广播。

    我怀疑你的fun 可以写成作用于整个x,而不需要vectorize 所做的迭代。

    fun 更改为使用np.maximum,允许我提供一个数组x

    def fun(x, pivot, truth):
        if truth: return np.maximum(0, x - pivot)
        else:     return np.maximum(0, pivot - x)
    

    然后我可以计算X,只对pivotstruths这3种情况进行循环,一次计算所有interval值:

    X = np.stack([fun(interval, p, t) for p, t in zip(pivots, truths)], axis=-1)
    y2 = np.dot(X, coeffs)
    

    另一种应用这 3 个“案例”的方法

    Xlist = [fun(interval, p, t)*c for p, t, c in zip(pivots, truths, coeffs)]
    y2 = np.sum(Xlist, axis=0)
    

    因为np.dot(..., coeffs) 只是一个加权和。我不确定它是否更好。

    【讨论】:

      【解决方案2】:

      为了应用正确的转换规则,numpy 偶尔会使用你的函数和标记值 (numpy.int64) 来检查它输出的数据类型,如果它输出整数 0,因为那是 max 返回的,那么它假设计算的结果应该都是整数,并且对其他结果进行四舍五入,但是如果您将函数更改为始终返回浮点数,在 max 中使用 0.0

      def fun(x, pivot, truth):
          if truth: return max(0.0, x - pivot)
          else:     return max(0.0, pivot - x)
      

      那么 numpy 应用的检查将始终产生浮点结果,并且不会应用舍入。

      【讨论】:

        猜你喜欢
        • 2022-01-13
        • 2018-03-07
        • 2015-12-24
        • 2016-09-01
        • 1970-01-01
        • 2011-10-09
        • 1970-01-01
        • 2017-08-11
        • 2016-05-02
        相关资源
        最近更新 更多