<jupyter_start><jupyter_text>Cartpole DQN Deep Q-Learning Network with Keras and OpenAI Gym, based on [<NAME>'s code](https://github.com/keon/deep-q-learning/blob/master/dqn.py).  Import dependencies<jupyter_code>import random
import gym
import numpy as np
from collections import deque
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
import os<jupyter_output><empty_output><jupyter_text>Set parameters<jupyter_code>env = # FILL IN
state_size = env.observation_space.shape[0]
state_size
action_size = env.action_space.n
action_size
batch_size = # FILL IN
n_episodes = # FILL IN
output_dir = 'model_output/cartpole/'
if not os.path.exists(output_dir):
    os.makedirs(output_dir)<jupyter_output><empty_output><jupyter_text>Define agent<jupyter_code>class DQNAgent:
    
    def __init__(self, state_size, action_size):
        self.state_size = state_size
        self.action_size = action_size
        
        self.memory = deque(maxlen=2000) 
        
        self.gamma = # FILL IN
        
        self.epsilon = # FILL IN
        self.epsilon_decay = # FILL IN
        self.epsilon_min = # FILL IN
        
        self.learning_rate = # FILL IN
        
        self.model = self._build_model() 
    
    def _build_model(self):

        model = Sequential()

        # FILL IN NEURAL NETWORK ARCHITECTURE

        # COMPILE MODEL
        
        return model
    
    def remember(self, state, action, reward, next_state, done):
        self.memory.append((state, action, reward, next_state, done)) 

    def act(self, state):
        if np.random.rand() <= self.epsilon: 
            return random.randrange(self.action_size)
        act_values = self.model.predict(state)
        return np.argmax(act_values[0]) 

    def replay(self, batch_size): 
        
        minibatch = random.sample(self.memory, batch_size) 
        
        for state, action, reward, next_state, done in minibatch: 
            target = reward # N.B.: if done
            if not done: 
                target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0])) # (maximum target Q based on future action a')
            target_f = self.model.predict(state) 
            target_f[0][action] = target
            
            self.model.fit(state, target_f, epochs=1, verbose=0)

        if self.epsilon > self.epsilon_min:
            self.epsilon *= self.epsilon_decay

    def load(self, name):
        self.model.load_weights(name)

    def save(self, name):
        self.model.save_weights(name)<jupyter_output><empty_output><jupyter_text>Interact with environment<jupyter_code>agent = DQNAgent(state_size, action_size) 
done = False

for e in range(n_episodes): 

    state = env.reset() 
    state = np.reshape(state, [1, state_size])
    
    for time in range(5000):  
        
        #  env.render()

        action = agent.act(state) 
    
        next_state, reward, done, _ = env.step(action) 
        
        reward = reward if not done else -10 
        
        next_state = np.reshape(next_state, [1, state_size])
        
        agent.remember(state, action, reward, next_state, done) 

        state = next_state 
        
        if done: 
            print("episode: {}/{}, score: {}, e: {:.2}".format(e, n_episodes, time, agent.epsilon))
            break 

    if len(agent.memory) > batch_size:
        agent.replay(batch_size)

    if e % 50 == 0:
        agent.save(output_dir + "weights_" + '{:04d}'.format(e) + ".hdf5")         
# saved agents can be loaded with agent.load("./path/filename.hdf5")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10542335362479248, 'fraction_numerical': 0.007194244604316547, 'mean_word_length': 2.486017357762777, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 20, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '635324', 'license': 'MIT', 'n_tokens_mistral': 1211, 'n_tokens_neox': 1146, 'n_words': 257, 'path': 'notebooks/live_training/cartpole_dqn_LT.ipynb', 'repo_name': 'GodefroyClair/TensorFlow-LiveLessons', 'size': '3616'}