在金融和强化学习中,一个常见的术语是基于原始奖励时间序列
在python中,使用numpy数组计算这个值的一种数值稳定的方法可能是:
R[i]
的折扣累积奖励C[i]
。给定数组R
,我们想要计算满足递归关系C[i] = R[i] + discount * C[i+1]
(其中C[-1] = R[-1]
)的C[i]
,并返回完整的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循环。考虑到这是如此常见的计算,肯定有一些现有的利用其他标准函数的矢量化解决方案,而无需采用cython化。
请注意,任何使用类似np.power(discount,np.arange(len(rewards))
的解决方案都不稳定。