【问题标题】:Vectorize a numpy discount calculation向量化一个 numpy 折扣计算
【发布时间】:2017-12-25 17:23:25
【问题描述】:

金融和强化学习中的一个常用术语是基于原始奖励时间序列R[i] 的折扣累积奖励C[i]。给定一个数组R,我们想计算C[i],满足C[i] = R[i] + discount * C[i+1]和C[-1] = R[-1]的递归(并返回完整的数组C)。

在 python 中使用 numpy 数组计算它的数值稳定方法可能是:

import numpy as np
def cumulative_discount(rewards, discount):
    future_cumulative_reward = 0
    assert np.issubdtype(rewards.dtype, np.floating), rewards.dtype
    cumulative_rewards = np.empty_like(rewards)
    for i in range(len(rewards) - 1, -1, -1):
        cumulative_rewards[i] = rewards[i] + discount * future_cumulative_reward
        future_cumulative_reward = cumulative_rewards[i]
    return cumulative_rewards

但是,这依赖于 python 循环。鉴于这是一个如此常见的计算,肯定有一个现有的矢量化解决方案,它依赖于一些其他标准函数,而不诉诸 cythonization。

请注意,任何使用 np.power(discount, np.arange(len(rewards)) 之类的解决方案都不会稳定。

【问题讨论】:

  • @CrazyIvan 同意,我有点马虎,会解决的。
  • @CrazyIvan 哦,那是另一个错误,你回答正确,但我没有问我想要的问题。对于那个很抱歉。 (我已经修改了问题;for 循环仍然是应该被矢量化的同一个循环)。

标签: python numpy recursion


【解决方案1】:

你可以使用scipy.signal.lfilter来解决递归关系:

def alt(rewards, discount):
    """
    C[i] = R[i] + discount * C[i+1]
    signal.lfilter(b, a, x, axis=-1, zi=None)
    a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M]
                          - a[1]*y[n-1] - ... - a[N]*y[n-N]
    """
    r = rewards[::-1]
    a = [1, -discount]
    b = [1]
    y = signal.lfilter(b, a, x=r)
    return y[::-1]

此脚本测试结果是否相同:

import scipy.signal as signal
import numpy as np

def orig(rewards, discount):
    future_cumulative_reward = 0
    cumulative_rewards = np.empty_like(rewards, dtype=np.float64)
    for i in range(len(rewards) - 1, -1, -1):
        cumulative_rewards[i] = rewards[i] + discount * future_cumulative_reward
        future_cumulative_reward = cumulative_rewards[i]
    return cumulative_rewards

def alt(rewards, discount):
    """
    C[i] = R[i] + discount * C[i+1]
    signal.lfilter(b, a, x, axis=-1, zi=None)
    a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M]
                          - a[1]*y[n-1] - ... - a[N]*y[n-N]
    """
    r = rewards[::-1]
    a = [1, -discount]
    b = [1]
    y = signal.lfilter(b, a, x=r)
    return y[::-1]

# test that the result is the same
np.random.seed(2017)

for i in range(100):
    rewards = np.random.random(10000)
    discount = 1.01
    expected = orig(rewards, discount)
    result = alt(rewards, discount)
    if not np.allclose(expected,result):
        print('FAIL: {}({}, {})'.format('alt', rewards, discount))
        break

【讨论】:

  • 哇,这很好。对于这种特殊情况,它是否归结为相同的数值计算?
  • 是的,我相信是的。定义lfilter的C代码可以是found here。
  • 确实,this function 确认了这一点。 (顺便说一句,在这些情况下,折扣通常
  • 仅供参考,快速检查%timeit orig(np.ones(1000), 0.95) 与 alt(np.ones(1000), 0.95) 告诉我每个循环(原始)295 µs ± 6.29 µs 和每个循环(alt)11.5 µs ± 28.7 ns,所以方法在性能方面似乎做得很好。
【解决方案2】:

您描述的计算称为Horner's rule 或霍纳的多项式求值方法。它在 NumPy polynomial.polyval 中实现。

但是,您需要整个 cumulative_rewards 列表,即霍纳规则的所有中间步骤。 NumPy 方法不返回那些中间值。用 Numba 的 @jit 装饰的函数可能是最佳选择。

作为一种理论上的可能性,我会指出polyval 可以返回整个列表,如果给定一个Hankel matrix 的系数。这是矢量化的,但最终的效率低于 Python 循环,因为累积奖励的每个值都是从头开始计算的,独立于其他值。

from numpy.polynomial.polynomial import polyval
from scipy.linalg import hankel

rewards = np.random.uniform(10, 100, size=(100,))
discount = 0.9
print(polyval(discount, hankel(rewards)))

这匹配

的输出
print(cumulative_discount(rewards, discount))

【讨论】:

  • 好吧,就像你说的 polyval 在这里还不够,因为我们对整个数组感兴趣。我接受它是因为您建议 Numba 对我最初的问题的答案是否定的?
【解决方案3】:

如果您想要一个仅限 numpy 的解决方案,请选择这个(从 unutbu 的答案中借用结构):

def alt2(rewards, discount):
    tmp = np.arange(rewards.size)
    tmp = tmp - tmp[:, np.newaxis]
    w = np.triu(discount ** tmp.clip(min=0)).T
    return (rewards.reshape(-1, 1) * w).sum(axis=0)

下面的证明。

import numpy as np

def orig(rewards, discount):
    future_cumulative_reward = 0
    cumulative_rewards = np.empty_like(rewards, dtype=np.float64)
    for i in range(len(rewards) - 1, -1, -1):
        cumulative_rewards[i] = rewards[i] + discount * future_cumulative_reward
        future_cumulative_reward = cumulative_rewards[i]
    return cumulative_rewards

def alt2(rewards, discount):
    tmp = np.arange(rewards.size)
    tmp = tmp - tmp[:, np.newaxis]
    w = np.triu(discount ** tmp.clip(min=0)).T
    return (rewards.reshape(-1, 1) * w).sum(axis=0)

# test that the result is the same
np.random.seed(2017)

for i in range(100):
    rewards = np.random.random(100)
    discount = 1.01
    expected = orig(rewards, discount)
    result = alt2(rewards, discount)
    if not np.allclose(expected,result):
        print('FAIL: {}({}, {})'.format('alt', rewards, discount))
        break
else:
    print('success')

但是,此解决方案不能很好地扩展到大型奖励数组,但您仍然可以使用跨步技巧来解决问题,as pointed out here。

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多