Package: rlmodels
rlmodels: a reinforcement learning libraryThis project is a collection of some popular optimisation algorithms for reinforcement learning problem. At the moment the available models are:DQNDDPGCMAESACwith some more going to be added in the future.It works with Pytorch models and environment classes like the OpenAI gym ones. Any environment class wrapper that mimic their basic functionality should be fine, but more on that below.Getting StartedPrerequisitesThe project usespython >= 3.6,torch 1.1.0and relies on OpenAI'sgymenvironments.InstallingIt can be installed directly from pip likepipinstallrlmodelsUsageBelow is a summary of how the program works.To see the full documentation clickhereInitializationThe following is an example with the popular CartPole environment using a double Q network. First the setup.importnumpyasnpimporttorchimporttorch.optimasoptimimportgymfromrlmodels.models.DQNimport*fromrlmodels.netsimportFullyConnectedimportlogging#logger parametersFORMAT='%(asctime)-15s:%(message)s'logging.basicConfig(level=logging.INFO,format=FORMAT,filename="model_fit.log",filemode="a")max_ep_ts=200env=gym.make('CartPole-v0')env._max_episode_steps=max_ep_tsenv.seed(1)np.random.seed(1)torch.manual_seed(1)the episode and timepstep numbers as well as the average reward trace is logged to the filemodel_fit.log. Setting the logging level tologging.DEBUGwill also log information about gradient descent steps.The library also has a basic network definition, FullyConnected, to which we only need to specify number and size of hidden layer, input and output sizes, and last activation function. It uses ReLU everywhere else by default.let's create the basic objectsdqn_scheduler=DQNScheduler(batch_size=lambdat:200,#constantexploration_rate=lambdat:max(0.01,0.05-0.01*int(t/2500)),#decrease exploration down to 1% after 10,000 stepsPER_alpha=lambdat:1,#constantPER_beta=lambdat:1,#constanttau=lambdat:100,#constantagent_lr_scheduler_fn=lambdat:1.25**(-int(t/1000)),#decrease step size every 2,500 steps,steps_per_update=lambdat:1)#constantagent_lr=0.5#initial learning rateagent_model=FullyConnected([60],4,2,None)agent_opt=optim.SGD(agent_model.parameters(),lr=agent_lr,weight_decay=0,momentum=0)agent=Agent(agent_model,agent_opt)the models take a scheduler object as argument which allows parameters to be changed at runtime accordint to user-defined rules. For example reducing learning rate and exploration rate after a certain number of iterations, as above. Finally, all gradient-based algorithms receive as input anAgentinstance that contains the network deffinition and optimisation algorithm. Once all this is setup we are good to go.dqn=DQN(agent,env,dqn_scheduler)dqn.fit(n_episodes=170,max_ts_by_episode=max_ep_ts,max_memory_size=2000,td_steps=1)Once the agent is trained we can visualize the reward trace. If we are using an environment with a render method (like OpenAI ones) we can also visualise the trained agent. We can also use the trained model using theforwardmethod of theddqobject or simply extract it withddq.agentdqn.plot()#plot reward tracesdqn.play(n=200)#observe the agent playsee theexamplefolder for an analogous use of the other algorithms.EnvironmentFor custom environments or custom rewards, its possible to make a wrapper tha mimics te behavior of the step() and reset() function of gym's environemntsclassMyCustomEnv(object):def__init__(self,env):self.env=envdefstep(self,action):## get next state s, reward, termination flag (boolean) and any additional inforeturns,r,terminated,info#need to output these 4 things (info can be None)defreset(self):#somethingdefseed(self):#something