<?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 Artem Arutyunov on Medium]]></title>
        <description><![CDATA[Stories by Artem Arutyunov on Medium]]></description>
        <link>https://medium.com/@artem.a.arutyunov?source=rss-8d26b20a79d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oeersLcTBv1PWfQEU6gNsQ.jpeg</url>
            <title>Stories by Artem Arutyunov on Medium</title>
            <link>https://medium.com/@artem.a.arutyunov?source=rss-8d26b20a79d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:13:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@artem.a.arutyunov/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[PyTorch for Everyone: Everything I know and More.]]></title>
            <link>https://medium.com/the-power-of-ai/pytorch-for-everyone-everything-i-know-and-more-f7bb3be386b9?source=rss-8d26b20a79d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7bb3be386b9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[course]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Artem Arutyunov]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 15:14:02 GMT</pubDate>
            <atom:updated>2023-08-17T15:14:02.813Z</atom:updated>
            <content:encoded><![CDATA[<p>The story begins on one of those May days when the wind is still cold, but the sun shines promisingly, hinting at the forthcoming summer. Me and my colleague Joseph were taking a walk through one of many elaborate gardens of our office. Being less cautious than Joseph, I found myself frequently struck by low-hanging tree branches. Meanwhile, Joseph was struck by amazing ideas and challenges that he discussed with me. One of those challenges was rather interesting: How could we teach someone <strong>all the PyTorch fundamentals, starting from tensors and extending to convolutional neural networks, in less than 24 hours</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nh3UtE_0ckDwOpt2PHdX5Q.png" /></figure><p>Developed by Meta AI (basically Facebook), <strong>PyTorch </strong>provides a high-level interface for building and training deep learning models. It has emerged as one of the most popular frameworks for deep learning, renowned for its flexibility and ease of use. Researchers and developers use it to build and train complex neural networks with remarkable efficiency.</p><blockquote>Even <strong>ChatGPT</strong> is built on top of <strong>PyTorch.</strong></blockquote><p>It allows you to express your ideas in code fluidly, enabling rapid experimentation and prototyping.</p><p>The goal was set, the execution was almost flawless and now I present to you the product of our work, blood and tears: <strong><em>PyTorch Learning Path</em></strong></p><p>You can find the whole learning path here:</p><p><a href="https://cognitiveclass.ai/learn/learn-ai-hands-on-pytorch">Learn AI Hands-On - PyTorch</a></p><p>This <strong>Learning Path </strong>consists of 5 courses and 2 guided projects. It is a summary of everything I know and a small fraction of what Joseph knows about PyTorch and ML in general. Each course is important and valuable, and combined together they shouldn’t take more than 24 hours to pass. Through a series of lectures and hands-on exercises, you will gain a deep understanding of PyTorch and develop practical skills to apply your knowledge to real-life problems. It not only covers the basics of PyTorch for machine learning but also provides explanations on how to build deep learning models using PyTorch. Additionally, it delves into the theoretical fundamentals of machine learning, such as back-propagation and cost functions.</p><p>Let’s delve into the details:</p><h4>1: PyTorch Tensor, Dataset and Data Augmentation</h4><p>Data preparation plays a crucial role in effectively solving machine learning problems. PyTorch, a powerful deep learning framework, offers a plethora of tools to make data loading easy. The PyTorch Tensor, Dataset, and Data Augmentation Fundamentals course will give a solid understanding of the basics and core principles of PyTorch, specifically focusing on tensor manipulation, dataset management, and data augmentation techniques.</p><p>This course is free and published, you can access it by clicking here:</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+AI0111EN+v1">PyTorch: Tensor, Dataset and Data Augmentation</a></p><h4><strong>2: Linear Regression with PyTorch</strong></h4><p>This course is designed to provide you with a comprehensive understanding of linear regression modeling using the PyTorch framework. Equipped with these skills, you will be prepared to tackle real-world regression problems and utilize PyTorch effectively for predictive analysis tasks. It focuses specifically on the implementation and practical application of linear regression algorithms for predictive analysis.</p><p>This course is free and published, you can access it by clicking here:</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+AI0116EN+v1">Linear Regression with PyTorch</a></p><h4><strong>3: Classification with PyTorch</strong></h4><p>Designed for students and enthusiasts, this course equips you with the knowledge and practical skills to build powerful and accurate classification models using PyTorch. It offers a hands-on learning experience, allowing you to apply your knowledge through coding exercises and lessons so by the end of the course, you will possess the skills to build, train, and evaluate classification models using PyTorch.</p><p>This course is free and published, you can access it by clicking here:</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+AI0112EN+v1">Classification with PyTorch</a></p><h4>4: Build a Neural Network with PyTorch</h4><p>In this course, you will be focusing on how PyTorch creates and optimizes Neural Network models. We will quickly iterate through different aspects of PyTorch Neural Networks, giving you strong foundations and all the prerequisites you need to build deep learning models. Designed for students and professionals interested in machine learning and deep learning, this course offers a comprehensive understanding of the theory and practical applications of building and deploying neural networks.</p><p>This course is published, and you can access it by clicking here:</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+AI0114EN+v1">Build a Neural Network with PyTorch</a></p><h4>5: Convolutional Neural Networks with PyTorch</h4><p>In this course you will gain practical skills to tackle real-world image analysis and computer vision challenges using PyTorch. Uncover the power of Convolutional Neural Networks (CNNs) and explore the fundamentals of convolution, max pooling, and convolutional networks. Learn to train your models with GPUs and leverage pre-trained networks for transfer learning.</p><p>This course is published, and you can access it by clicking here:</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+AI0113EN+v1">Convolutional Neural Networks with PyTorch</a></p><p>All you need to start learning is some basic understanding of Python for programming and school level math for theory behind ML concepts.</p><p>Note that since it’s a Learning Path, It follows a sequential structure, requiring completion or a solid understanding of the concepts covered in the previous courses before progressing to the next. For instance, to begin the “Classification with PyTorch” course, the prerequisites include:</p><ol><li>Completion of PyTorch: Tensor, Dataset and Data Augmentation course</li><li>Completion of Linear Regression with PyTorch course</li></ol><p>or</p><p>Good understanding of PyTorch Tensors, DataSets and Linear Regression</p><p>We have made those courses as a small textbook for ourself and others on ML and PyTorch basics and we also wanted to share it with the public for others to have a quick and easy access to this knowledge. You can find a lot of <strong>FREE </strong>courses and projects about data science or any other technology topics in <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p><strong>A Small Bonus:</strong></p><p>In addition to the Course work, we have added 2 more projects for you to further practice and apply your PyTorch Skills. In the first project, you will be utilizing simple learning rules to “teach” a neural network how to recognize objects the images and solve the big question: hotdog or not hotdog? In the second project you will have a chance to launch an AI Hotdog Detector as a Serverless Python App.</p><h4>Author:</h4><p><a href="https://author.skills.network/instructors/artem_arutyunov">Artem Arutyunov</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7bb3be386b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-power-of-ai/pytorch-for-everyone-everything-i-know-and-more-f7bb3be386b9">PyTorch for Everyone: Everything I know and More.</a> was originally published in <a href="https://medium.com/the-power-of-ai">The Power of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlock the Power of AI Optimization , Train Models 3 Times Faster.]]></title>
            <link>https://medium.com/the-power-of-ai/unlock-the-power-of-ai-optimization-train-models-3-times-faster-c215b9ac9955?source=rss-8d26b20a79d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c215b9ac9955</guid>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[mashine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Artem Arutyunov]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 20:04:21 GMT</pubDate>
            <atom:updated>2023-04-11T15:56:32.485Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlock the Power of AI Optimization, Train Models 3 Times Faster.</h3><p>Wondering how Machine Learning can help with credit card fraud detection? In this blog, we will discuss how to utilize the high-performance IBM Library Snap ML to accelerate the training of your Machine Learning models for detecting fraudulent credit card transactions.</p><p>As the world shifts towards online payment methods at a faster pace, enhancing credit card fraud detection has been a priority for all financial organizations. With the help of Machine Learning, organizations can detect credit card fraud more easily and efficiently. Want to know how? Read the blog and find out :)</p><p>To see all of the detailed explanations for the mentioned concepts and analyze/experiment with the code for this blog. Click on:</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBM+GPXX0RHPEN+v1">Credit Card Fraud Detection using Scikit-Learn and Snap ML</a></p><p>You can also take a lot of <strong>FREE </strong>courses and projects about data science or any other technology topics from <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p><strong>Let’s start:</strong></p><p><strong>Snap ML</strong> is a library for accelerated training and inference of Machine Learning models such as linear models, decision trees, random forests, and boosting machines. It’s a library developed and maintained by <a href="https://www.zurich.ibm.com/snapml/">IBM Research</a>. The library binaries are freely available on <a href="https://pypi.org/project/snapml/">PyPi</a> and it supports Linux/x86, Linux/Power, MacOS, Windows, Linux/Z. GPU support is also available for Linux. If you are curious, you can find detailed <a href="https://snapml.readthedocs.io/?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel--2022-01-01">documentation</a> and usage <a href="https://github.com/IBM/snapml-examples">examples</a>.</p><p>We will focus on training acceleration in particular by using two popular classification models to recognize fraudulent credit card transactions. They are the Decision Tree and Support Vector Machine.</p><p>Scikit-learn application can be seamlessly optimized by using Snap ML. The seamless integration of the Snap ML library is possible due to its Scikit-learn Python API compatibility.</p><h3><strong>Data:</strong></h3><p>When you are building a model that predicts if a credit card transaction is fraudulent or not, you can model the problem as a binary classification problem. A transaction belongs to the positive class (1) if it is a fraud, otherwise, it belongs to the negative class (0).</p><p>The dataset that we will be using is the <a href="https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0RHPEN82-2022-01-01">Credit Card Fraud Detection</a> dataset from Kaggle.</p><p>We will use pandas to work with the dataset itself, let’s see how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Nvf4MlSjhX1cAhmxF1PiA.png" /></figure><p>Each row in the dataset represents a credit card transaction. As shown above, each row has 31 variables. One variable (the last variable in the table above) is called `Class` and represents the target variable. Our objective will be to train a model that uses the other variables to predict the value of the `Class` variable. Let’s first retrieve basic statistics about the target variable.</p><p><strong>Note</strong>: For confidentiality reasons, the original names of most features are anonymize as V1, V2 .. V28. The values of these features are the result of a PCA transformation and are numerical.</p><p>Let’s see what the target class parameters are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*OCaQrhHRCMLbaa61wnHbiw.png" /></figure><p>As shown above, the Class variable has two values:</p><p>- 0 (the credit card transaction is legitimate) <br>- 1 (the credit card transaction is fraudulent)</p><p>Most transactions usually are legitimate and only a small fraction are non-legitimate. Thus, typically you have access to a dataset that is highly unbalanced. This is also the case of the current dataset: only 492 transactions out of 2,848,070 are fraudulent (the positive class — the frauds — accounts for 0.172% of all transactions).</p><p>Thus, you need to model a binary classification problem. Moreover, <strong>the dataset is highly unbalanced</strong> the target variable classes are not represented equally. This case requires special attention when training or when evaluating the quality of a model. One way of handling this case at training time is to bias the model to pay more attention to the samples in the minority class. The models under the current study will be configured to take into account the class weights of the samples at train/fit time.</p><h4>Data Processing:</h4><p>Data preprocessing such as scaling/normalization is typically useful for linear models to accelerate the training convergence. We standardize features by removing the mean and scaling to unit variance.</p><pre>big_raw_data.iloc[:, 1:30] = StandardScaler().fit_transform(big_raw_data.iloc[:, 1:30])<br>data_matrix = big_raw_data.values<br><br># X: feature matrix (for this analysis, we exclude the Time variable from the dataset)<br>X = data_matrix[:, 1:30]<br><br># y: labels vector<br>y = data_matrix[:, 30]<br><br># data normalization<br>X = normalize(X, norm=&quot;l1&quot;)<br><br># print the shape of the features matrix and the labels vector<br>print(&#39;X.shape=&#39;, X.shape, &#39;y.shape=&#39;, y.shape)</pre><pre>X.shape= (2848070, 29) y.shape= (2848070,)</pre><p>Now that the dataset is ready for building the classification models, to train the model you can use part of the input dataset and the remaining data can be used to assess the quality of the trained model.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)   </pre><pre>X_train.shape= (1993649, 29) Y_train.shape= (1993649,)<br>X_test.shape= (854421, 29) Y_test.shape= (854421,)</pre><p><strong>Model 1. Decision Trees with Scikit-Learn:</strong></p><p>Let’s first use Decision Trees for the problem and evaluate the performance of the classifiers from Scikit-learn and Snap ML.</p><p>First, we will compute the `sample_weights` to be used as input to the training routine so that it takes into account the class imbalance present in this dataset.</p><pre>w_train = compute_sample_weight(&#39;balanced&#39;, y_train)</pre><p>Let’s import the Decision Tree Classifier Model from scikit-learn and set the max depth of the tree to 4. Let’s train it using our train dataset.</p><pre>from sklearn.tree import DecisionTreeClassifier<br>sklearn_dt = DecisionTreeClassifier(max_depth=4, random_state=35)<br>sklearn_dt.fit(X_train, y_train, sample_weight=w_train)</pre><p>It took the model approximately 1 min to train. We can evaluate the Compute Area Under the Receiver Operating Characteristic Curve, the <strong>ROC-AUC </strong>score of the predictions of the classifier using the <strong>roc_auc_score </strong>command, and the probabilities of the test samples belonging to the class of fraudulent transactions returned by the model. It results in ROC-AUC score of 0.966, which is really good.</p><p><strong>Model 2. Decision Trees with Snap-Ml:</strong></p><p>Let’s import the Decision Tree Classifier Model from Snap ML. We can reuse the same sample weights we computed before using Scikit-learn’s <strong>compute_sample_weight</strong> function for training the Decision Tree from Snap ML. The seamless integration of the Snap ML library is possible due to its Scikit-learn Python API compatibility.</p><pre>snapml_dt = DecisionTreeClassifier(max_depth=4, random_state=45, n_jobs=4)</pre><p>Next, we create a model. Snap ML offers multi-threaded CPU/GPU training of decision trees, unlike scikit-learn. To set the number of CPU threads used at training time, set the `n_jobs` parameter. Let’s train it using our training dataset:</p><pre>snapml_dt = DecisionTreeClassifier(max_depth=4, random_state=45, n_jobs=4)<br>snapml_dt.fit(X_train, y_train, sample_weight=w_train)</pre><p>It took the model approximately 10 seconds to train. Wow, nice improvement, more than 5 times faster. We can again use the <strong>ROC-AUC </strong>score of the predictions of the classifier using the <strong>roc_auc_score </strong>command, and the probabilities of the test samples belonging to the class of fraudulent transactions returned by the model. It results in the same ROC-AUC score: 0.966, which is really good.</p><p>As shown above, both Decision Tree classifiers provide the same score on the test dataset. However, Snap ML runs the training routine multiple times faster than Scikit-Learn. This is one of the advantages of using Snap ML: <strong>acceleration of training of classical machine learning models, such as linear and tree-based models</strong>.</p><p>We can do a similar comparison with a Support Vector Machine.</p><h4>Support Vector Machine</h4><p>Import the linear Support Vector Machine (SVM) model from Scikit-Learn. Define a scikit-learn SVM model and indicate the class imbalance at training time by setting `class_weight=’balanced’` and train a linear Support Vector Machine model using Scikit-Learn.</p><pre>from sklearn.svm import LinearSVC<br>sklearn_svm = LinearSVC(class_weight=&#39;balanced&#39;, random_state=31, loss=&quot;hinge&quot;, fit_intercept=False)<br>sklearn_svm.fit(X_train, y_train)</pre><p>Timing and testing it with <strong>ROC-AUC, </strong>we get that the training time is around 87 seconds and the ROC-AUC score of 0.984.</p><p>Let’s do the same thing with <strong>Snap-ML:</strong></p><pre>from snapml import SupportVectorMachine<br>snapml_svm = SupportVectorMachine(class_weight=&#39;balanced&#39;, random_state=25, n_jobs=4, fit_intercept=False)<br>model = snapml_svm.fit(X_train, y_train)</pre><p>Timing and testing it in a similar manner with <strong>ROC-AUC, </strong>we get that the training time is around 32 seconds and the ROC-AUC score of 0.985.</p><p>Once again we can see that both SVM models provide the same score on the test dataset. However, as in the case of Decision Trees, Snap ML runs the training routine way faster than Scikit-Learn.</p><p>Moreover, as shown above, not only is Snap ML seamlessly accelerating sci-kit-learn applications, but the library’s Python API is also compatible with sci-kit-learn metrics and data preprocessor.</p><p>If you want to know more about the power of SnapML, check the implementation and get more detailed explanations on the above concepts then click on <a href="https://cognitiveclass.ai/courses/course-v1:IBM+GPXX0RHPEN+v1">Credit Card Fraud Detection using Scikit-Learn</a> and Snap ML. or explore other <strong>FREE </strong>courses and projects about data science or machine learning on <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p>Thanks for reading. Author:</p><p><a href="https://www.linkedin.com/in/artem-arutyunov/">https://www.linkedin.com/in/artem-arutyunov/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c215b9ac9955" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-power-of-ai/unlock-the-power-of-ai-optimization-train-models-3-times-faster-c215b9ac9955">Unlock the Power of AI Optimization , Train Models 3 Times Faster.</a> was originally published in <a href="https://medium.com/the-power-of-ai">The Power of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying Client Behaviour with ML]]></title>
            <link>https://medium.com/the-power-of-ai/classifying-client-behaviour-with-ml-826c621a7b6c?source=rss-8d26b20a79d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/826c621a7b6c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Artem Arutyunov]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 17:15:49 GMT</pubDate>
            <atom:updated>2023-03-22T17:15:49.303Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s world, banks are handling an enormous amount of data every day, including transactions, user behavior, and account information. This data can be analyzed to gain insights into client behavior, which is essential for developing effective business strategies, identifying potential fraud, and improving customer experience. One crucial aspect of data analysis in banking is the classification of client behavior. In this blog, we will discuss various techniques and tools banks can use to classify their clients. We will see how we can use multiple python libraries for preprocessing of the dataset, features selection, and model training to classify the data. So, let’s dive in!</p><p>To see all of the detailed explanations for the mentioned concepts and analyze/experiment with the code for this blog. Click on:</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBM+GPXX0GN4EN+v1">Client behavior classification in Banking</a></p><p>You can also take many <strong>FREE </strong>courses and projects about data science or any other technology topics from <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><h4>Data:</h4><p>Let’s see what kind of data we will be working with. The data that we are going to use is a subset of an open-source<a href="https://archive.ics.uci.edu/ml/datasets/bank+marketing"> Bank Marketing Data Set</a> from the UCI ML repository. The data is related to direct marketing campaigns of a Portuguese banking institution and in our case, the classification goal will be to predict if the client will subscribe to a term deposit. We will be using the <a href="https://pandas.pydata.org/"><em>pandas</em></a> library to work with data. Let’s first of all load the data:</p><pre>df = pd.read_csv(&#39;bank-additional/bank-additional-full.csv&#39;, sep = &#39;;&#39;)<br>df.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzS02LxXdb6KcF5uujr0KQ.png" /></figure><p>Let’s also check the shape of our data by using:</p><pre>df.shape<br>#Returns (41188, 21)</pre><p>As you can see DataSet consists 21 columns. Last column — target. Also DataSet consists 41188 rows. Some of the columns are:</p><p>Input features (column names):</p><ol><li>age - client age in years (numeric)</li><li>job - type of job (categorical: admin., blue-collar, entrepreneur, housemaid, management, retired, self-employed, services, student, technician, unemployed, unknown)</li><li>marital - marital status (categorical: divorced, married, single, unknown)</li><li>education - client education (categorical: basic.4y, basic.6y, basic.9y, high.school, illiterate, professional.course, university.degree, unknown)</li><li>default - has credit in default? (categorical: no, yes, unknown)</li><li>housing - has housing loan? (categorical: no, yes, unknown)</li><li>loan - has personal loan? (categorical: no, yes, unknown)</li><li>contact - contact communication type (categorical: cellular, telephone)</li><li>euribor3m - euribor 3 month rate, daily indicator (numeric)</li><li>nr.employed - number of employees, quarterly indicator (numeric)</li></ol><p>…</p><p>Output feature (desired target):</p><ol><li>y - has the client subscribed a term deposit? (binary: yes,no)</li></ol><p>*If you wanna see the complete list of columns, click <a href="https://archive.ics.uci.edu/ml/datasets/bank+marketing">here</a>.</p><p>Note that all categorical features are recognized as objects. We must change their type to “categorical”.</p><pre>col_cat = list(df.select_dtypes(include=[&#39;object&#39;]).columns)<br>df.loc[:, col_cat] = df[col_cat].astype(&#39;category&#39;)</pre><p>To see the unique values of the exact feature (column) we can use:</p><p>As was signed earlier the dataset contains 41188 objects (rows), for each of which 21 features are set (columns), including 1 target feature (y). 11 features, including target are categorical. These data types of values cannot be used for classification. We must transform it to int or float. <br>To do this we can use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01)">Label Encoder</a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01">Ordinal Encoder</a>. These functions can encode categorical features as an integer array.</p><p>Let’s separate DataSet on input and output(target) DataSets and convert categorical to numerical:</p><pre>X = df.iloc[:,:-1]  #input columns<br>y = df.iloc[:,-1]    #target column <br>col_cat = list(X.select_dtypes(include=[&#39;category&#39;]).columns)<br>oe = OrdinalEncoder()<br>oe.fit(X[col_cat])<br>X_cat_enc = oe.transform(X[col_cat])<br><br>#Convert back into the dataframe <br>X_cat_enc = pd.DataFrame(X_cat_enc)<br>X_cat_enc.columns = col_cat<br>X_cat_enc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHUF_noxdjFh0kkBjecyQQ.png" /></figure><p>Numerical fields can have a different scale and can consist of negative values. These will lead to round mistakes and exceptions for some AI methods. To avoid it these features must be normalized.</p><p>Let’s create a list of numerical fields and normalize it by using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01"><strong>MinMaxScaler</strong></a></p><pre>col_num = [&#39;age&#39;, &#39;duration&#39;, &#39;campaign&#39;, &#39;pdays&#39;,<br>       &#39;previous&#39;, &#39;emp.var.rate&#39;, &#39;cons.price.idx&#39;,<br>       &#39;cons.conf.idx&#39;, &#39;euribor3m&#39;, &#39;nr.employed&#39;]<br><br>#Apply the scaler <br>scaler = MinMaxScaler(feature_range=(0, 1))<br>X_num_enc = scaler.fit_transform(X[col_num])<br><br>#Convert back into the dataframe<br>X_num_enc = pd.DataFrame(X_num_enc)<br>X_num_enc.columns = col_num<br>X_num_enc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQeZNcXsrtmD6YpunE3olg.png" /></figure><p>Then we should concatenate both data frames in one input data frame and not forget to do the same thing with a target variable as well. Now we have a processed dataset for the initial analysis.</p><h4>Features selection:</h4><p>As was mentioned before, input fields consist of 20 features. Of course, some of them are more significant for classification. There are two popular feature selection techniques that can be used for categorical input data and a categorical (class) target variable.</p><p>They are:</p><ul><li>Chi-Squared Statistic.</li><li>Mutual Information Statistic.</li></ul><p>Let’s take a closer look at each in turn. To do this we can use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01">SelectKBest</a>, a method from <em>scikit-learn</em> library. Let’s see what it is and how we can do it:</p><blockquote><strong>Chi-Squared Statistic</strong>: Pearson’s chi-squared statistical hypothesis test is an example of a test for independence between categorical variables.You can learn more about this statistical test in the tutorial: <a href="https://machinelearningmastery.com/chi-squared-test-for-machine-learning/?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01">A Gentle Introduction to the Chi-Squared Test for Machine Learning</a>.</blockquote><p>The results of this test can be used for feature selection, where those features that are independent of the target variable can be removed from the dataset. The <em>scikit-learn</em> machine library provides an implementation of the chi-squared test in the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.chi2.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01#sklearn.feature_selection.chi2">chi2</a> function. This function can be used in a feature selection strategy, such as selecting the top k most relevant features (largest values) via the SelectKBest class.</p><p>We can define the SelectKBest class to use the chi2() function and select all (or most significant) features, then transform the train and test sets. Let’s apply SelectKBest class to extract the top 10 best features:</p><pre>bestfeatures = SelectKBest(score_func=chi2, k=10)<br>fit = bestfeatures.fit(x_enc,y_enc)<br>dfscores = pd.DataFrame(fit.scores_)<br>dfcolumns = pd.DataFrame(X.columns)</pre><p>Let’s see which features are the most significant ones:</p><pre>Specs:       Score:<br>euribor3m    890.69<br>loan         547.96<br>emp.var.rate 541.30<br>nr.employed  502.66<br>poutcome     441.45<br>campaign     358.02<br>education    321.92<br>marital      167.61<br>previous     157.98<br>day_of_week  98.23</pre><p>Let’s apply another method and compare the results:</p><blockquote><strong>Mutual information</strong> from the field of information theory is the application of information gain (typically used in the construction of decision trees) to feature selection. Mutual information is calculated between two variables and measures the reduction in uncertainty for one variable given a known value of the other variable. You can learn more about mutual information in the following <a href="https://machinelearningmastery.com/information-gain-and-mutual-information?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01">tutorial</a>.</blockquote><p>The <em>scikit-learn</em> machine learning library provides an implementation of mutual information for feature selection via the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.mutual_info_classif.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01#sklearn.feature_selection.mutual_info_classif"><em>mutual_info_classif</em></a> function. Like chi2(), it can be used in the SelectKBest feature selection strategy (and other strategies).</p><pre>bestfeatures = SelectKBest(score_func=mutual_info_classif, k=10)<br>fit = bestfeatures.fit(x_enc,y_enc)<br>dfscores = pd.DataFrame(fit.scores_)<br>dfcolumns = pd.DataFrame(X.columns)</pre><p>Let’s see which features are the most significant ones:</p><pre>Specs            Score<br>campaign         0.08<br>euribor3m        0.07<br>cons.price.idx   0.07<br>cons.conf.idx    0.07<br>nr.employed      0.06<br>emp.var.rate     0.05<br>previous         0.04<br>day_of_week      0.04<br>contact          0.03<br>poutcome         0.02</pre><p>As you can see these 2 functions select different significant features. Let’s try one more method.</p><p><strong>Feature importance: </strong>You can get the feature importance of each feature of your DataFrame by using the feature importance property of the exact classification model. Feature importance gives you a score for each feature of your data, the higher the score more important or relevant the feature is to your output variable. For example, Feature importance is an inbuilt class that comes with <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesClassifier.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01"><strong>Tree-Based Classifiers</strong></a><strong> </strong>(<em>scikit-learn</em> library), we will be using Extra Tree Classifier for extracting the top 10 features for the dataset.</p><pre>#Train our Model<br>model = ExtraTreesClassifier()<br>model.fit(x_enc,y_enc)<br><br>#Extract the features importance, transform it into Series and plot them.<br>feat_importances = pd.Series(model.feature_importances_, index=x_enc.columns)<br>feat_importances.nlargest(10).plot(kind=&#39;barh&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhXWj_xfKebCU7NMKcrrRg.png" /></figure><p>As you can see Extra Tree Classifier&#39;s importance of features are different than in previous cases. It means that there are no exact rules for feature selection. And their importance is strictly dependent on the model.</p><h4>Correlation Matrix with Heat-map:</h4><p>Correlation states how the features are related to each other. Correlation can be positive (an increase in one value of a feature increases the value of the other variable) or negative (an increase in one value of the feature decreases the value of the other variable). Heat-map makes it easy to identify which features are most related to the other variable, we will plot the heat-map of correlated features using the <em>seaborn </em>library.</p><pre>corrmat = x_enc.corr()<br>top_corr_features = corrmat.index<br>plt.figure(figsize=(20,20))<br>g=sns.heatmap(x_enc[top_corr_features].corr(),annot=True,cmap=&quot;RdYlGn&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kwk6FIgFkS9SvkuHk3RIDQ.png" /></figure><p>As you can see fields ‘euribor3m’, ‘emp.var.rate’, ‘nr.employed’ strictly correlate with each other. It means that two of them must be removed from the calculation because there are linear dependencies between them. If we know one of them we can easily calculate another two. We will remove ‘emp.var.rate’ and ‘nr.employed’ from the dataset.</p><p>Now know which features to include we will try to make our predictions using our processed dataset and classification models.</p><h4>Classification Models:</h4><p>First of all, we must separate DataSets for training and testing DataSets to calculate the accuracy of our models. To do this we can use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01"><em>train_test_split</em></a>. Let’s separate DataSets in 0.33 train/test proportion:</p><pre>X_train, X_test, y_train, y_test = train_test_split(x_enc, y_enc, test_size=0.33, random_state=1)</pre><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01"><strong>Logistic regression</strong></a><strong>: </strong>There are many different techniques for scoring features and selecting features based on scores; how do you know which one to use?</p><p>A robust approach is to evaluate models using different feature selection methods (and numbers of features) and select the method that results in a model with the best performance.</p><p>Logistic regression is a good model for testing feature selection methods as it can perform better if irrelevant features are removed from the model. Let’s train it and evaluate the accuracy:</p><pre>model = LogisticRegression(solver=&#39;lbfgs&#39;)<br>model.fit(X_train, y_train)<br>yhat = model.predict(X_test)<br>accuracy = accuracy_score(y_test, yhat)</pre><p>It returns a stunning 91% accuracy, let’s try one more</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01"><strong>Decision Trees</strong></a><strong> </strong>are a popular supervised learning method for a variety of reasons. The benefits of decision trees include that they can be used for both regression and classification, they don’t require feature scaling, and they are relatively easy to interpret as you can visualize decision trees. This is not only a powerful way to understand your model, but also to communicate how your model works.</p><p>A<strong> Decision Tree</strong> is a supervised algorithm used in machine learning. It is using a binary tree graph (each node has two children) to assign for each data sample a target value. The target values are presented in the tree leaves. To reach the leaf, the sample is propagated through nodes, starting at the root node. In each node, a decision is made, as to which descendant node it should go, and the decision is made based on the selected sample’s features. Decision Tree learning is a process of finding the optimal rules in each internal tree node according to the selected metric. Let’s fit a Decision Tree model from scikit library:</p><pre>model = DecisionTreeClassifier()<br>model.fit(X_train, y_train)<br>yhat = model.predict(X_test)<br>accuracy = accuracy_score(y_test, yhat)</pre><p>It gives us an accuracy of 89.14%, a bit worse than a linear regression one.</p><p>As was mentioned earlier, this method allows us to calculate the features&#39; importance. Let’s experiment a bit, by calculating them, choosing the best 10 of them to refit the model, and see if the accuracy has increased or decreased.</p><pre><br>feat_importances = pd.Series(model.feature_importances_, index=x_enc.columns)<br>feat_importances.nlargest(10).plot(kind=&#39;barh&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UES3Lppt-k05Em1oDGGUA.png" /></figure><p>Let’s refit the model on the most important features:</p><pre>col = feat_importances.nlargest(10).index<br>X_train_dt = X_train[col]<br>X_test_dt = X_test[col]<br>model.fit(X_train_dt, y_train)<br>yhat = model.predict(X_test_dt)<br>accuracy = accuracy_score(y_test, yhat)</pre><p>It returns us an accuracy of 89%. As you can see Accuracy is a little worse because we don’t use all features. So sometimes removing features can be harmful to the model&#39;s accuracy. It’s important to note that we kept only half of all features but the accuracy decreased only by 2%, which is a great increase in the training efficiency.</p><h4>Visualization of the decision tree:</h4><p>As was mentioned earlier, Decision trees are relatively easy to interpret as you can visualize them. let’s visualize the decision tree that we have trained earlier. There are many ways to do it. One of the fastest ways is to use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkGuidedProjectsIBMGPXX0GN4EN438-2022-01-01"><strong>python-graphviz</strong></a> library. You the following code to do it:</p><pre>import graphviz<br>dot_data = tree.export_graphviz(model,<br>               feature_names = col, <br>               class_names = y.unique(),<br>                                filled=True)</pre><p>After creating, you can plot the graph:</p><pre>graph = graphviz.Source(dot_data, format=&quot;png&quot;) <br>graph</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOgfyQi8E2_x18PWewTUjA.png" /><figcaption>Visualisation of a Decision Tree</figcaption></figure><p>As you can see, our decision tree is very big and complex, but to better visualise how it’s working, here’s a small part of it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1JXG1Y1KD6wIuUCKlh-LQ.png" /></figure><p>You can also render it into file:</p><pre>graph.render(&quot;decision_tree_graphivz&quot;)</pre><p>In conlcusion, we were able to do preliminary data processing. In particular, change data types, normalize and process categorical data, make feature selection by different methods. Learned how to build training and test DataSets. Shows how to work with different classifiers and how to visualize them. With the final result of an 90% accuracy, which is not bad at all.</p><p>If you want to know more ways some to visualise your Trees, check the code for the project, or experiment yourself with possible classifications models then click on <a href="https://cognitiveclass.ai/courses/course-v1:IBM+GPXX0GN4EN+v1">Client behavior classification in Banking</a> or explore other <strong>FREE </strong>courses and projects about data science or machine learning on <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p>Thanks for reading.</p><p><a href="https://author.skills.network/instructors/artem_arutyunov">Artem Arutyunov</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=826c621a7b6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-power-of-ai/classifying-client-behaviour-with-ml-826c621a7b6c">Classifying Client Behaviour with ML</a> was originally published in <a href="https://medium.com/the-power-of-ai">The Power of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own Unbeatable TicTacToe AI with Reinforcement Learning.]]></title>
            <link>https://medium.com/@artem.a.arutyunov/build-your-own-unbeatable-tictactoe-ai-with-reinforcement-learning-411502c54c22?source=rss-8d26b20a79d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/411502c54c22</guid>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gaming]]></category>
            <dc:creator><![CDATA[Artem Arutyunov]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 16:48:37 GMT</pubDate>
            <atom:updated>2023-03-20T16:48:21.317Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the exciting world of reinforcement learning! As you may already know, Tic-Tac-Toe is a simple but addictive game played on a 3x3 grid. But what if we could train a machine to play Tic-Tac-Toe against a human opponent, and potentially even beat us at our own game? That’s where reinforcement learning comes in.<em> It was thought it would take decades before a computer beat a Go champion. But now, thanks to reinforcement learning, computers can easily beat Go champions, beat Chess Grandmasters, and outperform Humans in every game. In this blog, we will use Monte Carlo Reinforcement learning algorithms to train agents </em>for Tic-Tac-Toe by applying O<em>pen AI’s gym, the go-to framework for Reinforcement learning.</em></p><p>To see all of the detailed explanations for the mentioned concepts and analyze/experiment with the code for this blog. Click on:</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+GPXX0HAUEN+v1">Build your own Unbeatable TicTacToe AI</a></p><p>You can also take a lot of <strong>FREE </strong>courses and projects about data science or any other technology topics from <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p>Let’s start:</p><h3>What’s Reinforcement Learning?</h3><p><strong>Reinforcement Learning</strong> is a machine learning method, which is based on rewarding desired actions/output and punishing the undesired ones. Reinforcement learning models are choosing which action to make based on the expected return of each action. Model takes some information about the current situation and possible actions as input, then you must reward it based on the decision that it decides to make. Reinforcement learning models learn to perform a task through repeated trial-and-error interactions with an environment and do so without any human intervention.</p><h3>Basics:</h3><ul><li><strong>Agent</strong>: is your reinforcement learning model, it’s a decision maker and learner.</li><li><strong>Environment</strong>: is a world around your agent, the agent learns and acts inside of it. The environment takes the action provided by the agent and returns to the next <strong>state</strong> and the <strong>reward</strong>.</li><li><strong>State</strong>: is a complete description of the state of the environment.</li><li><strong>Action</strong>: is a way agent interacts with the environment. <strong>Action Space</strong> is the set of all possible actions.</li><li><strong>Reward</strong>: is feedback from the environment, it can be negative or positive. It impacts the agent and serves as an indication to an agent of what it should achieve. Rewards are generally unknown and agents learn how to correctly estimate the rewards.</li><li><strong>Policy</strong>: a rule used by an agent to decide what actions to take, given the specific state. It works as a map from state to some action and can sometimes be defined as a set of probabilities for each action in the action space.</li><li><strong>Value Function</strong>: this is the function that returns the expected total reward your agent can get from following the specific policy. The agent uses this value function to make decisions and learns by updating the expected reward values of the parameters of this function. In this lab, we will be using the state-action value function, so our function <em>Q(s,a)</em> will take the state-action pair and will return an estimated reward for taking action <em>a</em> from state <em>s</em>.</li></ul><p>The reinforcement Learning Process can be simply summarized by the following process:<br>1. <strong>Agent </strong>plays a number of games<br>2. In every game, the agent chooses an <strong>Action</strong> from the action space by using <strong>Policy</strong> and <strong>Value Function</strong><br>3. <strong>Action</strong> impacts the environment and the <strong>Reward</strong> and the new <strong>State</strong> is returned to the <strong>agent</strong>.<br>4. Agent keeps track of what <strong>reward</strong> it receives after choosing a specific <strong>action</strong> from a specific set. <br>5. After completing the game, the agent updates the estimated <strong>reward</strong> for each state and action by using the actual rewards values received while playing the game. <br>6. The whole process repeats again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9xbvOS7YPazl3wZq.jpeg" /></figure><p>Summary of RL process.</p><p>Famous RL models that play Chess, Go or Atari Games on superhuman levels, are all based on the aforementioned principles and concepts.</p><p>Let’s check our environment:</p><h3>TicTacToe Environment:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*ELxNO3RFHEpG_2JsViRILw.png" /></figure><p><strong>Note: OpenAI</strong> Gym is a python library for developing environments that can be used to train reinforcement learning algorithms. An environment can be thought of as the situation or game you are trying to replicate/model which in our case is TicTacToe. We use Gym because it standardizes the structure of the environments so communication between the player and the environment is easy and the same across Gym environments. A player/agent/robot then interacts with the environment by taking action.</p><p>I will assume that everyone knows the rules of the game. In this blog, we will be using a custom tictactoe environment.</p><p>We create an openAI gym environment by calling gym method, we will use the `make` function to do so.</p><pre>environment= gym.make(&#39;TicTacToe-v0&#39;)</pre><p>In our case, the actual <strong>Environment</strong> is just a board. let’s see how it looks:</p><pre>env.render()</pre><p>Which returns:</p><pre>Board<br>[&#39;-&#39;, &#39;-&#39;, &#39;-&#39;]<br>[&#39;-&#39;, &#39;-&#39;, &#39;-&#39;]<br>[&#39;-&#39;, &#39;-&#39;, &#39;-&#39;]</pre><p>In addition `hash` function returns a string representation of our environment, which will be used to record the states.</p><pre>env.hash() </pre><p>Which returns:</p><pre>&#39;---------&#39;</pre><p>Let’s check the <strong>action space</strong> of the environment. It should be the set of all empty places on the board:</p><pre>env.available_actions()</pre><p>Which returns:</p><pre>[0, 1, 2, 3, 4, 5, 6, 7, 8]</pre><p>Actions in our environment are integers representing the position on the board you would like the player to act on. 0 is the top left of the board and 8 is the bottom right. Note that it just gives all of the empty places on the board, now we can make some action and see what our environment returns: step(self, action, player). When we take a step in our environment we provide the player taking the action which is a string “X” or “O”, so each time-advancing decision is a <strong>step</strong>.</p><pre>new_state, reward, done, info = env.step(0, “X”)</pre><p>So now the value of a <em>new_state is</em></p><pre>&#39;X--------&#39;</pre><p><strong>Reward</strong> is a tuple representing the reward each agent receives after the action is performed. The first value is the reward X receives and the second value is the reward O receives. We will use this reward to learn what states are good and bad.</p><ul><li>If X wins the reward is (10, -10)</li><li>If O wins the reward is (-10, 10)</li><li>If the game is a tie or not done yet the reward is (0, 0)</li></ul><p><strong>done</strong> is a boolean used to keep track of whether the game is done or not so we know when to stop and <strong>info </strong>is not used in this environment, but can contain information like &quot;X Wins&quot; or &quot;O Loses&quot;.</p><p><strong>The episode</strong> is an agent-environment interaction from initial to final states, so it’s one game that the agent plays. It’s easy to see that each episode consists of a series of steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*uN7-9bByfdXLcl6lQDXtMw.png" /><figcaption>A random episode of the game</figcaption></figure><p>Just for you to better visualize what and how <strong>policy</strong> works. As a reminder, policy is just a map that maps each state to some action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0AkkM8tiwj0kLgh0S7i1w.png" /><figcaption>In this example, we are playing TicTacToe and we are going second. After the first player places their X, we can see how our policy will tell us to react given the state.</figcaption></figure><p>The<strong> state-action value function</strong> is a mathematical function that takes in a particular state of the game board and the action taken by an agent in that state and returns the expected reward of that action. For example, if an agent takes the action of placing their “O” on the middle square of a game board, where there is already one “X” in the right corner, the state action value function would take in this state and action and return the expected value for that move (which is -0.17 in our diagram below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0K5izV4UMbwRANvGGJvOQA.png" /><figcaption>Here are some visualized examples of state action pairs and what expected return may be returned by state-action value function (represented as Q(s,a))</figcaption></figure><h3>Epsilon-Greedy Policy</h3><p>Let’s clarify a few things with the title.<strong> Epsilon</strong> is just some constant 0≤ and ≤1, and it will define some probability. <strong>Greedy,</strong> is a concept in computer science where a greedy algorithm is the one that makes a locally optimal choice at each stage. In our case, greedy policy implies that it will choose an action with the biggest estimated return.</p><p>For now assume that <em>Q(s,a)</em> is our value function, it will return an <em>estimated </em>reward based on the given state and action. Let <em>A</em> be the action space then our policy can be simply defined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iivWmUbgwht8wnaa.png" /></figure><p>You may ask if we want to maximize our returns, why can’t we always use the best action, the action with the best-estimated reward, what’s the point of epsilon? To answer this question we will have to learn about 2 more concepts:</p><ul><li><strong>Exploitation</strong> happens when the agent makes the best decision given current information, it uses the best-estimated action to maximize the reward.</li><li><strong>Exploration</strong> happens when the agent takes random action to explore more opportunities, and gather more information about possible actions and the environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VNjav_7Ot5_7Vyyi.png" /></figure><p><strong>Epsilon</strong> defines the trade-off between Exploration and Exploitation. We need it because the best long-term strategy may involve short-term sacrifices and in most cases, agents must explore the environment and gather enough information to make the best overall decisions. It may save our agent from doing decisions that work instead of finding the best actions</p><h3>Monte Carlo Method:</h3><p>Let’s talk about the heart of our algorithm, the Value function that we will be using, and how it estimates the reward for each action given the state.</p><p>Monte Carlo Method was invented by Stanislaw Ulman in 1940s, while trying to calculate the probability of a successful Canfield solitaire (He was sick and had nothing better to do). Ulman randomly lay the cards out and simply calculated the number of successful plays. We will apply the same approach to create our value function. The basic principle of Monte Carlo method can be summarized in 4 steps:</p><ol><li>Define the Domain of Possible inputs</li><li>Generate inputs randomly from a probability distribution over the domain</li><li>Perform a deterministic computation on the inputs</li><li>Average the results</li></ol><p>Before we can see it in action let’s define a few things. Review that Episode is a set of agent-environment interactions from initial to final states which consists of steps in a discrete-time game.</p><p>Monte Carlo reinforcement learning learns from <strong>episodes of experience</strong>, it functions by setting the value function equal to the empirical mean return.<br>Let’s assume that we have some initialized policy <strong>π</strong> that our agent follows. Then let’s play a game once and gain the following episode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cyTNrZwDEVKWg9eG.png" /></figure><p>Now let’s look at the total expected reward of taking an Action A_t in the state S_t , where t is some time step.</p><p>At time step <em>t=0</em> (the first time step), the environment (including the agent) is in some state <em>S_t = S_0</em> (the initial state), takes an action <em>A_t = A_0</em> (the first action in the game), and receives a reward <em>R_t = R_0</em> and the environment (including the agent) moves to a next state<em> S_{0+1} = S_1</em>. Let’s define a function <em>G</em>, which will just give us the expected total discounted reward at each time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*DE6Ta51bs-koibfu.png" /></figure><p>Discount factor 0≤gamma≤ 1 is an important constant. We add the initial reward <em>R_1</em> as it is, without modifying the value, then to get the total reward we are adding <em>R_{t+1}</em> but note that the value is multiplied by gamma, so <em>R_{t+1}</em> is only partially added to <em>R_1</em>,<em> R_{t+2}</em> is multiplied by gamma², <em>R_{t+3}</em> is multiplied by gamma³ and so on. Gamma determines how much the reinforcement learning agent cares about rewards in the distant future relative to those in the immediate future. Note that if <em>gamma=0</em> then total expected return will be defined just by initial reward, so agent will only learn and care about actions that produce an immediate reward.</p><p>Now we can define our action-value function $Q_<strong>π</strong>(S, A)$ for some state S and action A as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*Rm04P6YIHS4om418.png" /></figure><p>So value function returns the expected value of a total discounted reward G(t) for the time step t at which S_t = S and A_t = A.</p><p>Now, after completing a series of episodes in the game, how can we adjust the expected values or a bigger question is how’s the learning process itself happening in Monte Carlo Method. For it we will the concept of <strong>Incremental means</strong> is used</p><p>Now we can put everything together to describe the Monte Calro Method Learning Process. Let’s have an episode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgU799DJMyDCHtfDqhbMUw.png" /></figure><p>For each (state, action) pair we will keep track of the number of times this (state, action) was visited, let’s define function N(s_t,a_t), then every time we visit (state, action) we will update the visits counter and then adjust the running mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*VOiR7NUoNAxoFNEWP9YoHQ.png" /></figure><p>So now we know how to update the action-value function and how to use it in combination with our policy to maximize the rewards, it can be summarized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*obLclsOQ4NwvABKR.png" /></figure><p>Monte Carlo algorithm/method is a type of <strong>model-free</strong> reinforcement learning, since the agent does not use predictions of the environmental response, so it’s not trying to create a statistical <strong>model </strong>of the environment.</p><h4><strong>Notes on Training:</strong></h4><ul><li>We will be training AgentX, so the one who plays as “X” on the board.</li><li>We will be training our agent against a random opponent (so the opponent, 𝐴𝑔𝑒𝑛𝑡𝑂 will make random actions).</li><li>In the training procedure, the Reward is updated each time either AgentX or AgentO takes an action since the game may end and the reward may be received after AgentX or 𝐴𝑔𝑒𝑛𝑡𝑂 action. The state is updated only after AgentO takes an action, as it is the state from which AgentX takes an action. Let’s look at the diagram of the last time step in the episode:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqF2IVozkbmktACnjbo2kg.png" /></figure><p>Let’s train our model:</p><pre>policy_X, Q= monte_carlo_X(env,N_episodes=100000,epsilon=0.1, discount_factor=0.95)</pre><p>Let’s check the results of our training and analyze how our agent performs against a random<em> AgentO : </em>in 1000 cases it gives us an amazing result of 986 wins, which is not bad at all.</p><p>Let’s check how the policy looks for <em>AgentX:</em></p><pre>{&#39;OO-XX-XO-&#39;: 2,<br> &#39;OO-X--X--&#39;: 2,<br> &#39;-O-X-----&#39;: 4,<br> &#39;---------&#39;: 3,<br> &#39;O-OXOXOXX&#39;: 1,<br> &#39;O-OXO--XX&#39;: 6,<br> &#39;O-OX---X-&#39;: 4,<br> &#39;O--X-----&#39;: 4,...</pre><p>Now let’s analyze how our agent performs against a similarly trained <em>AgentO: </em>in 1000 cases it gives us an amazing result, all 1000 of them were tied, which does make sense since it’s a simple environment and agents were trained using a similar algorithm.</p><p>If you are interested, the policy of <em>AgentO </em>looks like<em>:</em></p><pre>{&#39;X-O-O--XX&#39;: 6,<br> &#39;----O--XX&#39;: 6,<br> &#39;-------X-&#39;: 4,<br> &#39;OX-XXXOO-&#39;: 8,<br> &#39;-X-XX-OO-&#39;: 8,<br> &#39;-X--X-O--&#39;: 0,...</pre><p>So as we can see, we have created a successful algorithm, that allowed us to create a successful TicTacToe agent with an optimal policy.</p><p>If you want to play against your opponent, learn more about Monte Carlo Method, or look at the implementation of the algorithm itself, then click on <a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+GPXX0HAUEN+v1">Build your own Unbeatable TicTacToe AI</a> or explore other <strong>FREE </strong>courses and projects about data science or machine learning on <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p>Thanks for reading.</p><p><a href="https://author.skills.network/instructors/artem_arutyunov">Artem Arutyunov</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=411502c54c22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Win at Blackjack with Reinforcement Learning]]></title>
            <link>https://medium.com/the-power-of-ai/blackjack-with-reinforcement-learning-95f588dd670c?source=rss-8d26b20a79d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/95f588dd670c</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[monte-carlo-method]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Artem Arutyunov]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 17:00:45 GMT</pubDate>
            <atom:updated>2023-02-07T17:13:19.983Z</atom:updated>
            <content:encoded><![CDATA[<p>As a popular casino card game, many have studied Blackjack closely in order to devise strategies for improving their likelihood of winning.</p><p>In this project, we will use Reinforcement Learning to find the best playing strategy for Blackjack. <em>We will use Monte Carlo Reinforcement learning algorithms </em>to do it; you will see how Reinforcement Learning can determine the optimum Blackjack strategy in just a few minutes. <em>You will quickly grasp important concepts of Reinforcement learning and apply open AI’s gym, the go-to framework for Reinforcement learning.</em></p><p>To see all of the detailed explanations for the mentioned concepts and analyze/experiment with the code for this blog. Click on</p><p><a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+GPXX0EP1EN+v1">Win Blackjack with Reinforcement Learning</a></p><p>You can also take a lot of <strong>FREE </strong>courses and projects about data science or any other technology topics from <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p>Let’s start.</p><h3>What’s Reinforcement Learning?</h3><p><strong>Reinforcement Learning</strong> is a machine learning method, which is based on rewarding desired actions/output and punishing for the undesired ones. Reinforcement learning models are choosing which action to make based on the expected return of each action. Model takes some information about the current situation and possible actions as input, then you must reward it based on the decision that it decides to make. Reinforcement learning models learn to perform a task through repeated trial-and-error interactions with an environment and do so without any human intervention.</p><h3>Basics</h3><ul><li><strong>Agent</strong> is your reinforcement learning model, it’s a decision maker and learner.</li><li><strong>Environment</strong> is a world around your agent, the agent learns and acts inside of it. The environment takes the action provided by the agent and returns the next <strong>state</strong> and the <strong>reward</strong>.</li><li><strong>State</strong> is a complete description of the state of the environment.</li><li><strong>Action</strong> is a way agent interacts with the environment. <strong>Action Space</strong> is the set of all possible actions.</li><li><strong>Reward</strong> is a feedback from the environment, it can be negative or positive. It impacts the agent and serves as an indication to an agent of what it should achieve. Rewards are generally unknown and agents learn how to correctly estimate the rewards.</li><li><strong>Policy</strong> is a rule used by an agent to decide what actions to take, given the specific state. It works as a map from state to some action can sometimes be defined as a set of probabilities for each action in the action space.</li><li><strong>Value Function</strong> is the function that returns the expected total reward your agent can get from following the specific policy. The agent uses this value function to make decisions and learns by updating the expected reward values of the parameters of this function. In this lab, we will be using the state-action value function, so our function <em>Q(s,a)</em> will take the state-action pair and will return an estimated reward for taking action <em>a</em> from state <em>s</em>.</li></ul><p>The reinforcement Learning Process can be simply summarized by the following process:</p><p>1. <strong>Agent </strong>plays a number of games<br>2. In every game, the agent chooses an <strong>Action</strong> from the action space by using <strong>Policy</strong> and <strong>Value Function</strong><br>3. <strong>Action</strong> impacts the environment and the <strong>Reward</strong> and the new <strong>State</strong> is returned to the <strong>agent</strong>.<br>4. Agent keeps track of what <strong>reward</strong> it received after choosing a certain <strong>action</strong> from a certain set. <br>5. After completing the game, the agent updates the estimated <strong>reward</strong> for each state and action by using the actual rewards values received while playing the game. <br>6. The whole process repeats again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*sRcT3MT7wsurUDtBK3k8fw.jpeg" /><figcaption>Summary of RL process.</figcaption></figure><p>Famous RL models that play Chess, Go or Atari Games on superhuman levels, are all based on the aforementioned principles and concepts.</p><p>Let’s check our environment.</p><h3>BlackJack Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QDhXyadPID-I7JJBBFr9HA.gif" /></figure><p><strong>Blackjack</strong> is a card game played against a dealer. At the start of a round, both player and dealer are dealt 2 cards. The player can only see one of the dealer’s cards. The goal of the game is to get the value of your cards as close to 21 as possible, without crossing 21. The value of each card is listed below.</p><ul><li>10/Jack/Queen/King → 10</li><li>2 through 9 → Same value as the card</li><li>Ace → 1 or 11 (Player’s choice). Note that ace is called useful when It can be counted as 11 without going bust.</li></ul><p>If the player has less than 21, they can choose to “hit” and receive a random card from the deck. They can also choose to “stand” and keep the cards they have. If the player exceeds 21, they go “bust” and automatically lose the round. If the player has exactly 21, they automatically win. Otherwise, the player wins if they are closer to 21 than the dealer.</p><p>A few notes on <strong>Open Ai Gym</strong>: Open Ai Gym is a toolkit for developing and comparing reinforcement learning algorithms. This is the open-source gym library, which gives you access to a standardized set of environments. It’s quite useful in our case since we are working with a pretty standard environment. It also allows you to create your own custom environment but for now, we will only explore a pre-define Blackjack environment.</p><p>We create an OpenAI gym blackjack environment by calling gym method, we will use the `make` function to do so.</p><pre>environment= gym.make(‘Blackjack-v1’)</pre><p>Now let’s see what the <strong>observation space</strong> for our environment is. Observation space is a set of all possible states. We can view the space using the method <em>observation_space</em> :</p><pre>environment.observation_space</pre><p>Which returns:</p><pre>Tuple(Discrete(32), Discrete(11), Discrete(2))</pre><p>The observation is a 3-tuple of: the player’s (you) current sum, the dealer’s one showing card (1–10 where 1 is ace), and whether or not the player holds a usable ace (0 or 1) or (`True` or `False`). <br>Then we can explain `Tuple(Discrete(32), Discrete(11), Discrete(2))` as</p><ul><li>The highest score you can achieve is (11,10,11), and the lowest is (1), so there are 32 states for the player’s score.</li><li>The dealer only shows one card, which can be anything from 1 to 11.</li><li>The ‘usable ace’ space is True/False, so the size of the space is 2.</li></ul><p>So there are 32x11x2 = 704 possible states.</p><p>Let’s check the <strong>action space</strong> of this environment. Think what it should be before running the code:</p><pre>environment.action_space.n</pre><p>It returns 2, cause we can either <em>hit</em> or <em>stay</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*TjZhBx8MAu7d1fpUrsZFZA.png" /></figure><pre>print(environment.observation_space.sample())<br>print(environment.player)<br>print(environment.dealer)</pre><p>Which returns:</p><pre>(23, 7, 1)<br>[4, 8]<br>[7, 2]</pre><p><strong>The episode</strong> is an agent-environment interaction from initial to final states, so it’s one game that the agent plays. In addition, our agents are operating in a discrete-time game. Each time-advancing decision is a<strong> step</strong> (e.x. taking some action from some state). It’s easy to see that each <strong>episode</strong> consists of a series of steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SDMnQqn-S_Le0l2MuG9gg.png" /><figcaption>Example of 2 episodes of BlackJack game.</figcaption></figure><p>What will help us to win at this Casino Game, is ironically a casino name method: <strong>Monte Carlo Method</strong>. But before jumping there, lets define some things that will build an infrastructure for our learning process and elaborate/ implement previously defined terminology.</p><h3>Epsilon-Greedy Policy</h3><p>If you remember, as was mentioned before, policy is just a function that defines which action our agent should take based on the current state. In our environment, a simple deterministic policy π for the state (15,10,0) may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*339SMse-xl0MOPev4d0KKA.png" /></figure><p>Now let’s clarify a few things with the title.<strong> Epsilon</strong>, is just some constant 0≤ and ≤1, and it will define some probability. <strong>Greedy,</strong> is a concept in computer science where a greedy algorithm is the one that makes a locally optimal choice at each stage. In our case, greedy policy implies that it will choose an action with the biggest estimated return.</p><p>For now assume that <em>Q(s,a)</em> is our value function, it will return an <em>estimated </em>reward based on the given state and action. Let <em>A</em> be the action space then our policy can be simply defined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DCOcontYZjQlKMzB.png" /></figure><p>You may ask if we want to maximize our returns, why can’t we always use the best action, the action with the best-estimated reward, what’s the point of epsilon? To answer this question we will have to learn about 2 more concepts:</p><ul><li><strong>Exploitation</strong> happens when the agent makes the best decision given current information, it uses the best-estimated action to maximize the reward.</li><li><strong>Exploration</strong> happens when the agent takes random action to explore more opportunities, and gather more information about possible actions and the environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6dcRrIplhOlli_yJaFDvA.png" /></figure><p><strong>Epsilon</strong> defines the trade-off between Exploration and Exploitation. We need it because the best long-term strategy may involve short-term sacrifices and in most cases, agents must explore the environment and gather enough information to make the best overall decisions. It may save our agent from doing decisions that work instead of finding the best actions</p><h3>Monte Carlo Method</h3><p>Let’s talk about the heart of our algorithm, the Value function that we will be using and how it estimates the reward for each action given the state.</p><p>Monte Carlo Method was invented by Stanislaw Ulman in 1940s, while trying to calculate the probability of a successful Canfield solitaire (He was sick and had nothing better to do). Ulman randomly lay the cards out and simply calculated the number of successful plays. We will apply the same approach to create our value function. The basic principle of Monte Carlo method can be summarized in 4 steps:</p><ol><li>Define the Domain of Possible inputs</li><li>Generate inputs randomly from a probability distribution over the domain</li><li>Perform a deterministic computation on the inputs</li><li>Average the results</li></ol><p>Before we can see it in action let’s define a few things. Review that Episode is a set of agent-environment interactions from initial to final states which consists of steps in a discrete-time game.</p><p>Monte Carlo reinforcement learning learns from <strong>episodes of experience</strong>, it functions by setting the value function equal to the empirical mean return.<br>Let’s assume that we have some initialized policy <strong>π</strong> that our agent follows. Then let’s play a game once and gain the following episode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wJBM-hAP2S2lbzuY.png" /></figure><p>Now let’s look at the total expected reward of taking an Action A_t in the state S_t , where t is some time step.</p><p>At time step <em>t=0</em> (the first time step), the environment (including the agent) is in some state <em>S_t = S_0</em> (the initial state), takes an action <em>A_t = A_0</em> (the first action in the game), and receives a reward <em>R_t = R_0</em> and the environment (including the agent) moves to a next state<em> S_{0+1} = S_1</em>. Let’s define a function <em>G</em>, which will just give us the expected total discounted reward at each time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*UfD2mRBvOFL4u3Xj.png" /></figure><p>Discount factor 0≤gamma≤ 1 is an important constant. We add the initial reward <em>R_1</em> as it is, without modifying the value, then to get the total reward we are adding <em>R_{t+1}</em> but note that the value is multiplied by gamma, so <em>R_{t+1}</em> is only partially added to <em>R_1</em>,<em> R_{t+2}</em> is multiplied by gamma², <em>R_{t+3}</em> is multiplied by gamma³ and so on. Gamma determines how much the reinforcement learning agent cares about rewards in the distant future relative to those in the immediate future. Note that if <em>gamma=0</em> then the total expected return will be defined just by the initial reward, so the agent will only learn and care about actions that produce an immediate reward.</p><p>Now we can define our action-value function $Q_<strong>π</strong>(S, A)$ for some state S and action A as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*JVxb24V4jm9hVD2J.png" /></figure><p>So value function returns the expected value of a total discounted reward G(t) for the time step t at which S_t = S and A_t = A.</p><p>Now, after completing a series of episodes in the game, how can we adjust the expected values or a bigger question is how’s the learning process itself happening in Monte Carlo Method. For it, we will use the concept of <strong>Incremental means</strong>.</p><p><strong>Incremental means</strong> is just the average of values that is computed incrementally. Let x_1, x_2,…, x_n be the set of values, Let <strong>μ</strong>_1, <strong>μ</strong>_2, … , <strong>μ</strong>_{n-1} be a sequence of means, where <strong>μ</strong>_1 = x_1, <strong>μ</strong>_2 = (x_1+x_2)/2 and <strong>μ</strong>_3 = (x_1+x_2+x_3)/3 and so on. Let’s see how the mean is defined incrementally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*i-NQcDvZYfAot6AC.png" /></figure><p>Now we can put everything together to describe the Monte Calro Method Learning Process. Let’s have an episode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2GTgcF6Xlwm5z2TZ.png" /></figure><p>For each (state, action) pair we will keep track of the number of times this (state, action) was visited, let’s define function N(s_t,a_t), then every time we visit (state, action) we will update the visits counter and then adjust the running mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*0EvtIgYLc8L68-sh.png" /></figure><p>Let’s look for at an example episode where we update our Q function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3kpbhU1WH5WEXSYhfZNkg.png" /></figure><p>Now we can see how in this episode, before the game begins the number of visits of this state with this action is 0, then the game starts and the number of visits functions is updated. Return is 0 in the beginning. The action is made, by using the predefined policy, we are changing the state and the reward is received since we have more than the dealer. The total reward is updated and the Q function is updated by calculating the average reward of making action 0 in this state. Since it was the first time this state action pair was visited, we are just performing 1/1 so we get 1.</p><p>So now we know how to update the action-value function and how to use it in combination with our policy to maximize the rewards, it can be summarized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8KQvojFEQTN6H46jjYpJw.png" /></figure><p>Monte Carlo algorithm/method is a type of <strong>model-free</strong> reinforcement learning, since the agent does not use predictions of the environmental response, so it’s not trying to create a statistical <strong>model </strong>of the environment.</p><p>We will add a few more tricks and parameters to make this method more efficient.</p><h4>Monte Carlo with First Starts</h4><p>Note that for every episode, we update our Q function, based on states and actions that were visited, some state-action pairs can be visited more than once per episode. <strong>Every-Visit</strong> is Monte Carlo algorithm that averages returns for every time the state-action pair is visited in an episode, where <strong>First-visit MC</strong> averages return only for the first time state-action pair is visited in an episode.</p><p>Let’s check its implementation in the <strong>First-visit MC</strong> pseudo-code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9Z8sejvyjDLsHvfDzmbMA.png" /></figure><p>Where T is the last step in the episode, T-1 is the second last one and so on.</p><p>Since it’s impossible to have the same state appearing more than once in the Blackjack episode, we will only use the First-visit implementation.</p><p>Let’s train our model:</p><pre>policy, V, Q,DELTA= monte_carlo_ES(environment,N_episodes=50000, discount_factor=1,epsilon = 0.1,first_visit=True,theta=0)</pre><p>We are using a value function <em>V(s)</em> for some state<em> s </em>as an indication of what our model thinks the expected return is when following the best action given by the<em> Q</em> function. So <em>V(s) = max(Q(s,a))</em> for all <em>a</em> in the action space. Our implementation returns the value function <em>V</em> as a dictionary. <em>DELTA</em> indicates the value by which the<em> V</em> function for each state was updated. The last parameter is <em>theta</em>, which indicated a stopping threshold, so if delta is very small, there is no reason to continue training the algorithm, since updates to the values are minimal we will stop the training process.</p><p>Let’s plot the delta value for each episode to see how the update rates are changing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUPUEq-02n4QDMTtmiX81Q.png" /></figure><p>As you can see the delta parameter is generally decreasing, which makes sense since our model comes closer and closer to the optimal values for the value function. Speaking of which, let’s see the map of expected returns based on what the player has and what the dealer has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abBe2WQT1fnzrPnybs6o2g.png" /></figure><p>We see a general trend, as the score of the player increases the value function takes on higher values so our expected return grows. Let&#39;s see the average result of playing ten thousand games. Let’s compare the result, first using the random policy.</p><p>The random policy gives us around 28% of wins, and the agent that uses the trained policy is returning us around 42%. More than 10 % increase. Let’s actually visualize the policy itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14cOKm0YtFPRu_aBRC5xew.png" /></figure><p>It looks like the optimal policy for blackjack is: If the agent has no ace, the higher the dealer is showing, the more likely the agent is to hit, the exception is if the dealer has an ace. If the agent has an ace, the strategy is different. The agent will stick if the sum of their cards is over 11 and, for the most part, hold the player’s sum is over 18.</p><p>We have created a successful algorithm, that was able to give us perhaps not a winning, but an optimal strategy for blackjack.</p><p>If you want to know the answer to the aforementioned questions and learn some simple trick that may help you to improve your algorithm or look at the implementation of the algorithm itself, then click on <a href="https://cognitiveclass.ai/courses/course-v1:IBMSkillsNetwork+GPXX0EP1EN+v1">Win Blackjack with Reinforcement Learning.</a> or explore other <strong>FREE </strong>courses and projects about data science or machine learning on <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p>Thanks for reading.</p><p><a href="https://author.skills.network/instructors/artem_arutyunov">Artem Arutyunov</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f588dd670c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-power-of-ai/blackjack-with-reinforcement-learning-95f588dd670c">Win at Blackjack with Reinforcement Learning</a> was originally published in <a href="https://medium.com/the-power-of-ai">The Power of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn to Win Games with Monte Carlo Reinforcement Learning AI]]></title>
            <link>https://medium.com/the-power-of-ai/monte-carlo-reinforcement-learning-for-simple-games-71dc8f4ffda4?source=rss-8d26b20a79d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/71dc8f4ffda4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Artem Arutyunov]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 18:23:12 GMT</pubDate>
            <atom:updated>2023-01-31T22:34:17.685Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Deep Blue a chess computer beat world chess champion Garry Kasparov in 1997. The game of Go is played on a 19 by 19 board and is much more difficult to play as there are about 10 to the power 360 different combinations. It was thought it would take decades before a computer beat a Go champion. But now, thanks to reinforcement learning, computers can easily beat Go champions, beat Chess Grandmasters, and outperform Humans in every game. In this blog, we will use Monte Carlo Reinforcement learning algorithms for the simple game Frozen lake.</em></p><h4>CLICK ON: <a href="https://cognitiveclass.ai/courses/course-v1:IBM+GPXX0MNFRU+v1">Monte Carlo Reinforcement Learning for Simple Games</a></h4><p>To see all of the detailed explanations for the mentioned concepts and analyze/experiment with the code for this blog. You can also learn a lot of <strong>FREE </strong>courses and projects about data science or any other technology topics from <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><p>Let’s start then.</p><h3>What’s Reinforcement Learning?</h3><p>In general <strong>Reinforcement Learning</strong> is just another machine learning method, which is based on rewarding desired actions/output and punishing for the undesired ones. Reinforcement learning models, just like people, are choosing which action to make based on the expected return of each action. You must give your model some input which include the information about current situation and possible actions, then you must reward it based on the decision that it decides to make. Reinforcement learning models learn to perform a task through repeated trial and error interactions with an environment and does so without any human intervention.</p><h4>Basic Terminology:</h4><p><strong>Agent</strong>: is your reinforcement learning model, it’s a decision maker and learner.</p><ul><li><strong>Environment</strong>: is a world around your agent, the agent learns and acts inside of it. The environment takes action provided by the agent and returns to the next <strong>state</strong> and the <strong>reward</strong>.</li><li><strong>State</strong>: is a complete description of the state of the environment.</li><li><strong>Action</strong>: is a way agent interacts with the environment. <strong>Action Space</strong> is the set of all possible actions.</li><li><strong>Reward</strong>: is a feedback from the environment, it can be negative or positive. It impacts the agent and serves as an indication to an agent of what it should achieve. Rewards are generally unknown and agents learn how to correctly estimate the rewards.</li><li><strong>Policy</strong>: is a rule used by an agent to decide what actions to take, given the specific state. It works as a map from state to some action can sometimes be defined as a set of probabilities for each action in the action space.</li><li><strong>Value Function</strong>: is the function that returns the expected total reward your agent can get from following the specific policy. The agent uses this value function to make decisions and learns by updating the expected reward values of the parameters of this function. In this lab, we will be using the state-action value function, so our function <em>Q(s,a)</em> will take the state-action pair and will return an estimated reward for taking action <em>a</em> from state <em>s</em>.</li></ul><p>Reinforcement Learning Process:</p><p>1. <strong>Agent </strong>plays a number of games<br>2. In every game, the agent chooses an <strong>Action</strong> from the action space by using <strong>Policy</strong> and <strong>Value Function</strong><br>3. <strong>Action</strong> impacts the environment and the <strong>Reward</strong> and the new <strong>State</strong> is returned to the <strong>agent</strong>.<br>4. Agent keeps track of what <strong>reward</strong> it received after choosing a certain <strong>action</strong> from a certain set. <br>5. After completing the game, the agent updates the estimated <strong>reward</strong> for each state and action by using the actual rewards values received while playing the game. <br>6. The whole process repeats again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*sRcT3MT7wsurUDtBK3k8fw.jpeg" /><figcaption>Summary of RL process.</figcaption></figure><p>Let’s check our environement:</p><h3>Frozen Lake Environment:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OitcJ-rUdAHjMytWFkhJ_g.gif" /><figcaption>Frozen Lake Environment</figcaption></figure><p>Winter is here. You and your friends were tossing around a frisbee at the park when you made a wild throw that left the frisbee out in the middle of the lake. The water is mostly frozen, but there are a few holes where the ice has melted. If you step into one of those holes, you’ll fall into the freezing water. You have to navigate across the lake and retrieve the disc.</p><p>In our case, Frozen Lake will be a grid-like environment where each tile can be:</p><p>1. <strong>S</strong>: starting point, safe <br>2. <strong>F</strong>: frozen surface, safe<br>3. <strong>H</strong>: hole, fall to your doom<br>4. <strong>G</strong>: goal, where the disc is located</p><p>Important things to know are:</p><ul><li>The game ends if you step into a hole or get to your goal</li><li>You receive a reward of 1 if you reach the goal, and zero otherwise.</li></ul><p>Let’s initialize our environment and explore it a bit using Open Ai gym library:</p><pre>env = gym.make(&quot;FrozenLake-v1&quot;, is_slippery=False)</pre><p>Let’s see what our environment looks like, in our case, it should be a 4 by 4 grid:</p><pre>env.render()</pre><p>Which returns a simple grid:</p><pre>SFFF<br>FHFH<br>FFFH<br>HFFG</pre><p>Now let’s check the <strong>action space</strong> of the environment.</p><pre>env.action_space</pre><p>It returns <em>Discrete(4)</em> so we have 4 possible actions, the action space is {0,1,2,3}:</p><ul><li>Left: 0</li><li>Down: 1</li><li>Right: 2</li><li>Up: 3</li></ul><p>Now we can make a random action and see what our environment returns:</p><pre>#choose a random action from the action space<br>action = env.action_space.sample()<br><br>#Execute this aciton <br>new_observation, reward, done, prob = env.step(action)<br>new_observation, reward, done, prob</pre><pre>#Returns:<br>(0, 0.0, False, {&#39;prob&#39;: 1.0})</pre><p>It returns the first observation. Currently, we are on tile 4, the reward is 0 since we didn’t get to the goal, the binary parameter represents if the game is finished, and prob shows the probability of the execution of the chosen action, we have a deterministic environment, so for example, if we choose to go down we’ll go down.</p><p>We will introduce a bit more terminology, <strong>Episode</strong> is an agent-environment interaction from initial to final states, so it’s one game that the agent plays. In addition, our agents are operating in a discrete-time game. Each time-advancing decision is a<strong> step</strong> (e.x. taking some action from some state). It’s easy to see that each <strong>Episode</strong> consists of a series of steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SDzxIkY4idyXXK8DdFMAw.png" /><figcaption>Example of an episode with returns from the environment. Note that as mentioned, only when we reach the final goal, the G tile (index:15) we get the desired reward of 1.</figcaption></figure><p>Now let’s see what policy we are gonna use:</p><h4>Epsilon-Greedy Policy</h4><p>If you remember, as was mentioned before, policy is just a function that defines which action our agent should take based on the current state. In our environment, a simple deterministic policy pi for the first 4 states 0,1,2,3 may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0pgIT2gkR_5nNCGI-jWNA.png" /></figure><p>Now let’s clarify a few things with the title.<strong> Epsilon</strong>, is just some constant 0≤ and ≤1, and it will define some probability. <strong>Greedy,</strong> is a concept in computer science where a greedy algorithm is the one that makes a locally optimal choice at each stage. In our case, greedy policy implies that it will choose an action with the biggest estimated return.</p><p>For now assume that <em>Q(s,a)</em> is our value function, it will return an <em>estimated </em>reward based on the given state and action. Let <em>A</em> be the action space then our policy can be simply defined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XdmuW7mRhwvg-RxXQWl5g.png" /></figure><p>You may ask if we want to maximize our returns, why can’t we always use the best action, the action with the best-estimated reward, what’s the point of epsilon? To answer this question we will have to learn about 2 more concepts:</p><ul><li><strong>Exploitation</strong> happens when the agent makes the best decision given current information, it uses the best-estimated action to maximize the reward.</li><li><strong>Exploration</strong> happens when the agent takes random action to explore more opportunities, gather more information about possible actions and the environment.</li></ul><p><strong>Epsilon</strong> defines the trade-off between Exploration and Exploitation. We need it because the best long-term strategy may involve short-term sacrifices and in most cases, agents must explore the environment and gather enough information to make the best overall decisions. It may save our agent from doing decisions that work instead of finding the best actions.</p><h4>Monte Carlo Method:</h4><p>Let’s talk about the heart of our algorithm, the Value function that we will be using and how it estimates the reward for each action given the state.</p><p>Monte Carlo Method was invented by Stanislaw Ulman in 1940s, while trying to calculate the probability of a successful Canfield solitaire (He was sick and had nothing better to do). Ulman randomly lay the cards out and simply calculated the number of successful plays. We will apply the same approach to create our value function. The basic principle of Monte Carlo method can be summarized in 4 steps:</p><ol><li>Define the Domain of Possible inputs</li><li>Generate inputs randomly from a probability distribution over the domain</li><li>Perform a deterministic computation on the inputs</li><li>Average the results</li></ol><p>Before we can see it in action let’s define a few things. Review that Episode is a set of agent-environment interactions from initial to final states which consists of steps in a discrete-time game.</p><p>Monte Carlo reinforcement learning learns from <strong>episodes of experience</strong>, it functions by setting the value function equal to the empirical mean return.<br>Let’s assume that we have some initialized policy <strong>π</strong> that our agent follows. Then let’s play a game once and gain the following episode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjqlO2nnZo3Dbxg27hBI8A.png" /></figure><p>Now let’s look at the total expected reward of taking an Action A_t in the state S_t , where t is some time step.</p><p>At time step <em>t=0</em> (the first time step), the environment (including the agent) is in some state <em>S_t = S_0</em> (the initial state), takes an action <em>A_t = A_0</em> (the first action in the game) and receives a reward <em>R_t = R_0</em> and the environment (including the agent) moves to a next state<em> S_{0+1} = S_1</em>. Let’s define a function <em>G</em>, which will just give us the expected total discounted reward at each time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*UVlFAMSOJ06UKT7--Nyh7A.png" /></figure><p>Discount factor 0≤gamma≤ 1 is an important constant. We add the initial reward <em>R_1</em> as it is, without modifying the value, then to get the total reward we are adding <em>R_{t+1}</em> but note that the value is multiplied by gamma, so <em>R_{t+1}</em> is only partially added to <em>R_1</em>,<em> R_{t+2}</em> is multiplied by gamma², <em>R_{t+3}</em> is multiplied by gamma³ and so on. Gamma determines how much the reinforcement learning agent cares about rewards in the distant future relative to those in the immediate future. Note that if <em>gamma=0</em> then total expected return will be defined just by initial reward, so agent will only learn and care about actions that produce an immediate reward.</p><p>Now we can define our action-value function $Q_<strong>π</strong>(S, A)$ for some state S and action A as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*vzjDPSghUrUc2daxjsamLg.png" /></figure><p>So value function returns the expected value of a total discounted reward G(t) for the time step t at which S_t = S and A_t = A.</p><p>Now, after completing a series of episodes in the game, how can we adjust the expected values or a bigger question is how’s the learning process itself happening in Monte Carlo Method. For it, we will use the concept of <strong>Incremental means</strong>.</p><p><strong>Incremental means</strong> is just the average of values that is computed incrementally. Let x_1, x_2,…, x_n be the set of values, Let <strong>μ</strong>_1, <strong>μ</strong>_2, … , <strong>μ</strong>_{n-1} be a sequence of means, where <strong>μ</strong>_1 = x_1, <strong>μ</strong>_2 = (x_1+x_2)/2 and <strong>μ</strong>_3 = (x_1+x_2+x_3)/3 and so on. Let’s see how the mean is defined incrementally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*VZZJfTu9Pofz75HIZqzJQA.png" /></figure><p>Now we can put everything together to describe the Monte Carlo Method Learning Process. Let’s have an episode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jj4gF4JCPVUjPy_U10CHiw.png" /></figure><p>For each (state, action) pair we will keep track of the number of times this (state, action) was visited, let’s define function N(s_t,a_t), then every time we visit (state, action) we will update the visits counter and then adjust the running mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*1roMUxObir9W7BELH_r5QA.png" /></figure><p>As an example, our state-value for the start state $S = 0$ may look something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7IurvP-DeitXUgi8cdBEw.png" /></figure><p>So now we know how to update the action-value function and how to use it in combination with our policy to maximize the rewards. It can be summarized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8KQvojFEQTN6H46jjYpJw.png" /></figure><p>Note that Monte Carlo algorithm/method is a type of model-free reinforcement learning, since the agent does not use predictions of the environmental response, so it’s not trying to create a statistical model of the environment.</p><p>Let’s see the results of using the Monte Carlo Method, we will train it with 1000 episodes, an epsilon of 0.2 and a discount factor of 0.8. The training process should be rather fast.</p><pre>policy, Q = monte_carlo(env,N_episodes=1000,epsilon=0.01, discount_factor=0.8)  </pre><p>Plotting the policy we can see that our agent has indeed created an optimal well-defined path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*X6Y-zAOsb-xOS66t2M-nQw.png" /></figure><p>We can also try doing applying the same method to a bigger and more Complicated environment.<br>Let’s try working with a bigger Frozen lake environment. Before we were working with 4x4, let&#39;s change it to 8x8. Note that if before we had 4x4x4= 64 possible state action pairs (counting holes and goal tiles), now we will have 8x8x4 = 256$ possible state action pairs.</p><p>Let’s try training our model in this bigger environment. First import the environment itself:</p><pre># import the frozen lake gym environment<br>env = gym.make(&#39;FrozenLake8x8-v1&#39;, is_slippery=False) <br># warning: setting slippery=True results in very complex environment dynamics</pre><p>Let’s check how it looks, to visually understand the complexity of this environment.</p><pre>env.render()</pre><pre>SFFFFFFF<br>FFFFFFFF<br>FFFHFFFF<br>FFFFFHFF<br>FFFHFFFF<br>FHHFFFHF<br>FHFFHFHF<br>FFFHFFFG</pre><p>Let’s train our agent with the same model as the last time. It will help us to understand both the efficiency and scalability of a simple Monte Carlo algorithm.</p><pre>policy, Q = monte_carlo(env,N_episodes=10000,epsilon=0.2, discount_factor=0.9)  </pre><p>Let’s once again visualize the path that we will take using the resulting policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*3pH-rA7LkzHbilEc4b0NZg.png" /><figcaption>Policy Path for a bigger enviroment</figcaption></figure><p>Great Results once again, but there are some limitations.</p><p>Note that a simple Monte Carlo Algorithm may not be efficient enough, because in only 1000 episodes our agent is not able to reach the only tile which returns the reward a sufficient amount of times. In this environment, G tile is also the furthest tile from the initial S tile. It clearly demonstrates the inefficiency of a simple Monte Carlo Algorithm. Think about how you can improve the algorithm to avoid this sampling inefficiency.</p><p>Learn More:</p><p>If you want to know the answer to the aforementioned questions and learn some simple trick that may help you to improve your algorithm or look at the implementation of the algorithm itself, then click on <a href="https://cognitiveclass.ai/courses/course-v1:IBM+GPXX0MNFRU+v1">Monte Carlo Reinforcement Learning for Simple Games</a> or explore other <strong>FREE </strong>courses and projects about data science or machine learning on <a href="https://cognitiveclass.ai/">Cognitive Class</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71dc8f4ffda4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-power-of-ai/monte-carlo-reinforcement-learning-for-simple-games-71dc8f4ffda4">Learn to Win Games with Monte Carlo Reinforcement Learning AI</a> was originally published in <a href="https://medium.com/the-power-of-ai">The Power of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>