<jupyter_start><jupyter_text>Reinforcement learning Uno de los 3 paradigmas básicos de machine Learning, junto con **aprendizaje supervisado** (ej: clasificación) y **aprendizaje no supervisado** (ej: clustering con K-means) En Reinforcement Learning, un **agente** hace observaciones, realiza acciones en base a estas en relación con un ambiente (**environment**), recibiendo **recompensas**El objetivo es lograr que este agente aprenda a maximizar su recompesa, mediante prueba y error.Pero qué cosas pueden ser un agente?- Un programa controlando un robot, un termostato, etc.- Un programa jugando un juego tipo Pac-Man o Go- Puede der un programa que observando precios de acciones, decida cuanto comprarReinforcement Learning se usa en sistemas de recomendación, autos sin conductor, etc El algoritmo que el agente usa para determinar sus acciones se denomina **policy** o política, pudiendo ser por ejemplo una red neuronal que toma como entrada los estímulos u observaciones y como da como outputs las acciones a tomar por el agente. Sacado de https://github.com/ageron/handson-ml/blob/master/16_reinforcement_learning.ipynb<jupyter_code># To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals

# Common imports
import numpy as np
import os
import sys

# to make this notebook's output stable across runs
def reset_graph(seed=42):
    tf.compat.v1.reset_default_graph()
    tf.compat.v1.set_random_seed(seed)
    np.random.seed(seed)

# To plot pretty figures and animations
%matplotlib nbagg
import matplotlib
import matplotlib.animation as animation
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "rl"

def save_fig(fig_id, tight_layout=True):
    path = os.path.join(PROJECT_ROOT_DIR, "img", fig_id + ".png")
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format='png', dpi=300)<jupyter_output><empty_output><jupyter_text>Introduction to OpenAI gym In this notebook we will be using [OpenAI gym](https://gym.openai.com/), a great toolkit for developing and comparing Reinforcement Learning algorithms. It provides many environments for your learning *agents* to interact with. Let's start by importing `gym`:<jupyter_code>import gym<jupyter_output><empty_output><jupyter_text>Next we will load the MsPacman environment, version 0.<jupyter_code>env = gym.make('MsPacman-v0')<jupyter_output><empty_output><jupyter_text>Let's initialize the environment by calling is `reset()` method. This returns an observation:<jupyter_code>obs = env.reset()<jupyter_output><empty_output><jupyter_text>Observations vary depending on the environment. In this case it is an RGB image represented as a 3D NumPy array of shape [width, height, channels] (with 3 channels: Red, Green and Blue). In other environments it may return different objects, as we will see later.<jupyter_code>obs.shape<jupyter_output><empty_output><jupyter_text>An environment can be visualized by calling its `render()` method, and you can pick the rendering mode (the rendering options depend on the environment). In this example we will set `mode="rgb_array"` to get an image of the environment as a NumPy array:<jupyter_code>img = env.render(mode="rgb_array")<jupyter_output><empty_output><jupyter_text>Let's plot this image:<jupyter_code>plt.figure(figsize=(5,4))
plt.imshow(img)
plt.axis("off")
save_fig("MsPacman")
plt.show()<jupyter_output><empty_output><jupyter_text>Welcome back to the 1980s! :) In this environment, the rendered image is simply equal to the observation (but in many environments this is not the case):<jupyter_code>(img == obs).all()<jupyter_output><empty_output><jupyter_text>Let's create a little helper function to plot an environment:<jupyter_code>def plot_environment(env, figsize=(5,4)):
    plt.close()  # or else nbagg sometimes plots in the previous cell
    plt.figure(figsize=figsize)
    img = env.render(mode="rgb_array")
    plt.imshow(img)
    plt.axis("off")
    plt.show()<jupyter_output><empty_output><jupyter_text>Let's see how to interact with an environment. Your agent will need to select an action from an "action space" (the set of possible actions). Let's see what this environment's action space looks like:<jupyter_code>env.action_space<jupyter_output><empty_output><jupyter_text>`Discrete(9)` means that the possible actions are integers 0 through 8, which represents the 9 possible positions of the joystick (0=center, 1=up, 2=right, 3=left, 4=down, 5=upper-right, 6=upper-left, 7=lower-right, 8=lower-left). Next we need to tell the environment which action to play, and it will compute the next step of the game. Let's go left for 110 steps, then lower left for 40 steps:<jupyter_code>env.reset()
for step in range(110):
    env.step(3) #left
for step in range(40):
    env.step(8) #lower-left<jupyter_output><empty_output><jupyter_text>Where are we now?<jupyter_code>plot_environment(env)<jupyter_output><empty_output><jupyter_text>The `step()` function actually returns several important objects:<jupyter_code>obs, reward, done, info = env.step(0)<jupyter_output><empty_output><jupyter_text>The observation tells the agent what the environment looks like, as discussed earlier. This is a 210x160 RGB image:<jupyter_code>obs.shape<jupyter_output><empty_output><jupyter_text>The environment also tells the agent how much reward it got during the last step:<jupyter_code>reward<jupyter_output><empty_output><jupyter_text>When the game is over, the environment returns `done=True`:<jupyter_code>done<jupyter_output><empty_output><jupyter_text>Finally, `info` is an environment-specific dictionary that can provide some extra information about the internal state of the environment. This is useful for debugging, but your agent should not use this information for learning (it would be cheating).<jupyter_code>info<jupyter_output><empty_output><jupyter_text>Let's play one full game (with 3 lives), by moving in random directions for 10 steps at a time, recording each frame:<jupyter_code>frames = []

n_max_steps = 1000
n_change_steps = 10

obs = env.reset()
for step in range(n_max_steps):
    img = env.render(mode="rgb_array")
    frames.append(img)
    if step % n_change_steps == 0:
        action = env.action_space.sample() # play randomly
    obs, reward, done, info = env.step(action)
    if done:
        break<jupyter_output><empty_output><jupyter_text>Now show the animation (it's a bit jittery within Jupyter):<jupyter_code>def update_scene(num, frames, patch):
    patch.set_data(frames[num])
    return patch,

def plot_animation(frames, repeat=False, interval=40):
    plt.close()  # or else nbagg sometimes plots in the previous cell
    fig = plt.figure()
    patch = plt.imshow(frames[0])
    plt.axis('off')
    return animation.FuncAnimation(fig, update_scene, fargs=(frames, patch), frames=len(frames), repeat=repeat, interval=interval)
video = plot_animation(frames)
plt.show()<jupyter_output><empty_output><jupyter_text>Once you have finished playing with an environment, you should close it to free up resources:<jupyter_code>env.close()<jupyter_output><empty_output><jupyter_text>To code our first learning agent, we will be using a simpler environment: the Cart-Pole.   A simple environment: the Cart-Pole The Cart-Pole is a very simple environment composed of a cart that can move left or right, and pole placed vertically on top of it. The agent must move the cart left or right to keep the pole upright.<jupyter_code>env = gym.make("CartPole-v0")
obs = env.reset()
obs<jupyter_output><empty_output><jupyter_text>The observation is a 1D NumPy array composed of 4 floats: they represent the cart's horizontal position, its velocity, the angle of the pole (0 = vertical), and the angular velocity. Let's render the environment... unfortunately we need to fix an annoying rendering issue first. ![](img/environment.png)<jupyter_code>from PIL import Image, ImageDraw

try:
    from pyglet.gl import gl_info
    openai_cart_pole_rendering = True   # no problem, let's use OpenAI gym's rendering function
except Exception:
    openai_cart_pole_rendering = False  # probably no X server available, let's use our own rendering function

def render_cart_pole(env, obs):
    if openai_cart_pole_rendering:
        # use OpenAI gym's rendering function
        return env.render(mode="rgb_array")
    else:
        # rendering for the cart pole environment (in case OpenAI gym can't do it)
        img_w = 600
        img_h = 400
        cart_w = img_w // 12
        cart_h = img_h // 15
        pole_len = img_h // 3.5
        pole_w = img_w // 80 + 1
        x_width = 2
        max_ang = 0.2
        bg_col = (255, 255, 255)
        cart_col = 0x000000 # Blue Green Red
        pole_col = 0x669acc # Blue Green Red

        pos, vel, ang, ang_vel = obs
        img = Image.new('RGB', (img_w, img_h), bg_col)
        draw = ImageDraw.Draw(img)
        cart_x = pos * img_w // x_width + img_w // x_width
        cart_y = img_h * 95 // 100
        top_pole_x = cart_x + pole_len * np.sin(ang)
        top_pole_y = cart_y - cart_h // 2 - pole_len * np.cos(ang)
        draw.line((0, cart_y, img_w, cart_y), fill=0)
        draw.rectangle((cart_x - cart_w // 2, cart_y - cart_h // 2, cart_x + cart_w // 2, cart_y + cart_h // 2), fill=cart_col) # draw cart
        draw.line((cart_x, cart_y - cart_h // 2, top_pole_x, top_pole_y), fill=pole_col, width=pole_w) # draw pole
        return np.array(img)

def plot_cart_pole(env, obs):
    plt.close()  # or else nbagg sometimes plots in the previous cell
    img = render_cart_pole(env, obs)
    plt.imshow(img)
    plt.axis("off")
    plt.show()
plot_cart_pole(env, obs)<jupyter_output><empty_output><jupyter_text>Now let's look at the action space:<jupyter_code>env.action_space<jupyter_output><empty_output><jupyter_text>Yep, just two possible actions: accelerate towards the left or towards the right. Let's push the cart left until the pole falls:<jupyter_code>action = 1 # accelerate right
obs, reward, done, info = env.step(action)
obs
reward
done
obs = env.reset()
while True:
    obs, reward, done, info = env.step(0)
    if done:
        break
plt.close()  # or else nbagg sometimes plots in the previous cell
img = render_cart_pole(env, obs)
plt.imshow(img)
plt.axis("off")
save_fig("cart_pole_plot")
img.shape<jupyter_output><empty_output><jupyter_text>Notice that the game is over when the pole tilts too much, not when it actually falls. Now let's reset the environment and push the cart to right instead:<jupyter_code>obs = env.reset()
while True:
    obs, reward, done, info = env.step(1)
    if done:
        break
plot_cart_pole(env, obs)<jupyter_output><empty_output><jupyter_text>Looks like it's doing what we're telling it to do. Now how can we make the poll remain upright? We will need to define a _policy_ for that. This is the strategy that the agent will use to select an action at each step. It can use all the past actions and observations to decide what to do.  A simple hard-coded policy Let's hard code a simple strategy: if the pole is tilting to the left, then push the cart to the left, and _vice versa_. Let's see if that works:<jupyter_code>frames = []

n_max_steps = 1000
n_change_steps = 10

obs = env.reset()
for step in range(n_max_steps):
    img = render_cart_pole(env, obs)
    frames.append(img)

    # hard-coded policy
    position, velocity, angle, angular_velocity = obs
    if angle < 0:
        action = 0
    else:
        action = 1

    obs, reward, done, info = env.step(action)
    if done:
        break
video = plot_animation(frames)
plt.show()
def basic_policy(obs):
    angle = obs[2]
    return 0 if angle < 0 else 1
totals = []
for episode in range(500):
    episode_rewards = 0
    obs = env.reset()
    for step in range(1000): # 1000 steps max, we don't want to run forever
        action = basic_policy(obs)
        obs, reward, done, info = env.step(action)
        episode_rewards += reward
        if done:
            break
    totals.append(episode_rewards)
import numpy as np
np.mean(totals), np.std(totals), np.min(totals), np.max(totals)<jupyter_output><empty_output><jupyter_text>Nope, the system is unstable and after just a few wobbles, the pole ends up too tilted: game over. We will need to be smarter than that!  Neural Network Policies Let's create a neural network that will take observations as inputs, and output the action to take for each observation. To choose an action, the network will first estimate a probability for each action, then select an action randomly according to the estimated probabilities. In the case of the Cart-Pole environment, there are just two possible actions (left or right), so we only need one output neuron: it will output the probability `p` of the action 0 (left), and of course the probability of action 1 (right) will be `1 - p`. Note: instead of using the `fully_connected()` function from the `tensorflow.contrib.layers` module (as in the book), we now use the `dense()` function from the `tf.layers` module, which did not exist when this chapter was written. This is preferable because anything in contrib may change or be deleted without notice, while `tf.layers` is part of the official API. As you will see, the code is mostly the same.The main differences relevant to this chapter are:* the `_fn` suffix was removed in all the parameters that had it (for example the `activation_fn` parameter was renamed to `activation`).* the `weights` parameter was renamed to `kernel`,* the default activation is `None` instead of `tf.nn.relu`<jupyter_code>import tensorflow as tf
tf.compat.v1.disable_eager_execution()

# 1. Specify the network architecture
n_inputs = 4  # == env.observation_space.shape[0]
n_hidden = 4  # it's a simple task, we don't need more than this
n_outputs = 1 # only outputs the probability of accelerating left
initializer = tf.compat.v1.variance_scaling_initializer()

# 2. Build the neural network
X = tf.compat.v1.placeholder(tf.float32, shape=[None, n_inputs])
hidden = tf.compat.v1.layers.dense(X, n_hidden, activation=tf.nn.elu,
                         kernel_initializer=initializer)
outputs = tf.compat.v1.layers.dense(hidden, n_outputs, activation=tf.nn.sigmoid,
                          kernel_initializer=initializer)

# 3. Select a random action based on the estimated probabilities
p_left_and_right = tf.concat(axis=1, values=[outputs, 1 - outputs])
action = tf.compat.v1.multinomial(tf.compat.v1.log(p_left_and_right), num_samples=1)

init = tf.compat.v1.global_variables_initializer()<jupyter_output>WARNING:tensorflow:From <ipython-input-41-d54f3e6114e8>:13: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.
Instructions for updating:
Use keras.layers.Dense instead.
WARNING:tensorflow:From /Users/jrchatruc/anaconda3/lib/python3.7/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.
Instructions for updating:
Please use `layer.__call__` method instead.<jupyter_text>In this particular environment, the past actions and observations can safely be ignored, since each observation contains the environment's full state. If there were some hidden state then you may need to consider past actions and observations in order to try to infer the hidden state of the environment. For example, if the environment only revealed the position of the cart but not its velocity, you would have to consider not only the current observation but also the previous observation in order to estimate the current velocity. Another example is if the observations are noisy: you may want to use the past few observations to estimate the most likely current state. Our problem is thus as simple as can be: the current observation is noise-free and contains the environment's full state. You may wonder why we are picking a random action based on the probability given by the policy network, rather than just picking the action with the highest probability. This approach lets the agent find the right balance between _exploring_ new actions and _exploiting_ the actions that are known to work well. Here's an analogy: suppose you go to a restaurant for the first time, and all the dishes look equally appealing so you randomly pick one. If it turns out to be good, you can increase the probability to order it next time, but you shouldn't increase that probability to 100%, or else you will never try out the other dishes, some of which may be even better than the one you tried. Let's randomly initialize this policy neural network and use it to play one game:<jupyter_code>n_max_steps = 1000
frames = []

with tf.compat.v1.Session() as sess:
    init.run()
    obs = env.reset()
    for step in range(n_max_steps):
        img = render_cart_pole(env, obs)
        frames.append(img)
        action_val = action.eval(feed_dict={X: obs.reshape(1, n_inputs)})
        obs, reward, done, info = env.step(action_val[0][0])
        if done:
            break

env.close()<jupyter_output><empty_output><jupyter_text>Now let's look at how well this randomly initialized policy network performed:<jupyter_code>video = plot_animation(frames)
plt.show()<jupyter_output><empty_output><jupyter_text>Yeah... pretty bad. The neural network will have to learn to do better. First let's see if it is capable of learning the basic policy we used earlier: go left if the pole is tilting left, and go right if it is tilting right. The following code defines the same neural network but we add the target probabilities `y`, and the training operations (`cross_entropy`,  `optimizer` and `training_op`):<jupyter_code>import tensorflow as tf
tf.compat.v1.disable_eager_execution()

reset_graph()

n_inputs = 4
n_hidden = 4
n_outputs = 1

learning_rate = 0.01

initializer = tf.compat.v1.variance_scaling_initializer()

X = tf.compat.v1.placeholder(tf.float32, shape=[None, n_inputs])
y = tf.compat.v1.placeholder(tf.float32, shape=[None, n_outputs])

hidden = tf.compat.v1.layers.dense(X, n_hidden, activation=tf.nn.elu, kernel_initializer=initializer)
logits = tf.compat.v1.layers.dense(hidden, n_outputs)
outputs = tf.compat.v1.nn.sigmoid(logits) # probability of action 0 (left)
p_left_and_right = tf.compat.v1.concat(axis=1, values=[outputs, 1 - outputs])
action = tf.compat.v1.multinomial(tf.compat.v1.log(p_left_and_right), num_samples=1)

cross_entropy = tf.compat.v1.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits)
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate)
training_op = optimizer.minimize(cross_entropy)

init = tf.compat.v1.global_variables_initializer()
saver = tf.compat.v1.train.Saver()<jupyter_output><empty_output><jupyter_text>We can make the same net play in 10 different environments in parallel, and train for 1000 iterations. We also reset environments when they are done.<jupyter_code>n_environments = 1
n_iterations = 4000

envs = [gym.make("CartPole-v0") for _ in range(n_environments)]
observations = [env.reset() for env in envs]

with tf.compat.v1.Session() as sess:
    init.run()
    for iteration in range(n_iterations):
        target_probas = np.array([([1.] if obs[2] < 0 else [0.]) for obs in observations]) # if angle<0 we want proba(left)=1., or else proba(left)=0.
        action_val, _ = sess.run([action, training_op], feed_dict={X: np.array(observations), y: target_probas})
        for env_index, env in enumerate(envs):
            obs, reward, done, info = env.step(action_val[env_index][0])
            observations[env_index] = obs if not done else env.reset()
    saver.save(sess, "./my_policy_net_basic.ckpt")

for env in envs:
    env.close()
def render_policy_net(model_path, action, X, n_max_steps = 1000):
    frames = []
    env = gym.make("CartPole-v0")
    obs = env.reset()
    with tf.compat.v1.Session() as sess:
        saver.restore(sess, model_path)
        for step in range(n_max_steps):
            img = render_cart_pole(env, obs)
            frames.append(img)
            action_val = action.eval(feed_dict={X: obs.reshape(1, n_inputs)})
            obs, reward, done, info = env.step(action_val[0][0])
            if done:
                break
    env.close()
    return frames        
frames = render_policy_net("./data/my_policy_net_basic.ckpt", action, X)
video = plot_animation(frames)
plt.show()<jupyter_output>INFO:tensorflow:Restoring parameters from ./data/my_policy_net_basic.ckpt<jupyter_text>Looks like it learned the policy correctly. Now let's see if it can learn a better policy on its own.  Policy Gradients To train this neural network we will need to define the target probabilities `y`. If an action is good we should increase its probability, and conversely if it is bad we should reduce it. But how do we know whether an action is good or bad? The problem is that most actions have delayed effects, so when you win or lose points in a game, it is not clear which actions contributed to this result: was it just the last action? Or the last 10? Or just one action 50 steps earlier? This is called the _credit assignment problem_.The _Policy Gradients_ algorithm tackles this problem by first playing multiple games, then making the actions in good games slightly more likely, while actions in bad games are made slightly less likely. First we play, then we go back and think about what we did.<jupyter_code>import tensorflow as tf

reset_graph()

n_inputs = 4
n_hidden = 4
n_outputs = 1

learning_rate = 0.01

initializer = tf.compat.v1.variance_scaling_initializer()

X = tf.compat.v1.placeholder(tf.float32, shape=[None, n_inputs])

hidden = tf.compat.v1.layers.dense(X, n_hidden, activation=tf.nn.elu, kernel_initializer=initializer)
logits = tf.compat.v1.layers.dense(hidden, n_outputs)
outputs = tf.compat.v1.nn.sigmoid(logits)  # probability of action 0 (left)
p_left_and_right = tf.compat.v1.concat(axis=1, values=[outputs, 1 - outputs])
action = tf.compat.v1.multinomial(tf.compat.v1.log(p_left_and_right), num_samples=1)

y = 1. - tf.compat.v1.to_float(action)
cross_entropy = tf.compat.v1.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits)
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate)
grads_and_vars = optimizer.compute_gradients(cross_entropy)
gradients = [grad for grad, variable in grads_and_vars]
gradient_placeholders = []
grads_and_vars_feed = []
for grad, variable in grads_and_vars:
    gradient_placeholder = tf.compat.v1.placeholder(tf.float32, shape=grad.get_shape())
    gradient_placeholders.append(gradient_placeholder)
    grads_and_vars_feed.append((gradient_placeholder, variable))
training_op = optimizer.apply_gradients(grads_and_vars_feed)

init = tf.compat.v1.global_variables_initializer()
saver = tf.compat.v1.train.Saver()
def discount_rewards(rewards, discount_rate):
    discounted_rewards = np.zeros(len(rewards))
    cumulative_rewards = 0
    for step in reversed(range(len(rewards))):
        cumulative_rewards = rewards[step] + cumulative_rewards * discount_rate
        discounted_rewards[step] = cumulative_rewards
    return discounted_rewards

def discount_and_normalize_rewards(all_rewards, discount_rate):
    all_discounted_rewards = [discount_rewards(rewards, discount_rate) for rewards in all_rewards]
    flat_rewards = np.concatenate(all_discounted_rewards)
    reward_mean = flat_rewards.mean()
    reward_std = flat_rewards.std()
    return [(discounted_rewards - reward_mean)/reward_std for discounted_rewards in all_discounted_rewards]
discount_rewards([10, 0, -50], discount_rate=0.8)
discount_and_normalize_rewards([[10, 0, -50], [10, 20]], discount_rate=0.8)
env = gym.make("CartPole-v0")

n_games_per_update = 10
n_max_steps = 1000
n_iterations = 250
save_iterations = 10
discount_rate = 0.95

with tf.compat.v1.Session() as sess:
    init.run()
    for iteration in range(n_iterations):
        print("\rIteration: {}".format(iteration), end="")
        all_rewards = []
        all_gradients = []
        for game in range(n_games_per_update):
            current_rewards = []
            current_gradients = []
            obs = env.reset()
            for step in range(n_max_steps):
                action_val, gradients_val = sess.run([action, gradients], feed_dict={X: obs.reshape(1, n_inputs)})
                obs, reward, done, info = env.step(action_val[0][0])
                current_rewards.append(reward)
                current_gradients.append(gradients_val)
                if done:
                    break
            all_rewards.append(current_rewards)
            all_gradients.append(current_gradients)

        all_rewards = discount_and_normalize_rewards(all_rewards, discount_rate=discount_rate)
        feed_dict = {}
        for var_index, gradient_placeholder in enumerate(gradient_placeholders):
            mean_gradients = np.mean([reward * all_gradients[game_index][step][var_index]
                                      for game_index, rewards in enumerate(all_rewards)
                                          for step, reward in enumerate(rewards)], axis=0)
            feed_dict[gradient_placeholder] = mean_gradients
        sess.run(training_op, feed_dict=feed_dict)
        if iteration % save_iterations == 0:
            saver.save(sess, "./my_policy_net_pg.ckpt")
env.close()
frames = render_policy_net("./data/my_policy_net_pg.ckpt", action, X, n_max_steps=1000)
video = plot_animation(frames)
plt.show()<jupyter_output>INFO:tensorflow:Restoring parameters from ./data/my_policy_net_pg.ckpt
{'fraction_non_alphanumeric': 0.08988589009619503, 'fraction_numerical': 0.01343614908283678, 'mean_word_length': 4.401346234749685, 'pattern_counts': {'":': 0, '<': 131, '<?xml version=': 0, '>': 127, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '32', 'dir': 'jupyter-structured-clean-dedup', 'id': '280670', 'license': 'MIT', 'n_tokens_mistral': 8271, 'n_tokens_neox': 7852, 'n_words': 2653, 'path': 'clases/clase_7/clase_7_reinforcement_learning.ipynb', 'repo_name': 'lambdaclass/data_etudes', 'size': '25677'}