<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Antonio Lisi on Medium]]></title>
        <description><![CDATA[Stories by Antonio Lisi on Medium]]></description>
        <link>https://medium.com/@antonai91?source=rss-4bba14bd6b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7jj1lRss90gVfbUquCKrNw.jpeg</url>
            <title>Stories by Antonio Lisi on Medium</title>
            <link>https://medium.com/@antonai91?source=rss-4bba14bd6b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:31:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@antonai91/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Accelerating Tensorflow using M1 Chip — The Antonai Blog]]></title>
            <link>https://medium.com/analytics-vidhya/accelerating-tensorflow-using-m1-chip-the-antonai-blog-2a4388e3bd36?source=rss-4bba14bd6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a4388e3bd36</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[m1-chip]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[m1-mac]]></category>
            <dc:creator><![CDATA[Antonio Lisi]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 21:00:01 GMT</pubDate>
            <atom:updated>2022-02-25T17:05:30.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>Accelerating Tensorflow using M1 Chip — The Antonai Blog</h3><h3>An installation guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*bXm11gaofkcoev2e" /></figure><p><em>by Antonio Lisi</em></p><h3>Introduction</h3><p>Hello everyone, and welcome back to another data science blog post. Today we’re going to talk about the M1 chip and how to use it to accelerate Tensorflow.</p><p>Last spring, I decided to finally buy an M1 MacBook air. Apple really did the trick with this machine. It is perfect for everyday use, has great battery life, no fan noise, and its speed is astonishing.</p><p>But I’m not just a casual user. I want to use my laptop for light programming tasks and prototyping in the data science field.</p><p>I was able to use it for everything, but installing Tensorflow with the native support for the M1 chip was not so straightforward. So I thought that an installation guide can be useful to others that like me want to use Tensorflow to exploit the M1 GPU capabilities.</p><h3>Official Apple Guide</h3><p>You can find the official Apple instructions <a href="https://developer.apple.com/metal/tensorflow-plugin/">here</a>. So first of all we need to have the latest beta version of macOS 12. You can find the instructions to join the Apple Beta Software Program <a href="https://beta.apple.com/sp/betaprogram/enroll">here</a>.</p><p>Then we need to download and install miniconda for MacOS from <a href="https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh">here</a>. Once installed make sure to have the conda command linked to the one that you just downloaded.</p><p>So we’re going to create a virtual environment called tensorflow_m1:</p><pre>conda create --name tensorflow_m1</pre><p>Now we can activate the environment just created:</p><pre>conda activate tensorflow_m1</pre><p>You should always create a virtual environment before installing something new and/or starting a new project. It’s a good habit and can save you a lot of time in case of screw-ups.</p><p>We can now install tensorflow dependencies:</p><pre>​​conda install -c apple tensorflow-deps==2.5.0</pre><p>We’re specifying here the version just to avoid errors/problems with the newest one.</p><p>We then install tensorflow for MacOS and the tensorflow-metal plugin:</p><pre>python -m pip install tensorflow-macos <br>python -m pip install tensorflow-metal</pre><p>With this, we’ve done from following the official Apple guide. Here are the main issues that I’ve experienced following these steps:</p><ul><li>If you use ​​<em>conda install -c apple tensorflow-deps </em>without the version can result in failing to import tensorflow</li><li>If you don’t have the latest beta version of macOS it doesn’t work at all</li><li>Even following the steps above you can get the error “Importing the numpy c-extensions failed”</li></ul><p>To solve the numpy error. I found this <a href="https://stackoverflow.com/questions/58868528/importing-the-numpy-c-extensions-failed">page</a>, where it explains that you can simply reinstall numpy. So I just typed the following command in the terminal:</p><pre>pip install --upgrade --force-reinstall numpy</pre><h3>Final checks</h3><p>You should be able to accelerate TensorFlow using the M1 chip. To make sure that everything is all right, just type in the terminal (after activating the environment) python. You should get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tHV7PU1j2ax4fYhA" /></figure><p>Now you can import tensorflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mytBIzGco7SYaFtE" /></figure><p>And we can check if it can use the GPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BF-hscpkBkr8BkXj" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PgCMPrdSvKm7tVpn" /></figure><p>And that’s it.</p><p>I hope that you found the guide useful. For any questions, you can reach me through Linkedin.</p><p>If you enjoyed this article, share it with your friends and colleagues! I’ll see you in the next post. In the meantime, take care, stay safe, and remember don’t be another brick in the wall.</p><p>Anton.ai</p><p><em>Originally published at </em><a href="https://antonai.blog/accelerating-tensorflow-using-m1-chip/"><em>https://antonai.blog</em></a><em> on November 22, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a4388e3bd36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/accelerating-tensorflow-using-m1-chip-the-antonai-blog-2a4388e3bd36">Accelerating Tensorflow using M1 Chip — The Antonai Blog</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Agent Reinforcement Learning: OpenAI’s MADDPG]]></title>
            <link>https://medium.com/analytics-vidhya/multi-agent-reinforcement-learning-openais-maddpg-a741c6cf3869?source=rss-4bba14bd6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a741c6cf3869</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Antonio Lisi]]></dc:creator>
            <pubDate>Wed, 12 May 2021 07:34:25 GMT</pubDate>
            <atom:updated>2021-06-16T05:12:25.803Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring MADDPG algorithm from OpeanAI to solve environments with multiple agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*EB1hBAn6EBR8MZ-H" /></figure><p>By Antonio Lisi</p><h3>Intro</h3><p>Hello everyone, we’re coming back to solving reinforcement learning environments after having a little fun exercising with classic deep learning applications.</p><p>Today we’re going to solve an environment with multiple agents using OpenAI’s MADDPG algorithm. This is going to be different and at the same time similar to what we’ve seen so far. With multiple agents we’re adding complexity and computational requirements but, as we’ll see, we’re going to use what we’ve learned solving single-agent environments.</p><p>As always, we’re going to implement everything from scratch using Tensorflow 2. But we’re going to use a lot of the code in the post about <a href="https://antonai.blog/?p=260#more-260">DDPG</a>, given that MADDPG is the multi-agent version of DDPG. So if you didn’t read it, I recommend doing it before going forward.</p><h3>Multi-Agent Environments</h3><p>Most of the developments in the reinforcement learning field have been in single-agent domains. But there are a number of important use cases where multiple agents learn concurrently to coordinate their actions.</p><p>In multi-agent environments due to the continually changing decision-making policies of agents, there’s one major challenge, the non-stationarity of the environment from the perspective of any individual agent.</p><p>Standard RL algorithms aren’t really suited to multi-agent environments. Researchers have proposed different approaches to deal with this non-stationarity, that can be classified in centralized and decentralized architectures.</p><h3>Centralized and Decentralized Architectures</h3><p>In decentralized learning, the agents are trained separately from each other. Every agent has its policy network trained using local observations as inputs. In order to handle nonstationarity, it’s typically used some form of self-play where agents play against their current or previous versions to learn the optimal policy.</p><p>In centralized learning, agents are collectively modeled in some way. <a href="https://arxiv.org/pdf/1706.02275.pdf">Lowe et al. (2017)</a> proposed MADDPG, a multi-agent centralized architecture using the deterministic policy gradient algorithm. This algorithm, based on the actor-critic architecture, has a centralized critic and a decentralized actor. The centralized critic advises on how to update the actor policy looking at the global information. Since each agent has access to the observations and actions of all the other agents through the critic, the policy gradient estimation is conditioned on the policy of the other agents, and therefore the non-stationarity is addressed. During testing, the centralized critic is removed, leaving only the actors, their policies, and local observations.</p><h3>MADDPG</h3><p>MADDPG was proposed by Researchers from OpenAI, UC Berkeley and McGill University in the paper <a href="https://arxiv.org/pdf/1706.02275.pdf">Multi-Agent Actor-Critic for Mixed Cooperative-Competitive Environments by Lowe et al. (2017)</a>. MADDPG is the multi-agent counterpart of the Deep Deterministic Policy Gradients algorithm (DDPG) based on the actor-critic framework.</p><p>While in DDPG, we have just one agent. Here we have multiple agents with their own actor and critic networks. The actor-network takes as input the local observation of the agent and output the recommended action, so nothing new compared to the DDPG actor-network. On the contrary, the critic network takes as input the global observation of the environment, so it takes as input, not just the state of the environment and the agent’s action, but also the local observations and other agents’ actions. The output of the critic network will still be the q-value estimation. So the critic network is only used in the training part to give the actor a global vision to adapt to the global environment and other agents’ actions. In this way, cooperative or competitive strategies can be learned by the actors. Further, since the training of each agent is conditioned on the observation and action of all the other agents, each agent perceives the environment as stationary.</p><p>Like in DDPG, to improve learning stability, we’ll also use a target actor and critic network for every agent with the same soft update mechanism. And like in DDPG, we’re also going to use some noise to improve exploration. Dissimilarly from what we implemented in the <a href="https://antonai.blog/?p=260#more-260">DDPG</a> post, we’re not going to implement an Ornstein-Uhlenbeck process, but we’ll use a simple random noise.</p><h3>Multi-Agent Particle Environment</h3><p>We’re going to solve the same environments used in the paper <a href="https://arxiv.org/pdf/1706.02275.pdf">Multi-Agent Actor-Critic for Mixed Cooperative-Competitive Environments</a>. You can find the python package <a href="https://github.com/openai/multiagent-particle-envs">here</a> with all the instructions on how to install and use it.</p><p>We can start to explore a simple environment to understand how the library works:</p><pre><em>def</em> make_env(scenario_name, benchmark=False):<br>    &#39;&#39;&#39;<br>    Creates a MultiAgentEnv object as env. This can be used similar to a gym<br>    environment by calling env.reset() and env.step().<br>    Use env.render() to view the environment on the screen.<br>    Input:<br>        scenario_name   :   name of the scenario from ./scenarios/ to be Returns<br>                            (without the .py extension)<br>        benchmark       :   whether you want to produce benchmarking data<br>                            (usually only done during evaluation)<br>    Some useful env properties (see environment.py):<br>        .observation_space  :   Returns the observation space for each agent<br>        .action_space       :   Returns the action space for each agent<br>        .n                  :   Returns the number of Agents<br>    &#39;&#39;&#39;<br>    from multiagent.environment import MultiAgentEnv<br>    import multiagent.scenarios as scenarios<br><br>    # load scenario from script<br>    scenario = scenarios.load(scenario_name + &quot;.py&quot;).Scenario()<br>    # create world<br>    world = scenario.make_world()<br>    # create multiagent environment<br>    if benchmark:        <br>        env = MultiAgentEnv(world, scenario.reset_world,     scenario.reward, scenario.observation, scenario.benchmark_data)<br>    else:<br>        env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation)<br>    return env<br><br><br>env = make_env(&quot;simple_adversary&quot;)<br>print(env.action_space)</pre><p><em>[Discrete(5), Discrete(5), Discrete(5)]</em></p><p>We used the make_env function that you can find in the Github repository of the library. As you can see we have three action spaces in the simple adversary environment, so we have three agents that need to output an actions vector with length 5. We can also see the input for the three agents:</p><pre>print(env.observation_space)</pre><p><em>[Box(-inf, inf, (8,), float32), Box(-inf, inf, (10,), float32), Box(-inf, inf, (10,), float32)]</em></p><p>So we have for the first agent an (8,0) continuous input vector and a (10,) continuous input vector for the other two.</p><p>We’re going to use simple adversary as the development environment and then we’re going also to solve simple tag in order to see how our algorithm performs solving a different environment.</p><p>From the documentation:</p><ul><li>Simple adversary: 1 adversary (red), N good agents (green), N landmarks (usually N=2). All agents observe position of landmarks and other agents. One landmark is the ‘target landmark’ (colored green). Good agents rewarded based on how close one of them is to the target landmark, but negatively rewarded if the adversary is close to target landmark. Adversary is rewarded based on how close it is to the target, but it doesn’t know which landmark is the target landmark. So good agents have to learn to ‘split up’ and cover all landmarks to deceive the adversary.</li><li>Simple tag: Predator-prey environment. Good agents (green) are faster and want to avoid being hit by adversaries (red). Adversaries are slower and want to hit good agents. Obstacles (large black circles) block the way.</li></ul><h3>Replay Buffer</h3><p>We start by implementing the replay buffer where we save the states, agents’ actions, rewards, and so on. The code is very similar to the one implemented for DDPG but we need to consider the fact that we have multiple agents so it’s a little different:</p><pre><em>class</em> ReplayBuffer():<br>    <em>def</em> __init__(self, env, buffer_capacity=BUFFER_CAPACITY, batch_size=BATCH_SIZE, min_size_buffer=MIN_SIZE_BUFFER):<br>        self.buffer_capacity = buffer_capacity<br>        self.batch_size = batch_size<br>        self.min_size_buffer = min_size_buffer<br>        self.buffer_counter = 0<br>        self.n_games = 0<br>        self.n_agents = env.n<br>        self.list_actors_dimension = [env.observation_space[index].shape[0] for index in <em>range</em>(self.n_agents)]<br>        self.critic_dimension = <em>sum</em>(self.list_actors_dimension)        <br>        self.list_actor_n_actions = [env.action_space[index].n for index in <em>range</em>(self.n_agents)]<br>        <br>        self.states = np.zeros((self.buffer_capacity, self.critic_dimension))<br>        self.rewards = np.zeros((self.buffer_capacity, self.n_agents))<br>        self.next_states = np.zeros((self.buffer_capacity, self.critic_dimension))<br>        self.dones = np.zeros((self.buffer_capacity, self.n_agents), dtype=<em>bool</em>)<br><br>        self.list_actors_states = []<br>        self.list_actors_next_states = []<br>        self.list_actors_actions = []<br>        <br>        for n in <em>range</em>(self.n_agents):<br>            self.list_actors_states.append(np.zeros((self.buffer_capacity, self.list_actors_dimension[n])))<br>            self.list_actors_next_states.append(np.zeros((self.buffer_capacity, self.list_actors_dimension[n])))<br>            self.list_actors_actions.append(np.zeros((self.buffer_capacity, self.list_actor_n_actions[n])))</pre><p>We’re initializing lists of NumPy vectors to store all the states and actions of the multiple agents, while we’re using single NumPy vectors for the global states and rewards.</p><pre><em>    def</em> __len__(self):<br>        return self.buffer_counter<br>        <br>    <em>def</em> check_buffer_size(self):<br>        return self.buffer_counter &gt;= self.batch_size and self.buffer_counter &gt;= self.min_size_buffer<br>    <br>    <em>def</em> update_n_games(self):<br>        self.n_games += 1<br>          <br>    <em>def</em> add_record(self, actor_states, actor_next_states, actions, state, next_state, reward, done):<br>        <br>        index = self.buffer_counter % self.buffer_capacity<br><br>        for agent_index in <em>range</em>(self.n_agents):<br>            self.list_actors_states[agent_index][index] = actor_states[agent_index]<br>            self.list_actors_next_states[agent_index][index] = actor_next_states[agent_index]<br>            self.list_actors_actions[agent_index][index] = actions[agent_index]<br><br>        self.states[index] = state<br>        self.next_states[index] = next_state<br>        self.rewards[index] = reward<br>        self.dones[index] = done<br>            <br>        self.buffer_counter += 1</pre><p>The add_record function needs to take care of the fact that we have multiple agents, so we’re using a for-cycle in order to update the states and actions inside the list that we initialized before. In the multiagent-particle-envs the agents identified by numbers, so we can just use lists and indexes. There are other multi-agent environments where every agent has a name, in that case, we should just use some dictionary instead of lists using the names as keys.</p><pre><em>    def</em> get_minibatch(self):<br>        # If the counter is less than the capacity we don&#39;t want to take zeros records, <br>        # if the cunter is higher we don&#39;t access the record using the counter <br>        # because older records are deleted to make space for new one<br>        buffer_range = <em>min</em>(self.buffer_counter, self.buffer_capacity)<br><br>        batch_index = np.random.choice(buffer_range, self.batch_size, replace=False)<br><br>        # Take indices<br>        state = self.states[batch_index]<br>        reward = self.rewards[batch_index]<br>        next_state = self.next_states[batch_index]<br>        done = self.dones[batch_index]<br>            <br>        actors_state = [self.list_actors_states[index][batch_index] for index in <em>range</em>(self.n_agents)]<br>        actors_next_state = [self.list_actors_next_states[index][batch_index] for index in <em>range</em>(self.n_agents)]<br>        actors_action = [self.list_actors_actions[index][batch_index] for index in <em>range</em>(self.n_agents)]<br><br>        return state, reward, next_state, done, actors_state, actors_next_state, actors_action<br>    <br>    <em>def</em> save(self, folder_path):<br>        &quot;&quot;&quot;<br>        Save the replay buffer<br>        &quot;&quot;&quot;<br>        if not os.path.isdir(folder_path):<br>            os.mkdir(folder_path)<br>        <br>        np.save(folder_path + &#39;/states.npy&#39;, self.states)<br>        np.save(folder_path + &#39;/rewards.npy&#39;, self.rewards)<br>        np.save(folder_path + &#39;/next_states.npy&#39;, self.next_states)<br>        np.save(folder_path + &#39;/dones.npy&#39;, self.dones)<br>        <br>        for index in <em>range</em>(self.n_agents):<br>            np.save(folder_path + &#39;/states_actor_{}.npy&#39;.<em>format</em>(index), self.list_actors_states[index])<br>            np.save(folder_path + &#39;/next_states_actor_{}.npy&#39;.<em>format</em>(index), self.list_actors_next_states[index])<br>            np.save(folder_path + &#39;/actions_actor_{}.npy&#39;.<em>format</em>(index), self.list_actors_actions[index])<br>            <br>        dict_info = {&quot;buffer_counter&quot;: self.buffer_counter, &quot;n_games&quot;: self.n_games}<br>        <br>        with <em>open</em>(folder_path + &#39;/dict_info.json&#39;, &#39;w&#39;) as f:<br>            json.dump(dict_info, f)<br>            <br>    <em>def</em> load(self, folder_path):<br>        self.states = np.load(folder_path + &#39;/states.npy&#39;)<br>        self.rewards = np.load(folder_path + &#39;/rewards.npy&#39;)<br>        self.next_states = np.load(folder_path + &#39;/next_states.npy&#39;)<br>        self.dones = np.load(folder_path + &#39;/dones.npy&#39;)<br>        <br>        self.list_actors_states = [np.load(folder_path + &#39;/states_actor_{}.npy&#39;.<em>format</em>(index)) for index in <em>range</em>(self.n_agents)]<br>        self.list_actors_next_states = [np.load(folder_path + &#39;/next_states_actor_{}.npy&#39;.<em>format</em>(index)) for index in <em>range</em>(self.n_agents)]<br>        self.list_actors_actions = [np.load(folder_path + &#39;/actions_actor_{}.npy&#39;.<em>format</em>(index)) for index in <em>range</em>(self.n_agents)]<br>        <br>        with <em>open</em>(folder_path + &#39;/dict_info.json&#39;, &#39;r&#39;) as f:<br>            dict_info = json.load(f)<br>        self.buffer_counter = dict_info[&quot;buffer_counter&quot;]<br>        self.n_games = dict_info[&quot;n_games&quot;]</pre><p>Then we have the get_minibatch and save/load functions, they’re very similar to the single-agent version, but we’re always using lists and indexes to get and save/load the observations regarding the agents.</p><h3>Networks</h3><p>We need to implement an Actor and a Critic for every agent, here we can just use the same code implemented for DDPG, the logic is the same but the states input for the Critic will not be the same of the Actor like in the single-agent counterpart:</p><pre><em>class</em> Critic(tf.keras.Model):<br>    <em>def</em> __init__(self, name, hidden_0=CRITIC_HIDDEN_0, hidden_1=CRITIC_HIDDEN_1):<br>            <br>        <em>super</em>(Critic, self).__init__()<br>        <br>        self.hidden_0 = hidden_0<br>        self.hidden_1 = hidden_1<br><br>        self.net_name = name<br><br>        self.dense_0 = Dense(self.hidden_0, activation=&#39;relu&#39;)<br>        self.dense_1 = Dense(self.hidden_1, activation=&#39;relu&#39;)<br>        self.q_value = Dense(1, activation=None)<br>    <br>    <em>def</em> call(self, state, actors_actions):<br>        state_action_value = self.dense_0(tf.concat([state, actors_actions], axis=1)) # multiple actions<br>        state_action_value = self.dense_1(state_action_value)<br><br>        q_value = self.q_value(state_action_value)<br><br>        return q_value<br><br><em>class</em> Actor(tf.keras.Model):<br>    <em>def</em> __init__(self, name, actions_dim, hidden_0=ACTOR_HIDDEN_0, hidden_1=ACTOR_HIDDEN_1):<br>        <em>super</em>(Actor, self).__init__()<br>        self.hidden_0 = hidden_0<br>        self.hidden_1 = hidden_1<br>        self.actions_dim = actions_dim<br>        <br>        self.net_name = name<br><br>        self.dense_0 = Dense(self.hidden_0, activation=&#39;relu&#39;)<br>        self.dense_1 = Dense(self.hidden_1, activation=&#39;relu&#39;)<br>        self.policy = Dense(self.actions_dim, activation=&#39;sigmoid&#39;) # we want something beetween zero and one<br><br>    <em>def</em> call(self, state):<br>        x = self.dense_0(state)<br>        policy = self.dense_1(x)<br>        policy = self.policy(policy)<br>        return policy</pre><h3>Agents</h3><p>We can now define the logic of the single agents. We’re not going to define the loss functions here like for the individual counterpart since we need to have a global view of the environment to define the loss function for the Critic:</p><pre><em>class</em> Agent:<br>    <em>def</em> __init__(self, env, n_agent, actor_lr=ACTOR_LR, critic_lr=CRITIC_LR, gamma=GAMMA, tau=TAU):<br>        <br>        self.gamma = gamma<br>        self.tau = tau<br>        self.actor_lr = actor_lr<br>        self.critic_lr = critic_lr<br>        <br>        self.actor_dims = env.observation_space[n_agent].shape[0]<br>        self.n_actions = env.action_space[n_agent].n<br>        <br>        self.agent_name = &quot;agent_number_{}&quot;.<em>format</em>(n_agent)<br>        <br>        self.actor = Actor(&quot;actor_&quot; + self.agent_name, self.n_actions)<br>        self.critic = Critic(&quot;critic_&quot; + self.agent_name)<br>        self.target_actor = Actor(&quot;target_actor_&quot; + self.agent_name, self.n_actions)<br>        self.target_critic = Critic(&quot;critic_&quot; + self.agent_name)<br>        <br>        self.actor.<em>compile</em>(optimizer=opt.Adam(learning_rate=actor_lr))<br>        self.critic.<em>compile</em>(optimizer=opt.Adam(learning_rate=critic_lr))<br>        self.target_actor.<em>compile</em>(optimizer=opt.Adam(learning_rate=actor_lr))<br>        self.target_critic.<em>compile</em>(optimizer=opt.Adam(learning_rate=critic_lr))<br>        <br>        actor_weights = self.actor.get_weights()<br>        critic_weights = self.critic.get_weights()<br>        <br>        self.target_actor.set_weights(actor_weights)<br>        self.target_critic.set_weights(critic_weights)<br>        <br>    <em>def</em> update_target_networks(self, tau):<br>        actor_weights = self.actor.weights<br>        target_actor_weights = self.target_actor.weights<br>        for index in <em>range</em>(<em>len</em>(actor_weights)):<br>            target_actor_weights[index] = tau * actor_weights[index] + (1 - tau) * target_actor_weights[index]<br><br>        self.target_actor.set_weights(target_actor_weights)<br>        <br>        critic_weights = self.critic.weights<br>        target_critic_weights = self.target_critic.weights<br>    <br>        for index in <em>range</em>(<em>len</em>(critic_weights)):<br>            target_critic_weights[index] = tau * critic_weights[index] + (1 - tau) * target_critic_weights[index]<br><br>        self.target_critic.set_weights(target_critic_weights)<br>        <br>    <em>def</em> get_actions(self, actor_states):<br>        noise = tf.random.uniform(shape=[self.n_actions])<br>        actions = self.actor(actor_states)<br>        actions = actions + noise<br><br>        return actions.numpy()[0]<br>    <br>    <em>def</em> save(self, path_save):<br>        self.actor.save_weights(f&quot;{path_save}/{self.actor.net_name}.h5&quot;)<br>        self.target_actor.save_weights(f&quot;{path_save}/{self.target_actor.net_name}.h5&quot;)<br>        self.critic.save_weights(f&quot;{path_save}/{self.critic.net_name}.h5&quot;)<br>        self.target_critic.save_weights(f&quot;{path_save}/{self.target_critic.net_name}.h5&quot;)<br>        <br>    <em>def</em> load(self, path_load):<br>        self.actor.load_weights(f&quot;{path_load}/{self.actor.net_name}.h5&quot;)<br>        self.target_actor.load_weights(f&quot;{path_load}/{self.target_actor.net_name}.h5&quot;)<br>        self.critic.load_weights(f&quot;{path_load}/{self.critic.net_name}.h5&quot;)<br>        self.target_critic.load_weights(f&quot;{path_load}/{self.target_critic.net_name}.h5&quot;)</pre><p>It’s all pretty standard. The bigger difference compared to DDPG is the lack of the Ornstein-Uhlenbeck noise substituted with a simple uniform noise for simplicity. As for the DDPG, we also use a target Critic and Actor to stabilize the training.</p><h3>Super-agent</h3><p>We’re now going to define the global logic that is going to lead the agents’ actions. I called this module <em>“Super-agent”</em>, but there isn’t really one super-agent but a bunch of <em>“Super-Critics”</em> that help the single Actors to improve their policies:</p><pre><em>class</em> SuperAgent:<br>    <em>def</em> __init__(self, env, path_save=PATH_SAVE_MODEL, path_load=PATH_LOAD_FOLDER):<br>        self.path_save = path_save<br>        self.path_load = path_load<br>        self.replay_buffer = ReplayBuffer(env)<br>        self.n_agents = <em>len</em>(env.agents)<br>        self.agents = [Agent(env, agent) for agent in <em>range</em>(self.n_agents)]<br>        <br>    <em>def</em> get_actions(self, agents_states):<br>        list_actions = [self.agents[index].get_actions(agents_states[index]) for index in <em>range</em>(self.n_agents)]<br>        return list_actions<br>    <br>    <em>def</em> save(self):<br>        date_now = time.strftime(&quot;%Y%m%d%H%M&quot;)<br>        full_path = f&quot;{self.path_save}/save_agent_{date_now}&quot;<br>        if not os.path.isdir(full_path):<br>            os.makedirs(full_path)<br>        <br>        for agent in self.agents:<br>            agent.save(full_path)<br>            <br>        self.replay_buffer.save(full_path)<br>    <br>    <em>def</em> load(self):<br>        full_path = self.path_load<br>        for agent in self.agents:<br>            agent.load(full_path)<br>            <br>        self.replay_buffer.load(full_path)</pre><p>We start by defining the replay buffer, the agents, and the get_actions function that just recalls the get_actions function of the single actors. The same logic is used for the save and load functions that just recall the save and load of the single agents and the same function for the replay buffer.</p><p>Let’s go to the interesting part, i.e. the training of the agents:</p><pre><em>def</em> train(self):<br>        if self.replay_buffer.check_buffer_size() == False:<br>            return<br>        <br>        state, reward, next_state, done, actors_state, actors_next_state, actors_action = self.replay_buffer.get_minibatch()<br>        <br>        states = tf.convert_to_tensor(state, dtype=tf.float32)<br>        rewards = tf.convert_to_tensor(reward, dtype=tf.float32)<br>        next_states = tf.convert_to_tensor(next_state, dtype=tf.float32)<br>        <br>        actors_states = [tf.convert_to_tensor(s, dtype=tf.float32) for s in actors_state]<br>        actors_next_states = [tf.convert_to_tensor(s, dtype=tf.float32) for s in actors_next_state]<br>        actors_actions = [tf.convert_to_tensor(s, dtype=tf.float32) for s in actors_action]<br>        <br>        with tf.GradientTape(persistent=True) as tape:<br>            target_actions = [self.agents[index].target_actor(actors_next_states[index]) for index in <em>range</em>(self.n_agents)]<br>            policy_actions = [self.agents[index].actor(actors_states[index]) for index in <em>range</em>(self.n_agents)]<br>            <br>            concat_target_actions = tf.concat(target_actions, axis=1)<br>            concat_policy_actions = tf.concat(policy_actions, axis=1)<br>            concat_actors_action = tf.concat(actors_actions, axis=1)<br>            <br>            target_critic_values = [tf.squeeze(self.agents[index].target_critic(next_states, concat_target_actions), 1) for index in <em>range</em>(self.n_agents)]<br>            critic_values = [tf.squeeze(self.agents[index].critic(states, concat_actors_action), 1) for index in <em>range</em>(self.n_agents)]<br>            targets = [rewards[:, index] + self.agents[index].gamma * target_critic_values[index] * (1-done[:, index]) for index in <em>range</em>(self.n_agents)]<br>            critic_losses = [tf.keras.losses.MSE(targets[index], critic_values[index]) for index in <em>range</em>(self.n_agents)]<br>            <br>            actor_losses = [-self.agents[index].critic(states, concat_policy_actions) for index in <em>range</em>(self.n_agents)]<br>            actor_losses = [tf.math.reduce_mean(actor_losses[index]) for index in <em>range</em>(self.n_agents)]<br>        <br>        critic_gradients = [tape.gradient(critic_losses[index], self.agents[index].critic.trainable_variables) for index in <em>range</em>(self.n_agents)]<br>        actor_gradients = [tape.gradient(actor_losses[index], self.agents[index].actor.trainable_variables) for index in <em>range</em>(self.n_agents)]<br>        <br>        for index in <em>range</em>(self.n_agents):<br>            self.agents[index].critic.optimizer.apply_gradients(<em>zip</em>(critic_gradients[index], self.agents[index].critic.trainable_variables))<br>            self.agents[index].actor.optimizer.apply_gradients(<em>zip</em>(actor_gradients[index], self.agents[index].actor.trainable_variables))<br>            self.agents[index].update_target_networks(self.agents[index].tau)</pre><p>We start by getting the observations from the replay buffer calling the get_minibatch function. Then we convert all the NumPy vectors into TensorFlow vectors. Then we obtain the target and policy actions from the target actors and standard actors. We create the global view on them with also the actions taken concatenating the actions taken, the policy, and target actions of all the agents. So we can then obtain the values from the Critics feeding them the global view on states and actions and define the loss function as always using the Bellman equation.</p><p>Given the q-value, we can define the actor losses, apply the gradient for both the critics and actors, and soft-update the target networks.</p><h3>Wandb initialization and training loop</h3><p>We can now initialize the wandb configuration:</p><pre>config = <em>dict</em>(<br>  learning_rate_actor = ACTOR_LR,<br>  learning_rate_critic = CRITIC_LR,<br>  batch_size = BATCH_SIZE,<br>  architecture = &quot;MADDPG&quot;,<br>  infra = &quot;Colab&quot;,<br>  env = ENV_NAME<br>)<br><br>wandb.init(<br>  project=f&quot;tensorflow2_madddpg_{ENV_NAME.lower()}&quot;,<br>  tags=[&quot;MADDPG&quot;, &quot;RL&quot;],<br>  config=config,<br>)</pre><p>Then we initialize the environment and load a trained model if we’re restarting a training session:</p><pre>env = make_env(ENV_NAME)<br>super_agent = SuperAgent(env)<br><br>scores = []<br><br>if PATH_LOAD_FOLDER is not None:<br>    print(&quot;loading weights&quot;)<br>    actors_state = env.reset()<br>    actors_action = super_agent.get_actions([actors_state[index][None, :] for index in <em>range</em>(super_agent.n_agents)])<br>    [super_agent.agents[index].target_actor(actors_state[index][None, :]) for index in <em>range</em>(super_agent.n_agents)]<br>    state = np.concatenate(actors_state)<br>    actors_action = np.concatenate(actors_action)<br>    [super_agent.agents[index].critic(state[None, :], actors_action[None, :]) for index in <em>range</em>(super_agent.n_agents)]<br>    [super_agent.agents[index].target_critic(state[None, :], actors_action[None, :]) for index in <em>range</em>(super_agent.n_agents)]<br>    super_agent.load()<br><br>    print(super_agent.replay_buffer.buffer_counter)<br>    print(super_agent.replay_buffer.n_games</pre><p>In the end, we implement the training loop:</p><pre>for n_game in tqdm(<em>range</em>(MAX_GAMES)):<br>    start_time = time.time()<br>    actors_state = env.reset()<br>    done = [False for index in <em>range</em>(super_agent.n_agents)]<br>    score = 0<br>    step = 0<br>    <br>    if (super_agent.replay_buffer.n_games + 1) &gt; 5000:<br>        MAX_STEPS = <em>int</em>((super_agent.replay_buffer.n_games + 1) / 200)<br><br>    while not <em>any</em>(done):<br>        actors_action = super_agent.get_actions([actors_state[index][None, :] for index in <em>range</em>(super_agent.n_agents)])<br>        actors_next_state, reward, done, info = env.step(actors_action)<br>        <br>        state = np.concatenate(actors_state)<br>        next_state = np.concatenate(actors_next_state)<br>        <br>        super_agent.replay_buffer.add_record(actors_state, actors_next_state, actors_action, state, next_state, reward, done)<br>        <br>        actors_state = actors_next_state<br>        <br>        score += <em>sum</em>(reward)<br>        step += 1<br>        if step &gt;= MAX_STEPS:<br>            break<br>    <br>    if super_agent.replay_buffer.check_buffer_size():<br>        super_agent.train()<br>        <br>    super_agent.replay_buffer.update_n_games()<br>    <br>    scores.append(score)<br>    <br>    wandb.log({&#39;Game number&#39;: super_agent.replay_buffer.n_games, &#39;# Episodes&#39;: super_agent.replay_buffer.buffer_counter, <br>               &quot;Average reward&quot;: <em>round</em>(np.mean(scores[-10:]), 2), \<br>                      &quot;Time taken&quot;: <em>round</em>(time.time() - start_time, 2), &#39;Max steps&#39;: MAX_STEPS})<br>    <br>    if (n_game + 1) % EVALUATION_FREQUENCY == 0 and super_agent.replay_buffer.check_buffer_size():<br>        actors_state = env.reset()<br>        done = [False for index in <em>range</em>(super_agent.n_agents)]<br>        score = 0<br>        step = 0<br>        while not <em>any</em>(done):<br>            actors_action = super_agent.get_actions([actors_state[index][None, :] for index in <em>range</em>(super_agent.n_agents)])<br>            actors_next_state, reward, done, info = env.step(actors_action)<br>            state = np.concatenate(actors_state)<br>            next_state = np.concatenate(actors_next_state)<br>            actors_state = actors_next_state<br>            score += <em>sum</em>(reward)<br>            step += 1<br>            if step &gt;= MAX_STEPS:<br>                break<br>        wandb.log({&#39;Game number&#39;: super_agent.replay_buffer.n_games, <br>                   &#39;# Episodes&#39;: super_agent.replay_buffer.buffer_counter, <br>                   &#39;Evaluation score&#39;: score, &#39;Max steps&#39;: MAX_STEPS})<br>            <br>    if (n_game + 1) % SAVE_FREQUENCY == 0 and super_agent.replay_buffer.check_buffer_size():<br>        print(&quot;saving weights and replay buffer...&quot;)<br>        super_agent.save()<br>        print(&quot;saved&quot;)</pre><p>It’s all pretty standard. The only specific thing is the MAX_STEPS parameter that we increase with the number of games played. This because the particle environments don’t really end, so we need a parameter to escape the loop.</p><h3>Results</h3><p>We can now see the results. We start by looking at the simple adversary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jTcQPTJBj4N3WphF" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hnkKTtIi1eAFxsem" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EbwT8EddSDzWysSz" /></figure><p>In the first plot, we can see how we increment the MAX_STEPS parameter. In the second one, we can see how the average reward in training is changing. As you can see, there’s a lot of variability with largely negative results followed by large positive ones. This is typical of DDPG, and we also saw it in the single-agent counterpart. In the last plot, we can see how the evaluation score increases in time until we stop it, but the agents are learning.</p><p>We used the simple adversary environment to develop everything, but we also test it on another environment, simple tag, to be sure that it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HThxb3wEoLYbN68M" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a7e1IzV534BlWX4A" /></figure><p>From the two plots, we can see that the agents are learning, there’s still high variability, and in this case, the performances are getting worst for around 10k games before getting better.</p><h3>Conclusion</h3><p>So in this post, we showed how to implement and use the multi-agent MADDPG to solve toy environments provided by OpenAI, replicating what was achieved in the paper <a href="https://arxiv.org/pdf/1706.02275.pdf">Multi-Agent Actor-Critic for Mixed Cooperative-Competitive Environments by Lowe et al. (2017)</a>.</p><p>You can find all the code on my <a href="https://github.com/antonai91/reinforcement_learning/tree/master/maddpg">Github</a>. For any questions, you can reach me through <a href="https://www.linkedin.com/in/lisiantonio/">Linkedin</a>.</p><p>If you enjoyed this article, share it with your friends and colleagues! I’ll see you in the next post. In the meantime, take care, stay safe, and remember <em>don’t be another brick in the wall</em>.</p><p>Anton.ai</p><p><em>Originally published at </em><a href="https://antonai.blog/multi-agent-reinforcement-learning-openais-maddpg/"><em>https://antonai.blog</em></a><em> on May 12, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a741c6cf3869" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/multi-agent-reinforcement-learning-openais-maddpg-a741c6cf3869">Multi-Agent Reinforcement Learning: OpenAI’s MADDPG</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a Recommendation System from scratch using Keras]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-create-a-recommendation-system-from-scratch-using-keras-f3647fc5c6f8?source=rss-4bba14bd6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3647fc5c6f8</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <dc:creator><![CDATA[Antonio Lisi]]></dc:creator>
            <pubDate>Thu, 22 Apr 2021 06:59:37 GMT</pubDate>
            <atom:updated>2021-05-03T16:24:18.183Z</atom:updated>
            <content:encoded><![CDATA[<p>Using the IMDB dataset to train a movie recommendation engine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*BITUyojCfwjmqQk0" /></figure><p>By Antonio Lisi</p><h3>Intro</h3><p>Hello everyone, we continue our series on how to train algorithms from scratch in classic deep learning applications.</p><p>In this post, we will see how to create from scratch and interpret a recommendation engine using a collaborative filtering algorithm.</p><p>A Recommendation engine is a tool that predicts what a user may or may not like. It’s typically used when you have a large number of users and products, and you want to recommend which products are most likely to be useful for which users.</p><p>There are several examples of recommendation systems, think for example about Netflix or Amazon homepages.</p><h3>Dataset</h3><p>The Dataset that we’re going to use to test our models is the MovieLens 25M Dataset that we downloaded from <a href="https://grouplens.org/datasets/movielens/">here</a>. The dataset has 25 million ratings and one million tag applications applied to 62,000 movies by 162,000 users.</p><p>From the link, we downloaded a total of six datasets. But we’re interested in just two of them:</p><ol><li>ratings.csv that contains the ratings given by the users to different movies</li><li>movies.csv that maps every movieId with title and genre</li></ol><p>Let’s have a look at them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*Sf3Ej-BH3nZ0UkI5" /></figure><p>The first thing to do is to join the two datasets to have all the information in one pandas dataframe:</p><pre>df = df.merge(df_movie, how=&quot;left&quot;, on=&quot;movieId&quot;)</pre><p>Where df is the rating dataset and df_movie is the movie dataset. So we obtain something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*JaNkJqv6II3V0uLq" /></figure><p>So we can save this dataframe in a parquet file that we can easily load in the next notebooks:</p><pre>df.to_parquet(&quot;../data/processed/df_rating_movie.parquet&quot;)</pre><h3>Data Exploration</h3><p>Let’s explore our data. We start by looking at the movies with higher ratings:</p><pre>df.groupby([&quot;movieId&quot;, &quot;title&quot;, &quot;genres&quot;]).agg({&quot;rating&quot;: &quot;mean&quot;, &quot;userId&quot;: &quot;count&quot;}).rename(columns={&quot;userId&quot;: &quot;n_reviews&quot;}).sort_values(&quot;rating&quot;, ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*DvmV7tjs68ZbXXj9" /></figure><p>We can see that we have a lot of movies with just one or two reviews. In order to make sense we need to filter out the movies with just a few reviews:</p><pre>df_top_review = df.groupby([&quot;movieId&quot;, &quot;title&quot;, &quot;genres&quot;]).agg({&quot;rating&quot;: &quot;mean&quot;, &quot;userId&quot;: &quot;count&quot;}).rename(columns={&quot;userId&quot;: &quot;n_reviews&quot;}) </pre><pre>df_top_review = df_top_review[df_top_review.n_reviews &gt; 10] <br>df_top_review.sort_values(&quot;rating&quot;, ascending=False)[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*a3kX_-qls4Cz21h0" /></figure><p>We can now recognize some movies, but there are still some movies with few reviews like <a href="https://www.imdb.com/title/tt0314519/">Pollyanna</a>.</p><p>Let’s see the most reviewed movies:</p><pre>df_top_review.sort_values(&quot;n_reviews&quot;, ascending=False)[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*B_L8o6A0pq6yfmZk" /></figure><p>We can also see the genres with the highest rating:</p><pre>df_top_genres = df.groupby([&quot;genres&quot;]).agg({&quot;rating&quot;: &quot;mean&quot;, &quot;userId&quot;: &quot;count&quot;}).rename(columns={&quot;userId&quot;: &quot;n_reviews&quot;}) </pre><pre>df_top_genres = df_top_genres[df_top_genres.n_reviews &gt; 10] df_top_genres.sort_values(&quot;rating&quot;, ascending=False)[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*6T741OGNbl96H3m5" /></figure><p>And as before, we can see the most reviewed genres:</p><pre>df_top_genres.sort_values(&quot;n_reviews&quot;, ascending=False)[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/0*A3vbqdXa5t5bH1Ss" /></figure><p>Drama and comedy, no surprise here, but as we can see, Comedy has a very low rate. That’s because there are many mediocre comedies out there. The same can’t be said for Drama.</p><p>Then divide our dataset into train and validation set:</p><pre>df_train, df_val = train_test_split(df, random_state=42, test_size=0.2, stratify=df.rating)</pre><h3>Data Pre-processing</h3><p>Before starting training the model, we need to implement some basic pre-processing steps. We start by encoding the movies and users Id so that they start from zero so that we can easily use the Embedding Layer from Keras:</p><pre>dict_movies = {} <br>index = 0 <br>for ids in sorted(movies_ids): <br>    dict_movies[ids] = index <br>    index += 1 </pre><pre>dict_users = {} <br>index = 0 <br>for ids in sorted(users_ids): <br>    dict_users[ids] = index <br>    index += 1 </pre><pre>df_train[&quot;movieId&quot;] = df_train[&quot;movieId&quot;].map(dict_movies) df_val[&quot;movieId&quot;] = df_val[&quot;movieId&quot;].map(dict_movies) df_train[&quot;userId&quot;] = df_train[&quot;userId&quot;].map(dict_users) df_val[&quot;userId&quot;] = df_val[&quot;userId&quot;].map(dict_users)</pre><p>Then we convert ratings and Ids to float32 NumPy vectors:</p><pre>for col in [&quot;userId&quot;, &quot;movieId&quot;, &quot;rating&quot;]: <br>    df_train[col] = df_train[col].astype(np.float32) <br>    df_val[col] = df_val[col].astype(np.float32)</pre><p>In the end, we define the number of unique users and movies that we’ll use in the Embeddings layer:</p><pre>num_unique_users=len(set(list(df_train.userId.unique()) + list(df_val.userId.unique()))) </pre><pre>num_unique_movies=len(set(list(df_train.movieId.unique()) + list(df_val.movieId.unique())))</pre><h3>Collaborative Filter Algorithm</h3><p>The fundamental concept behind the Collaborative Filter Algorithm is the idea that latent factors can be captured using the users’ behavior. We have users’ and movies’ latent factors. Similar users will have similar tastes in movies, and at the same time, similar movies will be liked by the same users.</p><p>Let’s start by implementing the Collaborative Filter Algorithm. We’re going to use the Keras Functional API to define our model:</p><pre>users_input = Input(shape=(1,), name=&quot;users_input&quot;) </pre><pre>users_embedding = Embedding(num_unique_users + 1, EMBEDDING_SIZE, name=&quot;users_embeddings&quot;)(users_input) </pre><pre>users_bias = Embedding(num_unique_users + 1, 1, name=&quot;users_bias&quot;)(users_input) </pre><pre>movies_input = Input(shape=(1,), name=&quot;movies_input&quot;) </pre><pre>movies_embedding = Embedding(num_unique_movies + 1, EMBEDDING_SIZE, name=&quot;movies_embedding&quot;)(movies_input) </pre><pre>movies_bias = Embedding(num_unique_movies + 1, 1, name=&quot;movies_bias&quot;)(movies_input) </pre><pre>dot_product_users_movies = multiply([users_embedding, movies_embedding]) </pre><pre>input_terms = dot_product_users_movies + users_bias + movies_bias input_terms = Flatten(name=&quot;fl_inputs&quot;)(input_terms) </pre><pre>output = Dense(1, activation=&quot;relu&quot;, name=&quot;output&quot;)(input_terms) model = Model(inputs=[users_input, movies_input], outputs=output)</pre><p>Let’s see the model summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*1YnYvkCsOSxDfIuD" /></figure><p>So let’s explain it. We’re going to have two inputs:</p><ul><li>UserId that represents the user that made the review</li><li>MovieId that represents the movie reviewed</li></ul><p>Then we have users’ and movies’ embeddings. Basically, we’re creating a vector of length 50 to represent the single user and movie to approximate the latent factors that we want to approximate.</p><p>We’re also considering another two Embeddings called Users’ and Movies’ biases. Like in a regression model, we have a bias term that represents for the Users the propensity of the single user to give a high review. Simultaneously, some movies are liked by everyone, so they have a base high review without considering the specific user that is doing the review.</p><p>We take the Users and Movies latent factors, we multiply them, and we add the two biases. Then we use a dense layer to output a single number that is our predicted rating.</p><p>We can now define our optimizer and loss function as always:</p><pre>opt_adam = opt.Adam(lr = 0.005) </pre><pre>model.compile(optimizer=opt_adam, loss= [&#39;mse&#39;], metrics=[&#39;mean_absolute_error&#39;])</pre><p>We’re using the Adam optimizer and the mean squared error as the loss function. We can now launch our training:</p><pre>model.fit(x=[df_train.userId, df_train.movieId], y=df_train.rating, batch_size=512, epochs=3, verbose=1, validation_data=([df_val.userId, df_val.movieId], df_val.rating))</pre><p><em>Epoch 1/3<br>39063/39063 [==============================] — 2303s 59ms/step — loss: 0.9431 — mean_absolute_error: 0.7221 — val_loss: 0.6360 — val_mean_absolute_error: 0.6075<br>Epoch 2/3<br>39063/39063 [==============================] — 2298s 59ms/step — loss: 0.5564 — mean_absolute_error: 0.5623 — val_loss: 0.6213 — val_mean_absolute_error: 0.5936<br>Epoch 3/3<br>39063/39063 [==============================] — 2298s 59ms/step — loss: 0.4777 — mean_absolute_error: 0.5171 — val_loss: 0.6310 — val_mean_absolute_error: 0.5989</em></p><p>We’re not doing half bad, but we can make some improvements.</p><h3>Constraining the output range</h3><p>We know that our rating has a minimum and maximum value that can be given on IMDB. We can infer it from the data:</p><pre>min_rating=min(df_train.rating.min(), df_val.rating.min()) max_rating=max(df_train.rating.max(), df_val.rating.max())</pre><p>We have a minimum rating of 0.5 and a maximum rating of 5. So we can now restrict our model in a way that is constrained to predict values in that range. We do this by using a sigmoid activation function in the final layer to have something between 0 and 1. Then we multiply this number for the difference between the maximum and the minimum, and then we add the minimum:</p><pre>output = Dense(1, activation=&quot;sigmoid&quot;, name=&quot;output&quot;)(input_terms) output = output * (max_rating - min_rating) + min_rating</pre><p>We can see the summary of the new model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*LCj8NVrAvfMJUerG" /></figure><p>As before, we use the Adam optimizer and the mean squared error loss function. So we compile and train the model:</p><pre>opt_adam = opt.Adam(lr = 0.005) </pre><pre>model.compile(optimizer=opt_adam, loss= [&#39;mse&#39;], metrics=[&#39;mean_absolute_error&#39;]) </pre><pre>model.fit(x=[df_train.userId, df_train.movieId], y=df_train.rating, batch_size=2048, epochs=3, verbose=1, validation_data=([df_val.userId, df_val.movieId], df_val.rating))</pre><p><em>Epoch 1/3<br>9766/9766 [==============================] — 600s 61ms/step — loss: 0.7700 — mean_absolute_error: 0.6722 — val_loss: 0.6254 — val_mean_absolute_error: 0.5998<br>Epoch 2/3<br>9766/9766 [==============================] — 588s 60ms/step — loss: 0.5347 — mean_absolute_error: 0.5544 — val_loss: 0.6104 — val_mean_absolute_error: 0.5910<br>Epoch 3/3<br>9766/9766 [==============================] — 566s 58ms/step — loss: 0.4472 — mean_absolute_error: 0.5053 — val_loss: 0.6192 — val_mean_absolute_error: 0.5949</em></p><p>We improved from 0.63 to 0.62 in the validation loss, not much of a gain but it was a very simple improvement.</p><p>We could improve the model using a more “deep” approach. For example, the approach proposed in the paper Neural Collaborative Filtering by He et al.. It’s a straightforward approach. Instead of multiplying the latent factors and adding the biases, we concatenate the inputs and add on top fully connected layers with regularization.</p><p>We’re not going to implement this because I find it more interesting to analyze the latent factors and biases we created.</p><h3>Exploring Movies’ Latent Factors and Biases</h3><p>First of all we need to extract the layers’ weights:</p><pre>dict_weights = {} </pre><pre>for layer in model.layers: <br>    if layer.name in [&quot;users_embeddings&quot;, &quot;movies_embeddings&quot;, &quot;users_bias&quot;, &quot;movies_bias&quot;]: <br>        dict_weights[layer.name] = layer.weights</pre><p>Being the users anonymized, it makes more sense to explore the movies’ latent factors and biases. We start by looking at the latent factors.</p><p>We save the embeddings in a pandas dataframe and define the key MovieId as we have in the original dataset:</p><pre>df_movies_embeddings = pd.DataFrame(dict_weights[&quot;movies_embeddings&quot;][0].numpy()) df_movies_embeddings.columns = [&quot;emb_&quot; + str(col) for col in df_movies_embeddings.columns] </pre><pre>df_movies_embeddings.reset_index(inplace=True) df_movies_embeddings.rename(columns={&quot;index&quot;:&quot;movieId&quot;}, inplace=True)</pre><p>We can now recover from the original dataset genres and name of the movies:</p><pre>df_movies_embeddings = df_movies_embeddings.merge(df_train[[&quot;movieId&quot;, &quot;title&quot;, &quot;genres&quot;]].drop_duplicates(), how=&quot;left&quot;, on=&quot;movieId&quot;)</pre><p>In order to see the movies in a two-dimension scatterplot, we’re going to use the statistical method <a href="https://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html">t-distributed stochastic neighbor embedding (t-SNE) </a>to reduce the 50 length embedding in a vector with 2 dimensions:</p><pre>vec_tsne = TSNE(n_components=2).fit_transform(df_movies_embeddings[[col for col in df_movies_embeddings.columns if &quot;emb&quot; in col]]) </pre><pre>df_movies_embeddings[&quot;tsne_0&quot;] = vec_tsne[:, 0] df_movies_embeddings[&quot;tsne_1&quot;] = vec_tsne[:, 1]</pre><p>We can now see the first 100 movies in the two dimensions created:</p><pre>plt.figure(figsize=(12,12)) plt.scatter(df_movies_embeddings.tsne_0[:100], df_movies_embeddings.tsne_1[:100]) for i, x, y in zip(df_movies_embeddings.title[:100], df_movies_embeddings.tsne_0[:100], df_movies_embeddings.tsne_1[:100]): plt.text(x,y,i, color=np.random.rand(3)*0.7, fontsize=11)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*lIbV80vvYB_vhQm7" /></figure><p>In this way, we can’t really infer much. We have too many movies. But we can use some clustering methods on the embeddings. We’re going to use a kmeans with 100 clusters:</p><pre>km = KMeans(100, random_state=101) <br>km.fit(df_movies_embeddings[[col for col in df_movies_embeddings.columns if &quot;emb&quot; in col]]) </pre><pre>clusters = km.predict(df_movies_embeddings[[col for col in df_movies_embeddings.columns if &quot;emb&quot; in col]]) </pre><pre>df_movies_embeddings[&quot;cluster_n10&quot;] = clusters</pre><p>Let’s look at some cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*bNmHSlwb9oBG2zfT" /></figure><p>So cluster 56 is just the Pirates of the Caribbean series. Let’s explore other clusters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*4keJh-9lVE6_tbPD" /></figure><p>Cluster 81 is the <a href="https://www.wikiwand.com/en/Faces_of_Death">Faces of Death series.</a></p><p>Cluster 84 is very interesting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*E8_GJJ8l4d0YB0fX" /></figure><p>It is grouping together the Star Trek, Star Wars, Harry Potter, and Lord of the Rings sagas. So it’s a sort of mix of Fantasy/Sci-fi.</p><p>This is very interesting and can be used as a new way to define genres based on the users’ tastes that we inferred from the reviews.</p><p>In the end, we can see the movies’ bias:</p><pre>df_movies_embeddings[&quot;bias&quot;] = dict_weights[&quot;movies_bias&quot;][0].numpy()</pre><p>Looking at the movies with the highest biases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*DxC5glmFRvyIU96p" /></figure><p>So we can see the Planet Earth is the movie with the highest bias. What is saying is that even if you don’t normally enjoy a certain type of movie (documentary, for example), you might enjoy Planet Earth.</p><h3>Conclusion</h3><p>So in this post, we showed how to code a recommendation system from scratch using Keras and to interpret the biases and latent factors.</p><p>You can find all the code on my <a href="https://github.com/antonai91/recommendation_system">Github</a>. For any questions, you can reach me through <a href="https://www.linkedin.com/in/lisiantonio/">Linkedin</a>.</p><p>If you enjoyed this article, share it with your friends and colleagues! I’ll see you in the next post. In the meantime, take care, stay safe, and remember <em>don’t be another brick in the wall.</em></p><p>Anton.ai</p><p><em>Originally published at </em><a href="https://antonai.blog/how-to-create-a-recommendation-system-from-scratch-using-keras/"><em>https://antonai.blog</em></a><em> on April 22, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3647fc5c6f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-create-a-recommendation-system-from-scratch-using-keras-f3647fc5c6f8">How to create a Recommendation System from scratch using Keras</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to achieve state of the art results on NLP classification tasks]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-achieve-state-of-the-art-results-on-nlp-classification-tasks-342fa07c7fe9?source=rss-4bba14bd6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/342fa07c7fe9</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Antonio Lisi]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 09:08:27 GMT</pubDate>
            <atom:updated>2021-04-13T16:05:16.009Z</atom:updated>
            <content:encoded><![CDATA[<p>Unleashing the power of transfer learning using Hugging Face library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XWFCPAE550K9KiQU" /></figure><p>By Antonio Lisi</p><h3>Intro</h3><p>Hello everyone, after my previous post on “How to create a State of the Art Image Classifier in less than 10 minutes”, I decided to do something similar for the NLP space.</p><p>So in this post, we’re going to see how to easily create a state-of-the-art model classifier using the Hugging Face library and exploiting the power of transfer learning as we did for the Rover Classification challenge.</p><h3>Dataset</h3><p>The Dataset that we’re going to use to test our models is the classic <a href="https://ai.stanford.edu/~amaas/data/sentiment/">IMDB dataset </a>that we downloaded from <a href="https://www.kaggle.com/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews">Kaggle</a>. The dataset has 50K movie reviews with a binary label positive/negative based on the vote of the review, &gt;=7 out of 10 is positive and &lt;7 is negative. So this is a dataset for binary sentiment classification.</p><h3>Data Exploration</h3><p>Let’s have a look at the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/0*f_vyCF3nbQrfUCJl" /></figure><p>Nothing complicated here, let’s look at some statistics regarding the review and sentiments variables.</p><p>Looking at our target variable “sentiment”, we can see that the data is perfectly balanced, we have 25k positive and 25k negative review:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*uBcZSi5FL2s43-WT" /></figure><p>We can also look at the distribution of the length of the reviews:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*jwnkINUQlX3oeR_T" /></figure><p>Looking at the reviews with more than 7000 characters, we obtain a 71/29 distribution in favor of positive reviews from the 50/50 distribution on the entire dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*_IA_BqaMfok7gXZ9" /></figure><p>So, it seems that long reviews have a higher probability of having a positive sentiment. This could be a good variable to use in our modeling, but here we’re interested in using a pure NLP pipeline, so we will ignore it.</p><p>Before going to the modeling phase, we need to split the dataset into train and test set:</p><pre>df_train = df[:25000]<br>df_test = df[25000:]</pre><p>Ok, we’re now ready to launch some neural networks.</p><h3>Starting simple</h3><p>We’re going to start very simply using some standard architecture used in the NLP world. First of all, we define some parameters:</p><pre>MAX_SEQUENCE_LENGTH = 1000<br>MAX_NUM_WORDS = 20000<br>EMBEDDING_DIM = 100</pre><p>The MAX_SEQUENCE_LENGTH parameter is the maximum length of the sequence of words that we’re going to consider in our model. MAX_NUM_WORDS is the maximum number of words considered in the tokenizer based on their frequency. EMBEDDING_DIM is the size of the embedding layer that we’re going to use in our models.</p><h3>Data Pre-Processing</h3><p>Let’s start by tokenizing our reviews:</p><pre>tokenizer = Tokenizer(num_words=MAX_NUM_WORDS) tokenizer.fit_on_texts(df_train.review.values) </pre><pre>train_sequences = tokenizer.texts_to_sequences(df_train.review.values) </pre><pre>test_sequences = tokenizer.texts_to_sequences(df_test.review.values) </pre><pre>word_index = tokenizer.word_index</pre><p>We’re using the tokenizer from Keras to recognize the single words in the reviews. Then we use the method texts_to_sequences to transform from a text array to a number array where every word has its own index saved in a dictionary (word_index).</p><p>We fit it on the training set and apply it to both training and test sets. Then we pad the sequences generated. This is necessary because the GPU wants all matrices of the same length, so we’re going to use the MAX_SEQUENCE_LENGHT parameter to define the shape of the array and when the sequence is shorter we pad the beginning with a bunch of zeros.</p><pre>X_train = pad_sequences(train_sequences, maxlen=MAX_SEQUENCE_LENGTH) X_test = pad_sequences(test_sequences, maxlen=MAX_SEQUENCE_LENGTH)</pre><p>For the target variable, we need to transform from a single value variable (1, 0, 1 and so on) to a one hot encoding form ([0, 1], [1, 0], [0, 1]). We can use the to_categorical function from Keras:</p><pre>y_train = to_categorical(np.asarray(df_train.sentiment.map(labels_index)))</pre><pre>y_test = to_categorical(np.asarray(df_test.sentiment.map(labels_index)))</pre><p>Ok, we’re basically done with the data pre-processing we can now define our first neural network.</p><h3>1-D Convolutional Neural Network</h3><p>Our first model will be a 1-D Convolutional Neural Network:</p><pre>model = Sequential() model.add(Embedding(num_words, EMBEDDING_DIM, input_length=MAX_SEQUENCE_LENGTH)) <br>model.add(Conv1D(128, 5, activation=&#39;relu&#39;)) model.add(MaxPooling1D(5)) model.add(Conv1D(128, 5, activation=&#39;relu&#39;)) <br>model.add(MaxPooling1D(5)) <br>model.add(Conv1D(128, 5, activation=&#39;relu&#39;)) model.add(GlobalMaxPooling1D()) <br>model.add(Dense(128, activation=&#39;relu&#39;)) model.add(Dense(len(labels_index), activation=&#39;softmax&#39;))</pre><p>We can use the summary() method to easily see the model’s architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/0*A2MWXFHwNgtX2Exo" /></figure><p>Ok let’s train it:</p><pre>model = Sequential() <br>model.add(Embedding(MAX_NUM_WORDS, 128)) <br>model.add(LSTM(128, dropout=0.2)) model.add(Dense(2, activation=&#39;sigmoid&#39;)) </pre><pre>model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;]) model.fit(X_train, y_train, batch_size=128, epochs=4)</pre><p>Epoch 1/5<br> 196/196 [==============================] — 27s 53ms/step — loss: 0.6013 — acc: 0.6137<br> Epoch 2/5<br> 196/196 [==============================] — 10s 53ms/step — loss: 0.2510 — acc: 0.9005<br> Epoch 3/5<br> 196/196 [==============================] — 10s 53ms/step — loss: 0.1656 — acc: 0.9382<br> Epoch 4/5<br> 196/196 [==============================] — 10s 53ms/step — loss: 0.1101 — acc: 0.9615<br> Epoch 5/5<br> 196/196 [==============================] — 10s 53ms/step — loss: 0.0779 — acc: 0.9734</p><p>And at the end we can evaluate it on the test set:</p><pre>score, acc = model.evaluate(X_test, y_test, batch_size=128)</pre><p>196/196 [==============================] — 4s 18ms/step — loss: 0.3681 — acc: 0.8878</p><p>And we obtain an accuracy of 88.78%. Not bad for the first try, our model is overfitting right now, we should use some Dropout layer to limit it, but that’s not our final goal. Let’s try another architecture typically used in NLP tasks, the LSTM network.</p><h3>LSTM</h3><p>Let’s start by defining our LSTM model:</p><pre>model.add(Embedding(MAX_NUM_WORDS, 128)) <br>model.add(LSTM(128, dropout=0.2)) model.add(Dense(2, activation=&#39;sigmoid&#39;))</pre><pre>model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=&#39;adam&#39;,metrics=[&#39;accuracy&#39;])</pre><p>As before we can see the model using model.summary():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*PoZmlAHC53lt-zmk" /></figure><p>We can now fit it:</p><pre>model.fit(X_train, y_train, batch_size=128, epochs=4)</pre><p>Epoch 1/5<br>196/196 [==============================] — 25s 121ms/step — loss: 0.5804 — accuracy: 0.6935<br>Epoch 2/5<br>196/196 [==============================] — 24s 121ms/step — loss: 0.2336 — accuracy: 0.9126<br>Epoch 3/5<br>196/196 [==============================] — 24s 120ms/step — loss: 0.1427 — accuracy: 0.9523<br>Epoch 4/5<br>196/196 [==============================] — 23s 120ms/step — loss: 0.1033 — accuracy: 0.9663<br>Epoch 5/5<br>196/196 [==============================] — 23s 120ms/step — loss: 0.1092 — accuracy: 0.9616</p><p>And we evaluate it on the test set:</p><pre>score, acc = model.evaluate(X_test, y_test, batch_size=128)</pre><p>196/196 [==============================] — 8s 41ms/step — loss: 0.4413 — accuracy: 0.8777</p><p>As before, there’s overfitting, and here we’re generalizing even less. Ok, let’s change our approach.</p><h3>Language model</h3><p>We’re going now to change the approach. Until now, we just defined the model and trained it, starting with random weights.</p><p>A different approach would be to use the text from the review to train a language model and then tune the weights for the classification task. In its simplest form, a language model learns to predict the next word based on the preceding ones, and that’s what we’re going to implement here.</p><p>We’re going to build a very basic and simple language model for two main reasons:</p><ul><li>Bigger networks translate in much more training time and GPU memory</li><li>The true strength of language models reside in training on a big different dataset (like wikitext) and then exploit transfer learning as we did with ResNet on the rover classification</li></ul><p>We’re going to use pre-trained language models in the last part of this post. For now, let’s build our very basic language model on the reviews.</p><p>We start like before with tokenizing the text:</p><pre>tokenizer = Tokenizer(num_words=MAX_NUM_WORDS) tokenizer.fit_on_texts(df_train.review.values) </pre><pre>train_sequences = tokenizer.texts_to_sequences(df_train.review.values) </pre><pre>test_sequences = tokenizer.texts_to_sequences(df_test.review.values)</pre><p>Now we need to create an input sequence for the language model. First of all we tokenize the review, then we create a vector starting from the first two words (tokenized) and then adding the other ones:</p><pre>input_sequences = []</pre><pre>for line in df_train.review.values:<br>    token_list = tokenizer.texts_to_sequences([line])[0]<br>    for i in range(1, len(token_list)):<br>        n_gram_sequence = token_list[:i+1]<br>        input_sequences.append(n_gram_sequence)</pre><p>The result is something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*wfRbEEiQRCvk2PxI" /></figure><p>So this is the first review, and we have 12 words because we’re considering the 11th element. The 12th element will be equal to the 11th plus one additional word. When we arrive at the end of the review and start a new one, the first element will be long 2. This is necessary because the reviews are uncorrelated between them.</p><p>Just for clarity, let’s see the second and third elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/0*UATBiy1FOVtG-vXt" /></figure><p>Same thing, a second element with three words and third with just one more.</p><p>Differently from before we can’t just give a numpy array to the model, it would be too much RAM consuming. Se we create a batch generator that yields a batch of our data:</p><pre>class KerasBatchGenerator(object):<br>    def __init__(self, input_sequences, batch_size):<br>        self.input_sequences = input_sequences<br>        self.batch_size = batch_size<br>        self.current_idx = 0<br>    <br>    def generate(self):<br>        while True:<br>            if (i + 1)*self.batch_size &lt; len(self.input_sequences):<br>                in_seq = input_sequences[i*self.batch_size: (i + 1)*self.batch_size]<br>                in_seq = np.array(pad_sequences(in_seq, maxlen=MAX_SEQUENCE_LENGTH, padding=&#39;pre&#39;))<br>                <br>            else:<br>                in_seq = input_sequences[i*self.batch_size:]<br>                in_seq = np.array(pad_sequences(in_seq, maxlen=MAX_SEQUENCE_LENGTH, padding=&#39;pre&#39;))<br>                <br>            X = in_seq[:,:-1]<br>            y = in_seq[:,-1]<br>            y = to_categorical(y, num_classes=num_words)<br>            self.current_idx += len(self.input_sequences) // self.batch_size<br>            yield (X, y)</pre><p>We can now create the generator and define our first language model. We’re going to use the same LSTM used before, but at the end, we will have a dense layer with n+1 words, where n is the maximum number of words to keep in the tokenizer, and the +1 refers to the unknown word (words not in the fitted vocabulary):</p><pre>gen = KerasBatchGenerator(input_sequences, 2048) <br>model = Sequential() <br>model.add(Embedding(num_words, EMBEDDING_DIM, input_length=MAX_SEQUENCE_LENGTH)) <br>model.add(LSTM(128, dropout=0.2)) <br>model.add(Dense(MAX_NUM_WORDS + 1, activation=&#39;softmax&#39;)) model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;)</pre><p>Finally we can now train our language model:</p><pre>model.fit(gen.generate(), steps_per_epoch=len(input_sequences)//2048, epochs=1, verbose=1)</pre><p>2777/2777 [==============================] — 2267s 815ms/step — loss: 3.8493</p><p>Once trained our language model, we can build a new model that use the embedding layer trained and on top build the same LSTM as before:</p><pre>new_model = Sequential()<br>for layer in model.layers[:-2]:<br>    new_model.add(layer)<br>new_model.add(LSTM(128, dropout=0.2))<br>new_model.add(Dense(2, activation=&#39;sigmoid&#39;))<br>print(new_model.summary())<br>new_model.compile(loss=&#39;binary_crossentropy&#39;,<br>              optimizer=&#39;adam&#39;,<br>              metrics=[&#39;accuracy&#39;])</pre><p>We can see the new model using the summary() method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/0*IeEW4XplkN7vc75H" /></figure><p>And we train it for five epochs and evaluate it on the train set as before:</p><pre>new_model.fit(X_train, y_train, batch_size=128, epochs=5) <br>score, acc = new_model.evaluate(X_test, y_test)</pre><p>Epoch 1/5<br>196/196 [==============================] — 22s 105ms/step — loss: 0.6124 — accuracy: 0.6411<br>Epoch 2/5<br>196/196 [==============================] — 21s 105ms/step — loss: 0.4067 — accuracy: 0.8216<br>Epoch 3/5<br>196/196 [==============================] — 21s 105ms/step — loss: 0.2396 — accuracy: 0.9067<br>Epoch 4/5<br>196/196 [==============================] — 21s 105ms/step — loss: 0.1835 — accuracy: 0.9335<br>Epoch 5/5<br>196/196 [==============================] — 21s 105ms/step — loss: 0.1504 — accuracy: 0.9474<br>782/782 [==============================] — 16s 20ms/step — loss: 0.3588 — accuracy: 0.8748</p><p>We obtain an accuracy of 87.48%. That’s the same result as before, and we’re overfitting as well. But the point here was not to improve the performance. We wanted to introduce the concept of the language model and how it is trained.</p><p>Now it’s time to bring out the big guns and radically improve our score.</p><h3>Unleashing the power of Transfer Learning</h3><p>Companies like Google and OpenAI train and make available very large language models trained on very large text dataset scraped from the internet. For example, the famous GPT-3 is trained with 499 Billion tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/0*baX5jdu-pEC-xIRT" /></figure><p>GPT-3 and GPT-2 are trained using next word prediction, just the same as our language model. Unfortunately GPT-3 is not an open-source model, OpenAI opted to make it available through a commercial API so we have to settle for GPT-2.</p><p>We’re going to use three pre-trained language models all based on the transformer architecture proposed in the famous paper <a href="https://arxiv.org/pdf/1706.03762.pdf">“Attention is all you need”</a> by Vaswani et al., 2017:</p><ul><li>Bert by Google AI</li><li>GPT-2 by OpenAI</li><li>XLNet by Carnegie Mellon University and Google Brain team</li></ul><p>The best way to use these models is to use the<a href="https://huggingface.co/transformers/"> transformers library from Hugging Face</a>. In this way, we can build a standard pipeline and just change the model used.</p><h3>Bert</h3><p>Let’s start with Bert.</p><p>We use the standard pipeline from Hugging Face. We load the configuration provided by Hugging Face and change to False the parameter regarding returning the output from the hidden state:</p><pre>model_name = &#39;bert-base-uncased&#39; <br>max_length = 1000 <br>config = BertConfig.from_pretrained(model_name) config.output_hidden_states = False</pre><p>We load the same tokenizer used to train bert and we load the pre-trained model using the config defined before.</p><pre>tokenizer = BertTokenizer.from_pretrained(pretrained_model_name_or_path = model_name, config = config) </pre><pre># Load the Transformers BERT model <br>transformer_model = TFBertModel.from_pretrained(model_name, config = config)</pre><p>We can see the model with the summary method as usual:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*d2xgqQjoH78BAaQa" /></figure><p>We take just the main layer:</p><pre>bert = transformer_model.layers[0]</pre><p>And we define our inputs that need to follow the format required by Hugging Face (you can find it in the <a href="https://huggingface.co/transformers/">documentation</a>):</p><pre>input_ids = Input(shape=(max_length,), name=&#39;input_ids&#39;, dtype=&#39;int32&#39;) </pre><pre>attention_mask = Input(shape=(max_length,), name=&#39;attention_mask&#39;, dtype=&#39;int32&#39;) </pre><pre>inputs = {&#39;input_ids&#39;: input_ids, &#39;attention_mask&#39;: attention_mask}</pre><p>We can now define our model:</p><pre>bert_model = bert(inputs)[1] <br>dropout = Dropout(config.hidden_dropout_prob, name=&#39;pooled_output&#39;) pooled_output = dropout(bert_model, training=False) <br>dense_inter = Dense(128, activation=&#39;relu&#39;)(pooled_output) <br>logits = Dense(2)(dense_inter) model = Model(inputs=inputs, outputs=logits)</pre><p>And we see it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*T6RuLhiPZ6jWLeni" /></figure><p>We define our optimizer, loss and metric and we compile it:</p><pre>optimizer = Adam(learning_rate=1e-05, epsilon=1e-08, decay=0.01, clipnorm=1.0)<br> <br>loss = CategoricalCrossentropy(from_logits=True) metric = &#39;accuracy&#39; <br>model.compile(optimizer=optimizer, loss=loss, metrics=metric)</pre><p>We tokenize our train and test inputs using the BertTokenizer:</p><pre>X_train = tokenizer(text=df_train[&#39;review&#39;].to_list(), add_special_tokens=True, max_length=max_length, truncation=True, padding=True, return_tensors=&#39;tf&#39;, return_token_type_ids = False, return_attention_mask = True, verbose = True) </pre><pre>X_test = tokenizer(text=df_test[&#39;review&#39;].to_list(), add_special_tokens=True, max_length=max_length, truncation=True, padding=True, return_tensors=&#39;tf&#39;, return_token_type_ids = False, return_attention_mask = True, verbose = True)</pre><p>We fit the model:</p><pre>model.fit({&quot;input_ids&quot;: X_train[&quot;input_ids&quot;], &quot;attention_mask&quot;: X_train[&quot;attention_mask&quot;]}, y_train, batch_size=4, epochs=2)</pre><p>Epoch 1/2<br>6250/6250 [==============================] — 4153s 663ms/step — loss: 0.3503 — accuracy: 0.8488<br>Epoch 2/2<br>6250/6250 [==============================] — 4141s 663ms/step — loss: 0.2460 — accuracy: 0.9132</p><p>In the end we look at the accuracy on the test set:</p><pre>score, acc = model.evaluate({&quot;input_ids&quot;: X_test[&quot;input_ids&quot;], &quot;attention_mask&quot;: X_test[&quot;attention_mask&quot;]}, y_test)</pre><p>782/782 [==============================] — 1186s 2s/step — loss: 0.2610 — accuracy: 0.9129</p><p>Ok, we have an accuracy of 91.29%, not bad. We’re going in the right direction. The problem here is the amount of time to train these models. We were able to train just 2 epochs with a tiny batch size of 4. With a larger batch size, the GPU would go out of memory.</p><h3>GPT-2</h3><p>It’s time to use GPT-2. To make things more interesting, we use the larger version of GPT-2, while for Bert, we used the standard version. But since we have a bigger model, we use a max sequence length of 300 to be able to train it:</p><pre>model_name = &#39;gpt2-large&#39; <br>max_length = 300 <br>config = GPT2Config.from_pretrained(model_name) config.output_hidden_states = False</pre><pre>tokenizer = GPT2Tokenizer.from_pretrained(pretrained_model_name_or_path=model_name, config=config)</pre><pre>transformer_model = TFGPT2Model.from_pretrained(model_name, config=config)</pre><p>The pipeline is the same, take the main layer, define the model, the inputs, train and evaluate it:</p><pre>gpt2 = transformer_model.layers[0]<br>input_ids = Input(shape=(max_length,), name=&#39;input_ids&#39;, dtype=&#39;int32&#39;)<br>inputs = {&#39;input_ids&#39;: input_ids} </pre><pre>gpt2_model = gpt2(inputs)[0] <br>dense_inter = Flatten()(gpt2_model) logits = Dense(2)(dense_inter) model = Model(inputs=inputs, outputs=logits) <br>optimizer = Adam( learning_rate=1e-05, epsilon=1e-08, decay=0.01, clipnorm=1.0) <br>loss = CategoricalCrossentropy(from_logits=True) metric = &#39;accuracy&#39; model.compile( optimizer = optimizer, loss = loss, metrics = metric) </pre><pre>X_train = tokenizer( text=df_train[&#39;review&#39;].to_list(), add_special_tokens=True, max_length=max_length, truncation=True, padding=True, return_tensors=&#39;tf&#39;, return_token_type_ids = False, return_attention_mask = False, verbose = True) </pre><pre>X_test = tokenizer( text=df_test[&#39;review&#39;].to_list(), add_special_tokens=True, max_length=max_length, truncation=True, padding=True, return_tensors=&#39;tf&#39;, return_token_type_ids = False, return_attention_mask = False, verbose = True)</pre><pre>model.fit(X_train[&quot;input_ids&quot;], y_train, batch_size=2, epochs=2) </pre><pre>score, acc = model.evaluate(X_test[&quot;input_ids&quot;], y_test)</pre><p>Epoch 1/2<br>12500/12500 [==============================] — 7667s 611ms/step — loss: 0.3798 — accuracy: 0.8894<br>Epoch 2/2<br>12500/12500 [==============================] — 7637s 611ms/step — loss: 0.2418 — accuracy: 0.9406<br>782/782 [==============================] — 1857s 2s/step — loss: 0.3151 — accuracy: 0.9274</p><p>The accuracy jumps to 92.74%. Ok let’s go to the last model.</p><h3>XLNet</h3><p>The pipeline is the same, we use the standard model because this is a bigger model and even in its base form we needed to reduce the sequence length to 500 to train it.</p><pre>model_name = &#39;xlnet-base-cased&#39; <br>max_length = 500 <br>config = XLNetConfig.from_pretrained(model_name) config.output_hidden_states = False</pre><pre>tokenizer = XLNetTokenizer.from_pretrained(pretrained_model_name_or_path=model_name, config=config) </pre><pre>transformer_model = TFXLNetModel.from_pretrained(model_name, config=config)</pre><p>We train the model:</p><pre>model.fit(X_train[&quot;input_ids&quot;], y_train, batch_size=4, epochs=2)</pre><p>Epoch 1/2<br>6250/6250 [==============================] — 3524s 562ms/step — loss: 0.4341 — accuracy: 0.8810<br>Epoch 2/2<br>6250/6250 [==============================] — 3512s 562ms/step — loss: 0.2526 — accuracy: 0.9397</p><p>And we evaluate it on the test set:</p><pre>score, acc = model.evaluate(X_test[&quot;input_ids&quot;], y_test)</pre><p>782/782 [==============================] — 941s 1s/step — loss: 0.2861 — accuracy: 0.9370</p><p>Ok so in the end we were able to reach an accuracy of 93.70%.</p><h3>Conclusion</h3><p>Our best score was 93.70%, and it’s not bad at all. But we could get better results in three ways:</p><ul><li>Train for more epochs</li><li>Train with a bigger sequence length</li><li>Fine-tune the language model on the reviews</li></ul><p>We couldn’t explore any of these options for one simple reason, we don’t have a powerful enough GPU. Right now, this is the biggest problem with NLP. To train big models, you need to spend a lot of money on cloud GPU (according to <a href="https://lambdalabs.com/blog/demystifying-gpt-3/">one estimate</a>, training GPT-3 would cost at least $4.6 million).</p><p>You can find all the code on my <a href="https://github.com/antonai91/nlp/tree/main/imdb">Github</a>. For any questions, you can reach me through <a href="https://www.linkedin.com/in/lisiantonio/">Linkedin</a>.</p><p>Before saying goodbye, if you want to be notified when I post something, you can subscribe below.</p><p>If you enjoyed this article, share it with your friends and colleagues! I’ll see you in the next post. In the meantime, take care, stay safe, and remember <em>don’t be another brick in the wall</em>.</p><p>Anton.ai</p><p><em>Originally published at </em><a href="https://antonai.blog/how-to-achieve-state-of-the-art-results-on-nlp-classification-tasks/"><em>https://antonai.blog</em></a><em> on April 1, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342fa07c7fe9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-achieve-state-of-the-art-results-on-nlp-classification-tasks-342fa07c7fe9">How to achieve state of the art results on NLP classification tasks</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning to walk using Reinforcement Learning]]></title>
            <link>https://medium.com/analytics-vidhya/learning-to-walk-using-reinforcement-learning-4e237aaf64a0?source=rss-4bba14bd6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e237aaf64a0</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Antonio Lisi]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 09:32:49 GMT</pubDate>
            <atom:updated>2021-04-09T07:43:14.421Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Teaching a robot to walk</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*vMxiDBFKTztHcFQ-.png" /></figure><p><em>By Antonio Lisi<br>To my grandma, I’ll miss you</em></p><h3>Intro</h3><p>Hello everyone, in this post, we’re going to teach a robot to walk using one of the latest state-of-the-art algorithms, called SAC.</p><p>As always, we implement everything from scratch using Tensorflow 2. We’ll use a lot of the code developed in the post about <a href="https://medium.com/analytics-vidhya/reinforcement-learning-in-continuous-action-spaces-ddpg-bbd64aa5434">DDPG</a>. So if you didn’t read it, I recommend doing it before going forward.</p><h3>Environment</h3><p>In the <a href="https://medium.com/analytics-vidhya/reinforcement-learning-in-continuous-action-spaces-ddpg-bbd64aa5434">DDPG post</a>, we solved two environments provided by OpenAI. But they were too easy, I wanted to try more challenging continuous action spaces environments.</p><p>One of the most popular packages is <a href="http://www.mujoco.org/">MuJoCo</a>. MuJoCo stands for Multi-Joint dynamics with Contact and citing from the site “is a physics engine aiming to facilitate research and development in robotics, biomechanics, graphics and animation, and other areas where fast and accurate simulation is needed. It offers a unique combination of speed, accuracy and modeling power, yet it is not merely a better simulator”. Unfortunately, MuJoCo isn’t free, it requires a license.</p><p>After googling around, I found an open-source alternative called PyBullet that is very similar to MuJoco. You can install it by running pip install pybullet, and you can find the list of the available environments <a href="https://docs.google.com/document/d/10sXEhzFRSnvFcl3XxNGhnD4N2SedqwdAvK3dsihxVUA/edit#heading=h.wz5to0x8kqmr">here</a>.</p><p>From all the environments available on pybullet I decided to solve the “Humanoid” where the goal is for a humanoid to learn to walk. Humanoid and other environments are ported the Roboschool environments to pybullet. The <a href="https://openai.com/blog/roboschool/">Roboschool</a> environments are harder than the MuJoCo Gym environments. In particular, from the documentation “Humanoid benefits from more realistic energy cost (= torque × angular velocity) subtracted from the reward.”</p><p>Let’s see how a Random Agent perform in this case:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FErqJOIJOBKc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DErqJOIJOBKc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FErqJOIJOBKc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/392e42c7ef3965acd6d43926db825d28/href">https://medium.com/media/392e42c7ef3965acd6d43926db825d28/href</a></iframe><p>Ok, we have a lot to improve. Let’s start talking about the algorithm that we’re going to use to teach this robot how to walk.</p><h3>Soft Actor Critic (SAC)</h3><p>Introduced in the paper <a href="http://proceedings.mlr.press/v80/haarnoja18b/haarnoja18b.pdf"><em>Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning</em></a> by <em>Tuomas Taarnoja et al.</em>, it is considered one of the best algorithms to solve continuous action spaces environments.</p><p>SAC combines off-policy updates with a stable stochastic actor-critic formulation. It forms a bridge between stochastic policy optimization and DDPG-style approaches.</p><p>SAC simultaneously tries to maximize the expected return and the entropy of the policy using the same intuition that we saw in PPO (you can find the post <a href="https://medium.com/analytics-vidhya/beating-pong-using-reinforcement-learning-part-2-a2c-and-ppo-b83391dd3657">here</a>). The main difference is that in SAC, we’re trying to maximize the entropy, while in PPO, we used the entropy as a regularizer. But the goal is the same, we want to encourage exploration and penalize policy with low entropy.</p><p>From the original paper we can see what the SAC will maximize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/0*xviTvzECaAxzCkVo.png" /></figure><p>The first part is the expected return, while the second part is the entropy of the policy. The α parameter is the temperature and determines the relative importance of the entropy term against the expected return. As stated in the paper, the temperature can always be subsumed into the reward by scaling it by α−1.</p><p>Also, from the paper, the maximum entropy reinforcement learning can make use<br>of Q-functions and value functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*9REEz8E5T5Rf0bQb.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*ayWffFrJr4FpJWnf.png" /></figure><p>SAC makes use of three types of networks to approximate:</p><ul><li>the state value function V</li><li>the soft Q-function Q</li><li>the policy function π</li></ul><p>As you can see in the above formulas, the V and Q functions are related through the policy. So in principle, we could derive one from the other, and we don’t need two separate approximations. But the authors say that in practice having separate function approximators helps in convergence.</p><p>The SAC algorithms also use the clipped double-Q trick, introduced in <a href="https://arxiv.org/pdf/1802.09477v3.pdf"><em>Addressing Function Approximation Error in Actor-Critic Methods</em></a> by Fujimoto et. al.. So there will be two networks to predict the Q-values, and we’ll take the minimum of the two predictions. This helps with dealing with Q-value overestimation during the training.</p><p>So in total, we’ll have 5 networks:</p><ul><li>the Actor that defines the policy</li><li>two Critic Q-values</li><li>the Critic Value</li><li>the Target Critic Value</li></ul><p>The target critic value is used as we saw in the DDPG post. It is a time-delayed copy of the original network that slowly updates its weights to improve learning stability.</p><p>The Q-networks are trained using the MSE objective by doing Bellman approximation using the target value network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*jJu_1CmZ804r5fZX.png" /></figure><p>The V-network is trained using the MSE objective with the following target:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*CBnNH6F0OFkbGXjn.png" /></figure><p>The actor is trained to maximize the expected future return plus expected future entropy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/0*XuYrp7y-AndiUX4s.png" /></figure><p>We’ll use here the reparameterization trick to make the randomness an input of the network. This will be clearer in the code.</p><h3>Replay Buffer</h3><p>As always we start with the Replay Buffer:</p><pre>class ReplayBuffer():<br>    def __init__(self, env, buffer_capacity=BUFFER_CAPACITY, batch_size=BATCH_SIZE, min_size_buffer=MIN_SIZE_BUFFER):<br>        self.buffer_capacity = buffer_capacity<br>        self.batch_size = batch_size<br>        self.min_size_buffer = min_size_buffer<br>        self.buffer_counter = 0<br>        self.n_games = 0<br>        <br>        self.states = np.zeros((self.buffer_capacity, env.observation_space.shape[0]))<br>        self.actions = np.zeros((self.buffer_capacity, env.action_space.shape[0]))<br>        self.rewards = np.zeros((self.buffer_capacity))<br>        self.next_states = np.zeros((self.buffer_capacity, env.observation_space.shape[0]))<br>        self.dones = np.zeros((self.buffer_capacity), dtype=bool)<br>        <br>        <br>    def __len__(self):<br>        return self.buffer_counter<br>    def add_record(self, state, action, reward, next_state, done):<br>        # Set index to zero if counter = buffer_capacity and start again (1 % 100 = 1 and 101 % 100 = 1) so we substitute the older entries<br>        index = self.buffer_counter % self.buffer_capacity<br>        self.states[index] = state<br>        self.actions[index] = action<br>        self.rewards[index] = reward<br>        self.next_states[index] = next_state<br>        self.dones[index] = done<br>        <br>        # Update the counter when record something<br>        self.buffer_counter += 1<br>    <br>    def check_buffer_size(self):<br>        return self.buffer_counter &gt;= self.batch_size and self.buffer_counter &gt;= self.min_size_buffer<br>    <br>    def update_n_games(self):<br>        self.n_games += 1<br>    <br>    def get_minibatch(self):<br>        # If the counter is less than the capacity we don&#39;t want to take zeros records, <br>        # if the cunter is higher we don&#39;t access the record using the counter <br>        # because older records are deleted to make space for new one<br>        buffer_range = min(self.buffer_counter, self.buffer_capacity)<br>        <br>        batch_index = np.random.choice(buffer_range, self.batch_size, replace=False)<br>        # Convert to tensors<br>        state = self.states[batch_index]<br>        action = self.actions[batch_index]<br>        reward = self.rewards[batch_index]<br>        next_state = self.next_states[batch_index]<br>        done = self.dones[batch_index]<br>        <br>        return state, action, reward, next_state, done<br>    <br>    def save(self, folder_name):<br>        &quot;&quot;&quot;<br>        Save the replay buffer<br>        &quot;&quot;&quot;<br>        if not os.path.isdir(folder_name):<br>            os.mkdir(folder_name)<br>        np.save(folder_name + &#39;/states.npy&#39;, self.states)<br>        np.save(folder_name + &#39;/actions.npy&#39;, self.actions)<br>        np.save(folder_name + &#39;/rewards.npy&#39;, self.rewards)<br>        np.save(folder_name + &#39;/next_states.npy&#39;, self.next_states)<br>        np.save(folder_name + &#39;/dones.npy&#39;, self.dones)<br>        <br>        dict_info = {&quot;buffer_counter&quot;: self.buffer_counter, &quot;n_games&quot;: self.n_games}<br>        <br>        with open(folder_name + &#39;/dict_info.json&#39;, &#39;w&#39;) as f:<br>            json.dump(dict_info, f)<br>    def load(self, folder_name):<br>        &quot;&quot;&quot;<br>        Load the replay buffer<br>        &quot;&quot;&quot;<br>        self.states = np.load(folder_name + &#39;/states.npy&#39;)<br>        self.actions = np.load(folder_name + &#39;/actions.npy&#39;)<br>        self.rewards = np.load(folder_name + &#39;/rewards.npy&#39;)<br>        self.next_states = np.load(folder_name + &#39;/next_states.npy&#39;)<br>        self.dones = np.load(folder_name + &#39;/dones.npy&#39;)<br>        <br>        with open(folder_name + &#39;/dict_info.json&#39;, &#39;r&#39;) as f:<br>            dict_info = json.load(f)<br>        self.buffer_counter = dict_info[&quot;buffer_counter&quot;]<br>        self.n_games = dict_info[&quot;n_games&quot;]</pre><p>It’s basically the same code from the DDPG article. We store all the states, actions, rewards, next_states, and terminal flags derived from the interaction with the environment calling the function add_record. We get a random minibatch using the get_minibatch method, and we can save and load the entire replay buffer with the save and load methods.</p><h3>Networks</h3><p>As said before, we need to define three types of networks that approximate the state value function V, the soft Q-function, and the policy function π. So we need two types of Critics and one Actor.</p><h3>Critic Q Value</h3><pre>class Critic(tf.keras.Model):<br>    def __init__(self, name, hidden_0=CRITIC_HIDDEN_0, hidden_1=CRITIC_HIDDEN_1):<br>        super(Critic, self).__init__()<br>        self.hidden_0 = hidden_0<br>        self.hidden_1 = hidden_1<br>        self.net_name = name<br>        self.dense_0 = Dense(self.hidden_0, activation=&#39;relu&#39;)<br>        self.dense_1 = Dense(self.hidden_1, activation=&#39;relu&#39;)<br>        self.q_value = Dense(1, activation=None)<br>    def call(self, state, action):<br>        state_action_value = self.dense_0(tf.concat([state, action], axis=1))<br>        state_action_value = self.dense_1(state_action_value)<br>        q_value = self.q_value(state_action_value)<br>        return q_value</pre><p>Nothing new here, it’s basically the same used in the DDPG article.</p><h3>Critic Value</h3><pre>class CriticValue(tf.keras.Model):<br>    def __init__(self, name, hidden_0=CRITIC_HIDDEN_0, hidden_1=CRITIC_HIDDEN_1):<br>        super(CriticValue, self).__init__()<br>        self.hidden_0 = hidden_0<br>        self.hidden_1 = hidden_1<br>        self.net_name = name<br>        <br>        self.dense_0 = Dense(self.hidden_0, activation=&#39;relu&#39;)<br>        self.dense_1 = Dense(self.hidden_1, activation=&#39;relu&#39;)<br>        self.value = Dense(1, activation=None)<br>    def call(self, state):<br>        value = self.dense_0(state)<br>        value = self.dense_1(value)<br>        value = self.value(value)<br>        return value</pre><p>We can see that we don’t need the actions as input to approximate the State Value, but just the state (the state value function maps a state to its expected reward).</p><h3>Actor</h3><pre>class Actor(tf.keras.Model):<br>    def __init__(self, name, upper_bound, actions_dim, hidden_0=CRITIC_HIDDEN_0, hidden_1=CRITIC_HIDDEN_1, epsilon=EPSILON, log_std_min=LOG_STD_MIN, log_std_max=LOG_STD_MAX):<br>        super(Actor, self).__init__()<br>        self.hidden_0 = hidden_0<br>        self.hidden_1 = hidden_1<br>        self.actions_dim = actions_dim<br>        self.net_name = name<br>        self.upper_bound = upper_bound<br>        self.epsilon = epsilon<br>        self.log_std_min = log_std_min<br>        self.log_std_max = log_std_max<br>        self.dense_0 = Dense(self.hidden_0, activation=&#39;relu&#39;)<br>        self.dense_1 = Dense(self.hidden_1, activation=&#39;relu&#39;)<br>        self.mean = Dense(self.actions_dim, activation=None)<br>        self.log_std = Dense(self.actions_dim, activation=None)<br>    def call(self, state):<br>        policy = self.dense_0(state)<br>        policy = self.dense_1(policy)<br>        mean = self.mean(policy)<br>        log_std = self.log_std(policy)<br>        log_std = tf.clip_by_value(log_std, self.log_std_min, self.log_std_max)<br>        return mean, log_std<br>    def get_action_log_probs(self, state, reparameterization_trick=True):<br>        mean, log_std = self.call(state)<br>        std = tf.exp(log_std)<br>        normal_distr = tfp.distributions.Normal(mean, std)<br>        # Reparameterization trick<br>        z = tf.random.normal(shape=mean.shape, mean=0., stddev=1.)<br>        if reparameterization_trick:<br>            actions = mean + std * z<br>        else:<br>            actions = normal_distr.sample()<br>        action = tf.math.tanh(actions) * self.upper_bound<br>        log_probs = normal_distr.log_prob(actions) - tf.math.log(1 - tf.math.pow(action,2) + self.epsilon)<br>        log_probs = tf.math.reduce_sum(log_probs, axis=1, keepdims=True)<br>        return action, log_probs</pre><p>The Actor network returns two outputs, the mean and the log standard deviation. We use the log standard deviations because the exponential always gives a positive number. The log standard deviation is also clipped to an interval to avoid extreme values that could create problems at the beginning of the training.</p><p>Note that in the get_action_log_probs method, we activate the reparameterization trick using a flag. When true, we sample some noise from a Standard Normal distribution, multiply it with the standard deviation (exponential value of the log that the Actor returns) and add the result to the mean. When False, we just use a Normal distribution with mean and standard deviation equal to the values returned by the Network.</p><p>The concept of the reparameterization trick was introduced in <a href="https://arxiv.org/pdf/1312.6114v10.pdf">Auto-Encoding Variational Bayes</a> by Kingma et al., and we need it to backpropagate through a random node. If you want to go deeper on this concept, I found a great explanation <a href="https://gregorygundersen.com/blog/2018/04/29/reparameterization/">here</a> that clarified the concept for me. But why we’re using it here? Because it has lower variance, and it helps a faster convergence of the algorithm.</p><h3>Agent</h3><p>We can now look at the <em>“brain”</em> of the Agent:</p><pre>class Agent:<br>    def __init__(self, env, path_save=PATH_SAVE, path_load=PATH_LOAD, actor_lr=ACTOR_LR, critic_lr=CRITIC_LR, gamma=GAMMA, tau=TAU, reward_scale=REWARD_SCALE):<br>        self.gamma = gamma<br>        self.tau = tau<br>        self.replay_buffer = ReplayBuffer(env)<br>        self.actions_dim = env.action_space.shape[0]<br>        self.upper_bound = env.action_space.high[0]<br>        self.lower_bound = env.action_space.low[0]<br>        self.actor_lr = actor_lr<br>        self.critic_lr = critic_lr<br>        self.path_save = path_save<br>        self.path_load = path_load</pre><pre>        self.actor = Actor(actions_dim=self.actions_dim, name=&#39;actor&#39;, upper_bound=env.action_space.high)<br>        self.critic_0 = Critic(name=&#39;critic_0&#39;)<br>        self.critic_1 = Critic(name=&#39;critic_1&#39;)<br>        self.critic_value = CriticValue(name=&#39;value&#39;)<br>        self.critic_target_value = CriticValue(name=&#39;target_value&#39;)</pre><pre>        self.actor.compile(optimizer=opt.Adam(learning_rate=self.actor_lr))<br>        self.critic_0.compile(optimizer=opt.Adam(learning_rate=self.critic_lr))<br>        self.critic_1.compile(optimizer=opt.Adam(learning_rate=self.critic_lr))<br>        self.critic_value.compile(optimizer=opt.Adam(learning_rate=self.critic_lr))<br>        self.critic_target_value.compile(optimizer=opt.Adam(learning_rate=self.critic_lr))</pre><pre>        self.reward_scale = reward_scale</pre><pre>        self.critic_target_value.set_weights(self.critic_value.weights)</pre><p>In the __init__ method, we define all the parameters from the config file that the Agent will use. We define the replay buffer and the 5 networks that we talked about. As always, we set the target network weights equal to the corresponding trained network.</p><p>We then have a series of utility methods that we also used in the DDPG code:</p><pre>def add_to_replay_buffer(self, state, action, reward, new_state, done):<br>        self.replay_buffer.add_record(state, action, reward, new_state, done)<br>        <br>    def save(self):<br>        date_now = time.strftime(&quot;%Y%m%d%H%M&quot;)<br>        if not os.path.isdir(f&quot;{self.path_save}/save_agent_{ENV_NAME.lower()}_{date_now}&quot;):<br>            os.makedirs(f&quot;{self.path_save}/save_agent_{ENV_NAME.lower()}_{date_now}&quot;)<br>        self.actor.save_weights(f&quot;{self.path_save}/save_agent_{ENV_NAME.lower()}_{date_now}/{self.actor.net_name}.h5&quot;)<br>        self.critic_0.save_weights(f&quot;{self.path_save}/save_agent_{ENV_NAME.lower()}_{date_now}/{self.critic_0.net_name}.h5&quot;)<br>        self.critic_1.save_weights(f&quot;{self.path_save}/save_agent_{ENV_NAME.lower()}_{date_now}/{self.critic_1.net_name}.h5&quot;)<br>        self.critic_value.save_weights(f&quot;{self.path_save}/save_agent_{ENV_NAME.lower()}_{date_now}/{self.critic_value.net_name}.h5&quot;)<br>        self.critic_target_value.save_weights(f&quot;{self.path_save}/save_agent_{ENV_NAME.lower()}_{date_now}/{self.critic_target_value.net_name}.h5&quot;)<br>        <br>        self.replay_buffer.save(f&quot;{self.path_save}/save_agent_{ENV_NAME.lower()}_{date_now}&quot;)</pre><pre>    def load(self):<br>        self.actor.load_weights(f&quot;{self.path_load}/{self.actor.net_name}.h5&quot;)<br>        self.critic_0.load_weights(f&quot;{self.path_load}/{self.critic_0.net_name}.h5&quot;)<br>        self.critic_1.load_weights(f&quot;{self.path_load}/{self.critic_1.net_name}.h5&quot;)<br>        self.critic_value.load_weights(f&quot;{self.path_load}/{self.critic_value.net_name}.h5&quot;)<br>        self.critic_target_value.load_weights(f&quot;{self.path_load}/{self.critic_target_value.net_name}.h5&quot;)<br>        <br>        self.replay_buffer.load(f&quot;{self.path_load}&quot;)</pre><pre>    def get_action(self, observation):<br>        state = tf.convert_to_tensor([observation])<br>        actions, _ = self.actor.get_action_log_probs(state, reparameterization_trick=False)</pre><pre>        return actions[0]</pre><p>Nothing new here, let’s look at the learn method where things get interesting:</p><pre>def learn(self):<br>        if self.replay_buffer.check_buffer_size() == False:<br>            return</pre><pre>        state, action, reward, new_state, done = self.replay_buffer.get_minibatch()</pre><pre>        states = tf.convert_to_tensor(state, dtype=tf.float32)<br>        new_states = tf.convert_to_tensor(new_state, dtype=tf.float32)<br>        rewards = tf.convert_to_tensor(reward, dtype=tf.float32)<br>        actions = tf.convert_to_tensor(action, dtype=tf.float32)</pre><pre>        with tf.GradientTape() as tape:<br>            value = tf.squeeze(self.critic_value(states), 1)<br>            target_value = tf.squeeze(self.critic_target_value(new_states), 1)</pre><pre>            policy_actions, log_probs = self.actor.get_action_log_probs(states, reparameterization_trick=False)<br>            log_probs = tf.squeeze(log_probs,1)<br>            q_value_0 = self.critic_0(states, policy_actions)<br>            q_value_1 = self.critic_1(states, policy_actions)<br>            q_value = tf.squeeze(tf.math.minimum(q_value_0, q_value_1), 1)</pre><pre>            value_target = q_value - log_probs<br>            value_critic_loss = 0.5 * tf.keras.losses.MSE(value, value_target)</pre><pre>        value_critic_gradient = tape.gradient(value_critic_loss, self.critic_value.trainable_variables)<br>        self.critic_value.optimizer.apply_gradients(zip(value_critic_gradient, self.critic_value.trainable_variables))<br></pre><pre>        with tf.GradientTape() as tape:<br>            new_policy_actions, log_probs = self.actor.get_action_log_probs(states, reparameterization_trick=True)<br>            log_probs = tf.squeeze(log_probs, 1)<br>            new_q_value_0 = self.critic_0(states, new_policy_actions)<br>            new_q_value_1 = self.critic_1(states, new_policy_actions)<br>            new_q_value = tf.squeeze(tf.math.minimum(new_q_value_0, new_q_value_1), 1)<br>        <br>            actor_loss = log_probs - new_q_value<br>            actor_loss = tf.math.reduce_mean(actor_loss)</pre><pre>        actor_gradient = tape.gradient(actor_loss, self.actor.trainable_variables)<br>        self.actor.optimizer.apply_gradients(zip(actor_gradient, self.actor.trainable_variables))<br>        </pre><pre>        with tf.GradientTape(persistent=True) as tape:<br>            q_pred = self.reward_scale * reward + self.gamma * target_value * (1-done)<br>            old_q_value_0 = tf.squeeze(self.critic_0(state, action), 1)<br>            old_q_value_1 = tf.squeeze(self.critic_1(state, action), 1)<br>            critic_0_loss = 0.5 * tf.keras.losses.MSE(old_q_value_0, q_pred)<br>            critic_1_loss = 0.5 * tf.keras.losses.MSE(old_q_value_1, q_pred)<br>    <br>        critic_0_network_gradient = tape.gradient(critic_0_loss, self.critic_0.trainable_variables)<br>        critic_1_network_gradient = tape.gradient(critic_1_loss, self.critic_1.trainable_variables)</pre><pre>        self.critic_0.optimizer.apply_gradients(zip(critic_0_network_gradient, self.critic_0.trainable_variables))<br>        self.critic_1.optimizer.apply_gradients(zip(critic_1_network_gradient, self.critic_1.trainable_variables))</pre><pre>        self.update_target_networks(tau=self.tau)<br>        <br>        self.replay_buffer.update_n_games()</pre><p>We have four networks to train:</p><ul><li>Critic Value</li><li>Actor</li><li>Critic Q-value 0</li><li>Critic Q-value 1</li></ul><h3>Critic Value</h3><pre>with tf.GradientTape() as tape:<br>            value = tf.squeeze(self.critic_value(states), 1)<br>            target_value = tf.squeeze(self.critic_target_value(new_states), 1)</pre><pre>            policy_actions, log_probs = self.actor.get_action_log_probs(states, reparameterization_trick=False)<br>            log_probs = tf.squeeze(log_probs,1)<br>            q_value_0 = self.critic_0(states, policy_actions)<br>            q_value_1 = self.critic_1(states, policy_actions)<br>            q_value = tf.squeeze(tf.math.minimum(q_value_0, q_value_1), 1)</pre><pre>            value_target = q_value - log_probs<br>            value_critic_loss = tf.keras.losses.MSE(value, value_target)<br>        value_critic_gradient = tape.gradient(value_critic_loss, self.critic_value.trainable_variables)<br>        self.critic_value.optimizer.apply_gradients(zip(value_critic_gradient, self.critic_value.trainable_variables))</pre><p>We take the prediction of the value network and its corresponding target network. Then we use the actor’s policy to have the q-value from the Q-value networks using the clipped double-Q trick that we talked about. We define the predicted/target value as the difference between the Q-value and the log probabilities. In the end, the loss is the mean squared error between the value estimated and the value that the value predicted by the value network.</p><h3>Actor</h3><pre>with tf.GradientTape() as tape:<br>            new_policy_actions, log_probs = self.actor.get_action_log_probs(states, reparameterization_trick=True)<br>            log_probs = tf.squeeze(log_probs, 1)<br>            new_q_value_0 = self.critic_0(states, new_policy_actions)<br>            new_q_value_1 = self.critic_1(states, new_policy_actions)<br>            new_q_value = tf.squeeze(tf.math.minimum(new_q_value_0, new_q_value_1), 1)<br>        <br>            actor_loss = log_probs - new_q_value<br>            actor_loss = tf.math.reduce_mean(actor_loss)</pre><pre>        actor_gradient = tape.gradient(actor_loss, self.actor.trainable_variables)<br>        self.actor.optimizer.apply_gradients(zip(actor_gradient, self.actor.trainable_variables))</pre><p>As before, we get the action and log probabilities from the actor, the Q-value from the two Critics, and we define the loss as the difference between the log distribution and the Q-value. Notice here that we want to maximize Q-value — log(π), so we define the loss as the objective function multiplied by -1.</p><h3>Critic Q-value</h3><pre>with tf.GradientTape(persistent=True) as tape:<br>            q_pred = self.reward_scale * reward + self.gamma * target_value * (1-done)<br>            old_q_value_0 = tf.squeeze(self.critic_0(state, action), 1)<br>            old_q_value_1 = tf.squeeze(self.critic_1(state, action), 1)<br>            critic_0_loss = tf.keras.losses.MSE(old_q_value_0, q_pred)<br>            critic_1_loss = tf.keras.losses.MSE(old_q_value_1, q_pred)<br>    <br>        critic_0_network_gradient = tape.gradient(critic_0_loss, self.critic_0.trainable_variables)<br>        critic_1_network_gradient = tape.gradient(critic_1_loss, self.critic_1.trainable_variables)</pre><pre>        self.critic_0.optimizer.apply_gradients(zip(critic_0_network_gradient, self.critic_0.trainable_variables))<br>        self.critic_1.optimizer.apply_gradients(zip(critic_1_network_gradient, self.critic_1.trainable_variables))</pre><p>We need to compute multiple gradients over the same computation for the Critic Q-value networks, so we use a persistent gradient tape. We define the predicted Q-value as the reward in the single episode plus the present value of the value predicted by the Target Critic Value Network. We can see here the reward scale that, as said before, is the inverse of the entropy temperature. The loss for the two networks is the mean squared error between this value and their predictions.</p><h3>Training loop and results</h3><p>We can now see the training loop and the results.</p><pre>config = dict(<br>  learning_rate_actor = ACTOR_LR,<br>  learning_rate_critic = ACTOR_LR,<br>  batch_size = BATCH_SIZE,<br>  architecture = &quot;SAC&quot;,<br>  infra = &quot;Colab&quot;,<br>  env = ENV_NAME<br>)</pre><pre>wandb.init(<br>  project=f&quot;tensorflow2_sac_{ENV_NAME.lower()}&quot;,<br>  tags=[&quot;SAC&quot;, &quot;FCL&quot;, &quot;RL&quot;],<br>  config=config,<br>)</pre><pre>env = gym.make(ENV_NAME)<br>agent = Agent(env)</pre><pre>scores = []<br>evaluation = True</pre><pre>if PATH_LOAD is not None:<br>    print(&quot;loading weights&quot;)<br>    observation = env.reset()<br>    action, log_probs = agent.actor.get_action_log_probs(observation[None, :], False)<br>    agent.actor(observation[None, :])<br>    agent.critic_0(observation[None, :], action)<br>    agent.critic_1(observation[None, :], action)<br>    agent.critic_value(observation[None, :])<br>    agent.critic_target_value(observation[None, :])<br>    agent.load()<br>    print(agent.replay_buffer.buffer_counter)<br>    print(agent.replay_buffer.n_games)</pre><p>We configure <a href="https://wandb.ai/">wandb</a> for logging and we load any pre-trained agent.</p><p>In the end, we have the training loop:</p><pre>for _ in tqdm(range(MAX_GAMES)):<br>    start_time = time.time()<br>    states = env.reset()<br>    done = False<br>    score = 0<br>    while not done:<br>        action = agent.get_action(states)<br>        new_states, reward, done, info = env.step(action)<br>        score += reward<br>        agent.add_to_replay_buffer(states, action, reward, new_states, done)<br>        agent.learn()<br>        states = new_states<br>    <br>    scores.append(score)<br>    agent.replay_buffer.update_n_games()</pre><pre>    wandb.log({&#39;Game number&#39;: agent.replay_buffer.n_games, &#39;# Episodes&#39;: agent.replay_buffer.buffer_counter, <br>               &quot;Average reward&quot;: round(np.mean(scores[-10:]), 2), \<br>                      &quot;Time taken&quot;: round(time.time() - start_time, 2)})<br>    <br>    if (_ + 1) % SAVE_FREQUENCY == 0:<br>        print(&quot;saving...&quot;)<br>        agent.save()<br>        print(&quot;saved&quot;)</pre><p>The training loop is always the same, we interact with the environment, save the states, actions, rewards, and terminal flags in the replay buffer, and we train the agent using the method learn() seen before. When the episode is over, we evaluate the results logging the mean of the last ten games, and we save the networks and replay buffer every SAVE_FREQUENCY (defined at 200 in the config file) times.</p><p>Looking at the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sPa6c2qQ6CVFfvEF.png" /></figure><p>As we can see, the average rewards start to increase after 1k interactions. This took a while, but we can see how the agent started learning to walk:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5hqy0zeHvZM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5hqy0zeHvZM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5hqy0zeHvZM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/071eba8f4896682b825b0d53eef7b49b/href">https://medium.com/media/071eba8f4896682b825b0d53eef7b49b/href</a></iframe><p>Ok, the guy can stand and do some little walking, but as you can see, there’s much more to learn. But at this point is just training time.</p><p>You can find the original article on my <a href="https://antonai.blog/learning-to-walk-using-reinforcement-learning/">blog</a> and all the code on my <a href="https://github.com/antonai91/reinforcement_learning/tree/master/sac">Github</a>. For any questions, you can reach me through <a href="https://www.linkedin.com/in/lisiantonio/">Linkedin</a>.</p><p>If you enjoyed this article, share it with your friends and colleagues! I’ll see you in the next post. In the meantime, take care, stay safe, and remember <em>don’t be another brick in the wall</em>.</p><p>Anton.ai</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e237aaf64a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/learning-to-walk-using-reinforcement-learning-4e237aaf64a0">Learning to walk using Reinforcement Learning</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning in Continuous Action Spaces: DDPG]]></title>
            <link>https://medium.com/analytics-vidhya/reinforcement-learning-in-continuous-action-spaces-ddpg-bbd64aa5434?source=rss-4bba14bd6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbd64aa5434</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Antonio Lisi]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 12:00:20 GMT</pubDate>
            <atom:updated>2021-04-09T07:43:46.908Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Diving deep into Reinforcement Learning</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*CovY52wifDrKoArS" /></figure><p><em>By Antonio Lisi</em></p><h3>Intro</h3><p>Hello everyone, this is the third post on reinforcement learning and the start of a new series that is focusing on continuous action environments.</p><p>In this post, we will implement DDPG from scratch, and we will try to solve <a href="https://gym.openai.com/envs/Pendulum-v0/">Pendulum</a> and <a href="https://gym.openai.com/envs/LunarLanderContinuous-v2/">Lunar Lander</a>.</p><h3>Why the Continuous Action Spaces?</h3><p>Before proceeding further, we need to motivate why we’re moving to solve continuous space environments. Until now, we always solved pong, but you could use the algorithms, the approach, and even all the code to solve any other Atari game.</p><p>But many real-world applications of reinforcement learning require an agent to select actions from continuous spaces. For example, Autonomous Robotics requires an agent to take action in a continuous space. The same goes for autonomous driving, which is, by the way, one of the hottest topics in the automotive industry.</p><h3>Environments to solve</h3><p>As said in the introduction section, we’ll solve two environments from the OpeanAI gym library.</p><h3>Pendulum</h3><p>We start with Pendulum, which is a classical environment to start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*ejDByj6ud2eatzmE" /></figure><p>The goal is to try to keep a frictionless pendulum standing up. We can see the input and the action characteristics with the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*D1CIfn-y5FLyvb7y" /></figure><p>The input consists of three observations. Looking at the <a href="https://github.com/openai/gym/wiki/Pendulum-v0">documentation</a>, we can see that they represent the angle of the pendulum (cosine and sine of theta) and its angular velocity (theta dot). On the other hand, we know that the action is a single value between -2.0 and 2.0, and it represents the amount of left or right force on the pendulum. The precise equation for the reward:</p><p>-(theta2 + 0.1*theta2dt + 0.001*action2)</p><h3>Lunar Lander</h3><p>Another classical environment to solve is Lunar Lander (in its continuous version).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zERVQi5VbPjX8Cmz" /></figure><p>The game’s main goal is to direct the agent to the landing pad as softly and fuel-efficiently as possible. From the <a href="https://github.com/openai/gym/wiki/Leaderboard#lunarlander-v2">documentation</a>, we know that the landing pad is always at coordinates (0,0). As before, we can see the input and action characteristics using the same code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*KCtHcq3RSfwzBQUA" /></figure><p>The input consist of 8 values that are:</p><ol><li>x coordinate of the lander</li><li>y coordinate of the lander</li><li>vx, the horizontal velocity</li><li>vy, the vertical velocity</li><li>θ, the orientation in space</li><li>vθ, the angular velocity</li><li>Left leg touching the ground (Boolean)</li><li>Right leg touching the ground (Boolean)</li></ol><p>The action is a two values array from -1 to +1 for both dimensions. The first one controls the main engine, -1.0 is off, and from 0 to 1.0, the engine’s power goes from 50% to 100% power. The engine can’t work with less than 50% of the power. The second value controls the left and right engines. From -1.0 to -0.5, it fires the left engine; from 0.5 to 1.0, it fires the right engine; from -0.5 to 0.5, the engines are off.</p><p>The Reward for moving from the top of the screen to the landing pad and zero speed is from 100 to 140 points. If the lander moves away from the landing pad, it loses the reward. The episode finishes if the lander crashes or comes to rest, receiving additional -100 or +100 points. Each leg ground contact is +10. Firing the main engine is -0.3 points for each frame.</p><h3>Deep Deterministic Policy Gradients</h3><p>The DDPG algorithm (Deep Deterministic Policy Gradients) was introduced in 2015 by Timothy P. Lillicrap and others in the paper called <a href="https://arxiv.org/pdf/1509.02971.pdf">Continuous Control with Deep Reinforcement Learning</a>. It belongs to the Actor-Critic family, but at the same time, the policy is deterministic (same input, same output/action to take). DDPG also shares some ideas with DQN. In particular, the network is trained off-policy with samples from a replay buffer (to avoid correlation) and with a target Q network.</p><p>In summary, DDPG has in common with DQN, the deterministic policy, and that is trained off-policy, but at the same time has the Actor-Critic Approach. All this may look a bit complex now, but it will become easier in the next section when we see the code.</p><h3>Replay Buffer</h3><p>Let’s start with the simples part, the replay buffer:</p><pre><em>class</em> ReplayBuffer():<br>    <em>def</em> __init__(self, env, buffer_capacity=BUFFER_CAPACITY, batch_size=BATCH_SIZE, min_size_buffer=MIN_SIZE_BUFFER):<br>        self.buffer_capacity = buffer_capacity<br>        self.batch_size = batch_size<br>        self.min_size_buffer = min_size_buffer<br>        self.buffer_counter = 0<br>        self.n_games = 0<br>        <br>        self.states = np.zeros((self.buffer_capacity, env.observation_space.shape[0]))<br>        self.actions = np.zeros((self.buffer_capacity, env.action_space.shape[0]))<br>        self.rewards = np.zeros((self.buffer_capacity))<br>        self.next_states = np.zeros((self.buffer_capacity, env.observation_space.shape[0]))<br>        self.dones = np.zeros((self.buffer_capacity), dtype=<em>bool</em>)<br>        </pre><pre>        <br>    <em>def</em> __len__(self):<br>        return self.buffer_counter</pre><pre>    <em>def</em> add_record(self, state, action, reward, next_state, done):<br>        # Set index to zero if counter = buffer_capacity and start again (1 % 100 = 1 and 101 % 100 = 1) so we substitute the older entries<br>        index = self.buffer_counter % self.buffer_capacity</pre><pre>        self.states[index] = state<br>        self.actions[index] = action<br>        self.rewards[index] = reward<br>        self.next_states[index] = next_state<br>        self.dones[index] = done<br>        <br>        # Update the counter when record something<br>        self.buffer_counter += 1<br>    <br>    <em>def</em> check_buffer_size(self):<br>        return self.buffer_counter &gt;= self.batch_size and self.buffer_counter &gt;= self.min_size_buffer<br>    <br>    <em>def</em> update_n_games(self):<br>        self.n_games += 1<br>    <br>    <em>def</em> get_minibatch(self):<br>        # If the counter is less than the capacity we don&#39;t want to take zeros records, <br>        # if the cunter is higher we don&#39;t access the record using the counter <br>        # because older records are deleted to make space for new one<br>        buffer_range = <em>min</em>(self.buffer_counter, self.buffer_capacity)<br>        <br>        batch_index = np.random.choice(buffer_range, self.batch_size, replace=False)</pre><pre>        # Take indices<br>        state = self.states[batch_index]<br>        action = self.actions[batch_index]<br>        reward = self.rewards[batch_index]<br>        next_state = self.next_states[batch_index]<br>        done = self.dones[batch_index]<br>        <br>        return state, action, reward, next_state, done<br>    <br>    <em>def</em> save(self, folder_name):<br>        &quot;&quot;&quot;<br>        Save the replay buffer<br>        &quot;&quot;&quot;<br>        if not os.path.isdir(folder_name):<br>            os.mkdir(folder_name)</pre><pre>        np.save(folder_name + &#39;/states.npy&#39;, self.states)<br>        np.save(folder_name + &#39;/actions.npy&#39;, self.actions)<br>        np.save(folder_name + &#39;/rewards.npy&#39;, self.rewards)<br>        np.save(folder_name + &#39;/next_states.npy&#39;, self.next_states)<br>        np.save(folder_name + &#39;/dones.npy&#39;, self.dones)<br>        <br>        dict_info = {&quot;buffer_counter&quot;: self.buffer_counter, &quot;n_games&quot;: self.n_games}<br>        <br>        with <em>open</em>(folder_name + &#39;/dict_info.json&#39;, &#39;w&#39;) as f:<br>            json.dump(dict_info, f)</pre><pre>    <em>def</em> load(self, folder_name):<br>        &quot;&quot;&quot;<br>        Load the replay buffer<br>        &quot;&quot;&quot;<br>        self.states = np.load(folder_name + &#39;/states.npy&#39;)<br>        self.actions = np.load(folder_name + &#39;/actions.npy&#39;)<br>        self.rewards = np.load(folder_name + &#39;/rewards.npy&#39;)<br>        self.next_states = np.load(folder_name + &#39;/next_states.npy&#39;)<br>        self.dones = np.load(folder_name + &#39;/dones.npy&#39;)<br>        <br>        with <em>open</em>(folder_name + &#39;/dict_info.json&#39;, &#39;r&#39;) as f:<br>            dict_info = json.load(f)<br>        self.buffer_counter = dict_info[&quot;buffer_counter&quot;]<br>        self.n_games = dict_info[&quot;n_games&quot;]</pre><p>The concept is the same used in the <a href="https://antonai.blog/?p=137#more-137">DDDQN article</a>. We are storing all the states, actions, rewards, next_states, and terminal flags derived from the interaction with the environment calling the function add_record. Then we have a get_minibatch method that returns a random subset of these observations.</p><p>Note that we have a check_buffer_size method that makes sure that the buffer size is larger than the batch size and the minimum value that we have defined in the config file.</p><p>In the end, we have the save and load methods that save and load the buffer. This is particularly useful when you need to stop and restart the training (if you’re using Google Colab, this will save your life).</p><h3>Networks</h3><p>As said by introducing the DDPG algorithm, we have the standard Actor and Critic in their trained and target version. So we actually have four neural networks, two Actors and two Critics.</p><p>Let’s start with the code to define the Actors.</p><h3>Actor</h3><pre><em>class</em> Actor(tf.keras.Model):<br>    <em>def</em> __init__(self, name, actions_dim, upper_bound, hidden_0=CRITIC_HIDDEN_0, hidden_1=CRITIC_HIDDEN_1, init_minval=INIT_MINVAL, init_maxval=INIT_MAXVAL):<br>        <em>super</em>(Actor, self).__init__()<br>        self.hidden_0 = hidden_0<br>        self.hidden_1 = hidden_1<br>        self.actions_dim = actions_dim<br>        self.init_minval = init_minval<br>        self.init_maxval = init_maxval<br>        self.upper_bound = upper_bound<br>        <br>        self.net_name = name</pre><pre>        self.dense_0 = Dense(self.hidden_0, activation=&#39;relu&#39;)<br>        self.dense_1 = Dense(self.hidden_1, activation=&#39;relu&#39;)<br>        self.policy = Dense(self.actions_dim, kernel_initializer=random_uniform(minval=self.init_minval, maxval=self.init_maxval), activation=&#39;tanh&#39;)</pre><pre>    <em>def</em> call(self, state):<br>        x = self.dense_0(state)<br>        policy = self.dense_1(x)<br>        policy = self.policy(policy)</pre><pre>        return policy * self.upper_bound</pre><p>As you can see, it’s a pretty easy network, with two hidden layers and a final layer with a tanh activation. Just to a reminder, the tanh function is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*uFxFoK8MnZhjp0sn" /></figure><p>You can find the definition of all the activation functions <a href="https://www.wikiwand.com/en/Activation_function">here</a>.</p><p>Its outputs range from -1 to 1, so we need to multiply for the action’s upper bound. For example, for the pendulum environment, we need to multiply the output of the tanh function by two to have an action between -2 and 2 as required by the environment. For the Lunar Landing, we don’t actually need it because the action space is limited from -1 to 1 in both dimensions.</p><p>As you can see, the Actor output is deterministic. There will be the same output vector (action) given the same input (state).</p><p>We can see something different here on the initialization of the last layer’s weights. We initialize them from a uniform distribution with a min and max value (+/-0.005 in our case). This is necessary to prevent having a zero gradient in the initial stages of the training since we use a tanh activation function.</p><h3>Critic</h3><p>We can now see the code for the Critic Networks:</p><pre><em>class</em> Critic(tf.keras.Model):<br>    <em>def</em> __init__(self, name, hidden_0=CRITIC_HIDDEN_0, hidden_1=CRITIC_HIDDEN_1):<br>        <em>super</em>(Critic, self).__init__()<br>        <br>        self.hidden_0 = hidden_0<br>        self.hidden_1 = hidden_1</pre><pre>        self.net_name = name</pre><pre>        self.dense_0 = Dense(self.hidden_0, activation=&#39;relu&#39;)<br>        self.dense_1 = Dense(self.hidden_1, activation=&#39;relu&#39;)<br>        self.q_value = Dense(1, activation=None)</pre><pre>    <em>def</em> call(self, state, action):<br>        state_action_value = self.dense_0(tf.concat([state, action], axis=1))<br>        state_action_value = self.dense_1(state_action_value)</pre><pre>        q_value = self.q_value(state_action_value)</pre><pre>        return q_value</pre><p>As always, the Critic estimates the Q-value, the discounted reward of the action taken in some state. But our action is an array, so we need to take as input both the state and the action. As you can see, in the call method, the states and actions are stacked together using the concat function from TensorFlow. As always, the output will be a single number.</p><p>The action is given by the actor, so the Critic will take as input the output of the Actor network.</p><h3>Agent</h3><p>We can see the implementation of the Agent’s logic.</p><pre><em>class</em> Agent:<br>    <em>def</em> __init__(self, env, actor_lr=ACTOR_LR, critic_lr=CRITIC_LR, gamma=GAMMA, max_size=BUFFER_CAPACITY, tau=TAU, path_save=PATH_SAVE, path_load=PATH_LOAD):<br>        <br>        self.gamma = gamma<br>        self.tau = tau<br>        self.replay_buffer = ReplayBuffer(env, max_size)<br>        self.actions_dim = env.action_space.shape[0]<br>        self.upper_bound = env.action_space.high[0]<br>        self.lower_bound = env.action_space.low[0]<br>        self.actor_lr = actor_lr<br>        self.critic_lr = critic_lr<br>        self.path_save = path_save<br>        self.path_load = path_load<br>        <br>        self.actor = Actor(name=&#39;actor&#39;, actions_dim=self.actions_dim, upper_bound=self.upper_bound)<br>        self.critic = Critic(name=&#39;critic&#39;)<br>        self.target_actor = Actor(name=&#39;target_actor&#39;, actions_dim=self.actions_dim, upper_bound=self.upper_bound)<br>        self.target_critic = Critic(name=&#39;target_critic&#39;)</pre><pre>        self.actor.<em>compile</em>(optimizer=opt.Adam(learning_rate=actor_lr))<br>        self.critic.<em>compile</em>(optimizer=opt.Adam(learning_rate=critic_lr))<br>        self.target_actor.<em>compile</em>(optimizer=opt.Adam(learning_rate=actor_lr))<br>        self.target_critic.<em>compile</em>(optimizer=opt.Adam(learning_rate=critic_lr))</pre><pre>        actor_weights = self.actor.get_weights()<br>        critic_weights = self.critic.get_weights()<br>        <br>        self.target_actor.set_weights(actor_weights)<br>        self.target_critic.set_weights(critic_weights)<br>        <br>        self.noise = np.zeros(self.actions_dim)</pre><p>Looking at the Class inputs, you can see how it’s taking the defined environment to define the actions’ dimensions, upper and lower bound, and to define the replay buffer.</p><p>Then we use these dimensions to define the four networks: Actor, Target Actor, Critic, and Target Critic. In the beginning, we just copy the Actor and Critic weights to the target networks.</p><h3>Target Networks</h3><p>The target networks are time-delayed copies of their original networks that slowly update their weights. As for DDDQN, we’re using these target networks to improve learning stability. We’ll see how they are used in the loss functions. For now, let’s see now how we update these networks:</p><pre><em>def</em> update_target_networks(self, tau):<br>        actor_weights = self.actor.weights<br>        target_actor_weights = self.target_actor.weights<br>        for index in <em>range</em>(<em>len</em>(actor_weights)):<br>            target_actor_weights[index] = tau * actor_weights[index] + (1 - tau) * target_actor_weights[index]</pre><pre>        self.target_actor.set_weights(target_actor_weights)<br>        <br>        critic_weights = self.critic.weights<br>        target_critic_weights = self.target_critic.weights<br>    <br>        for index in <em>range</em>(<em>len</em>(critic_weights)):<br>            target_critic_weights[index] = tau * critic_weights[index] + (1 - tau) * target_critic_weights[index]</pre><pre>        self.target_critic.set_weights(target_critic_weights)</pre><p>As you can see, we update the networks’ weights as a weighted average between the target weights and the trained networks’ weights. In our case, Tau is equal to 0.05 as defined in the config file. We’re using tau as the weight given to the trained networks’ weights. Given the low value of tau, we’re doing a “soft” update, but we’re updating them every time we update the trained networks’ weights, as we’ll see in the training loop.</p><h3>Save and load</h3><p>As always, we want to have some methods to save and load the networks’ weights and the replay buffer:</p><pre><em>def</em> save(self):<br>        date_now = time.strftime(&quot;%Y%m%d%H%M&quot;)<br>        if not os.path.isdir(f&quot;{self.path_save}/save_agent_{date_now}&quot;):<br>            os.makedirs(f&quot;{self.path_save}/save_agent_{date_now}&quot;)<br>        self.actor.save_weights(f&quot;{self.path_save}/save_agent_{date_now}/{self.actor.net_name}.h5&quot;)<br>        self.target_actor.save_weights(f&quot;{self.path_save}/save_agent_{date_now}/{self.target_actor.net_name}.h5&quot;)<br>        self.critic.save_weights(f&quot;{self.path_save}/save_agent_{date_now}/{self.critic.net_name}.h5&quot;)<br>        self.target_critic.save_weights(f&quot;{self.path_save}/save_agent_{date_now}/{self.target_critic.net_name}.h5&quot;)<br>        <br>        np.save(f&quot;{self.path_save}/save_agent_{date_now}/noise.npy&quot;, self.noise)<br>        <br>        self.replay_buffer.save(f&quot;{self.path_save}/save_agent_{date_now}&quot;)</pre><pre>    <em>def</em> load(self):<br>        self.actor.load_weights(f&quot;{self.path_load}/{self.actor.net_name}.h5&quot;)<br>        self.target_actor.load_weights(f&quot;{self.path_load}/{self.target_actor.net_name}.h5&quot;)<br>        self.critic.load_weights(f&quot;{self.path_load}/{self.critic.net_name}.h5&quot;)<br>        self.target_critic.load_weights(f&quot;{self.path_load}/{self.target_critic.net_name}.h5&quot;)<br>        <br>        self.noise = np.load(f&quot;{self.path_load}/noise.npy&quot;)<br>        <br>        self.replay_buffer.load(f&quot;{self.path_load}&quot;)</pre><p>Nothing special here, but you can notice that we’re also saving the noise variable that we’re now going to talk about.</p><h3>Exploration vs. Exploitation</h3><p>The price that we need to pay to have a deterministic policy is that we need some strategy to explore the environment. The simplest way would be to just add some noise to the action returned by the Actor. We can randomly take this noise from a normal distribution, for example. But in the original paper, they used an Ornstein-Uhlenbeck process, so we’re going to implement it in the same way:</p><pre><em>def</em> _ornstein_uhlenbeck_process(self, x, theta=THETA, mu=0, dt=DT, std=0.2):<br>        &quot;&quot;&quot;<br>        Ornstein–Uhlenbeck process<br>        &quot;&quot;&quot;<br>        return x + theta * (mu-x) * dt + std * np.sqrt(dt) * np.random.normal(size=self.actions_dim)</pre><pre>    <em>def</em> get_action(self, observation, noise, evaluation=False):<br>        state = tf.convert_to_tensor([observation], dtype=tf.float32)<br>        actions = self.actor(state)<br>        if not evaluation:<br>            self.noise = self._ornstein_uhlenbeck_process(noise)<br>            actions += self.noise</pre><pre>        actions = tf.clip_by_value(actions, self.lower_bound, self.upper_bound)</pre><pre>        return actions[0]</pre><p>For the Ornstein-Uhlenbeck process, I just used the formula you can easily find by just googling it. Next, in the get_action method, we use the noise to create randomness in the action value. In the end, we clip the value of the action using the lower and upper bounds.</p><h3>Loss functions and gradients</h3><p>In the end, we just need to update the weights of the Actor and Critic using the gradients computed from the loss functions.</p><p>The Critic loss is the Mean Squared Error between the expected return seen by the Target Networks and the Q value predicted by the Critic network.</p><p>The Actor loss is the mean of the Critic network’s value given the actions taken by the Actor network. We want to maximize this value (we want a higher Q value), so we use the minus sign to transform it into a loss function.</p><p>Looking at the code:</p><pre><em>def</em> learn(self):<br>        if self.replay_buffer.check_buffer_size() == False:<br>            return</pre><pre>        state, action, reward, new_state, done = self.replay_buffer.get_minibatch()</pre><pre>        states = tf.convert_to_tensor(state, dtype=tf.float32)<br>        new_states = tf.convert_to_tensor(new_state, dtype=tf.float32)<br>        rewards = tf.convert_to_tensor(reward, dtype=tf.float32)<br>        actions = tf.convert_to_tensor(action, dtype=tf.float32)</pre><pre>        with tf.GradientTape() as tape:<br>            target_actions = self.target_actor(new_states)<br>            target_critic_values = tf.squeeze(self.target_critic(<br>                                new_states, target_actions), 1)<br>            critic_value = tf.squeeze(self.critic(states, actions), 1)<br>            target = reward + self.gamma * target_critic_values * (1-done)<br>            critic_loss = tf.keras.losses.MSE(target, critic_value)</pre><pre>        critic_gradient = tape.gradient(critic_loss,<br>                                            self.critic.trainable_variables)<br>        self.critic.optimizer.apply_gradients(<em>zip</em>(<br>            critic_gradient, self.critic.trainable_variables))</pre><pre>        with tf.GradientTape() as tape:<br>            policy_actions = self.actor(states)<br>            actor_loss = -self.critic(states, policy_actions)<br>            actor_loss = tf.math.reduce_mean(actor_loss)</pre><pre>        actor_gradient = tape.gradient(actor_loss, <br>                                    self.actor.trainable_variables)<br>        self.actor.optimizer.apply_gradients(<em>zip</em>(<br>            actor_gradient, self.actor.trainable_variables))</pre><pre>        self.update_target_networks(self.tau)</pre><p>First of all, we check that the buffer size is larger than the batch size and the minimum size defined in the config script using the method check_buffer_size() of the ReplayBuffer class. Then we take a minibatch from the Replay buffer, and we start calculating the two losses as described above, the gradients that we apply to the Actor and Critic Network to update the weights. In the end, we “softly” update the weights of the target networks using the method update_target_networks.</p><h3>Training and results</h3><p>We can now go to the training loop and the results for the two environments.</p><pre>config = <em>dict</em>(<br>  learning_rate_actor = ACTOR_LR,<br>  learning_rate_critic = ACTOR_LR,<br>  batch_size = BATCH_SIZE,<br>  architecture = &quot;DDPG&quot;,<br>  infra = &quot;Ubuntu&quot;,<br>  env = ENV_NAME<br>)</pre><pre>wandb.init(<br>  project=f&quot;tensorflow2_ddpg_{ENV_NAME.lower()}&quot;,<br>  tags=[&quot;DDPG&quot;, &quot;FCL&quot;, &quot;RL&quot;],<br>  config=config,<br>)</pre><pre>env = gym.make(ENV_NAME)<br>agent = Agent(env)</pre><pre>scores = []<br>evaluation = True</pre><pre>if PATH_LOAD is not None:<br>    print(&quot;loading weights&quot;)<br>    observation = env.reset()<br>    action = agent.actor(observation[None, :])<br>    agent.target_actor(observation[None, :])<br>    agent.critic(observation[None, :], action)<br>    agent.target_critic(observation[None, :], action)<br>    agent.load()<br>    print(agent.replay_buffer.buffer_counter)<br>    print(agent.replay_buffer.n_games)<br>    print(agent.noise)</pre><p>As always, we start configuring wandb for logging, and in case we’re loading a previously trained agent, we’ll load the agent and the replay buffer. Before we can load everything, we need to call the four networks to build them, so we’ll use a random initial observation to initialize them.</p><p>Then we have the training loop:</p><pre>for _ in tqdm(<em>range</em>(MAX_GAMES)):<br>    start_time = time.time()<br>    states = env.reset()<br>    done = False<br>    score = 0<br>    while not done:<br>        action = agent.get_action(states, evaluation)<br>        new_states, reward, done, info = env.step(action)<br>        score += reward<br>        agent.add_to_replay_buffer(states, action, reward, new_states, done)<br>        agent.learn()<br>        states = new_states<br>        <br>    agent.replay_buffer.update_n_games()<br>    <br>    scores.append(score)<br>    </pre><pre>    wandb.log({&#39;Game number&#39;: agent.replay_buffer.n_games, &#39;# Episodes&#39;: agent.replay_buffer.buffer_counter, <br>               &quot;Average reward&quot;: <em>round</em>(np.mean(scores[-10:]), 2), \<br>                      &quot;Time taken&quot;: <em>round</em>(time.time() - start_time, 2)})</pre><pre>    if (_ + 1) % EVALUATION_FREQUENCY == 0:<br>        evaluation = True<br>        states = env.reset()<br>        done = False<br>        score = 0<br>        while not done:<br>            action = agent.get_action(states, evaluation)<br>            new_states, reward, done, info = env.step(action)<br>            score += reward<br>            states = new_states<br>        wandb.log({&#39;Game number&#39;: agent.replay_buffer.n_games, <br>                   &#39;# Episodes&#39;: agent.replay_buffer.buffer_counter, <br>                   &#39;Evaluation score&#39;: score})<br>        evaluation = False<br>     <br>    if (_ + 1) % SAVE_FREQUENCY == 0:<br>        print(&quot;saving...&quot;)<br>        agent.save()<br>        print(&quot;saved&quot;)</pre><p>In the training loop, we interact with the environment, we save the states, actions, rewards, and terminal flags in the replay buffer, and we train the agent using the method learn() seen before. When the episode is over, we evaluate the results logging the mean of the last ten games. We also log the evaluation score every 100 games where we simply don’t add the noise to the action, and every 200 games, we save the networks’ weights, noise, and replay buffer.</p><p>We can start looking at the pendulum results, keeping in mind that the <a href="https://gym.openai.com/evaluations/eval_GH4gO123SvukqlMmqhIyeQ/">OpenAI documentation</a> says that “Best 100-episode average reward was -138.98 ± 9.06. (Pendulum-v0 does not have a specified reward threshold at which it’s considered solved.)”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/0*KRIK9xNDLuJTDVVl" /></figure><p>As you can see, the algorithm converges very quickly. After just 300 games, we have similar performances, if not better than those in the documentation.</p><p>We finish looking at the Lunar Lander results; in this case, <a href="https://github.com/openai/gym/wiki/Leaderboard#lunarlander-v2">the documentation</a> says that “LunarLander-v2 defines “solving” as getting an average reward of 200 over 100 consecutive trials.”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*CT784b-ZzYTGIEEA" /></figure><p>Here we’re taking more time to obtain good results. We get an average score of 200 after almost 150.000 episodes. But the episodes are really short, so it wasn’t much in training time, in around an hour we solved the environment.</p><p>You can find the original article on my <a href="https://antonai.blog/reinforcement-learning-in-continuous-action-spaces-part-1-ddpg/">blog</a> and all the code on my <a href="https://github.com/antonai91/reinforcement_learning/tree/master/ddpg">Github</a>. For any questions, you can reach me through <a href="https://www.linkedin.com/in/lisiantonio/">Linkedin</a>.</p><p>If you enjoyed this article, share it with your friends and colleagues! I’ll see you in the next post. In the meantime, take care, stay safe, and remember <em>don’t be another brick in the wall</em>.</p><p>Anton.ai</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbd64aa5434" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/reinforcement-learning-in-continuous-action-spaces-ddpg-bbd64aa5434">Reinforcement Learning in Continuous Action Spaces: DDPG</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beating Pong using Reinforcement Learning — Part 2 A2C and PPO]]></title>
            <link>https://medium.com/analytics-vidhya/beating-pong-using-reinforcement-learning-part-2-a2c-and-ppo-b83391dd3657?source=rss-4bba14bd6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b83391dd3657</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Antonio Lisi]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 20:59:29 GMT</pubDate>
            <atom:updated>2021-02-24T16:33:21.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beating Pong using Reinforcement Learning — Part 2 A2C and PPO</h3><h3><em>Continuing my journey into Reinforcement Learning</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*K2hoEd2fHB6ogvEl" /></figure><p><em>By Antonio Lisi</em></p><h3>Intro</h3><p>Hello everyone, this is my second article on medium, and it’s the sequel of the <a href="https://medium.com/analytics-vidhya/beating-pong-using-reinforcement-learning-part-1-dddqn-f7fbf5ad7768">previous article</a>. We will use a lot of the code developed in the first part. So if you didn’t read it, I recommend doing it before going forward.</p><p>In this post, we will implement A2C and PPO from scratch to beat the atari pong game, as we did in the first part with DDDQN.</p><h3>Motivating A2C and PPO</h3><p>Before going any further, we need to discuss why we’re focusing on these two algorithms. First of all, both belong to the Policy gradient family of algorithms. While DQN learns the q-value function and derives the policy from it, the Policy gradient algorithms directly improve the policy. This means that the network’s weights will update to increase the probability of actions with good total reward and decrease bad outcomes. As an explanatory example, the policy output will be a vector of probabilities for each of the n actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*ZGF3F7mF9hVEWTFl" /></figure><p>A significant difference is that policy gradient algorithms are stochastic while q-value methods are deterministic. Deterministic methods will give the same input, given the same output, so we need some epsilon greedy policy to explore the environment; this is the classic exploitation vs. exploration trade-off. Gradient policy methods can give different outputs given the same input. The action is sampled from the distribution outputted from the network. So we don’t need any epsilon greedy strategy to explore the environment as we did for the DQN.</p><p>Another critical difference is that the DQN methods are off-policy, which means that they evaluate and improve a different policy from the one used to select the action. Off-policy algorithms can learn using observation generated by a separate policy, basically the buffer class in the previous post.</p><p>Policy gradient methods are on-policy, which means that they evaluate and improve the same policy that selects actions. On-policy methods can’t use past experiences generated by different policies, so they are less efficient in using the observations.</p><p>This is a critical point in the choice of the algorithm to use. If the environment is fast, so observations are easy to get, an on-policy method is the best choice. But if the observations are hard to acquire, off-policy methods should be preferred.</p><p>All this may look a bit cryptic, but it will become clearer when we’ll dive into the code. So without further ado, let’s do it.</p><h3>Environment Wrapper</h3><p>We’ll use the same wrapper with all the tricks to process the images and stack them discussed in the previous post. So nothing new here; let’s go to the fun stuff.</p><h3>Network</h3><p>We’ll utilize the same architecture used in the DDDQN algorithm to process the input image, but we’ll need some changes to the network’s heads.<br>The idea behind the actor-critic methods is that we have an actor, used to select actions, and a critic, which criticizes the actor&#39;s actions. The actor will output the probability distribution in the actions space, while the critic will output the estimated value function.</p><p>In the beginning, the actor doesn’t know how to play, so it will randomly try some actions. The Critic observes the taken actions and gives feedback in terms of estimated values. The actor will learn from its feedback updating the policy and being better at playing that game; simultaneously, the Critic will also update its way to provide feedback.</p><p>As we can see, Actor-Critic’s idea is to have two neural networks, the Actor and the Critic. In practice, the two networks partially overlap, mostly due to efficiency and convergence considerations. In our case, the Actor and Critic are implemented as different heads from the same common body.</p><p>They will both take the same input, but the Actor will return a tensor with n logits value where n is the number of actions, and the Critic will return a tensor with one value that represents the value of the state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*ROkZyyDuPgtJ5Ut7" /></figure><p>A2C and PPO share the same logic in building the network, so there’s no difference in this part of the code:</p><pre>import numpy as np<br>import tensorflow as tf<br>import tensorflow.keras.layers as kl<br>from tensorflow.keras.initializers import VarianceScaling</pre><pre><em>class</em> ProbabilityDistribution(tf.keras.Model):<br>    <em>def</em> call(self, logits, **kwargs):<br>        # Random distribution<br>        return tf.squeeze(tf.random.categorical(logits, 1), axis=-1)<br></pre><pre><em>class</em> Model(tf.keras.Model):<br>    <em>def</em> __init__(self, num_actions, hidden):<br>        # Note: no tf.get_variable(), just simple Keras API!<br>        <em>super</em>().__init__(&#39;mlp_policy&#39;)<br>        self.normalize = kl.Lambda(lambda layer: layer / 255)    # normalize by 255<br>        self.conv1 = kl.Conv2D(32, (8, 8), strides=4, kernel_initializer=VarianceScaling(scale=2.), activation=&#39;relu&#39;, use_bias=False)<br>        self.conv2 = kl.Conv2D(64, (4, 4), strides=2, kernel_initializer=VarianceScaling(scale=2.), activation=&#39;relu&#39;, use_bias=False)<br>        self.conv3 = kl.Conv2D(64, (3, 3), strides=1, kernel_initializer=VarianceScaling(scale=2.), activation=&#39;relu&#39;, use_bias=False)<br>        self.conv4 = kl.Conv2D(hidden, (7, 7), strides=1, kernel_initializer=VarianceScaling(scale=2.), activation=&#39;relu&#39;, use_bias=False)<br>        <br>        self.flatten = kl.Flatten()<br>        self.value = kl.Dense(1, kernel_initializer=VarianceScaling(scale=2.), name=&quot;value&quot;)<br>        self.logits = kl.Dense(num_actions, kernel_initializer=VarianceScaling(scale=2.), name=&#39;policy_logits&#39;)<br>        <br>        self.dist = ProbabilityDistribution()</pre><pre>    <em>def</em> call(self, inputs, **kwargs):<br>        # Inputs is a numpy array, convert to a tensor.<br>        x = tf.convert_to_tensor(inputs)<br>        # Separate hidden layers from the same input tensor.</pre><pre>        x = self.normalize(x)<br>        x = self.conv1(x)<br>        x = self.conv2(x)<br>        x = self.conv3(x)<br>        x = self.conv4(x)<br>        x = self.flatten(x)<br>        return self.logits(x), self.value(x)</pre><h3>Agent</h3><p>We can now implement the logic of the agent. Here we don’t have any buffer replay, so we can take the observation from the environment and feed them to the neural network to update the weights:</p><pre><em>class</em> Agent:<br>    <em>def</em> __init__(self, model, save_path=PATH_SAVE_MODEL, load_path=PATH_LOAD_MODEL, lr=LR, gamma=GAMMA, value_c=VALUE_C,<br>                 entropy_c=ENTROPY_C, clip_ratio=CLIP_RATIO, std_adv=STD_ADV, agent=AGENT, input_shape=INPUT_SHAPE,<br>                 batch_size = BATCH_SIZE, updates=N_UPDATES):<br>        # Coefficients are used for the loss terms.<br>        self.value_c = value_c<br>        self.entropy_c = entropy_c<br>        # `gamma` is the discount factor<br>        self.gamma = gamma<br>        self.save_path = save_path<br>        self.load_path = load_path<br>        self.clip_ratio = clip_ratio<br>        self.std_adv = std_adv<br>        self.agent = agent<br>        self.input_shape = input_shape<br>        self.batch_size = batch_size<br>        self.updates = updates<br>        self.opt = opt.RMSprop(lr=lr)<br>        <br>        self.model = model</pre><pre>        if load_path is not None:<br>            print(&quot;loading model in {}&quot;.<em>format</em>(load_path))<br>            self.load_model(load_path)<br>            print(&quot;model loaded&quot;)<br>            <br>            <br>    <em>def</em> train(self, wrapper):<br>        # Storage helpers for a single batch of data.<br>        actions = np.empty((self.batch_size), dtype=np.int32)<br>        rewards, dones, values = np.empty((3, self.batch_size))<br>        observations = np.empty((self.batch_size,) + self.input_shape)<br>        old_logits = np.empty((self.batch_size, wrapper.env.action_space.n), dtype=np.float32)</pre><pre>        # Training loop: collect samples, send to optimizer, repeat updates times.<br>        ep_rewards = [0.0]<br>        next_obs = wrapper.reset()<br>        for update in tqdm(<em>range</em>(self.updates)):<br>            start_time = time.time()<br>            for step in <em>range</em>(self.batch_size):<br>                observations[step] = next_obs.copy()<br>                old_logits[step], actions[step], values[step] = self.logits_action_value(next_obs[None, :])<br>                next_obs, rewards[step], dones[step] = wrapper.step(actions[step])<br>                next_obs = wrapper.state<br>                ep_rewards[-1] += rewards[step]<br>                if dones[step]:<br>                    ep_rewards.append(0.0)<br>                    next_obs = wrapper.reset()<br>                    wandb.log({&#39;Game number&#39;: <em>len</em>(ep_rewards) - 1, &#39;# Update&#39;: update, &#39;% Update&#39;: <em>round</em>(update / self.updates, 2),<br>                                &quot;Reward&quot;: <em>round</em>(ep_rewards[-2], 2), &quot;Time taken&quot;: <em>round</em>(time.time() - start_time, 2)})</pre><pre>            _, _, next_value = self.logits_action_value(next_obs[None, :])</pre><pre>            returns, advs = self._returns_advantages(rewards, dones, values, next_value, self.std_adv)<br></pre><pre>            # Performs a full training step on the collected batch.<br>            # Note: no need to mess around with gradients, Keras API handles it.<br>            with tf.GradientTape() as tape:<br>                logits, v = self.model(observations, training=True)<br>                if self.agent == &quot;A2C&quot;:<br>                    logit_loss = self._logits_loss_a2c(actions, advs, logits)<br>                elif self.agent == &quot;PPO&quot;:<br>                    logit_loss = self._logits_loss_ppo(old_logits, logits, actions, advs, wrapper.env.action_space.n)<br>                else:<br>                    raise Exception(&quot;Sorry agent can be just A2C or PPO&quot;)<br>                value_loss = self._value_loss(returns, v)<br>                loss = logit_loss + value_loss<br>            grads = tape.gradient(loss, self.model.trainable_variables)<br>            self.opt.apply_gradients(<em>zip</em>(grads, self.model.trainable_variables))</pre><pre>            if update % 5000 == 0 and self.save_path is not None:<br>                print(&quot;Saving model in {}&quot;.<em>format</em>(self.save_path))<br>                self.save_model(f&#39;{self.save_path}/save_agent_{time.strftime(&quot;%Y%m%d%H%M&quot;) + &quot;_&quot; + <em>str</em>(update).zfill(8)}/model.tf&#39;)<br>                print(&quot;model saved&quot;)<br>                </pre><pre>        return ep_rewards</pre><p>There are few things to notice here:</p><ul><li>We use the concept of advantage.</li><li>We are storing the old logits values. When we’ll see the loss functions, you’ll understand why.</li><li>The only difference between A2C and PPO is in the loss function.</li></ul><h3>Returns and Advantages</h3><p>To reduce the variance of the gradients and improve the stability of policy gradient methods, a good idea is to use the same concept used in the DDDQN algorithm and see the total reward as the value of the state plus the advantage of the action:</p><p>Q(s, a) = V(s) + A(s, a)</p><p>So the critic will estimate the state’s value using the same training procedure used in DQN methods carrying the Bellman step and minimizing the Mean Square error to improve V(s) approximation.</p><p>Another useful thing to stabilize the model is to standardize the advantages, but it doesn’t always work, so there will be a boolean variable to enable/disable it.</p><p>To get the advantages, we need to first compute the discounted total return for every step using the discount factor gamma.</p><pre><em>def</em> _returns_advantages(self, rewards, dones, values, next_value, standardize_adv):<br>        returns = np.append(np.zeros_like(rewards), next_value, axis=-1)</pre><pre>        # Returns are calculated as discounted sum of future rewards.<br>        for t in <em>reversed</em>(<em>range</em>(rewards.shape[0])):<br>            returns[t] = rewards[t] + self.gamma * returns[t + 1] * (1 - dones[t])<br>        returns = returns[:-1]</pre><pre>        # Advantages are equal to returns - baseline (value estimates in our case).<br>        advantages = returns - values<br>        <br>        if standardize_adv:<br>            advantages = (advantages - np.mean(advantages)) / (np.std(advantages) + 1e-10)</pre><pre>        return returns, advantages</pre><h3>Loss functions</h3><p>We start with the value loss that is the same both for A2C than PPO. It’s a classic mean squared error between the output of the value head and the returns collected:</p><pre><em>def</em> _value_loss(self, returns, value):<br>        # Value loss is typically MSE between value estimates and returns.<br>        return self.value_c * kloss.mean_squared_error(returns, value)</pre><p>Then we go to the policy loss, where there’s the real difference between A2C and PPO. We’ll start with A2C:</p><pre><em>def</em> _logits_loss_a2c(self, actions, advantages, logits):</pre><pre>        # Sparse categorical CE loss obj that supports sample_weight arg on `call()`.<br>        # `from_logits` argument ensures transformation into normalized probabilities.<br>        weighted_sparse_ce = kloss.SparseCategoricalCrossentropy(from_logits=True)</pre><pre>        # Policy loss is defined by policy gradients, weighted by advantages.<br>        # Note: we only calculate the loss on the actions we&#39;ve actually taken.<br>        actions = tf.cast(actions, tf.int32)<br>        policy_loss = weighted_sparse_ce(actions, logits, sample_weight=advantages)</pre><pre>        # Entropy loss can be calculated as cross-entropy over itself.<br>        probs = tf.nn.softmax(logits)<br>        entropy_loss = kloss.categorical_crossentropy(probs, probs)</pre><pre>        # We want to minimize policy and maximize entropy losses.<br>        # Here signs are flipped because the optimizer minimizes.<br>        return policy_loss - self.entropy_c * entropy_loss</pre><p>First of all, we take input actions (integer value from 0 to 5), advantages, and logits (one of the policy’s output). We cast the actions as int32 as expected by the Keras model class. Then we define the policy loss as the cross-entropy of the taken actions’ probabilities weighted by advantages. Under the hood, it takes the actions vector and converts it into the categorical or vectorized format, like [0,0,0,1,0,0]. Then it takes the logits vector, transforms it using the softmax function, obtaining the probabilities vector. In the end, it multiplies the log of the probability vector with the action and advantage vectors.</p><p>As we can see, there’s another therm of the final loss, that is the entropy loss. We subtract the entropy loss to encourage further exploration of the model, making the extreme distributions, namely the one with a probability value near to one, less appealing.</p><p>The OpenAI team introduced the PPO method in 2017 in the paper called <a href="https://arxiv.org/pdf/1707.06347.pdf">Proximal Policy Optimization Algorithms</a> by John Schulman et. al.. The core improvement over the classic A2C method is changing how it estimates the policy gradients. The PPO method uses the ratio between the new and the old policy scaled by the advantages instead of using the logarithm of the new policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*HL4Z-z3Ny39iNIst" /></figure><p>This is the objective maximize by the <a href="https://arxiv.org/pdf/1502.05477.pdf">TRPO</a> algorithm (that we will not cover here) with the constraint that the Kullback–Leibler divergence between the old and the new policy is less than a defined delta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*0QdVBJSJwm_lB2gx" /></figure><p>This constraint is necessary because L’s maximization would lead to a huge policy update without it.</p><p>The PPO algorithm uses the same logic but with a much simpler approach. Instead of defining a constraint, it just clips the probability ratio. In this way, the new policy can’t be too different from the old one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*iUA_VcC1TJoJnlxX" /></figure><p>Let’s see how this is translated in the code:</p><pre><em>def</em> _logits_loss_ppo(self, old_logits, logits, actions, advs, n_actions):<br>        actions_oh = tf.one_hot(actions, n_actions)<br>        actions_oh = tf.reshape(actions_oh, [-1, n_actions])<br>        actions_oh = tf.cast(actions_oh, tf.float32)<br>        actions_oh = tf.stop_gradient(actions_oh)<br>        <br>        new_policy = tf.nn.log_softmax(logits)<br>        old_policy = tf.nn.log_softmax(old_logits)<br>        old_policy = tf.stop_gradient(old_policy)<br>        <br>        old_log_p = tf.reduce_sum(old_policy * actions_oh, axis=1)<br>        log_p = tf.reduce_sum(new_policy * actions_oh, axis=1)<br>        ratio = tf.exp(log_p - old_log_p)<br>        clipped_ratio = tf.clip_by_value(<br>            ratio, 1 - self.clip_ratio, 1 + self.clip_ratio)<br>        advs = tf.stop_gradient(advs)<br>        advs = tf.cast(advs, tf.float32)<br>        surrogate = tf.minimum(ratio * advs, clipped_ratio * advs)<br>        return -tf.reduce_mean(surrogate) - self.entropy_c * kloss.categorical_crossentropy(new_policy, new_policy)</pre><p>Here we’ll transform the actions in their vectorized format, then we take the old and new logits of the actions taken and define the old and new policy as the logits’ softmax. To be more precise, we take the log softmax to have more numerical stability by defining the ratio as the log difference and then taking the exponential value. Mathematically is equivalent given the logarithms’ quotient rule. Finally, we clip the ratio and take the minimum between the clipped and standard ratio weighted for the advantages.</p><p>We can now launch the two algorithms to see the results.</p><h3>Training and results</h3><p>As always, we use wandb to log the results:</p><pre>wandb.init(<br>  project=&quot;tensorflow2_pong_{}&quot;.<em>format</em>(AGENT.lower()),<br>  tags=[AGENT.lower(), &quot;CNN&quot;, &quot;RL&quot;, &quot;atari_pong&quot;],<br>  config=CONFIG_WANDB,<br>)</pre><p>We define the environment, initialize the networks and the agent:</p><pre>pw = PongWrapper(ENV_NAME, history_length=4)<br>model = Model(num_actions=pw.env.action_space.n, hidden=HIDDEN)<br>agent = Agent(model)</pre><p>In the end, we have the main() function that will call the agent.train method. As always, there’s a try/except block saving the model when interrupting the training so that we can restart the training at another time:</p><pre><em>def</em> main():<br>    rewards_history = agent.train(pw)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    try:<br>        main()<br>    except KeyboardInterrupt:<br>        # Save the model, I need this in order to save the networks, frame number, rewards and losses. <br>        # if I want to stop the script and restart without training from the beginning<br>        if PATH_SAVE_MODEL is None:<br>            print(&quot;Setting path to ../model/{}&quot;.<em>format</em>(AGENT.lower()))<br>            PATH_SAVE_MODEL = &quot;../model/{}&quot;.<em>format</em>(AGENT.lower())<br>        print(&#39;Saving the model in &#39; + f&#39;{PATH_SAVE_MODEL}/save_agent_{time.strftime(&quot;%Y%m%d%H%M&quot;)}&#39;)<br>        agent.save_model(f&#39;{PATH_SAVE_MODEL}/save_agent_{time.strftime(&quot;%Y%m%d%H%M&quot;)}/model.tf&#39;)<br>        print(&#39;Saved.&#39;)</pre><p>We can now see the results using wandb’s plots.</p><p>Let’s start with A2C:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*oGrgXrd17c1vO9U2" /></figure><p>As you can see, with no restriction on the policy gradient, there’s high variability in the policy update, and the algorithms perform poorly after obtaining satisfactory results. So I decided to take the model saved around 1k steps and start training again using a much lower learning rate to avoid huge policy updates after the model was performing well. Let’s see the results of the second run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*4zsnDKqI-tZprxc_" /></figure><p>As you can see, the results are excellent, and the variability is very low. Someone can think to set the learning rate low since the start of the training, but it is counterproductive because it takes too much time to converge.</p><p>It makes more sense to set a high learning rate initially and then decrease it with the advance of the training process. We did something similar in the DDDQN with the epsilon greedy strategy that had a large epsilon at the beginning and a small one at the end of the training (to incentivize exploration initially and exploitation the end). Here we took a rudimentary approach to solve the problem. A better way would be to set the learning rate as a function of the number of steps. But it took a while to train, and I needed the time to train the PPO agent, so I decided to finish the train in this way.</p><p>Let’s see the PPO results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*6pQhtQIX2N4WY1Qe" /></figure><p>We used the same starting learning rate of the A2C algorithm, but we didn’t need any trick on the learning rate thanks to the loss function&#39;s clip mechanism.</p><p>You can find the original article on my <a href="https://antonai.blog/?p=229#more-229">blog</a> all the code on my <a href="https://github.com/antonai91/reinforcement_learning/tree/master/a2c_ppo">Github</a>. For any questions, you can reach me through <a href="https://www.linkedin.com/in/lisiantonio/">Linkedin</a>.</p><p>If you enjoyed this article, share it with your friends and colleagues! I’ll see you in the next post. In the meantime, take care, stay safe, and remember <em>don’t be another brick in the wall</em>.</p><p>Anton.ai</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b83391dd3657" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/beating-pong-using-reinforcement-learning-part-2-a2c-and-ppo-b83391dd3657">Beating Pong using Reinforcement Learning — Part 2 A2C and PPO</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beating Pong using Reinforcement Learning — Part 1 DDDQN]]></title>
            <link>https://medium.com/analytics-vidhya/beating-pong-using-reinforcement-learning-part-1-dddqn-f7fbf5ad7768?source=rss-4bba14bd6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7fbf5ad7768</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[tensorflow2]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Antonio Lisi]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 21:28:06 GMT</pubDate>
            <atom:updated>2021-02-18T17:09:21.111Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beating Pong using Reinforcement Learning — Part 1 DDDQN</h3><p><em>The start of my journey in Reinforcement Learning</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*tawUDYGdDUW7omuogvGM2g.jpeg" /></figure><p><em>By Antonio Lisi</em></p><h3>Intro</h3><p>Hello everyone, this is my first technical post on this blog. I hope you’ll enjoy it.</p><p>Today we talk about reinforcement learning. In the last few months, with the lockdown and so on, I had for the first time in years some free time, so I decided to study reinforcement learning (RL). Game theory was one of my favorite subjects at the university, but at the same time, I always thought that it couldn’t be applied in real life as it was. You can’t compute the expected value of all possible actions, states unless you have simple scenarios like the prisoner’s dilemma.</p><p>RL starts from the same concept, but the approach is very different. You define and train a Neural Network to approximate the value of every action/state (this is the so-called value-based approach).</p><p>I won’t go into the details of the theory, but I recommend <a href="https://www.perlego.com/book/771717/deep-reinforcement-learning-handson-apply-modern-rl-methods-with-deep-qnetworks-value-iteration-policy-gradients-trpo-alphago-zero-and-more-pdf?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=1-EU%20%7C%20en%20%7C%20DSA%20Test%2018.12.20&amp;utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=11871053709&amp;utm_term=&amp;utm_content=487151523099&amp;gclid=Cj0KCQiA6Or_BRC_ARIsAPzuer9g8uK3V8w7olmvOtR4S61TShe5U8MeV-S3-ZeyaNZvNbXHt3JjiLAaAiuJEALw_wcB">this book</a>. I received a free copy because I joined the <a href="https://events.linuxfoundation.org/ray-summit/">Ray summit conference </a>(it’s a very interesting library for building distributed applications, you can check it out <a href="https://github.com/ray-project/ray">here</a>).</p><p>If you prefer academic papers, I recently read the paper <a href="https://www.jair.org/index.php/jair/article/view/12412/26638">Deep Reinforcement Learning: A State-of-the-Art Walkthrough</a>. It’s a nice read to learn at a high level the algorithms that have been developed in this field.</p><p>Most of the code used below takes inspiration from this <a href="https://github.com/fg91/Deep-Q-Learning/blob/master/DQN.ipynb">notebook</a>, so a big thank you to Fabio M. Graetz.</p><p>So without further ado, I will share with you my first experiments trying to solve pong.</p><p>P.s. the initial plan was to write about two different approaches, DDDQN and A2C, but the post was too long, so I will cover DDDQN here and A2C in the next one.</p><h3>Hardware</h3><p>Before going deep into the code, I want to talk about the hardware used. To train the first algorithm (DDDQN), I developed it on my mac and then launched the train on a Google Cloud VM with a Tesla K80. This was the result (I had almost 200$ worth of credits, so I didn’t actually pay it):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*2yJ_y-vC5PkhTFV7" /></figure><p>So I needed an alternative, luckily at my home, I had my old pc with a GTX 1050 TI that I used for image recognition and, more recently, light gaming. So I decided to format it, install ubuntu 20.04, install the Nvidia Drivers, CUDA, and so on, and I was able to launch PyTorch and Jax. But here’s the catch, I wanted to use Tensorflow, but my CPU was too old for TF2; it needed to build from source. This was the beginning of a very frustrating process. I started with the setup of docker (I needed an isolated environment to avoid disasters), downloaded the last docker image of Tensorflow, installed Bazel, installed the NVIDIA Container Toolkit and build Tensorflow from source following the awful documentation (damn you google!). After 20 hours of compiling and multiple prayers, I was able to import TensorFlow and see the GPU, it was one of the most satisfying moments of 2020.</p><h3>The OpenAI Gym Environments</h3><p>The first step is choosing an environment to solve, you can find <a href="https://github.com/openai/gym/wiki/Table-of-environments">here</a> a list of all the environments made available by OpenAI. I choose to solve pong because it is relatively easy and fast to solve. In this way, I can focus on the implementation of the algorithms and see quickly if they’re converging, but at the same time, it is not that simple (like CartPole for example) that you can’t appreciate a change in the algorithm used.</p><h3>Utility functions and Environment</h3><p>We start looking at the environment given by OpenAI, to see the mp4 that we’ll generate in a jupyter notebook we’ll use the following function (you also need to run the jupyter notebook/lab with the command xvfb-run -s “-screen 0 1400x900x24”):</p><pre>import base64<br>import IPython</pre><pre><em>def</em> embed_mp4(filename):<br>  &quot;&quot;&quot;Embeds an mp4 file in the notebook.&quot;&quot;&quot;<br>  video = <em>open</em>(filename,&#39;rb&#39;).read()<br>  b64 = base64.b64encode(video)<br>  tag = &#39;&#39;&#39;<br>  &lt;video width=&quot;640&quot; height=&quot;480&quot; controls&gt;<br>    &lt;source src=&quot;data:video/mp4;base64,{0}&quot; type=&quot;video/mp4&quot;&gt;<br>  Your browser does not support the video tag.<br>  &lt;/video&gt;&#39;&#39;&#39;.<em>format</em>(b64.decode())</pre><pre>  return IPython.display.HTML(tag)</pre><p>To make the development easier in a jupyter notebook I also use the following ad-hoc plugin that can create text files and append code to them:</p><pre>from IPython.core.magic import register_cell_magic</pre><pre>@register_cell_magic<br><em>def</em> write_and_run(line, cell):<br>    argz = line.split()<br>    <em>file</em> = argz[-1]<br>    mode = &#39;w&#39;<br>    if <em>len</em>(argz) == 2 and argz[0] == &#39;-a&#39;:<br>        mode = &#39;a&#39;<br>    with <em>open</em>(<em>file</em>, mode) as f:<br>        f.write(cell)<br>    get_ipython().run_cell(cell)</pre><p>Now we can start to interact with the environment:</p><pre>import gym<br>import os<br>import matplotlib.pyplot as plt<br>from PIL import Image<br>import imageio<br>import random<br>import numpy as np<br>import cv2<br>import base64<br>import IPython<br>from config import ENV_NAME<br>from utilities import embed_mp4</pre><pre># Create environment<br>env = gym.make(ENV_NAME)<br>print(&quot;The environment has the following {} actions: {}&quot;.\<br>      <em>format</em>(env.action_space.n, env.unwrapped.get_action_meanings()))</pre><pre>with imageio.get_writer(&quot;../video/random_agent.mp4&quot;, fps=60) as video:<br>    terminal = True<br>    for frame in <em>range</em>(10000):<br>        if terminal:<br>            env.reset()<br>            terminal = False</pre><pre>        # Breakout require a &quot;fire&quot; action (action #1) to start the<br>        # game each time a life is lost.<br>        # Otherwise, the agent would sit around doing nothing.<br>        action = random.choice(<em>range</em>(env.action_space.n))</pre><pre>        # Step action<br>        _, reward, terminal, info = env.step(action)</pre><pre>        video.append_data(env.render(mode=&#39;rgb_array&#39;))</pre><p>As you can see our random agent, the one on the right and it is not playing very well:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRQTq-hP9Bj8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRQTq-hP9Bj8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRQTq-hP9Bj8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f484ad592fe01aa634b53a56ed4087b/href">https://medium.com/media/4f484ad592fe01aa634b53a56ed4087b/href</a></iframe><h3>Process Image</h3><p>The input of the environment is an image with shape (210, 160, 3), we can’t work directly with these images for two reasons:</p><ul><li>it would be computationally too expensive</li><li>the GPU Tensorflow 2 implementation of Conv2D expects square inputs</li></ul><p>So we use the following function to eliminate the colour, crop and resize the images:</p><pre># This function can resize to any shape but was built to resize to 84x84<br><em>def</em> process_image(image, shape=(84, 84)):<br>    &quot;&quot;&quot;Preprocesses a 210x160x3 frame to 84x84x1 grayscale</pre><pre>    Arguments:<br>        frame: The frame to process.  Must have values ranging from 0-255</pre><pre>    Returns:<br>        The processed frame<br>    &quot;&quot;&quot;<br>    image = image.astype(np.uint8)  # cv2 requires np.uint8</pre><pre>    image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)<br>    image = image[34:34+160, :160]  # crop image<br>    image = cv2.resize(image, shape, interpolation=cv2.INTER_NEAREST)<br>    image = image.reshape((*shape, 1))</pre><pre>    return image</pre><p>We use OpenCV to remove the last dimension that represents the colour (function COLOR_RGB2GRAY), we crop the image (we don’t need the scoreboard), and then because we need to have a square image to give as an input to our GPU we resize the image to 84x84x1 (this is a <a href="https://arxiv.org/pdf/1312.5602.pdf">best practice</a> for Atari games):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVf2FWxIw6jU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVf2FWxIw6jU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVf2FWxIw6jU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a9f901320c507e0f9b6da05f1b724b5/href">https://medium.com/media/0a9f901320c507e0f9b6da05f1b724b5/href</a></iframe><h3>Game Wrapper</h3><p>We define a wrapper around the OpenAi gym, the biggest improvements are:</p><ul><li>we apply the process_image function to obtain 84x84x1 images;</li><li>we define the input as the concatenation of four images, this gives the agent the capacity to see the dynamics of the ball basically;</li><li>when evaluating the agent, it will take the action 1 (“Fire”) at the beginning of each episode for a number of random times in the range [1, no_op_steps]. This will ensure to have each time different initial random conditions (<a href="https://www.datascienceassn.org/sites/default/files/Human-level%20Control%20Through%20Deep%20Reinforcement%20Learning.pdf">Mnih et al. 2015</a>).</li></ul><pre>import random<br>import gym<br>import numpy as np<br>from process_image import process_image</pre><pre><em>class</em> PongWrapper(<em>object</em>):<br>    &quot;&quot;&quot;<br>    Wrapper for the environment provided by Openai Gym<br>    &quot;&quot;&quot;</pre><pre>    <em>def</em> __init__(self, env_name: <em>str</em>, no_op_steps: <em>int</em> = 10, history_length: <em>int</em> = 4):<br>        self.env = gym.make(env_name)<br>        self.no_op_steps = no_op_steps<br>        self.history_length = 4 # number of frames to put together (we need dynamic to see where the ball is going)</pre><pre>        self.state = None<br>        <br>    <em>def</em> reset(self, evaluation: <em>bool</em> = False):<br>        &quot;&quot;&quot;Resets the environment<br>        Arguments:<br>            evaluation: Set to True when we are in evaluation mode, in this case the agent takes a random number of no-op steps if True.<br>        &quot;&quot;&quot;</pre><pre>        self.frame = self.env.reset()<br>        <br>        # If in evaluation model, take a random number of no-op steps<br>        if evaluation:<br>            for _ in <em>range</em>(random.randint(0, self.no_op_steps)):<br>                self.env.step(1)</pre><pre>        # For the initial state, we stack the first frame four times<br>        self.state = np.repeat(process_image(self.frame), self.history_length, axis=2)</pre><pre>    <em>def</em> step(self, action: <em>int</em>, render_mode=None):<br>        &quot;&quot;&quot;<br>        Arguments:<br>            action: An integer describe action to take<br>            render_mode: None doesn&#39;t render anything, &#39;human&#39; renders the screen in a new window, &#39;rgb_array&#39; returns also an np.array with rgb values<br>        Returns:<br>            processed_image: The processed new frame as a result of that action<br>            reward: The reward for taking that action<br>            terminal: Whether the game has ended<br>        &quot;&quot;&quot;<br>        new_frame, reward, terminal, info = self.env.step(action)</pre><pre>        processed_image = process_image(new_frame)</pre><pre>        self.state = np.append(self.state[:, :, 1:], processed_image, axis=2) # replace the first observation of the previous state with the last one</pre><pre>        if render_mode == &#39;rgb_array&#39;:<br>            return processed_image, reward, terminal, self.env.render(render_mode)<br>        elif render_mode == &#39;human&#39;:<br>            self.env.render(render_mode)</pre><pre>        return processed_image, reward, terminal</pre><h3>Replay Buffer</h3><p>The algorithm that we want to use (DDDQN) is an off-policy method because the updated policy is different from the behavior one. This will become clearer when we’ll build the network, for now, it basically means that our network can learn from past episodes with previous policies.</p><p>One of the fundamental requirements for SGD optimization, that we’ll use to train the network, is that the training data is independent and identically distributed (i.i.d.). But if the Agent interacts with the Environment, the sequence of inputs can be highly correlated. That’s why we need a Replay Buffer that records the experience collected by the agent and then we take a minibatch of training data from this collection to update the weights. The simplest implementation is a buffer of fixed size, with new data added to the end of the buffer so that it pushes the oldest experience out of it.</p><pre>import os<br>import random<br>import numpy as np</pre><pre><em>class</em> ReplayBuffer(<em>object</em>):<br>    &quot;&quot;&quot;<br>    Replay Memory that stores the last size transitions<br>    &quot;&quot;&quot;<br>    <em>def</em> __init__(self, size: <em>int</em>=1000000, input_shape: <em>tuple</em>=(84, 84), history_length: <em>int</em>=4, reward_type: <em>str</em> = &quot;integer&quot;):<br>        &quot;&quot;&quot;<br>        Arguments:<br>            size: Number of stored transitions<br>            input_shape: Shape of the preprocessed frame<br>            history_length: Number of frames stacked together that the agent can see<br>        &quot;&quot;&quot;<br>        self.size = size<br>        self.input_shape = input_shape<br>        self.history_length = history_length<br>        self.count = 0  # total index of memory written to, always less than self.size<br>        self.current = 0  # index to write to<br>        self.reward_type = reward_type</pre><pre>        # Pre-allocate memory<br>        self.actions = np.empty(self.size, dtype=np.int32)<br>        self.rewards = np.empty(self.size, dtype=np.float32)<br>        self.frames = np.empty((self.size, self.input_shape[0], self.input_shape[1]), dtype=np.uint8)<br>        self.terminal_flags = np.empty(self.size, dtype=np.<em>bool</em>)<br>        self.priorities = np.zeros(self.size, dtype=np.float32)</pre><pre>    <em>def</em> add_experience(self, action, frame, reward, terminal, clip_reward=True, reward_type=&quot;integer&quot;):<br>        &quot;&quot;&quot;Saves a transition to the replay buffer<br>        Arguments:<br>            action: An integer between 0 and env.action_space.n - 1 <br>                determining the action the agent perfomed<br>            frame: A (84, 84, 1) frame of the game in grayscale<br>            reward: A float determining the reward the agend received for performing an action<br>            terminal: A bool stating whether the episode terminated<br>        &quot;&quot;&quot;<br>        if frame.shape != self.input_shape:<br>            raise ValueError(&#39;Dimension of frame is wrong!&#39;)</pre><pre>        if clip_reward:<br>            if reward_type == &quot;integer&quot;:<br>                reward = np.sign(reward)<br>            else:<br>                reward = np.clip(reward, -1.0, 1.0)<br>        # Write memory<br>        self.actions[self.current] = action<br>        self.frames[self.current, ...] = frame<br>        self.rewards[self.current] = reward<br>        self.terminal_flags[self.current] = terminal<br>        self.priorities[self.current] = <em>max</em>(self.priorities.<em>max</em>(), 1)  # make the most recent experience important<br>        self.count = <em>max</em>(self.count, self.current+1)<br>        self.current = (self.current + 1) % self.size # when a &lt; b then a % b = a</pre><pre>    <em>def</em> get_minibatch(self, batch_size: <em>int</em> = 32):<br>        &quot;&quot;&quot;<br>        Returns a minibatch of size batch_size<br>        Arguments:<br>            batch_size: How many samples to return<br>        Returns:<br>            A tuple of states, actions, rewards, new_states, and terminals<br>        &quot;&quot;&quot;</pre><pre>        if self.count &lt; self.history_length:<br>            raise ValueError(&#39;Not enough memories to get a minibatch&#39;)</pre><pre>        indices = []<br>        for i in <em>range</em>(batch_size):<br>            while True:<br>                # Get a random number from history_length to maximum frame<br>                index = random.randint(self.history_length, self.count - 1)</pre><pre>                # We check that all frames are from same episode with the two following if statements.<br>                if index &gt;= self.current and index - self.history_length &lt;= self.current:<br>                    continue<br>                if self.terminal_flags[index - self.history_length:index].<em>any</em>():<br>                    continue<br>                break<br>            indices.append(index)</pre><pre>        # Retrieve states from memory<br>        states = []<br>        new_states = []<br>        for idx in indices:<br>            states.append(self.frames[idx-self.history_length:idx, ...])<br>            new_states.append(self.frames[idx-self.history_length+1:idx+1, ...])</pre><pre>        states = np.transpose(np.asarray(states), axes=(0, 2, 3, 1))<br>        new_states = np.transpose(np.asarray(new_states), axes=(0, 2, 3, 1))</pre><pre>        return states, self.actions[indices], self.rewards[indices], new_states, self.terminal_flags[indices]</pre><pre>    <em>def</em> save(self, folder_name):<br>        &quot;&quot;&quot;<br>        Save the replay buffer<br>        &quot;&quot;&quot;</pre><pre>        if not os.path.isdir(folder_name):<br>            os.mkdir(folder_name)</pre><pre>        np.save(folder_name + &#39;/actions.npy&#39;, self.actions)<br>        np.save(folder_name + &#39;/frames.npy&#39;, self.frames)<br>        np.save(folder_name + &#39;/rewards.npy&#39;, self.rewards)<br>        np.save(folder_name + &#39;/terminal_flags.npy&#39;, self.terminal_flags)</pre><pre>    <em>def</em> load(self, folder_name):<br>        &quot;&quot;&quot;<br>        Load the replay buffer<br>        &quot;&quot;&quot;<br>        self.actions = np.load(folder_name + &#39;/actions.npy&#39;)<br>        self.frames = np.load(folder_name + &#39;/frames.npy&#39;)<br>        self.rewards = np.load(folder_name + &#39;/rewards.npy&#39;)<br>        self.terminal_flags = np.load(folder_name + &#39;/terminal_flags.npy&#39;)</pre><p>The replay buffer stores from the interactions of the agent with the environment’s actions, rewards, inputs (frames), terminal flags (if the episode is over), a global count of the interactions, and a current index. Note that the rewards are clipped between -1 and 1 citing the paper <a href="https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf">Human-level control through deep reinforcement learning</a> “as the scale of scores varies greatly from game to game, we clipped all positive rewards at 1 and all negative rewards at -1, leaving 0 rewards unchanged. Clipping the rewards in this manner limits the scale of the error derivatives and makes it easier to use the same learning rate across multiple games”</p><p>The get_minibatch function goes over the replay buffer and returns arrays from the same episode of input and output states, actions, rewards, and terminal flags. Then we have save and load functions that save and load on/from disk the NumPy arrays of the replay buffer.</p><h3>Network</h3><p>The <a href="https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf">DQN (Deep Q-Network) algorithm</a> was developed by DeepMind in 2015 by enhancing a classic RL algorithm called Q-Learning with deep neural networks.</p><p>The Q-Learning algorithm is based on the concept of the Q(a, s) function that returns the expected future reward of that action at that state. The vanilla DQN just try to approximate the Q function using a neural network. DQN is an example of a value-based approach because it is trying to approximate the Q function. Another approach is the policy gradient that I’ll cover in the next post.</p><p>We’ll use a variation of DQN called DDDQN that stands for Dueling Double Deep Q-network. The double part comes from the paper titled <a href="https://arxiv.org/pdf/1509.06461.pdf"><em>Deep Reinforcement Learning with Double Q-Learning</em></a>. The authors demonstrated that the basic DQN tends to overestimate values for <em>Q</em> so they proposed the introduction of two Neural Networks, the target, and the trained network. The trained one for choosing actions for the next state, and the target network for estimating values of <em>Q </em>to update the weights of the network using the Bellman Equation. The target network will be updated every n steps using the weights from the trained one.</p><p>The Dueling Network Architectures was introduced in <a href="https://arxiv.org/pdf/1511.06581.pdf">Dueling Network Architectures for Deep Reinforcement Learning</a>, the authors<br>demonstrated that the Q values, that the network is trying to approximate can be divided into quantities:</p><ul><li>the value of the state, V(s)</li><li>the advantage of actions in this state, A(s, a).</li></ul><p>Dividing the task to estimate the Q values into two quantities produced better training stability, faster convergence, and better results.</p><p>Ok, now we can see the implementation, it’s nothing fancy, as you can see below it uses a bunch of 2d convolutions then flatten everything and split the NN into two heads to estimate the state value and the actions’ advantages:</p><pre>import tensorflow as tf<br>from tensorflow.keras.initializers import VarianceScaling<br>from tensorflow.keras.layers import (Add, Conv2D, Dense, Flatten, Input,<br>                                     Lambda, Subtract)<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.optimizers import Adam, RMSprop # we&#39;ll use Adam instead of RMSprop</pre><pre><em>def</em> build_q_network(n_actions, learning_rate=0.00001, input_shape=(84, 84), history_length=4, hidden=1024):<br>    &quot;&quot;&quot;<br>    Builds a dueling DQN as a Keras model<br>    Arguments:<br>        n_actions: Number of possible actions<br>        learning_rate: Learning rate<br>        input_shape: Shape of the preprocessed image<br>        history_length: Number of historical frames to stack togheter<br>        hidden: Integer, Number of filters in the final convolutional layer. <br>    Returns:<br>        A compiled Keras model<br>    &quot;&quot;&quot;<br>    model_input = Input(shape=(input_shape[0], input_shape[1], history_length))<br>    x = Lambda(lambda layer: layer / 255)(model_input)  # normalize by 255</pre><pre>    x = Conv2D(32, (8, 8), strides=4, kernel_initializer=VarianceScaling(scale=2.), activation=&#39;relu&#39;, use_bias=False)(x)<br>    x = Conv2D(64, (4, 4), strides=2, kernel_initializer=VarianceScaling(scale=2.), activation=&#39;relu&#39;, use_bias=False)(x)<br>    x = Conv2D(64, (3, 3), strides=1, kernel_initializer=VarianceScaling(scale=2.), activation=&#39;relu&#39;, use_bias=False)(x)<br>    x = Conv2D(hidden, (7, 7), strides=1, kernel_initializer=VarianceScaling(scale=2.), activation=&#39;relu&#39;, use_bias=False)(x)</pre><pre>    # Split into value and advantage streams<br>    val_stream, adv_stream = Lambda(lambda w: tf.split(w, 2, 3))(x)  # custom splitting layer</pre><pre>    val_stream = Flatten()(val_stream)<br>    val = Dense(1, kernel_initializer=VarianceScaling(scale=2.))(val_stream)</pre><pre>    adv_stream = Flatten()(adv_stream)<br>    adv = Dense(n_actions, kernel_initializer=VarianceScaling(scale=2.))(adv_stream)</pre><pre>    # Combine streams into Q-Values<br>    reduce_mean = Lambda(lambda w: tf.reduce_mean(w, axis=1, keepdims=True))  # custom layer to reduce mean</pre><pre>    q_vals = Add()([val, Subtract()([adv, reduce_mean(adv)])])</pre><pre>    # Build model<br>    model = Model(model_input, q_vals)<br>    model.<em>compile</em>(Adam(learning_rate), loss=tf.keras.losses.Huber())</pre><pre>    return model</pre><h3>Agent</h3><p>Finally we implement the logic of the agent.</p><p>To overcome the exploitation vs exploration trade-off, we use an epsilon greedy policy, so with probability epsilon, our agent will take a random action (epsilon will be high at the beginning of the training and decrease later).</p><p>We also have two neural networks, the trained and target network as explained before.</p><p>In the learn function we can see the Bellman equation used to compute the gradients and update the trained network weights, then we have save and load functions that just save the two networks and the replay buffer, in this way you can just restart a training session restarting from where you left.</p><pre>import json<br>import os<br>import numpy as np<br>import tensorflow as tf</pre><pre><em>class</em> DDDQN_AGENT(<em>object</em>):<br>    <em>def</em> __init__(self,<br>                 dqn,<br>                 target_dqn,<br>                 replay_buffer,<br>                 n_actions,<br>                 input_shape=(84, 84),<br>                 batch_size=32,<br>                 history_length=4,<br>                 eps_initial=1,<br>                 eps_final=0.1,<br>                 eps_final_frame=0.01,<br>                 eps_evaluation=0.0,<br>                 eps_annealing_frames=1000000,<br>                 replay_buffer_start_size=50000,<br>                 max_frames=25000000):</pre><pre>        self.n_actions = n_actions<br>        self.input_shape = input_shape<br>        self.history_length = history_length</pre><pre>        # Memory information<br>        self.replay_buffer_start_size = replay_buffer_start_size<br>        self.max_frames = max_frames<br>        self.batch_size = batch_size</pre><pre>        self.replay_buffer = replay_buffer</pre><pre>        # Epsilon information<br>        self.eps_initial = eps_initial<br>        self.eps_final = eps_final<br>        self.eps_final_frame = eps_final_frame<br>        self.eps_evaluation = eps_evaluation<br>        self.eps_annealing_frames = eps_annealing_frames</pre><pre>        # Slopes and intercepts for exploration decrease<br>        # Calculating epsilon based on frame number<br>        self.slope = -(self.eps_initial - self.eps_final) / self.eps_annealing_frames<br>        self.intercept = self.eps_initial - self.slope*self.replay_buffer_start_size<br>        self.slope_2 = -(self.eps_final - self.eps_final_frame) / (self.max_frames - self.eps_annealing_frames - self.replay_buffer_start_size)<br>        self.intercept_2 = self.eps_final_frame - self.slope_2*self.max_frames</pre><pre>        # DQN<br>        self.DQN = dqn<br>        self.target_dqn = target_dqn</pre><pre>    <em>def</em> get_action(self, frame_number, state, evaluation=False):<br>        &quot;&quot;&quot;<br>        Get the appropriate epsilon value from a given frame number and return the action to take (ExplorationExploitationScheduler)<br>        &quot;&quot;&quot;<br>        # Calculate epsilon based on the frame number<br>        <br>        if evaluation:<br>            eps = self.eps_evaluation<br>        elif frame_number &lt; self.replay_buffer_start_size:<br>            eps = self.eps_initial<br>        elif frame_number &gt;= self.replay_buffer_start_size and frame_number &lt; self.replay_buffer_start_size + self.eps_annealing_frames:<br>            eps = self.slope*frame_number + self.intercept<br>        elif frame_number &gt;= self.replay_buffer_start_size + self.eps_annealing_frames:<br>            eps = self.slope_2*frame_number + self.intercept_2</pre><pre>        # With chance epsilon, take a random action<br>        if np.random.rand(1) &lt; eps:<br>            return np.random.randint(0, self.n_actions)</pre><pre>        # Otherwise, query the DQN for an action<br>        q_vals = self.DQN.predict(state.reshape((-1, self.input_shape[0], self.input_shape[1], self.history_length)))[0]<br>        return q_vals.argmax()</pre><pre>    <em>def</em> update_target_network(self):<br>        &quot;&quot;&quot;<br>        Update the target Q network<br>        &quot;&quot;&quot;<br>        self.target_dqn.set_weights(self.DQN.get_weights())</pre><pre>    <em>def</em> add_experience(self, action, frame, reward, terminal, clip_reward=True):<br>        &quot;&quot;&quot;<br>        Just to simplify the add experience recall function<br>        &quot;&quot;&quot;<br>        self.replay_buffer.add_experience(action, frame, reward, terminal, clip_reward)</pre><pre>    <em>def</em> learn(self, batch_size, gamma):<br>        &quot;&quot;&quot;<br>        Sample a batch and use it to improve the DQN<br>        &quot;&quot;&quot;</pre><pre>        states, actions, rewards, new_states, terminal_flags = self.replay_buffer.get_minibatch(batch_size=self.batch_size)</pre><pre>        # Main DQN estimates best action in new states<br>        arg_q_max = self.DQN.predict(new_states).argmax(axis=1)</pre><pre>        # Target DQN estimates q-vals for new states<br>        future_q_vals = self.target_dqn.predict(new_states)<br>        double_q = future_q_vals[<em>range</em>(batch_size), arg_q_max]</pre><pre>        # Calculate targets (bellman equation)<br>        target_q = rewards + (gamma*double_q * (1-terminal_flags))</pre><pre>        # Use targets to calculate loss (and use loss to calculate gradients)<br>        with tf.GradientTape() as tape:<br>            q_values = self.DQN(states)</pre><pre>            one_hot_actions = tf.keras.utils.to_categorical(actions, self.n_actions, dtype=np.float32)<br>            Q = tf.reduce_sum(tf.multiply(q_values, one_hot_actions), axis=1)</pre><pre>            error = Q - target_q<br>            loss = tf.keras.losses.Huber()(target_q, Q)</pre><pre>        model_gradients = tape.gradient(loss, self.DQN.trainable_variables)<br>        self.DQN.optimizer.apply_gradients(<em>zip</em>(model_gradients, self.DQN.trainable_variables))</pre><pre>        return <em>float</em>(loss.numpy()), error</pre><pre>    <em>def</em> save(self, folder_name, **kwargs):<br>        &quot;&quot;&quot;<br>        &quot;&quot;&quot;</pre><pre>        # Create the folder for saving the agent<br>        if not os.path.isdir(folder_name):<br>            os.makedirs(folder_name)</pre><pre>        # Save DQN and target DQN<br>        self.DQN.save(folder_name + &#39;/dqn.h5&#39;)<br>        self.target_dqn.save(folder_name + &#39;/target_dqn.h5&#39;)</pre><pre>        # Save replay buffer<br>        self.replay_buffer.save(folder_name + &#39;/replay-buffer&#39;)</pre><pre>        # Save info<br>        with <em>open</em>(folder_name + &#39;/info.json&#39;, &#39;w+&#39;) as f:<br>            f.write(json.dumps({**{&#39;buff_count&#39;: self.replay_buffer.count, &#39;buff_curr&#39;: self.replay_buffer.current}, **kwargs}))  # save replay_buffer information and any other information</pre><pre>    <em>def</em> load(self, folder_name, load_replay_buffer=True):<br>        &quot;&quot;&quot;<br>        &quot;&quot;&quot;</pre><pre>        if not os.path.isdir(folder_name):<br>            raise ValueError(f&#39;{folder_name} is not a valid directory&#39;)</pre><pre>        # Load DQNs<br>        self.DQN = tf.keras.models.load_model(folder_name + &#39;/dqn.h5&#39;)<br>        self.target_dqn = tf.keras.models.load_model(folder_name + &#39;/target_dqn.h5&#39;)<br>        self.optimizer = self.DQN.optimizer</pre><pre>        # Load replay buffer<br>        if load_replay_buffer:<br>            self.replay_buffer.load(folder_name + &#39;/replay-buffer&#39;)</pre><pre>        # Load info<br>        with <em>open</em>(folder_name + &#39;/info.json&#39;, &#39;r&#39;) as f:<br>            info = json.load(f)</pre><pre>        if load_replay_buffer:<br>            self.replay_buffer.count = info[&#39;buff_count&#39;]<br>            self.replay_buffer.current = info[&#39;buff_curr&#39;]</pre><pre>        del info[&#39;buff_count&#39;], info[&#39;buff_curr&#39;]  # just needed for the replay_buffer<br>        return info</pre><h3>Training and results</h3><p>Before going into the details of the training we need to use something to track our progression, many use tensorboard, I prefer <a href="https://wandb.ai/site">wandb</a>. It’s very easy to use and it runs in the cloud so you can really check the progress from any computer. So we begin configuring wandb:</p><pre>config = <em>dict</em> (<br>  learning_rate = 0.00025,<br>  batch_size = 32,<br>  architecture = &quot;DDDQN&quot;,<br>  infra = &quot;Ubuntu&quot;<br>)</pre><pre>wandb.init(<br>  project=&quot;tensorflow2_pong&quot;,<br>  tags=[&quot;DDDQN&quot;, &quot;CNN&quot;, &quot;RL&quot;],<br>  config=config,<br>)</pre><p>Then we define the environment, initialize the target and trained networks, the replay buffer and the agent:</p><pre>pong_wrapper = PongWrapper(ENV_NAME, NO_OP_STEPS)<br>print(&quot;The environment has the following {} actions: {}&quot;.<em>format</em>(pong_wrapper.env.action_space.n, pong_wrapper.env.unwrapped.get_action_meanings()))</pre><pre>MAIN_DQN = build_q_network(pong_wrapper.env.action_space.n, LEARNING_RATE, input_shape=INPUT_SHAPE)<br>TARGET_DQN = build_q_network(pong_wrapper.env.action_space.n, input_shape=INPUT_SHAPE)</pre><pre>replay_buffer = ReplayBuffer(size=MEMORY_SIZE, input_shape=INPUT_SHAPE)<br>dddqn_agent = DDDQN_AGENT(MAIN_DQN, TARGET_DQN, replay_buffer, pong_wrapper.env.action_space.n, <br>                    input_shape=INPUT_SHAPE, batch_size=BATCH_SIZE, <br>                   replay_buffer_start_size=REPLAY_MEMORY_START_SIZE,<br>                   max_frames=MAX_FRAMES)</pre><p>Then we have the main() function that will be called in the script that contains the training loop, the evaluation of the algorithm with all the log in wandb:</p><pre><em>def</em> main():<br>    global frame_number, rewards, loss_list<br>    while frame_number &lt; MAX_FRAMES:<br>        epoch_frame = 0<br>        while epoch_frame &lt; EVAL_FREQUENCY:<br>            start_time = time.time()<br>            pong_wrapper.reset()<br>            episode_reward_sum = 0<br>            for _ in <em>range</em>(MAX_EPISODE_LENGTH):<br>                action = dddqn_agent.get_action(frame_number, pong_wrapper.state)<br>                processed_frame, reward, terminal = pong_wrapper.step(action)<br>                frame_number += 1<br>                epoch_frame += 1<br>                episode_reward_sum += reward</pre><pre>                # Add experience to replay memory<br>                dddqn_agent.add_experience(action=action,<br>                                     frame=processed_frame[:, :, 0], # shape 84x84, remove last dimension<br>                                     reward=reward, clip_reward=CLIP_REWARD,<br>                                     terminal=terminal)</pre><pre>                # Update agent<br>                if frame_number % UPDATE_FREQ == 0 and dddqn_agent.replay_buffer.count &gt; REPLAY_MEMORY_START_SIZE:<br>                    loss, _ = dddqn_agent.learn(BATCH_SIZE, gamma=DISCOUNT_FACTOR)<br>                    loss_list.append(loss)</pre><pre>                # Update target network<br>                if frame_number % NETW_UPDATE_FREQ == 0 and frame_number &gt; REPLAY_MEMORY_START_SIZE:<br>                    dddqn_agent.update_target_network()</pre><pre>                # Break the loop when the game is over<br>                if terminal:<br>                    terminal = False<br>                    break</pre><pre>            rewards.append(episode_reward_sum)</pre><pre>            wandb.log({&#39;Game number&#39;: <em>len</em>(rewards), &#39;# Frame&#39;: frame_number, &#39;% Frame&#39;: <em>round</em>(frame_number / MAX_FRAMES, 2), &quot;Average reward&quot;: <em>round</em>(np.mean(rewards[-10:]), 2), \<br>                      &quot;Time taken&quot;: <em>round</em>(time.time() - start_time, 2)})<br>        # Evaluation<br>        terminal = True<br>        eval_rewards = []<br>        evaluate_frame_number = 0</pre><pre>        for _ in <em>range</em>(EVAL_STEPS):<br>            if terminal:<br>                pong_wrapper.reset(evaluation=True)<br>                life_lost = True<br>                episode_reward_sum = 0<br>                terminal = False</pre><pre>            action = dddqn_agent.get_action(frame_number, pong_wrapper.state, evaluation=True)</pre><pre>            # Step action<br>            _, reward, terminal = pong_wrapper.step(action)<br>            evaluate_frame_number += 1<br>            episode_reward_sum += reward</pre><pre>            # On game-over<br>            if terminal:<br>                eval_rewards.append(episode_reward_sum)</pre><pre>        if <em>len</em>(eval_rewards) &gt; 0:<br>            final_score = np.mean(eval_rewards)<br>        else:<br>            # In case the first game is longer than EVAL_STEPS<br>            final_score = episode_reward_sum<br>        # Log evaluation score<br>        wandb.log({&#39;# Frame&#39;: frame_number, &#39;% Frame&#39;: <em>round</em>(frame_number / MAX_FRAMES, 2), &#39;Evaluation score&#39;: final_score})</pre><pre>        # Save the networks, frame number, rewards and losses. <br>        if <em>len</em>(rewards) &gt; 500 and PATH_SAVE_MODEL is not None:<br>            dddqn_agent.save(f&#39;{PATH_SAVE_MODEL}/save_agent_{time.strftime(&quot;%Y%m%d%H%M&quot;) + &quot;_&quot; + <em>str</em>(frame_number).zfill(8)}&#39;, \<br>                             frame_number=frame_number, rewards=rewards, loss_list=loss_list)</pre><p>So we conclude the script calling the main function:</p><pre>if __name__ == &quot;__main__&quot;:<br>    try:<br>        main()<br>    except KeyboardInterrupt:<br>        # Save the model, I need this to save the networks, frame number, rewards and losses. <br>        # if I want to stop the script and restart without training from the beginning<br>        if PATH_SAVE_MODEL is None:<br>            print(&quot;Setting path to ../model&quot;)<br>            PATH_SAVE_MODEL = &quot;../model&quot;<br>        print(&#39;Saving the model...&#39;)<br>        dddqn_agent.save(f&#39;{PATH_SAVE_MODEL}/save_agent_{time.strftime(&quot;%Y%m%d%H%M&quot;) + &quot;_&quot; + <em>str</em>(frame_number).zfill(8)}&#39;, \<br>                             frame_number=frame_number, rewards=rewards, loss_list=loss_list)<br>        print(&#39;Saved.&#39;)</pre><p>As you can see if we need to stop the running for whatever reason the script will the model and the replay buffer, in this way we can train in multiple sessions, this is very important given that to have good results it needs to run for a couple of days.</p><p>Below you can see the training rewards and the evaluation scores, as you can see the agent become very good after around 1 million frames:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*w3UhR96E0BqtlSkr" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*ePQ1YtlWLvoqJBao" /></figure><p>Now we can see how the agent plays the game:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiA1KtdrxDlY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiA1KtdrxDlY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiA1KtdrxDlY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c6b9e9776ad4c36092e4bcd07a94c9e/href">https://medium.com/media/2c6b9e9776ad4c36092e4bcd07a94c9e/href</a></iframe><p>You can find the original article <a href="https://antonai.blog/?p=137">here</a> and all the code on my <a href="https://github.com/antonai91/reinforcement_learning/tree/master/dddqn">Github</a>. For any questions, you can reach me through <a href="https://www.linkedin.com/in/lisiantonio/">Linkedin</a>.</p><p>If you enjoyed this article, share it with your friends and colleagues! I’ll see you in the next post, in the meantime take care, stay safe, and remember <em>don’t be another brick in the wall</em>.</p><p>Anton.ai</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7fbf5ad7768" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/beating-pong-using-reinforcement-learning-part-1-dddqn-f7fbf5ad7768">Beating Pong using Reinforcement Learning — Part 1 DDDQN</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>