我正在尝试将强化学习连续动作值
range(-1.0,1.0)
映射到实际输出。
假设我有 numpy 动作数组
actions = np.array([-1., 0.2, -0.3, 0.5])
。数组的值可能是 actions.min = -1.
和 actions.max = 1.
。
现在,我需要将每个条目映射到单独的范围
所以,映射行动
mapped_actions = np.array([-0.4, 1.484, -0.86, -0.085])
我目前的解决方案如下:
import numpy as np
actions = np.array([-1., 0.2, -0.3, 0.5])
mapped_low_high = np.array([[-0.4, 1.54], [1.4, 1.54],[-2.4, 2.], [-1.54, 0.4]])
mapped_actions = np.zeros_like(actions)
for i in range(actions.shape[0]):
mapped_actions[i] = np.interp(actions[i], (-1., 1.), mapped_low_high[i])
使用 numpy 数组循环很慢。编写可以一次对整个数组进行操作的向量化函数会更快。由于我们知道给定的数组始终在 -1 和 1 之间,并且我们有一个新范围的数组,因此代码是一个简单的函数,可从一个范围重新映射到另一个范围。一般技术是将原始数据重新映射到
[0, 1]
,然后将其重新映射到 [a, b]
。
import numpy as np
actions = np.array([-1., 0.2, -0.3, 0.5])
mapped_low_high = np.array([[-0.4, 1.54],
[1.4, 1.54],
[-2.4, 2.],
[-1.54, 0.4]])
def remap(arr, mappings):
out = arr.copy()
a, b = mappings.T
# remap out to 0 to 1
# assumes arr is [-1,1]
out += 1.
out /= 2.
# remap out from a to b
out *= b - a
out += a
return out
remapped = remap(actions, mapped_low_high) # array([-0.4 , 1.484, -0.86 , -0.085])