我注意到在使用 tf_agents.environments.TFPyEnvironment 将 Python 环境转换为 TF 环境时发生了一些奇怪的事情,我想问你发生了哪些一般性变化。
为了澄清这个问题,请在我的代码下面找到。我希望环境模拟(以一种过于简单的方式)与想要购买水果或蔬菜的顾客的互动。代理应该知道,当客户要水果时,例如应该执行动作 0。
class CustomEnv(py_environment.PyEnvironment):
def __init__(self):
self._action_spec = array_spec.BoundedArraySpec(
shape=(), dtype=np.int32, minimum=0, maximum=1)
self._observation_spec = array_spec.BoundedArraySpec(
shape=(1,1), dtype=np.int32, minimum=0, maximum=1)
self._state = [0]
self._counter = 0
self._episode_ended = False
self.dictionary = {0: ["Fruits"],
1: ["Vegetables"]}
def action_spec(self):
return self._action_spec
def observation_spec(self):
return self._observation_spec
def _reset(self):
self._state = [0]
self._counter = 0
self._episode_ended = False
return ts.restart(np.array([self._state], dtype=np.int32))
def preferences(self):
return np.random.randint(2)
def pickedBasket(self, yes):
reward = -1.0
if yes:
reward = 0.0
return reward
def _step(self, action):
if self._episode_ended:
self._reset()
if self._counter<50:
self._counter += 1
basket = self.preferences()
condition = basket in self.dictionary[action]
reward = self.pickedBasket(condition)
self._state[0] = basket
if self._counter==50:
self._episode_ended=True
return ts.termination(np.array([self._state],
dtype=np.int32),
reward,
1)
else:
return ts.transition(np.array([self._state],
dtype=np.int32),
reward,
discount=1.0)
当我执行以下代码以检查一切是否正常时:
py_env = ContextualMBA()
tf_env = tf_py_environment.TFPyEnvironment(py_env)
time_step = tf_env.reset()
action = 0
next_time_step = tf_env.step(action)
我得到了一个不可散列的类型:'numpy.ndarray',condition = basket in self.dictionary[action]
所以我把它改成了它condition = basket in self.dictionary[int(action)]
,它工作得很好。我还想准确地说,即使不添加int
部件,它也可以作为 Python 环境工作。所以我想问一下tf_agents.environments.TFPyEnvironment有什么变化。我看不出它如何影响动作的类型,action
因为它与action_spec
任何东西无关(至少直接在代码中)。