Collector#

From its literal meaning, we can easily know that the Collector in Tianshou is used to collect training data. More specifically, the Collector controls the interaction between Policy (agent) and the environment. It also helps save the interaction data into the ReplayBuffer and returns episode statistics.

Usages#

Collector can be used both for training (data collecting) and evaluation in Tianshou.

Policy evaluation#

We need to evaluate our trained policy from time to time in DRL experiments. Collector can help us with this.

First we have to initialize a Collector with an (vectorized) environment and a given policy (agent).

Hide code cell content
%%capture

import gymnasium as gym
import torch

from tianshou.data import Collector, CollectStats, VectorReplayBuffer
from tianshou.env import DummyVectorEnv
from tianshou.policy import PGPolicy
from tianshou.utils.net.common import Net
from tianshou.utils.net.discrete import Actor
env = gym.make("CartPole-v1")
test_envs = DummyVectorEnv([lambda: gym.make("CartPole-v1") for _ in range(2)])

# model
assert env.observation_space.shape is not None  # for mypy
net = Net(
    env.observation_space.shape,
    hidden_sizes=[
        16,
    ],
)

assert isinstance(env.action_space, gym.spaces.Discrete)  # for mypy
actor = Actor(net, env.action_space.n)
optim = torch.optim.Adam(actor.parameters(), lr=0.0003)

policy: PGPolicy = PGPolicy(
    actor=actor,
    optim=optim,
    dist_fn=torch.distributions.Categorical,
    action_space=env.action_space,
    action_scaling=False,
)
test_collector = Collector[CollectStats](policy, test_envs)

Now we would like to collect 9 episodes of data to test how our initialized Policy performs.

collect_result = test_collector.collect(reset_before_collect=True, n_episode=9)

collect_result.pprint_asdict()
CollectStats
----------------------------------------
{   'collect_speed': 1133.869981775973,
    'collect_time': 0.12611675262451172,
    'lens': array([10, 16, 11, 10, 21, 13, 23, 19, 20]),
    'lens_stat': {   'max': 23.0,
                     'mean': 15.88888888888889,
                     'min': 10.0,
                     'std': 4.771313456351975},
    'n_collected_episodes': 9,
    'n_collected_steps': 143,
    'pred_dist_std_array': array([[0.49406907],
       [0.49421367],
       [0.49355766],
       [0.4936427 ],
       [0.4940113 ],
       [0.49299672],
       [0.4935033 ],
       [0.49211603],
       [0.49293178],
       [0.49096006],
       [0.49204728],
       [0.49199876],
       [0.49284625],
       [0.4908641 ],
       [0.4931845 ],
       [0.49184778],
       [0.49338797],
       [0.49077165],
       [0.4930141 ],
       [0.4890565 ],
       [0.49332637],
       [0.49407542],
       [0.49309656],
       [0.49369633],
       [0.4926156 ],
       [0.4927934 ],
       [0.49170285],
       [0.49192828],
       [0.4925008 ],
       [0.49077272],
       [0.4927172 ],
       [0.48905253],
       [0.4935629 ],
       [0.4871627 ],
       [0.49304742],
       [0.48511705],
       [0.49361506],
       [0.48695695],
       [0.49310172],
       [0.48489454],
       [0.49238616],
       [0.48674485],
       [0.4909152 ],
       [0.49345112],
       [0.49266317],
       [0.49324217],
       [0.49351743],
       [0.4924816 ],
       [0.49406433],
       [0.4916178 ],
       [0.49392474],
       [0.49069357],
       [0.49401677],
       [0.4891657 ],
       [0.4940199 ],
       [0.48730174],
       [0.49397275],
       [0.4852839 ],
       [0.49405167],
       [0.48311332],
       [0.49393216],
       [0.4807926 ],
       [0.49408674],
       [0.49376202],
       [0.49389473],
       [0.49342015],
       [0.49339956],
       [0.49249953],
       [0.49261275],
       [0.4933501 ],
       [0.49155962],
       [0.4935404 ],
       [0.49287945],
       [0.4933418 ],
       [0.49425682],
       [0.49248412],
       [0.49376616],
       [0.4932528 ],
       [0.49286452],
       [0.49332562],
       [0.4920128 ],
       [0.4932278 ],
       [0.49284792],
       [0.49243045],
       [0.49198005],
       [0.49312252],
       [0.49087304],
       [0.49238437],
       [0.48917425],
       [0.49147534],
       [0.48729664],
       [0.49231103],
       [0.48526436],
       [0.49138707],
       [0.48709923],
       [0.49012822],
       [0.48882908],
       [0.49126098],
       [0.48692462],
       [0.49000832],
       [0.49396434],
       [0.48820063],
       [0.49346548],
       [0.48624024],
       [0.49294826],
       [0.48412848],
       [0.49362025],
       [0.48602298],
       [0.4941634 ],
       [0.49373534],
       [0.49365357],
       [0.49322885],
       [0.4941142 ],
       [0.4926425 ],
       [0.4936194 ],
       [0.49103147],
       [0.49416253],
       [0.4929257 ],
       [0.49366915],
       [0.4936441 ],
       [0.49420804],
       [0.4941855 ],
       [0.4936791 ],
       [0.49369267],
       [0.49302998],
       [0.4942321 ],
       [0.49217302],
       [0.49374127],
       [0.49125436],
       [0.4931987 ],
       [0.48971233],
       [0.49159363],
       [0.48789445],
       [0.48985338],
       [0.48959094],
       [0.491976  ],
       [0.4877644 ],
       [0.49019292],
       [0.4923368 ],
       [0.49054736],
       [0.49267867],
       [0.4909187 ],
       [0.49300408]], dtype=float32),
    'pred_dist_std_array_stat': {   0: {   'max': 0.4942568242549896,
                                           'mean': 0.4917278587818146,
                                           'min': 0.4807926118373871,
                                           'std': 0.002653212286531925}},
    'returns': array([10., 16., 11., 10., 21., 13., 23., 19., 20.]),
    'returns_stat': {   'max': 23.0,
                        'mean': 15.88888888888889,
                        'min': 10.0,
                        'std': 4.771313456351975}}

Now we wonder what is the performance of a random policy.

# Reset the collector
collect_result = test_collector.collect(reset_before_collect=True, n_episode=9, random=True)

collect_result.pprint_asdict()
CollectStats
----------------------------------------
{   'collect_speed': 3173.513120190605,
    'collect_time': 0.0740504264831543,
    'lens': array([10, 15, 34, 39, 14, 62, 26, 20, 15]),
    'lens_stat': {   'max': 62.0,
                     'mean': 26.11111111111111,
                     'min': 10.0,
                     'std': 15.659178667580552},
    'n_collected_episodes': 9,
    'n_collected_steps': 235,
    'pred_dist_std_array': None,
    'pred_dist_std_array_stat': None,
    'returns': array([10., 15., 34., 39., 14., 62., 26., 20., 15.]),
    'returns_stat': {   'max': 62.0,
                        'mean': 26.11111111111111,
                        'min': 10.0,
                        'std': 15.659178667580552}}

It seems like an initialized policy performs even worse than a random policy without any training.

Data Collecting#

Data collecting is mostly used during training, when we need to store the collected data in a ReplayBuffer.

train_env_num = 4
buffer_size = 100
train_envs = DummyVectorEnv([lambda: gym.make("CartPole-v1") for _ in range(train_env_num)])
replayBuffer = VectorReplayBuffer(buffer_size, train_env_num)

train_collector = Collector[CollectStats](policy, train_envs, replayBuffer)

Now we can collect 50 steps of data, which will be automatically saved in the replay buffer. You can still choose to collect a certain number of episodes rather than steps. Try it yourself.

train_collector.reset()
replayBuffer.reset()

print(f"Replay buffer before collecting is empty, and has length={len(replayBuffer)} \n")
n_step = 50
collect_result = train_collector.collect(n_step=n_step)
print(
    f"Replay buffer after collecting {n_step} steps has length={len(replayBuffer)}.\n"
    f"This may exceed n_step when it is not a multiple of train_env_num because of vectorization.\n",
)
collect_result.pprint_asdict()
Replay buffer before collecting is empty, and has length=0 

Replay buffer after collecting 50 steps has length=52.
This may exceed n_step when it is not a multiple of train_env_num because of vectorization.

CollectStats
----------------------------------------
{   'collect_speed': 1887.6092258427452,
    'collect_time': 0.02754807472229004,
    'lens': array([11, 12]),
    'lens_stat': {'max': 12.0, 'mean': 11.5, 'min': 11.0, 'std': 0.5},
    'n_collected_episodes': 2,
    'n_collected_steps': 52,
    'pred_dist_std_array': array([[0.49440366],
       [0.4942626 ],
       [0.49407572],
       [0.49458516],
       [0.49412194],
       [0.49387056],
       [0.49360237],
       [0.4941497 ],
       [0.49343494],
       [0.49423024],
       [0.49295923],
       [0.4946387 ],
       [0.4926048 ],
       [0.49381256],
       [0.49208936],
       [0.49424577],
       [0.4917139 ],
       [0.49419692],
       [0.4928998 ],
       [0.49461406],
       [0.4925402 ],
       [0.49377418],
       [0.49201456],
       [0.49426386],
       [0.491629  ],
       [0.4941625 ],
       [0.49281693],
       [0.49328262],
       [0.49014273],
       [0.49373308],
       [0.49191663],
       [0.4942043 ],
       [0.48835486],
       [0.4933056 ],
       [0.49094722],
       [0.49327227],
       [0.4864157 ],
       [0.49362525],
       [0.48927295],
       [0.49413052],
       [0.48819357],
       [0.4932467 ],
       [0.4874154 ],
       [0.49324772],
       [0.4935793 ],
       [0.49350944],
       [0.48541012],
       [0.49239773],
       [0.4930698 ],
       [0.49367538],
       [0.49388155],
       [0.49119055]], dtype=float32),
    'pred_dist_std_array_stat': {   0: {   'max': 0.49463871121406555,
                                           'mean': 0.49263718724250793,
                                           'min': 0.4854101240634918,
                                           'std': 0.002138425363227725}},
    'returns': array([11., 12.]),
    'returns_stat': {'max': 12.0, 'mean': 11.5, 'min': 11.0, 'std': 0.5}}
/home/docs/checkouts/readthedocs.org/user_builds/tianshou/checkouts/latest/tianshou/data/collector.py:509: UserWarning: n_step=50 is not a multiple of (self.env_num=4), which may cause extra transitions being collected into the buffer.
  warnings.warn(

Sample some data from the replay buffer.

replayBuffer.sample(10)
(Batch(
     obs: array([[-0.04319579,  0.15533724,  0.00517449, -0.2547591 ],
                 [ 0.03637407, -0.22514977,  0.02790066,  0.34702203],
                 [-0.02184147,  0.17497005, -0.06999612, -0.42613947],
                 [-0.03078246,  0.17026691, -0.04417668, -0.32173207],
                 [ 0.00565242, -0.0254684 , -0.02920871,  0.02911519],
                 [-0.00180642,  0.01240959, -0.01173507, -0.01358001],
                 [ 0.00565242, -0.0254684 , -0.02920871,  0.02911519],
                 [ 0.06281417,  0.7975427 , -0.1120344 , -1.2932065 ],
                 [-0.03357646,  0.3917173 ,  0.03126138, -0.4496251 ],
                 [-0.02574212,  0.19616745,  0.02226888, -0.14725429]],
                dtype=float32),
     act: array([1, 1, 1, 0, 0, 1, 0, 1, 0, 1]),
     rew: array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]),
     terminated: array([False, False, False, False, False, False, False, False, False,
                        False]),
     truncated: array([False, False, False, False, False, False, False, False, False,
                       False]),
     done: array([False, False, False, False, False, False, False, False, False,
                  False]),
     obs_next: array([[-4.0089048e-02,  3.5038492e-01,  7.9305108e-05, -5.4580539e-01],
                      [ 3.1871069e-02, -3.0435557e-02,  3.4841102e-02,  6.3266106e-02],
                      [-1.8342072e-02,  3.7101001e-01, -7.8518912e-02, -7.4004143e-01],
                      [-2.7377117e-02, -2.4199015e-02, -5.0611313e-02, -4.3301485e-02],
                      [ 5.1430473e-03, -2.2015956e-01, -2.8626403e-02,  3.1244123e-01],
                      [-1.5582271e-03,  2.0769785e-01, -1.2006673e-02, -3.0994228e-01],
                      [ 5.1430473e-03, -2.2015956e-01, -2.8626403e-02,  3.1244123e-01],
                      [ 7.8765020e-02,  9.9389595e-01, -1.3789853e-01, -1.6187592e+00],
                      [-2.5742117e-02,  1.9616745e-01,  2.2268880e-02, -1.4725429e-01],
                      [-2.1818768e-02,  3.9096355e-01,  1.9323794e-02, -4.3282947e-01]],
                     dtype=float32),
     info: Batch(
               env_id: array([0, 0, 1, 1, 2, 2, 2, 2, 3, 3]),
           ),
     policy: Batch(),
 ),
 array([ 1, 12, 32, 26, 62, 50, 62, 58, 83, 84]))

Further Reading#

The above collector actually collects 52 data at a time because 52 % 4 = 0. There is one asynchronous collector which allows you collect exactly 50 steps. Check the documentation for details.