<?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 NandaKishore Joshi on Medium]]></title>
        <description><![CDATA[Stories by NandaKishore Joshi on Medium]]></description>
        <link>https://medium.com/@nandakishorej8?source=rss-5738ab6748ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LibDkSq6meX6fm-dLmhPNA.jpeg</url>
            <title>Stories by NandaKishore Joshi on Medium</title>
            <link>https://medium.com/@nandakishorej8?source=rss-5738ab6748ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:59:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nandakishorej8/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[Revenue Forecast With Prophet — With Seasonality, External Regressor and Optuna]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nandakishorej8.medium.com/revenue-forecast-with-prophet-with-seasonality-external-regressor-and-optuna-92a3aeb3a9e5?source=rss-5738ab6748ef------2"><img src="https://cdn-images-1.medium.com/max/607/1*-NxJ0mO-lwpIOaAh-xr2SQ.png" width="607"></a></p><p class="medium-feed-snippet">Use multiple business regressors along with seasonality&apos;s to improve Revenue forecast using FB Prophet. Learn to use Optuna to tune models</p><p class="medium-feed-link"><a href="https://nandakishorej8.medium.com/revenue-forecast-with-prophet-with-seasonality-external-regressor-and-optuna-92a3aeb3a9e5?source=rss-5738ab6748ef------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nandakishorej8.medium.com/revenue-forecast-with-prophet-with-seasonality-external-regressor-and-optuna-92a3aeb3a9e5?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a3aeb3a9e5</guid>
            <category><![CDATA[seasonality]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[timeseries-forecasting]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 07:58:15 GMT</pubDate>
            <atom:updated>2025-01-14T07:58:15.725Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[LLM Finetuning — An inside story (part 2)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nandakishorej8.medium.com/llm-finetuning-an-inside-story-part-2-7decde42df5b?source=rss-5738ab6748ef------2"><img src="https://cdn-images-1.medium.com/max/1024/1*iQeXGRfrD8Bgm11eHd8TLA.jpeg" width="1024"></a></p><p class="medium-feed-snippet">This series of articles is aimed at bringing out the practical aspects of successfully fine tuning a LLM on a real world use case at an&#x2026;</p><p class="medium-feed-link"><a href="https://nandakishorej8.medium.com/llm-finetuning-an-inside-story-part-2-7decde42df5b?source=rss-5738ab6748ef------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nandakishorej8.medium.com/llm-finetuning-an-inside-story-part-2-7decde42df5b?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/7decde42df5b</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 17:45:32 GMT</pubDate>
            <atom:updated>2024-08-12T17:45:32.073Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[LLM Finetuning — An Inside Story (Part 1)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nandakishorej8.medium.com/llm-finetuning-an-inside-story-part-1-ddb8cc605f4b?source=rss-5738ab6748ef------2"><img src="https://cdn-images-1.medium.com/max/1024/1*iQeXGRfrD8Bgm11eHd8TLA.jpeg" width="1024"></a></p><p class="medium-feed-snippet">This series of articles is aimed at bringing out the practical aspects of successfully fine tuning a LLM on a real world use case at an&#x2026;</p><p class="medium-feed-link"><a href="https://nandakishorej8.medium.com/llm-finetuning-an-inside-story-part-1-ddb8cc605f4b?source=rss-5738ab6748ef------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nandakishorej8.medium.com/llm-finetuning-an-inside-story-part-1-ddb8cc605f4b?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddb8cc605f4b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm-finetuning]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 17:43:16 GMT</pubDate>
            <atom:updated>2024-08-12T17:46:04.236Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[When Retrieval Augmented Generation (RAG) Fails — Techniques to overcome limitations of RAG]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nandakishorej8.medium.com/when-retrieval-augmented-generation-rag-fails-techniques-to-overcome-limitations-of-rag-5634572ac499?source=rss-5738ab6748ef------2"><img src="https://cdn-images-1.medium.com/max/1043/1*IAfe1Me-PiBkMXI4fYICug.png" width="1043"></a></p><p class="medium-feed-snippet">In this article we try to explain the intricacies of RAG as a technique and there by understanding its limitations on enterprise use cases</p><p class="medium-feed-link"><a href="https://nandakishorej8.medium.com/when-retrieval-augmented-generation-rag-fails-techniques-to-overcome-limitations-of-rag-5634572ac499?source=rss-5738ab6748ef------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nandakishorej8.medium.com/when-retrieval-augmented-generation-rag-fails-techniques-to-overcome-limitations-of-rag-5634572ac499?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/5634572ac499</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 13:39:21 GMT</pubDate>
            <atom:updated>2023-10-23T13:39:21.003Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Emerging Architecture for Generative AI on Textual Data]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nandakishorej8.medium.com/emerging-architecture-for-generative-ai-on-textual-data-a71aaea0087f?source=rss-5738ab6748ef------2"><img src="https://cdn-images-1.medium.com/max/1760/1*JqBjHOXIVbujSPMMbhIm9w.png" width="1760"></a></p><p class="medium-feed-snippet">Applications of Generative AI are at the forefront post the LLM boom. This article helps you to use a LLM on custom document</p><p class="medium-feed-link"><a href="https://nandakishorej8.medium.com/emerging-architecture-for-generative-ai-on-textual-data-a71aaea0087f?source=rss-5738ab6748ef------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nandakishorej8.medium.com/emerging-architecture-for-generative-ai-on-textual-data-a71aaea0087f?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/a71aaea0087f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 14:57:15 GMT</pubDate>
            <atom:updated>2023-08-21T14:57:15.030Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[What is TensorFlow Extended (TFX)?]]></title>
            <link>https://nandakishorej8.medium.com/what-is-tensorflow-extended-tfx-e5a07b209f0a?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5a07b209f0a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-pipeline]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Fri, 29 Jul 2022 10:44:30 GMT</pubDate>
            <atom:updated>2022-07-29T12:58:25.053Z</atom:updated>
            <content:encoded><![CDATA[<h4>Google’s open source ML pipeline framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7ZtHRusUT81lTLcb.png" /><figcaption>Image by tensorflow.org</figcaption></figure><p>Unlike traditional software engineering, deploying production ready ML pipelines is not a very sort out task. Machine learning pipeline can include a variety of tasks like data ingestion, validation, pre-processing, model training and post-training tasks. In most cases Data scientists or ML engineers end up writing lots of boilerplate codes to perform these tasks and glue codes to pipe them together. These glue codes are often brittle and leads to pipeline failures.</p><p>Over the time machine learning pipelines can become very complicated and consume lot of overhead to manage task dependencies. Writing ones own boiler and glue codes has its disadvantages . Frequent manual interventions are needed to accommodate any changes in the input data format. Glue codes are platform dependent and change in platform may need complete refactoring. While working on large datasets for computer vision or NLP projects, custom glue codes may not utilize the power of distributed systems.</p><p>TFX is the Google’s open source ML pipeline frame work . TFX helps to simplify pipeline definitions and to minimize the boilerplate codes to write for every tasks. TFX has libraries to perform various pipeline tasks and glue code to tie the components together and automatically create pipeline definition for orchestration tools like Apache Airflow, Apache Beam, and Kubeflow Pipelines. <em>Refer figure 1 below</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*yf3WKMUN3Cb3KucPbgt4FA.png" /><figcaption>Figure 1 : ML pipeline architecture</figcaption></figure><p>TFX library provides components to perform machine learning pipeline tasks. These tasks can then be executed with a pipeline orchestrator such as Apache Airflow or Kubeflow . A data store is used to keep track of the intermediate pipeline results. Individual components interact with this data store to receive their inputs and also return the results. In a nutshell, TFX provides the layer that combines all of these tools, and it provides the individual components for the major pipeline tasks.</p><p>TFX provides various components to perform majority of data pipeline tasks. Some of them are mentioned below.</p><ul><li>Data ingestion with <em>ExampleGen</em></li><li>Data validation with <em>StatisticsGen</em>, <em>SchemaGen</em>, and the <em>ExampleValidator</em></li><li>Data preprocessing with <em>Transform</em></li><li>Model training with <em>Trainer</em></li><li>Checking for previously trained models with <em>ResolverNode</em></li><li>Model analysis and validation with <em>Evaluator</em></li><li>Model deployments with <em>Pusher</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Hn9a_CnBqVScPRXkSjxEQA.png" /><figcaption>Figure 2 : TFX components and libraries</figcaption></figure><p>From the above figure we can see that the TFX has components and libraries to do almost all the data pipeline tasks. We will discuss these components and libraries in great detail in future posts.</p><h4>Installation and Usage of TFX</h4><p>TFX comes as a python package. This can be installed as any other python package to use inbuilt pipeline component .</p><pre>$ pip install tfx</pre><p>Once TFX is installed, we can import the corresponding TFX components for building pipeline as shown below</p><pre>from tfx.components import ExampleValidator<br>from tfx.components import Evaluator<br>from tfx.components import Transform<br>...</pre><h4>Limitations of TFX</h4><p>As TFX is built by Google, TFX architecture and data structures expect you to use TensorFlow (Keras) as Machine learning framework. Some TFX components can be used with other ML frameworks. For example, data can be validated using TFX Data Validation component and then can be used to build a model using scikit-learn. TFX framework is closely associated with Tensorflow as of now.</p><h4>Alternatives to TFX</h4><p>Below table shows the alternate data pipeline frameworks developed by other organizations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*f84JekCOfjJisNdCG9z0mg.png" /><figcaption>Figure 3 : Alternatives to TFX</figcaption></figure><p>In the next article we will see how TFX work internally. This will include looking into various components of TFX and data storage methods.</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5a07b209f0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiclass Classification with Auto-Tuning CatBoost]]></title>
            <link>https://nandakishorej8.medium.com/multiclass-classification-with-auto-tuning-catboost-5d352e30778d?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d352e30778d</guid>
            <category><![CDATA[catboost]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[multiclass-classification]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Thu, 26 May 2022 12:34:06 GMT</pubDate>
            <atom:updated>2022-06-13T06:37:39.593Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>CatBoost with HyperOpt becomes a perfect tool for multiclass classification…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oHsSUJm1lw3fzt00" /><figcaption>Image from <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Flightfieldstudios.net%2Fstock-photos%2Fdates-fruit.html&amp;psig=AOvVaw0wuEZzZoABqoXX0LIblb9r&amp;ust=1653654249772000&amp;source=images&amp;cd=vfe&amp;ved=0CAwQjRxqFwoTCOiQvKyU_fcCFQAAAAAdAAAAABAP">Kaggle</a></figcaption></figure><p>In this article we will work on a Kaggle dataset of Date-fruits. The dataset consists of Date fruit of 7 types with 34 related features. Our task is to classify Date Fruits into 7 classes . You can read more on the dataset in the below link</p><p><a href="https://www.kaggle.com/datasets/muratkokludataset/date-fruit-datasets">Date Fruit Datasets</a></p><p>After going through the above link, we understand that external appearance of a Date fruit greatly impacts its type. The 34 features including morphological features, shape and color extracted are from the 898 images of the fruit.</p><p>Different techniques from Logistic Regression to ANN have been used previously on this dataset . Performance results achieved with these methods are 91.0% and 92.2%, respectively. Stacking the models resulted in max performance of 92.8%.</p><p>We will use CatBoost and tune the hyperparameters with HyperOpt and check if we can do better or match the previous results.</p><p>Let us now import the dataset and do some analysis.</p><pre>import numpy as np <br>import pandas as pd<br>import os<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score, f1_score, recall_score, confusion_matrix,precision_score<br><br>import catboost as ctb</pre><pre>from hyperopt import hp<br>from hyperopt import fmin, tpe, STATUS_OK, STATUS_FAIL, Trials</pre><pre>!pip install openpyxl # to read excel file</pre><pre>#reading the Kaggle dataset</pre><pre>data_path = &quot;../input/date-fruit-datasets/Date_Fruit_Datasets/Date_Fruit_Datasets.xlsx&quot;<br>data=pd.read_excel(data_path)<br></pre><pre>df = data.copy()</pre><pre>#To understand the data distribution<br>df.describe()</pre><pre>#To understand the data types<br>df.dtypes</pre><pre>#To check for nulls in data<br>df.isnull().sum()</pre><pre><em>#checking class distribution</em><br>df[&#39;Class&#39;].value_counts()*100/df.shape[0]</pre><p>By running the above code on the <a href="https://www.kaggle.com/code/nandakishorejoshi/datefruit-catboost-with-hyperopt">Kaggle Notebook</a>, we will be able to import Date_Fruit data into a pandas Data Frame (df). Post this we run few commands to analyze the data ,observations are</p><ol><li>After describing the data we see that the mean and median (50th Percentile) points for most features are very close. This means that the data is normally distributed.</li><li>Up on checking the datatypes, we see that except the target variable (Class), all other variables are of numeric type</li><li>There are no missing values in the dataset</li><li>All the seven classes of date fruits are not uniformly distributed. The distribution percentage of each class is shown in below image.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*2phlwW66uPn-wC8r_Y882g.png" /><figcaption>Figure 1 : Class distribution (in %)</figcaption></figure><p>With the above analysis and knowing that Logistic regression and ANN were previously used on this dataset (as mentioned in <a href="https://www.kaggle.com/datasets/muratkokludataset/date-fruit-datasets">dataset description</a> on Kaggle), we are left with using another powerful set of models.</p><blockquote><strong>The Boosting ones</strong></blockquote><p>Some of the common boosting algorithms that can be used here are XGBoost, LightGBM and CatBoost. Comparison of these algorithms are explained in the below article</p><p><a href="https://towardsdatascience.com/performance-comparison-catboost-vs-xgboost-and-catboost-vs-lightgbm-886c1c96db64">Performance Comparison: CatBoost vs XGBoost and CatBoost vs LightGBM</a></p><p>From the above article we can conclude that LightGBM over powers Catboost and XGBoost in both performance and execution speed. The next one with respect to speed is Catboost and then followed by XGBoost. We can also see that the performance of these three algorithms are almost same.</p><p>For this time we will choose Catboost (the newest and less explored in the lot) and try to set the new benchmark.</p><p>Now, let us label encode the classes and create test and train data sets</p><pre>#label encodeing the Class feature<br>le = LabelEncoder()<br>df[&#39;label&#39;] = le.fit_transform(df.Class.values)</pre><pre>#Creating train and test datasets by defining dependent and independent features</pre><pre>X,Y=df.drop([&#39;Class&#39;,&#39;label&#39;],axis=1),df[&#39;label&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, Y,<br>                                                    test_size=0.2,<br>                                                    random_state=42,<br>                                                    shuffle=True)</pre><p>As we are using Catboost, lets explore the set of hyperparameters which can be tuned in the below link</p><p><a href="https://catboost.ai/en/docs/concepts/parameter-tuning">Parameter tuning</a></p><p>From the above link we can see that there are quite a lot of hyperparameters with wide range of values. Some of the hyperparameters and its range of values are defined in the below code</p><pre><em>#define parameter range</em><br>learning_rate=np.linspace(0.01,0.1,10)<br>max_depth=np.arange(2, 18, 2)<br>colsample_bylevel=np.arange(0.3, 0.8, 0.1)<br>iterations=np.arange(50, 1000, 50)<br>l2_leaf_reg=np.arange(0,10)<br>bagging_temperature=np.arange(0,100,10)</pre><pre>#define the categorical features if any in the dataset for catboost to handle<br>categorical_features_indices = np.where(X_train.dtypes == np.object)[0]</pre><p>Manually tuning all the hyperparameters and finding the right values to build the best model is very difficult. For this reason we use an automatic hyperparameter tuning package called Hyperopt. Hyperopt is a Distributed Asynchronous Hyperparameters Optimization package written in Python. Details of the Hyperopt is mentioned in the below link.</p><p><a href="http://hyperopt.github.io/hyperopt/">Hyperopt Documentation</a></p><p>Hyperopt has mainly three components</p><ol><li>Objective function :</li></ol><p>Objective function is the task at hand. It might be solving a simple linear algebra equation or just a simple if statement resulting in a action or training a machine learning model to find the best hyperparameters.</p><p>2. Search space :</p><p>This is the space of values which objective function can use. In our case we call it as parameter space. Here we define value range each hyperparameter can take. The one defined in the above code piece</p><p>3. Minimization function :</p><p>This is the function which minimizes the loss generated by the objective function over the parameter space or search space.</p><p>Defining the right loss function for each objective is key to get the best combinations of hyperparameters. Code for all the above steps to tune hyperparameters for Catboost is shown below</p><pre><em>#Define parameter space, fit conditions</em><br>ctb_clf_params = {<br>    &#39;learning_rate&#39;:     hp.choice(&#39;learning_rate&#39;,    learning_rate),<br>    &#39;max_depth&#39;:         hp.choice(&#39;max_depth&#39;,         max_depth),<br>    <em>#&#39;colsample_bylevel&#39;: hp.choice(&#39;colsample_bylevel&#39;, colsample_bylevel),</em><br>    &#39;iterations&#39;:       hp.choice(&#39;iterations&#39;,            iterations),<br>    <em>#&#39;l2_leaf_reg&#39;:       hp.choice(&#39;l2_leaf_reg&#39;,            l2_leaf_reg),</em><br>    <em>#&#39;bagging_temperature&#39;:       hp.choice(&#39;bagging_temperature&#39;,            bagging_temperature),</em><br>    &#39;loss_function&#39;:       &#39;MultiClass&#39;,<br>    <br>}<br>ctb_fit_params = {<br>    &#39;early_stopping_rounds&#39;: 5,<br>    &#39;verbose&#39;: False,<br>    &#39;cat_features&#39;: categorical_features_indices<br>}<br>ctb_para = dict()<br>ctb_para[&#39;clf_params&#39;] = ctb_clf_params<br>ctb_para[&#39;fit_params&#39;] = ctb_fit_params</pre><p>In the above code we are defining the parameter space, with fit condition. (Some of the parameter spaces are commented as tuning on these parameters decreased the performance. Hence, default values are used. Representation is just to give an idea in case of an implementation). Fit conditions define the model fitting conditions.</p><pre><em>#define Hyperopt class</em><br>class <strong>HYPOpt</strong>(object):<br><br>    def __init__(self, x_train, x_test, y_train, y_test):<br>        self.x_train = x_train<br>        self.x_test  = x_test<br>        self.y_train = y_train<br>        self.y_test  = y_test<br><br>    def process(self, fn_name, space, trials, algo, max_evals):<br>        fn = getattr(self, fn_name)<br>        try:<br>            print(&#39;entering fmin&#39;)<br>            result = fmin(fn=fn, space=space, algo=algo, max_evals=max_evals, trials=trials)  <strong>#----1</strong><br>        except <strong>Exception</strong> as e:<br>            return {&#39;status&#39;: STATUS_FAIL,<br>                    &#39;exception&#39;: str(e)}<br>        return result<br><br>    def ctb_clf(self, para):     <strong>#---- 2</strong><br>        clf= ctb.CatBoostClassifier(**para[&#39;reg_params&#39;])<br>        print(&#39;ctb initialized&#39;)<br>        return self.train_clf(reg, para)<br><br>    def train_clf(self, clf, para):    <strong>#----- 3</strong><br>        print(&#39;fitting model&#39;)<br>        clf.fit(self.x_train, self.y_train,<br>                eval_set=[(self.x_train, self.y_train), (self.x_test, self.y_test)],<br>                **para[&#39;fit_params&#39;])<br>        print(&#39;model fitted&#39;)<br>        pred = clf.predict(self.x_test)<br>       f1=sklearn.metrics.f1_score(self.y_test,pred,average=&#39;micro&#39;)<br>        f1=f1*(-1)                     <strong>#---- 4</strong><br>        print(f1)<br>        return {&#39;loss&#39;: f1, &#39;status&#39;: STATUS_OK}</pre><p>#1- Defining inbuilt Hyperopt minimization function</p><p>#2- Objective fine</p><p>#3- Function to fit the model</p><p>#4- Loss function (negative F1 used as loss)</p><p>In the above code, we create a Hyperopt class and define an objective function. Here the objective is to build a Catboost model. We use function <em>ctb_clf</em> to define the model and <em>train_clf</em> to train the model.</p><p>We also define a loss function. Here we use F1 as metrics. Hyperopt always tries to minimize the loss with its inbuild <em>fmin</em> method. Hence we pass negative F1 into <em>fmin</em> to in turn maximize the F1 score.</p><pre><em>#define objective and find the best hyperparameters</em><br><br>obj = HYPOpt(X_train, X_test, y_train, y_test)<br>ctb_opt = obj.process(fn_name=&#39;ctb_clf&#39;, space=ctb_para, trials=Trials(), algo=tpe.suggest, max_evals=5)</pre><p>In the above code, we instantiate the class and call the <em>process</em> function to start the Hyperparameter optimization . Five iterations (max_evals =5) of catboost are created with different combinations of parameters from parameter space <em>ctb_para. </em>The parameters producing the minimum loss is stored as the output of <em>process</em> function into <em>ctb_opt </em>as shown in figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*iX4jSOihnYy4TtHEoWOdvA.png" /><figcaption>Figure 2 : Indexes of Optimal parameters</figcaption></figure><p>The above output is the index of the values of the hyperparameter space. We need to store the actual values. A dictionary is used to store the actual values as shown in below code</p><pre><em>#Save best parametrs in a dictionary</em><br>best_param={}<br>best_param[&#39;learning_rate&#39;]=learning_rate[ctb_opt[&#39;learning_rate&#39;]]<br>best_param[&#39;iterations&#39;]=iterations[ctb_opt[&#39;iterations&#39;]]<br>best_param[&#39;max_depth&#39;]=max_depth[ctb_opt[&#39;max_depth&#39;]]</pre><p>The optimal parameters chosen by Hyperopt looks something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*cI7JyxkWFbbRQ-_AmCEMMQ.png" /><figcaption>Figure 3 : Actual value of Optimal parameters</figcaption></figure><p>With best parameters from Hyperopt, we use these to build our final Catboost model and test it on test-data.</p><pre><em>#build model with the best hyperparameters</em><br>model=ctb.CatBoostClassifier(iterations=best_param[&#39;iterations&#39;], <br>                             depth=best_param[&#39;max_depth&#39;],<br>                             learning_rate=best_param[&#39;learning_rate&#39;],<br>                            loss_function=&#39;MultiClass&#39;,<br>                            random_seed=42<br>                            )</pre><pre>model.fit(X_train,y_train,cat_features=categorical_features_indices, eval_set=None, plot=True)</pre><p>With the best model built, we need to verify the results on test data. We will check various metrics from confusion matrix to accuracy of train and test data to check for overfitting. We will also see micro , macro and weighted precision , recall and F1- Score to understand the model performance on each class.</p><p>Below code helps us to check the accuracy on test and train and get confusion matrix</p><pre>train_pred = model.predict(X_train)<br>train_acc = accuracy_score(y_train,train_pred)<br>print(&#39;Train Accuracy: &#39;, train_acc)<br> <br>test_pred = model.predict(X_test)<br>test_acc = accuracy_score(y_test,test_pred)<br>print(&#39;Test Accuracy:&#39;, test_acc)<br>y_pred=test_pred</pre><pre>confusion = confusion_matrix(y_test, test_pred)<br>print(&#39;Confusion Matrix<strong>\n</strong>&#39;)<br>print(confusion)</pre><p>We can check micro, macro and weighted precision, recall and F1 score with the help of below code</p><pre>print(&#39;Micro Precision: <strong>{:.2f}</strong>&#39;.format(precision_score(y_test, y_pred, average=&#39;micro&#39;)))<br>print(&#39;Micro Recall: <strong>{:.2f}</strong>&#39;.format(recall_score(y_test, y_pred, average=&#39;micro&#39;)))<br>print(&#39;Micro F1-score: <strong>{:.2f}\n</strong>&#39;.format(f1_score(y_test, y_pred, average=&#39;micro&#39;)))<br><br>print(&#39;Macro Precision: <strong>{:.2f}</strong>&#39;.format(precision_score(y_test, y_pred, average=&#39;macro&#39;)))<br>print(&#39;Macro Recall: <strong>{:.2f}</strong>&#39;.format(recall_score(y_test, y_pred, average=&#39;macro&#39;)))<br>print(&#39;Macro F1-score: <strong>{:.2f}\n</strong>&#39;.format(f1_score(y_test, y_pred, average=&#39;macro&#39;)))<br><br>print(&#39;Weighted Precision: <strong>{:.2f}</strong>&#39;.format(precision_score(y_test, y_pred, average=&#39;weighted&#39;)))<br>print(&#39;Weighted Recall: <strong>{:.2f}</strong>&#39;.format(recall_score(y_test, y_pred, average=&#39;weighted&#39;)))<br>print(&#39;Weighted F1-score: <strong>{:.2f}</strong>&#39;.format(f1_score(y_test, y_pred, average=&#39;weighted&#39;)))</pre><p>Output of all the codes are shown in following figures</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*xQDZWaJYIPRCr7DmiYlbSg.png" /><figcaption>Figure 4 : Train and Test Accuracy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*J4VXssrXPJuNLwFFgwuMoQ.png" /><figcaption>Figure 5 : Confusion matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*2vNTQwRLltwknUU1ojXhqA.png" /><figcaption>Figure 6 : Micro, Macro, Weighted metrices</figcaption></figure><p>From the above figures we are able to see that the test accuracy is equal to the best results obtained by the Kaggle competition. The micro and weighted metrics exceed the best results.</p><p><strong>Summary</strong></p><p>In this article we tried to implement Catboost to solve a Kaggle dataset. Some of the key points we learnt are:</p><ol><li>Catboost is a very powerful model. It is mainly used when independent features contain categorical variables.</li><li>Catboost has large number of parameters to tune.</li><li>HyperOpt is an efficient and effective way to find the best hyperparameters for all most all ML models.</li></ol><p>Link to the Kaggle notebook with full code is below :</p><ul><li><a href="https://www.kaggle.com/code/nandakishorejoshi/datefruit-catboost-with-hyperopt">DateFruit_Catboost_With_Hyperopt</a></li><li><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d352e30778d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2 : Evolutionary Algorithms for Reinforcement Learning — Solving OpenAI’s Cartpole]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nandakishorej8.medium.com/part-2-evolutionary-algorithms-for-reinforcement-learning-solving-openais-cartpole-318aaef8a6eb?source=rss-5738ab6748ef------2"><img src="https://cdn-images-1.medium.com/max/964/0*lphkolHFbY_4NEOp.png" width="964"></a></p><p class="medium-feed-snippet">Solving the Cartpole problem with a genetic algorithm</p><p class="medium-feed-link"><a href="https://nandakishorej8.medium.com/part-2-evolutionary-algorithms-for-reinforcement-learning-solving-openais-cartpole-318aaef8a6eb?source=rss-5738ab6748ef------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nandakishorej8.medium.com/part-2-evolutionary-algorithms-for-reinforcement-learning-solving-openais-cartpole-318aaef8a6eb?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/318aaef8a6eb</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 15:02:59 GMT</pubDate>
            <atom:updated>2022-04-29T15:02:59.357Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Part 1 : Evolutionary Algorithms for Reinforcement Learning — An Introduction]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nandakishorej8.medium.com/part-1-evolutionary-algorithms-for-reinforcement-learning-an-introduction-e434d2a1d023?source=rss-5738ab6748ef------2"><img src="https://cdn-images-1.medium.com/max/1200/0*UwBzTEQayR5impvx.png" width="1200"></a></p><p class="medium-feed-snippet">In this Article we deep dive to understand the working of Evolutionary algorithms &amp; try to implement them to solve OpenAI&#x2019;s cartpole&#x2026;</p><p class="medium-feed-link"><a href="https://nandakishorej8.medium.com/part-1-evolutionary-algorithms-for-reinforcement-learning-an-introduction-e434d2a1d023?source=rss-5738ab6748ef------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nandakishorej8.medium.com/part-1-evolutionary-algorithms-for-reinforcement-learning-an-introduction-e434d2a1d023?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/e434d2a1d023</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 14:57:16 GMT</pubDate>
            <atom:updated>2025-02-12T16:52:51.422Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Part 1 : Policy Based Reinforcement Learning — A Detailed Study]]></title>
            <link>https://nandakishorej8.medium.com/part-1-policy-based-reinforcement-learning-a-detailed-study-1d4e9b8b5239?source=rss-5738ab6748ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d4e9b8b5239</guid>
            <category><![CDATA[policy-gradient]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[openai-gym]]></category>
            <dc:creator><![CDATA[NandaKishore Joshi]]></dc:creator>
            <pubDate>Sat, 26 Feb 2022 10:56:26 GMT</pubDate>
            <atom:updated>2022-02-26T10:56:26.335Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1 : Policy Based Reinforcement Learning — A Detailed Study</h3><p>In this article lets try to get a detailed understanding of what is On Policy and Off Policy Reinforcement Learning? What are the types of Policy functions? How to implement the policy function as a neural network?</p><p>A good teacher always explains the most complicated topics in a very simple and effective way. This article is inspired by the book from <a href="https://learning.oreilly.com/search/?query=author%3A%22Brandon%20Brown%22&amp;sort=relevance&amp;highlight=true">Brandon Brown</a>, <a href="https://learning.oreilly.com/search/?query=author%3A%22Alexander%20Zai%22&amp;sort=relevance&amp;highlight=true">Alexander Zai</a>.</p><p>We will start this article by comparing Off Policy and On Policy algorithms. Then we will see different types of policy functions. In the last section, we will see how we can implement the policy functions as a neural network.</p><p><strong>What are Off-Policy and On-Policy algorithms in Reinforcement learning?</strong></p><p>Well, we will answer this question with examples.</p><p>We will use deep Q-network to talk on Off-policy algorithms. If you are not familiar with deep Q-network , don’t worry we will give a basic introduction to it. If you want to enhance your learning on DQN along with implementation ,please go through <a href="https://towardsdatascience.com/part-1-building-a-deep-q-network-to-play-gridworld-deepminds-deep-q-networks-78842007c631">this</a> article.</p><p>Deep Q-network (DQN) is an off-policy algorithm that approximates the Q function with a neural network. The output of the Q-network is Q values for each action on a given state. The Q value is the expected (weighted average) of rewards at a particular state <em>S</em> taking an action <em>a</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*NuKbpNNlLbp_oltma2G60w.png" /><figcaption>Fig 1 : Illustration of a Deep Q-network</figcaption></figure><p>A Q-network takes a state and returns Q values (action values) for each action. We can use those action values to decide which actions to take. Various strategy can be employed to select the action using the predicted Q values. Epsilon-greedy approach is one famous strategy where we selected an action at random with probability ε, and with probability 1 — <em>ε</em> we selected the action associated with the highest Q value (the action the Q-network predicts is the best, given its experience so far)</p><p>What if instead of returning the Q values (action values) our neural network directly predicts the action? If we do that then our neural network is called a policy function or a policy network. Policy function accepts the state and returns the best action. More precisely, returns the probability distribution over the actions, which can be used to pick the best action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*c3AnretujbMIF31YA28SCA.png" /><figcaption>Fig 2 : On Policy Network</figcaption></figure><p>Unlike Off-Policy (DQN), in On Policy network there is no need to design an algorithm (eg: epsilon-greedy) to select the best action. Action corresponding to the highest probability can be chosen directly at each state.</p><p>Lets say the probability distribution P(A|S) is the jar filled with notes with an action written on them. In a game with four actions labelled 1–4 , choosing any action will fill the jar with respective notes. If policy network predicts label 2 can return the highest reward, the jar will be filled with lots of notes labelled 2 and few labelled 1,3,4. Now to choose the best action, all we do is close the eyes and pick a random note. We are most likely to pick note 2. But sometimes we may also pick 1,2 or 3. This will lead to exploration. Using this analogy, every time the state of the environment changes, we give the state to our policy network, and it uses that to fill the jar with a new set of labeled notes representing the actions in different proportions. Then we randomly pick from the jar.</p><p>This kind of algorithms are called as <em>Policy gradient methods. </em>There are some important differences between Policy gradients and DQN methods. One already mentioned is the method to choose the best action. DQN needs a additional algorithm to select the best action. Whereas, Policy gradients outputs the highest probability for the best action. Other important difference is that in DQN various methods like experience replay and target networks are employed to stabilize the learning process (ready more about them <a href="https://towardsdatascience.com/part-2-building-a-deep-q-network-to-play-gridworld-catastrophic-forgetting-and-experience-6b2b000910d7">here</a>). A policy network do not have these complexities.</p><p><strong>Types of Policy Gradient Algorithms</strong></p><ol><li><strong>Stochastic policy gradient</strong></li></ol><p>The policy method we described with the jar example above is the stochastic policy gradient. The output of our neural network is an action vector that represents a probability distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*c6-5tY6FJui6EHLt7iS2NQ.png" /><figcaption>Fig 3 : Stochastic policy gradient</figcaption></figure><p>A policy function accepts a state and returns a probability distribution over actions. It is stochastic because it returns a probability distribution over actions rather than returning a deterministic, single action. This means that if our agent ends up in the same state twice, it may not take the same action as we have small probabilities for other actions. This allows for exploration on new policies. In the above figure , we feed the agent with the state (1,2) and output is the vector of probabilities over four possible actions. We can see that the first action has highest probability of 0.5, followed by third and forth. But the second action is not at all prescribed.</p><p><strong>2. Deterministic Policy gradient</strong></p><p>If the environment is stationary, say state and rewards are constant then we use a deterministic strategy, we’d expect the probability distribution to eventually converge to a <em>degenerate probability distribution</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*JBA6NZ2lY30j4zJED-lWFw.png" /><figcaption>Fig 4 : Deterministic policy gradient</figcaption></figure><p>A deterministic policy function takes a state and returns a specific action to take, unlike a stochastic policy, which returns a probability distribution over actions.</p><p><em>How do policy gradient methods explore?</em></p><p>We use algorithms like epsilon-greedy etc. with DQN (off-policy) to make then explore the action space. How do we ensure that on-policy methods do sufficient exploration of action space?</p><p>For the stochastic policy gradient method, because our output is a probability distribution, there should be a small chance that we explore all spaces; only after sufficient exploration will the action distribution converge to producing the single best action, a degenerate distribution. Or if the environment itself has some randomness, the probability distribution will retain some probability mass to each action. When we initialize our model in the beginning, the probability of our agent picking each action should be approximately equal or uniform, since the model has zero information about which action is better.</p><p>Even with deterministic policy gradient we start with equal or random probability distribution. As the training progresses the agent learns the best action and outputs only the best action making probabilities of other actions zero.</p><p><strong>Implementing Policy functions with a neural networks</strong></p><p>Neural networks need objective functions that is differentiable from the network weights. Deep Q — network is trained to minimize the mean square error (MSE) between predicted Q values and the target Q values. We had a nice formula for calculating the target Q value based on the observed reward, since Q values are just averaged rewards (i.e., expectations), so this was not much different from how we would normally train a supervised deep learning algorithm.</p><p>Unlike DQN , policy network predicts actions and there is no way to come up with a target vector of actions we should have taken instead, given the rewards. All we know is whether the action led to positive or negative rewards. In fact, what the best action is secretly depends on a value function, but with a policy network we’re trying to avoid computing these action values directly.</p><p>Then how do we train and optimize our policy network?</p><p>Lets understand this with a example of Gridworld .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*YaKKc8fCzfJiqwNJ-Io-sg.png" /><figcaption>Fig 5 : GridWorld Game</figcaption></figure><p>The Gridworld game depicted in figure 5 shows the simple version of Gridworld. The agent (A) must navigate along the shortest path to the goal tile (+) and avoid falling into the pit (–). Our goal is to train a neural network to play Gridworld from scratch. The agent will have access to what the board looks like. There are four possible actions namely up, down, left and right. Based on the action taken by the agent reward will be received. Reward of -1 is awarded for each move. Any action which leads to a fall in pit or into the wall will receive a reward of -10. Positive reward of +10 is awarded for successfully reaching the goal.</p><p>Having understood the Gridworld game, let’s understand some notations with respect to policy network we are training. Our policy network is denoted <em>π</em> and is parameterized by a vector <em>θ</em>, which represents all of the parameters (weights) of the neural network. Whenever we run the policy network forward, the parameter vector <em>θ</em> is fixed; the variable is the data that gets fed into the policy network (i.e., the state). Hence, we denote the parameterized policy as <em>πsub(θ) (sub: subscript)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*Kt_kB2S4J_0Y8lewFmWLCg.png" /><figcaption>Fig 6 : Initial untrained policy network</figcaption></figure><p>Let’s say we give our initially untrained policy network <em>πθ</em> some initial game state for Gridworld, denoted <em>s</em>, and run it forward by computing <em>πθ</em>(<em>s</em>). It returns a probability distribution over the four possible actions, such as [0.25, 0.25, 0.25, 0.25]. We sample from this distribution, and since it’s a uniform distribution, we end up taking a random action. We continue to take actions by sampling from the produced action distribution until we reach the end of the episode.</p><p>An episode is a sequence of states, actions, and rewards from an initial state to the terminal state where we win or lose the game. We denote this episode as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*M57a9S7Q5Clp2FdQjxRczQ.png" /><figcaption>Fig 7 : Episode representation</figcaption></figure><p>Lets say that at the third step we reach our goal and end the episode with reward of +10. Then out episode can be represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*GX9lBgRiIWcxvRBvUv1Tiw.png" /><figcaption>Fig 8 : Sample episode</figcaption></figure><p>Form figure 8 we can see that we took action 3 , 1 and 3 at state S0,S1 and S2 respectively. Our episode ended at S2 with a reward of +10. As we know that action 3 has given us a good reward we want to reinforce it and make a smooth updates to our gradients to encourage the network to assign more probability to these winning actions in the future.</p><p>A naïve approach would be to update the probability density of action 3 (element 4) in the probability distribution to 1 [0,0,0,1]. This is what we do in a supervised classification model. But in RL we want the update to be smooth and have a small chance to explore better actions. We want something as shown in below image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*6YSfQsxp-8DLCb58eCPvcA.png" /><figcaption>Fig 9 : Reinforcing the action</figcaption></figure><p>The reward signal is used to reinforce the action that was taken, that is, it increases the probability of that action given the state if the reward is positive, or it decreases the probability if the reward is negative. Notice that we only received information about action 3 (element 4), but since the probabilities must sum to 1, we have to lower the probabilities of the other actions.</p><p>In order to reinforce action 3, we want to modify our policy network parameters <em>θ</em> such that we increase <em>πs</em>(<em>a</em>3|<em>θ</em>). Our objective function merely needs to maximize <em>πs</em>(<em>a</em>3|<em>θ</em>) where <em>a</em>3 is action 3 in our example. Before training, <em>πs</em>(<em>a</em>3|<em>θ</em>) = 0.25, but we want to modify <em>θ</em> such that <em>πs</em>(<em>a</em>3|<em>θ</em>) &gt; 0.25. Because all of our probabilities must sum to 1, maximizing <em>πs</em>(<em>a</em>3|<em>θ</em>) will minimize the other action probabilities. Since deep learning optimizers are good in minimizing the objective function we can concentrate on minimizing other probabilities and hence increasing the probabilities of the desired action. We want to minimize 1 — <em>πs</em>(<em>a</em>|<em>θ</em>). This loss function approaches 0 as <em>πs</em>(<em>a</em>|<em>θ</em>) nears 1, so we are encouraging the gradients to maximize <em>πs</em>(<em>a</em>|<em>θ</em>) for the action we took.</p><p>Let’s make this formula more mathematically stable. As probabilities are between 0 to 1 sometimes these values can become extremely tiny and may not help optimizers. So we can use log to over come this problem. So our objective would be to minimize the function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*P8q59nwWOp6yr5vvIY0T1Q.png" /><figcaption>Fig 10 : Log objective function</figcaption></figure><p>Now we know our objective function. But should we assign equal weightage to all the actions in the episode? In a game like Gridworld the last action plays a very important role. In episodic games usually the first action is suboptimal . The action importance increases as the time step increases. Keeping this in mind our final Objective function can be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*fmwp8tJY8QgP8lOU8tjd7Q.png" /><figcaption>Fig 11 : Final objective function</figcaption></figure><p>γ<em>t</em> is the discount factor, and the subscript <em>t</em> tells us its value will depend on the time step <em>t</em>, since we want to discount more distant actions more than more recent ones. The parameter <em>Gt</em> is called the <em>total return</em>, or <em>future return</em>, at time step <em>t</em>. It is the return we expect to collect from time step <em>t</em> until the end of the episode, and it can be approximated by adding the rewards from some state in the episode until the end of the episode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*c3VzaqcgDsCoPOgUWzcQEw.png" /><figcaption>Fig 12 : Total return</figcaption></figure><p>With this objective in place, the sequence of discounted reward from start to terminal state of a winning Gridworld game can be [0.970, 0.980, 0.99, 1.0]. The last action is given more prominence over initial once.</p><p>A string diagram explaining the entire training process of a policy network is given below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*443Ikr8pXH7_YKyqGWl5zw.png" /><figcaption>Fig 12 : Training process</figcaption></figure><p>The policy network is a neural network parameterized by θ (the weights) that accepts a 64-dimensional vector for an input state. It produces a discrete 4-dimensional probability distribution over the actions. The sample action box samples an action from the distribution and produces an integer as the action, which is given to the environment (to produce a new state and reward) and to the loss function so we can reinforce that action. The reward signal is also fed into the loss function, which we attempt to minimize with respect to the policy network parameters.</p><p>Until now we have learnt</p><ol><li>Difference between Off-policy and On-policy algorithms</li><li>Types of policy functions</li><li>Implementation of policy function using neural network</li></ol><p>In the next part of this article we will implement a Policy based reinforcement learning algorithm called REINFORCE to solve OpenAI’s Cartpole problem.</p><p>Check out the part 2 of this article here:</p><p><a href="https://nandakishorej8.medium.com/part-2-policy-based-reinforcement-learning-openais-cartpole-with-reinforce-algorithm-18de8cb5efa4">https://nandakishorej8.medium.com/part-2-policy-based-reinforcement-learning-openais-cartpole-with-reinforce-algorithm-18de8cb5efa4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d4e9b8b5239" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>