NumPy vectorize()或dot()似乎有问题 [英] NumPy vectorize() or dot() appears buggy

查看:145
本文介绍了NumPy vectorize()或dot()似乎有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,y1和y2应该相等,但不相等. vectorize()或dot()可能存在错误吗?

In the code below, y1 and y2 ought to be equal but they aren't. Could there be a bug in vectorize() or dot()?

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的图形:

Graphs of y1 and y2:

推荐答案

为了应用正确的转换规则,numpy偶尔将您的函数与前哨值(numpy.int64)一起使用,以检查其输出的数据类型(如果输出的是整数0,因为那是max返回的,则它假定计算结果应全部为整数,并对其他结果进行四舍五入,但是,如果将函数更改为始终通过在max中使用0.0返回浮点数,则: >

In order to apply proper casting rules numpy uses your function occasionally with sentinel values (numpy.int64) to check what kind of data it outputs, if it outputs the integer 0 because thats what max returned then it assumes the result of the calculation should all be integers and rounds the other results off, however if you change the function to always return floats by using 0.0 in max:

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

然后,对numpy应用的检查将始终导致浮点结果,并且不应用四舍五入.

Then the checks that numpy applies will always result in float results and no rounding will be applied.

这篇关于NumPy vectorize()或dot()似乎有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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