<?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 Wiwat Pitakworarat on Medium]]></title>
        <description><![CDATA[Stories by Wiwat Pitakworarat on Medium]]></description>
        <link>https://medium.com/@wiwat_quant?source=rss-8c819c68a306------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p6p6RHE--CbupkMHpiI2Gw.png</url>
            <title>Stories by Wiwat Pitakworarat on Medium</title>
            <link>https://medium.com/@wiwat_quant?source=rss-8c819c68a306------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:37:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wiwat_quant/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[How to Apply Reinforcement Learning to Solve Real-World Problems]]></title>
            <link>https://medium.com/@wiwat_quant/how-to-apply-reinforcement-learning-to-solve-real-world-problems-e7639541183f?source=rss-8c819c68a306------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7639541183f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai-real-world]]></category>
            <category><![CDATA[deep-q-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[custom-ai-model]]></category>
            <dc:creator><![CDATA[Wiwat Pitakworarat]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 16:22:27 GMT</pubDate>
            <atom:updated>2026-11-17T09:28:34.234Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1. Introduction</strong></p><p>In this article, we will explore how to design and implement an automatic temperature control system using Reinforcement Learning. By leveraging this advanced AI technique, we’ll enable the system to autonomously adjust the temperature to maintain optimal comfort levels, responding dynamically to changes in the environment. You can also set a target temperature, such as 25°C, and the air conditioner will intelligently attempt to maintain this temperature, adapting to fluctuations and constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xfbft6g4Z9N4pEvy2GWzA.png" /><figcaption>Automatic air conditioner temperature control using reinforcement learning, developed by Wiwat Pitakworarat.</figcaption></figure><p><strong>2. Understanding the Key Components: State, Action, Reward, and Termination</strong></p><ul><li><strong>State</strong>: The current temperature of the air conditioner.</li><li><strong>Action:</strong> Increase, Decrease, Maintain the temperature.</li><li><strong>Reward:</strong> Positive rewards are given when the temperature remains within the range of the target temperature ±1°C., outside the range will be negative reward.</li><li><strong>Done</strong>: The episode is considered done after N time steps.</li></ul><p><strong>3.</strong> <strong>Implementing the Code: Reinforcement Learning for Air Conditioner Temperature Control</strong></p><p>Section 3.1 Install Libraries</p><pre>#-- Action we can take to the environment and current state of that environment (Discrete, Box)<br>#-- Discrete : Discrete Space (Action Number)<br>#-- Box : Box Space (set 1-100 points)<br>import random<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from gym import Env<br>from gym.spaces import Discrete, Box <br>from rl.agents import DQNAgent<br>from rl.policy import BoltzmannQPolicy<br>from rl.memory import SequentialMemory<br>from keras.callbacks import Callback<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.optimizers import Adam<br>from tensorflow.keras.layers import Dense, Flatten</pre><p>Section 3.2 Create Custom Environment</p><pre>#-- Environment Class for Air Con Temp, try to optimal temp as long as possible<br>class ACT(Env):<br>    def __init__(self, temp_input = 20, temp_range = 1):<br>        self.target_temp = temp_input<br>        self.temp_range = temp_range<br>        #-- Set action type : decrease, stay, increase<br>        self.action_space = Discrete(3)<br>        #-- Temperature Range (1 - 100)<br>        self.observation_space = Box(low=np.array([0]), high=np.array([100]))<br>        #-- Set initial temperature<br>        self.state = self.target_temp + random.randint(-5,5)<br>        #-- Set Air Con Time Stop <br>        self.act_length = 120<br>    <br>    def step(self, action):<br>        #-- Action Type<br>        # 0 -1 = -1 decrease temperature<br>        # 1 -1 = 0 <br>        # 2 -1 = 1 increase temperature <br>        self.state += action -1 <br>        #-- Reduce Air Con Time Stop by 1 second<br>        self.act_length -= 1 <br>        <br>        #-- Reward calculation<br>        if self.state &gt;= self.target_temp - self.temp_range and self.state &lt;= self.target_temp + self.temp_range: <br>            reward =1 <br>        else: <br>            reward = -1 <br>        <br>        #-- Check if Air Con Time Stop is 0 : done<br>        if self.act_length &lt;= 0: <br>            done = True<br>        else:<br>            done = False<br>        info = {}<br>        return self.state, reward, done, info<br><br>    def render(self):<br>        pass<br>    <br>    def reset(self, temp_input=None):<br>        #-- Reset Air Con temperature<br>        #-- Reset target temperature if provided<br>        if temp_input is not None:<br>            self.target_temp = temp_input<br>        #-- Reset the temperature and Air Con Time Stop<br>        self.state = self.target_temp + random.randint(-5, 5)<br>        self.act_length = 120<br>        return self.state</pre><p>Section 3.3 Build Your Deep Learning and DQN Model</p><pre>#-- state is the number of input data shape<br>#-- actions = number of output data type<br>#-- Deep Learning Model<br>def build_model(states, actions):<br>    model = Sequential()    <br>    model.add(Dense(128, activation=&#39;relu&#39;, input_shape=states))<br>    model.add(Dense(128, activation=&#39;relu&#39;))<br>    model.add(Dense(actions, activation=&#39;linear&#39;))<br>    return model<br><br>#-- Build Deep Learning Model<br>states = env.observation_space.shape<br>actions = env.action_space.n<br>model = build_model(states, actions)<br>model.summary()<br><br>#-- Keras Rl model <br>def build_agent(model, actions):<br>    policy = BoltzmannQPolicy()<br>    memory = SequentialMemory(limit=100000, window_length=1)<br>    #-- weight update every 0.1% change<br>    dqn = DQNAgent(model=model, memory=memory, policy=policy, <br>                nb_actions=actions, nb_steps_warmup=1000, target_model_update=1e-3)<br>    return dqn<br><br>#-- Callback Function : Reward Store <br>class RewardLogger(Callback):<br>    def __init__(self):<br>        self.episode_rewards = []<br>        self.total_rewards = 0<br><br>    def on_episode_begin(self, episode, logs={}):<br>        self.total_rewards = 0<br><br>    def on_step_end(self, step, logs={}):<br>        self.total_rewards += logs[&#39;reward&#39;]<br><br>    def on_episode_end(self, episode, logs={}):<br>        self.episode_rewards.append(self.total_rewards)<br>    <br>    def plot_rewards(self):<br>        plt.plot(self.episode_rewards)<br>        plt.title(&quot;Total Reward per Episode&quot;)<br>        plt.xlabel(&quot;Episode&quot;)<br>        plt.ylabel(&quot;Total Reward&quot;)<br>        plt.show()</pre><p>Section 3.4 Train Reinforcement Model</p><pre>#- RL Model Training<br>for length in range(2):<br>    #-- Delete model cache<br>    del model <br><br>    #-- build deep learning model<br>    model = build_model(states, actions)<br>    reward_logger = RewardLogger()<br><br>    #-- Build Env For Training<br>    temp_input_val = [40,50]<br>    env = ACT(temp_input = temp_input_val[length])<br><br>    #-- build dqn model<br>    dqn = build_agent(model, actions)<br>    dqn.compile(Adam(lr=1e-3), metrics=[&#39;mae&#39;])<br>    dqn.fit(env, nb_steps=40000, visualize=False, verbose=1, callbacks=[reward_logger])<br>    dqn.save_weights(&#39;dqn_temp_&#39; + str(temp_input_val[length]) + &#39;_weights.h5f&#39;, overwrite=True)<br>    #-- Plot toal reward<br>    reward_logger.plot_rewards()</pre><p>Section 3.5 Running the Agent Environment</p><pre>#-- Running the Agent Environment (Temp Control Should be 40 and 50)<br>#-- delete model cache<br>del model <br>#-- build deep and dqn model<br>model = build_model(states, actions)<br>dqn = build_agent(model, actions)<br>dqn.compile(Adam(lr=1e-3), metrics=[&#39;mae&#39;])<br><br>#-- Set input temperature control <br>temp_control = int(input(&quot;Enter Your Air Condition Temperature: &quot;))<br>print(f&quot;Your Air Con Temperature Target is {temp_control} .&quot;)<br>if(temp_control == 40 or temp_control == 50):<br>    dqn.load_weights(&#39;dqn_temp_&#39; + str(temp_control) + &#39;_weights.h5f&#39;)<br>    env = ACT(temp_input = temp_control)<br>    scores = dqn.test(env, nb_episodes=10, visualize=False)<br>    print(&#39;Mean Reward Value is : &#39;,np.mean(scores.history[&#39;episode_reward&#39;]))<br>else: print(&quot;Please Adjust your Air Conditioner Temperature Control to be 40 or 50&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*10LObTR7VNWavCryXnJJ_A.png" /><figcaption>Total Reward Each Training</figcaption></figure><p>4. Conclusion</p><p>You’ve successfully trained the model for various temperatures. Now, when you set a new target temperature, the system will automatically adjust the current temperature to match your target. This solution can be applied effectively to real-world scenarios</p><p>To see this process in action, check out the video below. It provides a step-by-step guide on how to implement this model in practical applications, showcasing real-world examples that illustrate its effectiveness.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIcxlbb0hvnM%3Fstart%3D699%26feature%3Doembed%26start%3D699&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIcxlbb0hvnM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIcxlbb0hvnM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f65ff42ff600bcf32bfae50a21ee86ae/href">https://medium.com/media/f65ff42ff600bcf32bfae50a21ee86ae/href</a></iframe><p><strong>Check out my related work on this topic</strong></p><ul><li><a href="https://medium.com/@wiwat_quant/reinforcement-custom-your-own-environment-2024-e5e3f727dbd9">https://medium.com/@wiwat_quant/reinforcement-custom-your-own-environment-2024-e5e3f727dbd9</a> (Part 1)</li></ul><p><strong>Follow Me</strong></p><ul><li>Github: <a href="https://github.com/WiwatPtk">https://github.com/WiwatPtk</a></li><li>Youtube: <a href="https://www.youtube.com/@wiwat_ai_coaching">https://www.youtube.com/@wiwat_ai_coaching</a></li><li>Linkedin: <a href="https://www.linkedin.com/in/wiwat-pitakworarat/">https://www.linkedin.com/in/wiwat-pitakworarat/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7639541183f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Your Own Custom Reinforcement Learning Environment]]></title>
            <link>https://medium.com/@wiwat_quant/reinforcement-custom-your-own-environment-2024-e5e3f727dbd9?source=rss-8c819c68a306------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5e3f727dbd9</guid>
            <category><![CDATA[dqn-agent-implementation]]></category>
            <category><![CDATA[custom-ai-environment]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning-models]]></category>
            <category><![CDATA[control-temperature]]></category>
            <dc:creator><![CDATA[Wiwat Pitakworarat]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 09:54:57 GMT</pubDate>
            <atom:updated>2026-11-17T09:30:10.526Z</atom:updated>
            <content:encoded><![CDATA[<p>4 elements:</p><p><strong>1. Introduction</strong></p><p>In this project, we explore a reinforcement learning system designed to automatically control shower temperature, maintaining it between 37–39°C. The system continuously adapts, adjusting the temperature as it fluctuates over time to ensure optimal comfort and efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4MHrU0q98ux2LDuYqVWnQ.png" /><figcaption>Reinforcement Learning Application developed by Wiwat Pitakworarat</figcaption></figure><p><strong>2.</strong> <strong>Understanding the Key Components: State, Action, Reward, and Termination</strong></p><ul><li><strong>State</strong>: The current temperature of the water.</li><li><strong>Action:</strong> Increase, Decrease, Maintain the temperature.</li><li><strong>Reward:</strong> positive reward for temperature range between 37–39, outside the range will be negative reward.</li><li><strong>Done</strong>: The episode is considered done after 120 time steps.</li></ul><p><strong>3.</strong> <strong>Implementing the Code: Reinforcement Learning for Temperature Control</strong></p><p>Section 3.1 Install Libraries</p><pre>#-- Action we can take to the environment and current state of that environment (Discrete, Box)<br>#-- Discrete : Discrete Space (Action Number)<br>#-- Box : Box Space (set 1-100 points)<br>import random<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from gym import Env<br>from gym.spaces import Discrete, Box <br>from rl.agents import DQNAgent<br>from rl.policy import BoltzmannQPolicy<br>from rl.memory import SequentialMemory<br>from keras.callbacks import Callback<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.optimizers import Adam<br>from tensorflow.keras.layers import Dense, Flatten</pre><p>Section 3.2 Create Your Own Custom Environment</p><pre>#-- Environment Class for Shower Temp 37 to 39 (shower length is 60 second), try to optimal temp as long as possible<br>class ShowerEnv(Env):<br>    def __init__(self):<br>        #-- Set action type : decrease, stay, increase<br>        self.action_space = Discrete(3)<br>        #-- Temperature Range (1 - 100)<br>        self.observation_space = Box(low=np.array([0]), high=np.array([100]))<br>        #-- Set initial temperature<br>        self.state = 38 + random.randint(-5,5)<br>        #-- Set shower length (60sec)<br>        self.shower_length = 120<br>    <br>    def step(self, action):<br>        #-- Action Type<br>        # 0 -1 = -1 decrease temperature<br>        # 1 -1 = 0 <br>        # 2 -1 = 1 increase temperature <br>        self.state += action -1 <br>        #-- Reduce shower length by 1 second<br>        self.shower_length -= 1 <br>        <br>        #-- Reward calculation<br>        if self.state &gt;=37 and self.state &lt;=39: <br>            reward =1 <br>        else: <br>            reward = -1 <br>        <br>        #-- Check if shower length is 0 : done<br>        if self.shower_length &lt;= 0: <br>            done = True<br>        else:<br>            done = False<br>        <br>        #-- <br>        info = {}<br>        return self.state, reward, done, info<br><br>    def render(self):<br>        pass<br>    <br>    def reset(self):<br>        #-- Reset shower temperature<br>        self.state = 38 + random.randint(-5,5)<br>        #-- Reset shower length<br>        self.shower_length = 120<br>        return self.state</pre><p>Section 3.3 Build Your Deep Learning Model</p><pre>#-- state is the number of input data shape<br>#-- actions = number of output data type<br>#-- Deep Learning Model<br>def build_model(states, actions):<br>    model = Sequential()    <br>    model.add(Dense(128, activation=&#39;relu&#39;, input_shape=states))<br>    model.add(Dense(128, activation=&#39;relu&#39;))<br>    model.add(Dense(actions, activation=&#39;linear&#39;))<br>    return model<br><br>#-- Build Deep Learning Model<br>states = env.observation_space.shape<br>actions = env.action_space.n<br>model = build_model(states, actions)<br>model.summary()</pre><p>Section 3.4 Build Your RL Agent Model</p><pre>#-- Callback Function : Reward Store <br>class RewardLogger(Callback):<br>    def __init__(self):<br>        self.episode_rewards = []<br>        self.total_rewards = 0<br><br>    def on_episode_begin(self, episode, logs={}):<br>        self.total_rewards = 0<br><br>    def on_step_end(self, step, logs={}):<br>        self.total_rewards += logs[&#39;reward&#39;]<br><br>    def on_episode_end(self, episode, logs={}):<br>        self.episode_rewards.append(self.total_rewards)<br>    <br>    def plot_rewards(self):<br>        plt.plot(self.episode_rewards)<br>        plt.title(&quot;Total Reward per Episode&quot;)<br>        plt.xlabel(&quot;Episode&quot;)<br>        plt.ylabel(&quot;Total Reward&quot;)<br>        plt.show()<br><br>#-- Clear model cache and rebuild deep lerning model<br>del model <br>model = build_model(states, actions)<br><br>reward_logger = RewardLogger()<br><br>#-- Keras Rl model <br>def build_agent(model, actions):<br>    policy = BoltzmannQPolicy()<br>    memory = SequentialMemory(limit=100000, window_length=1)<br>    #-- weight update every 0.1% change<br>    dqn = DQNAgent(model=model, memory=memory, policy=policy, <br>                  nb_actions=actions, nb_steps_warmup=1000, target_model_update=1e-3)<br>    return dqn<br><br>#-- Build Rl model<br>dqn = build_agent(model, actions)<br>dqn.compile(Adam(lr=1e-3), metrics=[&#39;mae&#39;])<br>dqn.fit(env, nb_steps=40000, visualize=False, verbose=1, callbacks=[reward_logger])<br><br>#-- Plot toal reward<br>reward_logger.plot_rewards()</pre><p>Section 3.5 Running the Reinforcement Learning Model for Temperature Control</p><pre>#-- Running the Agent Environment<br>scores = dqn.test(env, nb_episodes=100, visualize=False)<br>print(np.mean(scores.history[&#39;episode_reward&#39;]))</pre><p><strong>4. Conclusion</strong></p><p>Successfully created your own custom environment, and the chart shows that the agent has learned to control the temperature. After some initial fluctuations, the rewards became stable, indicating that the agent is now consistently maintaining the target temperature range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5DuqIAG7-iIVUq3kisP2g.png" /></figure><p><strong>Check out my related work on this topic</strong></p><ul><li><a href="https://medium.com/@wiwat_quant/how-to-apply-reinforcement-learning-to-solve-real-world-problems-e7639541183f">https://medium.com/@wiwat_quant/how-to-apply-reinforcement-learning-to-solve-real-world-problems-e7639541183f</a> (Part 2)</li></ul><p><strong>Follow Me</strong></p><ul><li>Github: <a href="https://github.com/WiwatPtk">https://github.com/WiwatPtk</a></li><li>Youtube: <a href="https://www.youtube.com/@wiwat_ai_coaching">https://www.youtube.com/@wiwat_ai_coaching</a></li><li>Linkedin: <a href="https://www.linkedin.com/in/wiwat-pitakworarat/">https://www.linkedin.com/in/wiwat-pitakworarat/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5e3f727dbd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom DQN Reinforcement Algorithm for CartPole [2024]]]></title>
            <link>https://medium.com/@wiwat_quant/1-introduction-of-dqn-keras-cartpole-f03ed98e18ab?source=rss-8c819c68a306------2</link>
            <guid isPermaLink="false">https://medium.com/p/f03ed98e18ab</guid>
            <category><![CDATA[2024]]></category>
            <category><![CDATA[deep-q-network]]></category>
            <category><![CDATA[cartpole]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[custom-dqn-algorithm]]></category>
            <dc:creator><![CDATA[Wiwat Pitakworarat]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 07:00:36 GMT</pubDate>
            <atom:updated>2024-09-28T02:01:12.211Z</atom:updated>
            <content:encoded><![CDATA[<p>5 elements:</p><h4>1. Introduction of DQN Cartpole</h4><p>The CartPole environment is a classic problem in the field of reinforcement learning, where the goal is to balance a pole on a moving cart. Deep Q-Networks (DQN) is a powerful method that uses deep learning to approximate the Q-value function, which helps in deciding the best action to take in each state. In this article, we will walk through the implementation of a DQN to solve the CartPole problem using Keras.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pChFX8Nc3n4lrLX_QS3WA.png" /><figcaption>photo by wiwat pitakworarat</figcaption></figure><h4>2. Data for DQN Cartpole</h4><p>The CartPole environment is part of the OpenAI Gym toolkit. It provides a simple interface to interact with the environment and collect data for training our DQN model. The data consists of states, actions, rewards, and next states, which we will use to train our model.</p><ul><li><strong>State</strong>: A 4-dimensional vector representing the position and velocity of the cart and the angle and angular velocity of the pole.</li><li><strong>Action</strong>: Either move the cart left or right.</li><li><strong>Reward</strong>: +1 for every time step the pole remains upright.</li><li><strong>Next State</strong>: The state of the environment after taking the action.</li><li><strong>Done</strong>: A boolean indicating whether the episode has ended.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjAS4Duh4g8i30vk_zrKVg.jpeg" /><figcaption>photo by wiwat pitakworarat</figcaption></figure><h4>3. Platform: VSCode and Python</h4><p>For this project, we will use Visual Studio Code (VSCode) as our Integrated Development Environment (IDE) and Python as our programming language. VSCode provides a robust environment with extensions for Python that simplify development and debugging.</p><h4>4. Implementation of DQN with Cartpole</h4><p>Section 4.1: Import Libraries</p><pre>import gym<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd <br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import InputLayer, Dense<br>from tensorflow.keras import optimizers<br>from collections import deque <br>import random </pre><p>Section 4.2: Log Setting</p><pre>import logging<br>import os <br><br>#-- Define the log folder and file name<br>log_folder = &#39;logs&#39;<br>log_file = &#39;batch.log&#39;<br><br>#-- Create the log folder if it doesn&#39;t exist<br>if not os.path.exists(log_folder):<br>    os.makedirs(log_folder)<br><br>#-- Define the full path to the log file<br>log_path = os.path.join(log_folder, log_file)<br><br>#-- Create a logger with the name of the current module<br>logger = logging.getLogger(__name__)<br><br>#-- Specify the file handler to output logs to a file named &#39;logs.log&#39;, in write mode (&#39;w&#39;)<br>file_handler = logging.FileHandler(log_path, mode=&#39;w&#39;)  # &#39;w&#39; stands for write<br><br>#-- Set the logging level for the file handler<br>file_handler.setLevel(logging.INFO)  # Set to the desired level (e.g., WARNING)<br><br>#-- Define the format of the log messages<br>formatter = logging.Formatter(&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br>file_handler.setFormatter(formatter)<br><br>#-- Clear existing handlers (if any) and add the file handler to the logger , avoid duplicate logs<br>logger.handlers = []  <br><br>#-- connect to log file using logger.addHandler(file_handler)<br>logger.addHandler(file_handler)<br><br>#-- Example of logging a WARNING message<br>logger.warning(&quot;-------- Start --------&quot;)</pre><p>Section 4.3: Neural Network Creating</p><pre>#-- Inheritate from Sequential Class<br>class NeuralNetwork(Sequential):<br>    #-- number of observation and action <br>    def __init__(self, observation_space, action_space, learning_rate):<br>        #-- Constructor , we will set 2 hidden layer and 24 node for each <br>        #-- super().__init__() : USe for build DeepLearning<br>        super().__init__()<br><br>        #-- add input and first hidden layer<br>        self.add(Dense(24, input_shape=(observation_space,), activation = &quot;relu&quot;))<br>        self.add(Dense(24,activation = &quot;relu&quot;))<br>        self.add(Dense(action_space,activation=&quot;linear&quot;))<br>        self.compile(loss=&#39;mse&#39;,optimizer = optimizers.Adam(learning_rate=learning_rate))<br><br>    #-- State = X , target_output = Y (X data , Y Label)<br>    def train(self,state,target_output):<br>        self.fit(state, target_output, epochs =1, verbose= 0)<br><br>    #-- Predict <br>    def predict_expected_reward_for_each_action(self,state):<br>        return self.predict(state)</pre><p>Section 4.4: Building a Custom Agent Algorithm</p><pre>class Agent():<br>    def __init__(self, epsilon_initial=0.5):<br>        #-- 1 million data store max<br>        self.memory = deque(maxlen = 10000000)<br>        #--<br>        self.batch_size = 20<br>        self.learning_rate = 0.001<br>        #-- discount_factor <br>        self.discount_factor = 0.95<br>        self.epsilon = epsilon_initial<br>        #-- decay_factor for discount eplsilon <br>        self.decay_factor = 0.99<br>        #-- for append the data inside the function of class , store the data <br>        self.reward_for_each_episode = []<br>        self.batch_length_store = []<br>        self.batch_store = []<br>        self.state_store = []<br>        self.state_next_store = []<br>        self.action_store = []<br>        self.reward_store = []<br>        self.qupdate_store =[]<br>        self.qvalue_before_adj_store = []<br>        self.qvalue_after_adj_store = []<br>        self.terminal_store = [] <br>        self.neural_store = []<br>        self.epsilon_store = []<br>        self.q_values_train_store = 0<br>        self.run_count = 0<br>        self.reward_pergame_store = []<br>        #-- Neural Network <br>        self.neural_network = NeuralNetwork(4,2,self.learning_rate)<br><br><br>    def play(self, env, number_of_episode=10, isRender = False):<br><br>        for i_episode in range(number_of_episode):<br>            if(self.epsilon &lt; 0.025):<br>                    print(&quot;Epsilon is Lower than Value&quot;)<br>                    print(&quot;Last Episode Run :&quot;, i_episode)<br>                    break<br>            print(&quot;Episode {} of {} &quot;.format(i_episode + 1, number_of_episode))<br><br>            #-- state has 4 thing observation<br>            state, info = env.reset()<br>            #-- state : 1x4 array state <br>            state = np.reshape(state,[1,4])<br><br>            total_reward = 0<br>            end_game = False<br>            truncated = False<br>            <br>            while not (end_game or truncated):<br>                if isRender:<br>                    env.render()<br>                if self.__with_probability(self.epsilon):<br>                    action = self.__getActionByRandomly(env)<br>                else:<br>                    action = self.__getActionWithHighestExpectedReward(state)<br>                <br>                #-- Must have both end_game and truncated for end the loop <br>                new_state, reward, end_game, truncated ,info = env.step(action)<br>                new_state = np.reshape(new_state, [1,4])<br>                if end_game or truncated:<br>                    reward = -200<br>                    self.run_count += 1<br>                else: <br>                    total_reward += reward       <br>                self.reward_pergame_store.append([i_episode,reward])<br><br>                #-- record data in the store memory<br>                self.remember(state,action,reward,new_state,end_game or truncated)<br>                state = new_state<br>                self.experience_replay()<br>            self.reward_for_each_episode.append(total_reward)<br><br>    def __with_probability(self, probability):<br>        return np.random.random() &lt; probability<br><br>    def __getActionByRandomly(self, env):<br>        return env.action_space.sample()<br><br>    def __getActionWithHighestExpectedReward(self, state):<br>        return np.argmax(self.neural_network.predict_expected_reward_for_each_action(state)[0])<br><br>    def __getExpectedReward(self, state):<br>        return np.max(self.neural_network.predict_expected_reward_for_each_action(state)[0])<br><br>    def remember(self, state, action, reward, next_state, done):<br>        self.memory.append((state, action, reward, next_state, done))<br><br>    #-- Train Function<br>    def experience_replay(self):<br>        #-- if data is less than 20 do nothing <br>        if len(self.memory) &lt; self.batch_size:<br>            return <br>        #-- Get Random Sample<br>        batch = random.sample(self.memory, self.batch_size)<br>        #-- log batch<br>        batch_length = len(batch)<br>        self.batch_length_store.append(batch_length)<br>        self.batch_store.append(batch)<br>        logger.warning(f&quot;length of batch is : {batch_length}&quot;)<br>        <br>        for state, action, reward, state_next, terminal in batch:<br>            #-- Discover Data Using Append<br>            self.state_store.append(state)<br>            self.state_next_store.append(state_next)<br>            self.action_store.append(action)<br>            self.reward_store.append(reward)<br>            self.terminal_store.append(terminal)<br>            #-- <br>            q_update = reward<br>            if not terminal:<br>                q_update = reward + self.discount_factor * self.__getExpectedReward(state_next)<br>            self.qupdate_store.append([q_update,action])<br>            #-- q value neural network<br>            q_values = self.neural_network.predict_expected_reward_for_each_action(state)<br>            q_values_copy = q_values.copy()<br>            self.qvalue_before_adj_store.append(q_values_copy)<br>            q_values[0][action] = q_update<br>            self.neural_network.train(state,q_values)<br>            self.qvalue_after_adj_store.append(q_values)<br>            self.q_values_train_store = q_values<br><br>        #--<br>        self.epsilon *= self.decay_factor<br>        self.epsilon_store.append(self.epsilon)</pre><p>Section 4.5: Running the Agent Environment</p><pre>#-- Agent Play &amp; Visual Result<br>env = gym.make(&#39;CartPole-v1&#39;)<br>agent = Agent()<br>qtable_store = agent.play(env, 10<br>                          , False)<br>plt.title(&quot;Performance over time&quot;)<br>plt.ylabel(&#39;TotalReward&#39;)<br>plt.xlabel(&#39;Episode&#39;)<br>plt.plot(agent.reward_for_each_episode)<br>plt.show()</pre><p>Section 4.6: Check Result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*SaQwRKXfGhVoegvlWmKGfA.png" /></figure><pre>display(&quot;Q Update &amp; Action :&quot;, agent.qupdate_store[-5:])<br>display(&quot;Q Value Before Update :&quot;, agent.qvalue_before_adj_store[-5:])<br>display(&quot;Q Value After Update :&quot;,agent.qvalue_after_adj_store[-5:])<br>display(&quot;Q Value Last Update :&quot;,agent.q_values_train_store[0])</pre><h4>5. Conclusion for Custom DQN Reinforcement Algorithm for CartPole</h4><p>Implementing a DQN to solve the CartPole problem demonstrates the power of combining reinforcement learning with deep learning. Using Keras, we can build and train a neural network to approximate the Q-value function effectively. This method can be extended to more complex environments and problems, showcasing the versatility of DQNs. By following the steps outlined in this article, you can experiment with different architectures and hyperparameters to further enhance the performance of your model. Enjoy coding!</p><h4>Follow Me</h4><ul><li>Github: <a href="https://github.com/WiwatPtk">https://github.com/WiwatPtk</a></li><li>Youtube: <a href="https://www.youtube.com/@wiwat_ai_coaching">https://www.youtube.com/@wiwat_ai_coaching</a></li><li>Linkedin: <a href="https://www.linkedin.com/in/wiwat-pitakworarat/">https://www.linkedin.com/in/wiwat-pitakworarat/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f03ed98e18ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>