<?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 Juan Arturo Cruz Cardona on Medium]]></title>
        <description><![CDATA[Stories by Juan Arturo Cruz Cardona on Medium]]></description>
        <link>https://medium.com/@a01701804?source=rss-d6c73b2b3bd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aJWJ3MB8ic_COaC2.jpg</url>
            <title>Stories by Juan Arturo Cruz Cardona on Medium</title>
            <link>https://medium.com/@a01701804?source=rss-d6c73b2b3bd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:38:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a01701804/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[Build a Python Chatbot using Keras & NLTK]]></title>
            <link>https://a01701804.medium.com/build-a-python-chatbot-using-keras-nltk-db19eea77f74?source=rss-d6c73b2b3bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/db19eea77f74</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Juan Arturo Cruz Cardona]]></dc:creator>
            <pubDate>Fri, 21 May 2021 20:45:32 GMT</pubDate>
            <atom:updated>2021-05-24T23:05:40.933Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep Learning Project</h4><p>Through this tutorial, you will build a Chatbot capable of responding some of your messages after learning certain patterns the user can introduce. You require good python programming skills and basic knowledge about neural networks and deep learning.</p><h3>BEFORE STARTING</h3><blockquote><strong>SYSTEM REQUIREMENTS</strong></blockquote><p>The project was made using the following package versions:</p><ul><li><a href="https://www.python.org/downloads/">Python</a> 3.9.5 x64 bit (Tensorflow doesn’t run on 32-bit distributions)</li><li>Tensorflow 2.5.0</li><li>Keras 2.4.3</li><li>nltk 3.6.2</li><li>numpy 1.19.5</li></ul><blockquote><strong>ERRORS THAT MAY APPEAR</strong></blockquote><p>While running the project I encountered the following issues that you may also have to deal with:</p><ul><li><strong>Error Type #1</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*JvrqZw21FNrMFd6AClUulA.png" /></figure><p>To solve this error you may need to download a special module required by the libraries we are using, the name of it appears on a message asking for using an import to download a module.</p><p>So, in python shell you may introduce something like this</p><pre>&gt;&gt;&gt; import nltk<br>&gt;&gt;&gt; nltk.download(‘punkt’/‘wordnet’/’module_name’)</pre><ul><li><strong>Error Type #2</strong></li></ul><blockquote>ImportError: No module named ‘tkinter’ was found</blockquote><p>You need to be sure that your python installation has tkinter selected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*lA5TB4UQanPcypofzMRicg.png" /></figure><blockquote><strong>USEFUL INFORMATION</strong></blockquote><p>Before starting we need to define certain terminology and the purpose of the files that will be used throughout the execution of the chatbot.</p><p><strong>Terminology</strong></p><ul><li><strong>Tokenizing </strong>is the process of breaking the whole text into small parts like words.</li><li><strong>Lemmatizing</strong> is the process of converting a word into its lemma form, we use this while predicting.</li><li><strong>Lemma</strong> is the canonical form, dictionary form, or citation form of a set of words (headword).</li><li>A <strong>class</strong> will be a <strong>category</strong> of a list and each has a tag.</li><li>JSON (JavaScript Object Notation) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays.</li><li>A <strong>document</strong> is a combination between patterns and intents.</li></ul><p><strong>Files</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzNcbAfLdMUIi6yoAafp6A.png" /></figure><ul><li>The data file which has predefined patterns and responses is <strong><em>intents.json</em></strong>, you can change its content to have your own dataset.</li><li>The script to build the model and train our chatbot is inside the <strong><em>train.py</em></strong> file.</li><li>Words.pkl — This is a pickle file in which we store the words Python object that contains a list of our vocabulary.</li><li>The list of categories (classes) is inside of the pickle file called <strong><em>classes.pkl</em></strong></li><li>The trained model that contains information about the model and has weights of the neurons is <strong><em>model.h5</em></strong></li><li>Implemented GUI where users can easily interact with our chatbot is <strong><em>chat.py</em></strong></li></ul><h3>TRAINING THE CHATBOT</h3><blockquote><strong>Import and load the data file</strong></blockquote><p>We import the necessary packages for our chatbot and initialize the variables we will use in our Python project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*bdYdPn-FCJoAHEcCLmiZfg.png" /></figure><p>Is worth noticing that inside our intents.json file we can add more possible answers and even try to add more patterns. Also there is the possibility to do or select a completly different intent for another type of chatbot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1WaMzqkO4bMNnV9LjPvpA.png" /></figure><p>On this <a href="https://meta-guide.com/software/100-best-github-chatbot-dataset">link</a> you can find more intent datasets for the chatbot.</p><blockquote><strong>Preprocess data</strong></blockquote><p>We need to perform certain operations to preprocess the data before we make a machine learning or a deep learning model.</p><p>We will start with tokenizing, because is the most basic and first thing you can do on text data. Then we iterate through the patterns and tokenize the sentence using nltk.word_tokenize() and also create a list of categories for our tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*GZgIbCxx-lS2oTsrALRKHA.png" /></figure><p>Once we have the list we will lemmatize each word and remove duplicates from the list and generate the files needed for running the chatbot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*4aJ0z8ae9Jy5Hwyc2rFEsg.png" /><figcaption>Lemmatizing is the process of converting a word into its lemma form.</figcaption></figure><p>The generated files will be used while predicting.</p><blockquote><strong>Create training and testing data</strong></blockquote><p>Our input will be the pattern and output will be the class our input pattern belongs to. But the computer doesn’t understand text so we will convert text into numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*L7-I6qYf4f-rdiPtp8HznQ.png" /></figure><p>As you can see, we lemmatize each word to represent related words and then with the tokenized list we checked if each word matchs current pattern, if that is the case we add it to the bag we created using 1 and 0 otherwise.</p><blockquote><strong>Build the model</strong></blockquote><p>Now that we have the trainig data ready we proceed to use the Keras sequential API for building a deep neural network with 3 layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*4D1avq6-mCNU5uiW58ZmZA.png" /></figure><p>Notice that I trained the model for 200 epochs, this number achieved 100% accuracy on the model, but you can try different numbers to see how it changes the value.</p><p>Finally we save the model as &#39;model.h5&#39;.</p><h3>RUNNING THE CHATBOT</h3><blockquote><strong>Predict the response</strong></blockquote><p>To predict the sentences and get a response we will load the necessary packages, the trained model &#39;model.h5&#39; and the pickle files &#39;words.pkl&#39; &#39;classes.pkl&#39; which we have created when we trained our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*ZTcjMU59HQaIi5o0guercQ.png" /></figure><p>The model will only tell us the class it belongs to, so we will implement some functions which will perform text preprocessing, identify the class and then retrieve us a random response from the list of responses.</p><p><strong>Predict the class functions</strong></p><p>To predict the class, we will need to provide input in the same way as we did while training. So we will create some functions that will perform text preprocessing and prediction of the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*kdbOaSnTN2D104yeuSjvgw.png" /></figure><ul><li><strong>clean_up_sentence</strong> : Tokenizing the pattern creating a bag of words, 0 or 1 depending if the word exists in the sentece.</li><li><strong>bow</strong> : It calls <em>clean_up_sentence</em> function, once the pattern is tokenized checks if words are in the vocabulary and if are found in any bag to finally return it.</li><li><strong>predict_class</strong> : It calls <em>bow </em>function, filters predictions using a threshold and then sort the list by strength of probability.</li></ul><p><strong>Get a random response functions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*Q1iYodt7eg1TpXyinfxKww.png" /></figure><ul><li><strong>get_response</strong> : Returns a random response from the list of intents.</li><li><strong>chatbot_response</strong> : Main function of getting a response, it uses user input and the model we created.</li></ul><p>Fianlly, let’s use Tkinter library which is shipped with tons of useful libraries for GUI to create an interface where user can introduce their input messages and display the response from the bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*JjQlyIHREZltmjjgX5ZuvA.png" /></figure><ul><li><strong>send</strong> : It sends user input to <em>chatbot_response</em> function and displays the messages on the interface.</li></ul><blockquote><strong>Run the chatbot</strong></blockquote><p>First, we train the model using the command in the terminal:</p><p>python train.py</p><p>Then to run the app, we run the second file.</p><p>python chat.py</p><p>A GUI window will be open, and now you can easily chat with the bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*XAqqH1FYjtKRxY2qipQPJA.png" /></figure><h3>CONCLUSIONS</h3><blockquote><strong>Trying different epochs</strong></blockquote><p>Playing a bit with the values to see how the model behaved, I decided to train it with 10, 100 and 200 epochs obtaining the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*GH3qgXL6pHne6W__0NooAQ.png" /></figure><p>Also is worth saying that when I tried to run the chat application with 10 epochs the bot couldnt answer any of the messages I sent to it. But with 100 and 200 showed a good performance.</p><blockquote><strong>Using other intent dataset</strong></blockquote><p>I used a COVID-19 dataset for generating another intent file, it had up to 10,000 entries so it was quite heavy to learn, I had to do some changes on the training file, some of them are that I used 10,000 epochs for training the chatbot and adding more neurons to each layer.</p><p>Unfortunately, I was not able to reduce that much the loss, maybe changing the structure of the nueral network adding more layers, but the accuracy was good enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*-pGrQLfLO9nJqLSFkU5BWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SeooBWm1KG9ZaCGTSNH9Dg.png" /></figure><blockquote><strong>Personal reflection</strong></blockquote><p><strong>Does adding more layers or neurons always result in more accuracy? </strong>It completely depends upon how large your dataset is. Adding layers unnecessarily to any DNN (Deep neural network) will increase your number of parameters and increasing unnecessary parameters will only overfit your network.</p><p>The truth is you can customize the data according to business requirements and train the chatbot with great accuracy.</p><p>Here you can find the <a href="https://github.com/Alanespartan/Deep-Learning-Chatbot-Project">link to repository</a> and download the files.</p><h3>REFERENCES</h3><ul><li><a href="https://meta-guide.com/software/100-best-github-chatbot-dataset">https://meta-guide.com/software/100-best-github-chatbot-dataset</a></li><li><a href="https://towardsdatascience.com/deep-learning-for-nlp-creating-a-chatbot-with-keras-da5ca051e051">https://towardsdatascience.com/deep-learning-for-nlp-creating-a-chatbot-with-keras-da5ca051e051</a></li><li><a href="https://www.youtube.com/watch?v=CSpsB4_-5WQ">https://www.youtube.com/watch?v=CSpsB4_-5WQ</a></li><li><a href="https://data-flair.training/blogs/python-chatbot-project/">https://data-flair.training/blogs/python-chatbot-project/</a></li><li><a href="https://www.youtube.com/watch?v=YyKHwczZOMg">https://www.youtube.com/watch?v=YyKHwczZOMg</a></li><li><a href="https://www.udemy.com/course/nlp-natural-language-processing-with-python/">https://www.udemy.com/course/nlp-natural-language-processing-with-python/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db19eea77f74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Logistic Regression for Image Classification]]></title>
            <link>https://a01701804.medium.com/using-logistic-regression-for-image-classification-c4b1aec2f4ed?source=rss-d6c73b2b3bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4b1aec2f4ed</guid>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Juan Arturo Cruz Cardona]]></dc:creator>
            <pubDate>Sat, 13 Mar 2021 20:10:24 GMT</pubDate>
            <atom:updated>2021-03-15T18:58:17.216Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine Learning Project</p><h3>SYSTEM REQUIREMENTS</h3><ul><li>Basic python programming skills</li><li>Basic knowledge of logistic regression</li><li>Numpy python library</li><li>Pandas python library</li><li>Matplotlib python library</li></ul><p>Before anything else add this lines of code at the top of your file</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><p>In case you need it you can use the command “pip install <em>package_name” </em>to set up your work environment.</p><h3>PROBLEM STATEMENT</h3><p>The idea of this project is to develop and train a model that is able to take the pixel values of a digit and identify if it is an image of the digit one or not.</p><h3>SET UP OF DATA</h3><p>Here you can download the <a href="https://github.com/Alanespartan/Logistic-Regression-Project/blob/master/dataset.xlsx">dataset</a></p><p>Each row of the dataset represents the flattened pixel values of a digit, it goes from zero to nine but we will not use all of them because the goal of the binary classifiction model is return 1 if the digit is one and 0 otherwise.</p><p>To retrieve the digits data (X) and labels (Y) we must add in our code the following lines:</p><pre>df_x= pd.read_excel(&#39;dataset.xlsx&#39;, &#39;X&#39;, <em>header</em>=None)<br>df_x.head()</pre><pre>df_y= pd.read_excel(&#39;dataset.xlsx&#39;, &#39;Y&#39;, <em>header</em>=None)<br>df_y.head()</pre><p>Because this model will identify the digit 1 only, in the labels we need to convert the rest of digits that are not one to zero.</p><pre>y = df_y[0]<br>for i in range(len(y)):<br>   if y[i] != 1:<br>      y[i] = 0<br>y = pd.DataFrame(y)</pre><p>From the 5000 rows of data, 4000 will be used to train the model and the remaining 1000 will be used to test it, because is important for the model to be tested by unseen data. To do this we must add the following lines to our code:</p><pre>x_train = df_x.iloc[0:4000].T<br>x_test = df_x.iloc[4000:].T<br>x_train = np.array(x_train)<br>x_test = np.array(x_test)</pre><pre>y_train = y.iloc[0:4000].T<br>y_test = y.iloc[4000:].T<br>y_train = np.array(y_train)<br>y_test = np.array(y_test)</pre><p>These training and test datasets are in DataFrame form so they need to be in an array format for the convenience of calculation. Also it is worth noting that we are using .T to take the transpose of each dataset.</p><p>Once the training and test datasets are ready to be used it is time to focus on the model itself. To give it form we must define some formulas.</p><h3><strong>FORMULAS</strong></h3><p>We start from the basic linear regression formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*Jlw51Ih40fGrgRFD3JV60Q.png" /><figcaption>Formula 1</figcaption></figure><p>Where Y is the output, X is the independent variable, A is the slope and B is the intercept. But in logistic regression variables are expressed diferrently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*DX58lY2MJmTsBE_catwDfg.png" /><figcaption>Formula 2</figcaption></figure><p>Where:</p><ul><li>z is the output variable</li><li>x is the input variable</li><li>w and b will be initialized as zeros and they will be modified while training the model.</li></ul><p>Z should be passed through a non-linear function, this time we will use the sigmoid function that returns a value between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*ZsLgm693aa-jG3rGVCKy8Q.png" /><figcaption>Formula 3</figcaption></figure><p>It is worth saying that this <em>a</em> will be the final output that is the value in the <em>y_train</em> or <em>y_test</em>.</p><p>To define the sigmoid function in our code we add at the top:</p><pre>def sigmoid(z):<br>   s = 1/(1 + np.exp(-z))<br>   return s</pre><p>About <em>w</em> and <em>b</em> being initialized as zeros let’s define a function to do it:</p><pre><em>def</em> initialize_with_zeros(<em>dim</em>):<br>   w = np.zeros(<em>shape</em>=(dim, 1))<br>   b = 0<br>   return w, b</pre><blockquote><strong>Cost function and Gradient descent</strong></blockquote><p>The cost function is a measure of a model that reflects how much the predicted output differs from the original output. The model aim to lower the cost function value and for that we use the following formula for all the rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*AtxpWSm8CK8X71vS2uJHKQ.png" /><figcaption>Formula 4</figcaption></figure><p>Furthermore, we need to update the values of <em>w</em> and <em>b</em> in the formula 2. These values would be initialized as zeros but they will need more appropriate values and gradient descent will help us with that.</p><p>In Formula 4, the cost function is expressed as a function of <em>a</em> and <em>y,</em> but it can also be expressed as a function of <em>w</em> and <em>b</em> as well.</p><p>The differential <em>w</em> and <em>b</em> will be derived by taking the partial differentiation of cost function with respect to <em>w</em> and <em>b</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*HGe5ro6PAL2GakTG2XRi6w.png" /><figcaption>Formula 5 and 6</figcaption></figure><h3>CODING THE MODEL</h3><p>Once all the formulas are set, let’s put it all together in a function called <em>propagate</em> by adding the next lines in our code</p><pre><em>def</em> propagate(<em>w</em>, <em>b</em>, <em>X</em>, <em>Y</em>):<br>   #Find the number of training data<br>   m = X.shape[1]</pre><pre>   #Calculate the predicted output<br>   A = sigmoid(np.dot(w.T, X) + b)</pre><pre>   #Calculate the cost function<br>   cost = -1/m * np.sum(Y*np.log(A) + (1-Y) * np.log(1-A))</pre><pre>   #Calculate the gradients<br>   dw = 1/m * np.dot(X, (A-Y).T)<br>   db = 1/m * np.sum(A-Y)<br>   <br>   grads = {&quot;dw&quot;: dw, &quot;db&quot;: db}<br>   return grads, cost</pre><p>This function calculates:</p><ul><li>A: Predicted output</li><li>cost: Cost function</li><li>dw and db: Gradients</li></ul><p>By using this function now we are able to update <em>w</em> and <em>b</em> in Formula 2.</p><blockquote><strong><em>Optimize the parameters</em></strong></blockquote><p>To best fit the training data we will update the parameters which are the core of this model. The <em>propagate</em> function will be run through a number of iterations. In each iteration, <em>w</em> and <em>b</em> will be updated.</p><pre><em>def</em> optimize(<em>w</em>, <em>b</em>, <em>X</em>, <em>Y</em>, <em>num_iterations</em>, <em>learning_rate</em>):<br>   costs = []<br>   #propagate function will run for a number of iterations<br>   for i in range(num_iterations):<br>      grads, cost = propagate(w, b, X, Y)<br>      dw = grads[&quot;dw&quot;]<br>      db = grads[&quot;db&quot;]<br>      <br>      #Updating w and b by deducting the dw and db <br>      #times learning rate from the previous w and b<br>      w = w - learning_rate * dw<br>      b = b - learning_rate * db</pre><pre>      #Record the cost function value for each 100 iterations<br>      if i % 100 == 0:<br>         costs.append(cost)</pre><pre>   #The final updated parameters<br>   params = {&quot;w&quot;: w,&quot;b&quot;: b}<br>   #The final updated gradients<br>   grads = {&quot;dw&quot;: dw,&quot;db&quot;: db}<br>   <br>   return params, grads, costs</pre><p>The term <em>learning rate</em> was introduced in this function. It’s not a calculated value. It can vary depending the different machine learning algorithms. Later in the conclusions I will show the impact it has.</p><blockquote><strong><em>Predict the output</em></strong></blockquote><p>By now we can optimize the parameters, reduce the cost function and update the values of gradients, so is the time to predict the output.</p><pre><em>def</em> predict(<em>w</em>, <em>b</em>, <em>X</em>):<br>   m = X.shape[1]<br>   w = w.reshape(X.shape[0], 1)</pre><pre>   #Initializing an aray of zeros which has a size of the input<br>   #These zeros will be replaced by the predicted output<br>   Y_prediction = np.zeros((1, m))<br>   <br>   #Calculating the predicted output using the sigmoid function<br>   #This will return the values from 0 to 1<br>   A = sigmoid(np.dot(w.T, X) + b)</pre><pre>   #Iterating through A and predict an 1 if the value of A<br>   #is greater than 0.5 and zero otherwise<br>   for i in range(A.shape[1]):<br>      Y_prediction[:, i] = (A[:, i] &gt; 0.5) * 1</pre><pre>   return Y_prediction</pre><blockquote><strong><em>Model</em></strong></blockquote><p>By putting all the functions together the final model will look like this.</p><pre><em>def</em> model(<em>X_train</em>, <em>Y_train</em>, <em>X_test</em>, <em>Y_test</em>, <em>num_iterations</em>, <em>learning_rate</em>):<br>   #Initializing the w and b as zeros<br>   w, b = initialize_with_zeros(X_train.shape[0])</pre><pre>   #Best fit the training data<br>   parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate)   <br>   w = parameters[&quot;w&quot;]<br>   b = parameters[&quot;b&quot;]</pre><pre>   # Predicting the output for both test and training set<br>   Y_prediction_test = predict(w, b, X_test)<br>   Y_prediction_train = predict(w, b, X_train)</pre><pre>   #Calculating the training and test set accuracy by comparing<br>   #the predicted output and the original output<br>   print(&quot;train accuracy: {} %&quot;.format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))<br>   print(&quot;test accuracy: {} %&quot;.format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))</pre><pre>   d = {&quot;costs&quot;: costs,<br>   &quot;Y_prediction_test&quot;: Y_prediction_test,<br>   &quot;Y_prediction_train&quot; : Y_prediction_train,<br>   &quot;w&quot; : w,<br>   &quot;b&quot; : b,<br>   &quot;learning_rate&quot; : learning_rate,<br>   &quot;num_iterations&quot;: num_iterations}</pre><pre>   return d</pre><blockquote><strong><em>Using the model</em></strong></blockquote><p>To use the model and see how well it works let us pass our data that we prepared at the beginning by adding the next lines of code</p><pre>ni = 500 # num iterations<br>lr = 0.005 # learning rate<br>d = model(x_train, y_train, x_test, y_test, ni, lr)</pre><p>Once the code it is executed it will appear on the console something like this</p><pre>train accuracy: XX%<br>test accuracy: XX%</pre><p>Percentages may vary depending on the number of iterations and learning rate you use.</p><blockquote><strong><em>Plotting data</em></strong></blockquote><p>Is worth noting the <em>model</em> function returns a dictionary that contains:</p><ul><li>Costs</li><li>Final parameters</li><li>Predicted Outputs</li><li>Learning Rate</li><li>Number of iterarions used</li></ul><p>So, let us see how cost function changed with each updated ‘w’s and ‘b’s by adding the next lines of code.</p><pre>#Plot how cost function changed each updated w&#39;s and b&#39;s<br>plt.figure(<em>figsize</em>=(7,5))<br>plt.scatter(<em>x</em> = range(len(d[&#39;costs&#39;])), <em>y</em> = d[&#39;costs&#39;], <em>color</em>=&#39;black&#39;)<br>plt.title(&#39;Scatter Plot of Cost Functions&#39;, <em>fontsize</em>=18)<br>plt.ylabel(&#39;Costs&#39;, <em>fontsize</em>=12)<br>plt.show()</pre><p>After doing some tests changing values ​​I got the following results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvOI7clAyMaWaqdyVdgkgg.png" /><figcaption>Scatter Plot of Cost Functions with diferent learning rates and iterations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*gi5YFfqZQNgNg5Htjg_D8w.png" /><figcaption>Multiple values of test and train accuracy depending on learning rate and iterations</figcaption></figure><h3>CONCLUSIONS</h3><ul><li>With each iteration, the cost function went down as it should, that means the parameters <em>w </em>and <em>b</em> kept refining towards perfection.</li><li>It is worth noting that increasing the value of the learning rate will get us a better % at training accuracy but it will be lower on test accuracy. For this particular case I recommend using 0.015 that had both percentages more even.</li><li>To change the model for recognizing another digit apart from 1 you can go to the line where it changes all numbers that are not 1 to zero, but instead of 1 use the digit of your preference.</li><li>Reducing the number of rows for training the model will underfit it and if we increase the number it will overfit it. But you can try and check how it behaves.</li></ul><h3>REFERENCES</h3><ul><li><a href="https://towardsdatascience.com/logistic-regression-detailed-overview-46c4da4303bc">https://towardsdatascience.com/logistic-regression-detailed-overview-46c4da4303bc</a></li><li><a href="https://www.statisticssolutions.com/what-is-logistic-regression/">https://www.statisticssolutions.com/what-is-logistic-regression/</a></li><li><a href="https://towardsdatascience.com/a-complete-logistic-regression-algorithm-from-scratch-in-python-step-by-step-ce33eae7d703">https://towardsdatascience.com/a-complete-logistic-regression-algorithm-from-scratch-in-python-step-by-step-ce33eae7d703</a></li><li><a href="https://medium.com/swlh/logistic-regression-for-image-classification-e15d0ae59ce9">https://medium.com/swlh/logistic-regression-for-image-classification-e15d0ae59ce9</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4b1aec2f4ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Reinforcement Learning Terran Agent with PySC2 2.0 framework]]></title>
            <link>https://a01701804.medium.com/build-a-reinforcement-learning-terran-agent-with-pysc2-2-0-framework-c6be51b13d48?source=rss-d6c73b2b3bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6be51b13d48</guid>
            <category><![CDATA[pysc2]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[starcraft-2]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Juan Arturo Cruz Cardona]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 02:36:41 GMT</pubDate>
            <atom:updated>2020-11-26T18:57:37.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>USEFUL LINKS FOR THE TUTORIAL</h3><ul><li><a href="https://github.com/deepmind/pysc2/blob/master/pysc2/lib/units.py">Units PYSC2</a></li><li><a href="https://github.com/deepmind/pysc2/blob/master/pysc2/lib/actions.py">Functions PYSC2</a></li></ul><h3>BEFORE STARTING</h3><p>Through this tutorial, you will build a Smart Terran Agent capable of learning to develop a better strategy over time through a reward system based on the actions it tooks and the state resulting from those.</p><p>System requirements</p><ul><li>PySC2 2.0 framework installed</li><li>Pandas python library</li><li>Numpy python library</li><li>Basic python programming skills</li></ul><p>Also take into consideration that reinforcement learning to the complete game is extremely complex and takes a lot of time and computational power, we can make things easier for ourselves by significantly reducing the complexity of the game, that’s why the bot will be playing against “itself”, so instead of having an opponent with all the abilities in the game the opponent will have the same abilities, restrictions we will define and it will behave randomly.</p><h3><strong>1.- IMPORTS</strong></h3><p>Import the libraries at the top of the file as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*sBUVARkO15Z7tLLHMqBVKg.png" /></figure><h3><strong>2.- CREATE A QTABLE FOR R</strong>EINFORCMENT LEARNING</h3><p>We must define the algorithm for our Machine Learning Agent, there is where the QlearningTable comes to action, it is a simplified version of reinforcement learning.</p><p>It is essentially a spreadsheet of all the states the game has been in, and how good or bad each action is within each state. The bot updates the values of each action depending on whether it wins or loses, and over time it builds a fairly good strategy for a variety of scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*1ltGbrB1egBrloIO1403bg.png" /></figure><p>Inside the class of the QLearningTable we will also define the following methods</p><h4>Choose Action Method</h4><p>The main method of the learning table is choosing the action to perform, here with the e_greedy parameter means it will choose 90% of times the preferred action and the 10% of the time it will choose randomly for exploring extra possibilities of having a random action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*3REAxpUrUsCPY63b_wGW1A.png" /></figure><p>In order to choose the best action it first retrieves the value of each action for the current state, then chooses the highest value action. If multiple actions have the same highest value, it will choose one of those states at random.</p><h4>Learn Method</h4><p>The next important method here is learn. It takes as parameters:</p><ul><li>s refers to the <em>previous</em> state</li><li>a is that action that was performed in that state</li><li>r is the reward that was received after taking the action</li><li>s_ is the state the bot landed in after taking the action</li></ul><p>First in q_predict we get the value that was given for taking the action when we were first in the state.</p><p>Next we determine the maximum possible value across all actions in the current state, discount it by the decay rate (0.9), and add the reward we received.</p><p>Finally we take the difference between the new value and the previous value and multiply it by the learning rate. We then add this to the previous action value and store it back in the Q table.</p><p>The result of all this is that the action will either increase or decrease a little depending on the state we end up in, which will make it either more or less likely to be chosen if we ever get into the previous state again in the future.</p><p>In simple terms it does a sort of mathematical calculations and finally updates the table accordingly and that is how it learns over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*v2nytOSF9nUsZFKl0Yu7kA.png" /></figure><p>The check_state_exist method just check to see if the state is in the QLearningTable already, and if not it will add it with a value of 0 for all possible actions.</p><h3><strong>3.- DEFINE A BASE AGENT</strong></h3><p>Then we must define a Base Agent, an agent that both our random and learning agent will use. It has all of the actions that can be done and a few other methods that both agents can share to make them a little simpler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*TJlRF6PK4uM97orHup35VA.png" /></figure><h4>Helper Functions</h4><p>To perform these actions the bot will need helper functions described below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*JhlWSK9orq8-gOfk3pWIYA.png" /><figcaption>Returns a specific set of units of the army (applies for buildings and troops)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*8Qh599KMjMJvKeaZpXgf9w.png" /><figcaption>Returns the units that are finished and not the ones that are being created (applies for buildings and troops)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*0KY8a8KnHINESU2x7MwoiQ.png" /><figcaption>Calculate the distances between a list of units and a specified point</figcaption></figure><h4>Specific Actions</h4><p>And finally the actions that can be done are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*qYU37bFuDU0Ypiz5xVDOVA.png" /><figcaption>The method that will send an idle SCV back to a mineral patch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*KvOzHFVaHyUvRciO8nzN7w.png" /><figcaption>Generate buildings (for further and deep reinforcement learning you can consider to add more type of buildings)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*J20w1pcLuhKU1wapjOppsA.png" /><figcaption>Create an army of marines and sending them to attack</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*YDu_IK5H0AoRBrFe4XUQoQ.png" /><figcaption>Step method to know where our base is placed and do nothing (no operation to perform)</figcaption></figure><p>Its important to mention that unlike regular actions, raw actions do not crash if the action cannot be performed, but is best to perform your own checks so that error notifications do not appear in the game.</p><p>Finally each one of these methods will receive the observation from each step so that it can act independently.</p><h3>4.- RANDOM AGENT</h3><p>We choose an action at random here from our predefined list, and then we use Python’s getattr which essentially converts the action name into a method call, and passes in the observation as an argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*VI4-ahsBEN2YQ3Ay1p2bWw.png" /></figure><h3>5.- SMART AGENT</h3><p>The Smart Agent is like the random agent but having more machine learning stuff because here is where we initialize the QLearning Table once the Agent is created. It takes the actions of the Base Agent and that is how the QLearningTable knows those are the actions that it can choose from and then perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*w8kOHScqeqyC46D8BUkJuw.png" /></figure><h4>New Game Method</h4><p>Here we start a new game once the current it is finished by simply initializing some values like where the base is and the previous state and action.</p><p>Previous state and previous action are important for the reinforcement learning because we use those values each times it performs an action it stores that action in previous action variable so in the next step it knows what has already performed and the same with the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*xGRV4yB5olvNx7Ym9KmjHw.png" /></figure><h4>Get State Method</h4><p>Essentially takes all the values of the game that we can find useful and important for example how many barracks, or supplies, or idle svcs we have, and then returning those in a tuple that can feed into our machine learning algorithm and it can know which is the current state of the game at certain point in game.</p><p>To make the Machine Learning Algorithm learn faster we just simply want to know if we can afford or not to do certain actions and not putting too much attention in how many minerals we have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*jKQ6knpLS4BqbhE1Sqx-ow.png" /><figcaption>If you want to add more type of units or buildings and store its value, you can check the links at the top to find its function related</figcaption></figure><p>That seems like a lot of code but really we’re just keeping track of our units and the enemy units.</p><h4>Step Action Method</h4><p>It gets the current state of the game, it chooses and action, so it feeds the state into the QLearningTable and then chooses the best action or an action at random for finally return it.</p><p>Then what we want to do is to learn from that action and that state that were previously saved, so now we call the learn method in the QLeaningTable and pass those values and the reward received from the game (most of the times will be almost 0, 1 if we win or -1 if we lose) and then we pass in whether it is terminal or not and is kind of important because is not the same value a reward at the end of the game than the rewards we receive on the way to the end of the game.</p><p>Then we store the new previous state/action to use it in the next step of the game, and then we execute the action we have chosen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*YYKXshiBKS9UR-TEQYqgqw.png" /></figure><p>If we don’t reset the previous_state and previous_action it could teach our agent incorrectly at the start of each game, so let’s reset the values when we start a new game:</p><h3>6.- MAIN METHOD</h3><p>At the end we have the method that runs the game to see what happens in real time. Here we create the SmartAgent and our RandomAgent, set those as the players, pass those also in the run loop to control both agents instead of one and then, once it starts it will open 2 windows, one for each agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*--i6aEguyp0XNgG9yTdrPQ.png" /></figure><p>Here you can see both agents running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVOnG-u49gOeX3wCGbyQJw.png" /></figure><h3>CONCLUSIONS</h3><p>When you initially run this, both agents will do pretty much the same random actions, training some marines and attacking, building randomly or any other weird stuff, but this is just because the smart agent is still not smart enough.</p><p>Eventually the Smart Agent will discover that it can actually build more units for attacking, putting buildings in the front of the line to stop the enemy attack and by the time we get to hundreds of games played the strategy has already evolved.</p><p>There is also the fact that the random agent can have a better strategy just because is operating randomly, so the win percentage of the Smart Agent will not always be 100%.</p><p>There are things not considered like the health of the units, buildings, where the enemy marines are and more, so maybe implementing those in the future it can have better decisions and having a better win rate percentage.</p><p>Thanks for reading :) and you can find complete code <a href="https://github.com/Alanespartan/ReinforcementLearningStarcraftAgent">here</a>.</p><h3>References</h3><ul><li><a href="https://github.com/deepmind/pysc2">deepmind/pysc2</a></li><li><a href="https://medium.com/@a01700762/build-a-basic-terran-agent-with-pysc2-2-0-framework-b5adb073cf7a">Build a basic Terran agent with PySC2 2.0 framework</a></li><li><a href="https://itnext.io/create-a-protoss-bot-using-raw-observations-and-actions-in-pysc2-615f41aa283e">Create a Protoss Bot Using Raw Observations and Actions in PySC2</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOdn3fBH3-BQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOdn3fBH3-BQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOdn3fBH3-BQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b5b7ff00c0cf9e23acdfeb4720355e2/href">https://medium.com/media/8b5b7ff00c0cf9e23acdfeb4720355e2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6be51b13d48" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>