<?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 Oscar de Felice on Medium]]></title>
        <description><![CDATA[Stories by Oscar de Felice on Medium]]></description>
        <link>https://medium.com/@oscar-defelice?source=rss-5b4c877fa451------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wiPVEoQb6bn4BJ1KzCV30w.png</url>
            <title>Stories by Oscar de Felice on Medium</title>
            <link>https://medium.com/@oscar-defelice?source=rss-5b4c877fa451------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:45:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oscar-defelice/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[From Design to Deploy: The whole lifepath of a Machine Learning app]]></title>
            <link>https://medium.com/data-science/from-design-to-deploy-the-whole-lifepath-of-a-machine-learning-app-e9e0357525cc?source=rss-5b4c877fa451------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9e0357525cc</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Oscar de Felice]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 14:05:37 GMT</pubDate>
            <atom:updated>2022-04-20T13:51:53.057Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Design to Deploy: The whole Lifepath of a Machine Learning app</h3><h4>The step-by-step description to design, develop, deploy and maintain a Machine Learning application. Through an example. With code.</h4><p>Why should you read a 25min reading time medium post? Well, here I tried to condense the complete path of a machine learning project, from data analysis to deployment on AWS EC2.</p><h3>Introduction</h3><p>In the age of innocence, after following our first ML courses, we all thought that to be a data scientist, working on notebooks would have been enough.</p><p>Once we left kindergarten, we learnt that this is far from the truth.</p><p>Nowadays there is plenty of other skills a data scientist must have other than knowledge of machine learning algorithms (or more often library usage).</p><p>This post aims to go through an example (I will keep it easy on the model part) of a complete machine learning task example from design to deploy and maintain.</p><p>I do this because I have spoken and worked with dozens of data scientists, also not so junior in their career, and I got a picture of great confusion about the role. Data science is a great activity, but often data scientist codes are really difficult to bring in production (and even to read) because they have been written without thinking of the real-world use of the model. <br>I find this is a matter of respect — for the whole stack of poor devils working on the model after the data scientist — provide a solid and simple model deploy.<br>Furthermore, these days docker is a skill highly requested in all data science job offers, so why not take some time to see how dockerise a machine learning application?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*mC9AAF7LRih775yB.png" /><figcaption>The ubiquitous image used to illustrate the machine learning project lifecycle. Image by [<a href="https://www.jeremyjordan.me/ml-projects-guide/">https://www.jeremyjordan.me/ml-projects-guide/</a>]</figcaption></figure><p>The figure above is nice, but I think it may appear a bit too abstract. I will use my poor drawing abilities to redesign it as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0FRKMNhiAdphyKvaL218g.png" /><figcaption>A simplified model lifecycle. Image poorly drawn by the author.</figcaption></figure><p>The image above is also the schema we are going to follow in this post.</p><h3>Problem definition</h3><p>To be concrete, let’s start by defining our problem. Imagine you work in a consulting company (as I do) and your colleague from sales comes to you saying “Hey dude, an estate agency wants a house price estimator, can we do that?”.<br>I hope your answer would be “no problem”, hence we can start.</p><p>Before diving into the problem, let me make an observation. There should be an earlier (and important) step: data collection (that can be scraping, client database interrogation, etc.), that will be neglected here because this would lead us out of track.</p><h3>0. Preliminary analysis</h3><p>Under this part normally goes data collection, labelling, data analysis, some visualisation to better understand the kind of problem we are dealing with, data cleaning, etc.</p><p>Since these procedures are heavily influenced by the specific data to cope with, we keep it as simple as possible. We will briefly describe exploratory data analysis and that’s it.</p><h4>Data Collection</h4><p>I know, I wrote I would have neglected this part. I did not lie.<br>Here I imagine, the client gave us a nicely labelled dataset (this <a href="https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html">one</a>). In real (tough) life you usually spend a lot of time labelling data yourself, but we are still living in fairy tales for now.</p><p>Hence, let’s start by simply import our data into a pandas dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95ec6f3e57fe9adf9864687edafd18fe/href">https://medium.com/media/95ec6f3e57fe9adf9864687edafd18fe/href</a></iframe><p>The print(df.head()) command prints the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUff5V-nJY-EetK-MV-9Mw.png" /></figure><p>One can look at print the quantity boston_dataset.DESCR to have a brief description of the features.</p><pre><strong>CRIM</strong>: Per capita crime rate by town<br><strong>ZN</strong>: Proportion of residential land zoned for lots over 25,000 sq. ft<br><strong>INDUS</strong>: Proportion of non-retail business acres per town<br><strong>CHAS</strong>: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)<br><strong>NOX</strong>: Nitric oxide concentration (parts per 10 million)<br><strong>RM</strong>: Average number of rooms per dwelling<br><strong>AGE</strong>: Proportion of owner-occupied units built prior to 1940<br><strong>DIS</strong>: Weighted distances to five Boston employment centers<br><strong>RAD</strong>: Index of accessibility to radial highways<br><strong>TAX</strong>: Full-value property tax rate per $10,000<br><strong>PTRATIO</strong>: Pupil-teacher ratio by town<br><strong>B</strong>: 1000(Bk — 0.63)², where Bk is the proportion of [people of African American descent] by town<br><strong>LSTAT</strong>: Percentage of lower status of the population<br><strong>MEDV</strong>: Median value of owner-occupied homes in $1000s</pre><p>The last one is our target, and it is not included in the dataframe. Indeed, it is accessible by boston_dataset.target.</p><h4>Exploratory data analysis</h4><p>This is the part where you discover and familiarise yourself with your data.</p><p>First of all, it’s a good practice to see if there are any missing values in the data. We count the number of missing values for each feature using isnull(). In this case, you might not be surprised to discover there is no missing value.<br>Now, we will use some visualisation to characterise the distribution of our data and to understand how target and feature variables are related.<br>What we discover is that the distribution is more or less normal, with few outliers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/204def79c5c34d076a63f45721482145/href">https://medium.com/media/204def79c5c34d076a63f45721482145/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lTqgUgksSG9QYW6V78Rrw.png" /></figure><p>To better study feature variables one option is the correlation matrix or correlation plots. Since we have quite a few of them, we prefer the correlation matrix, easier to visualise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7905104f6a25e672ffc25f3863476fb5/href">https://medium.com/media/7905104f6a25e672ffc25f3863476fb5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fzee-qr9kxJBm8nUoiYhNg.png" /></figure><p>What we can notice:</p><ul><li>Some of the features have a strong positive correlation, both between them and with the target variable. If we want to go for a linear model, then we reasonably select such features. By looking at the correlation matrix we can see that RM has a strong positive correlation with the target (0.7) whereas LSTAT has a high negative correlation with it (-0.74).</li><li>For a linear regression model, it might be important is to check for multi-co-linearity. In our case, for example, RAD and TAX are really related (intuitively they can be exchanged without losing too much information).</li><li>To capture higher correlation orders, one may study the correlation matrix of features squared, or at the third power, etc.</li><li>One can reduce features with some other more systematic methods (like t-SNE, PCA, etc.) and study the correlation of the reduced features with the target variable.</li></ul><p>Based on the above observations we could keepRM and LSTAT as our features. However, since this is not the interest of this post, we will ignore this and use all the features.</p><h4>Preparing data to feed the model</h4><p>We can collect data into train test split using the popular method of sklearn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9812cd95cd2b0981fb129a32f63917bd/href">https://medium.com/media/9812cd95cd2b0981fb129a32f63917bd/href</a></iframe><p>There is one last step that is strongly advised to take: clean your data pipeline now. To do so, we will write a simple set of functions. The key-word is “<em>modular</em>” since you want to re-use this code in other projects and also you may want to maintain this model and maybe add/remove features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6532b4bf142777c204546a332c75cdc2/href">https://medium.com/media/6532b4bf142777c204546a332c75cdc2/href</a></iframe><p>Note how we used a dictionary to input arguments for the import_data function. This because we have in mind to feed such function with json or yml files through HTTP protocol.</p><p>Since I have already in mind the model I wanna use, I make this further consideration of data normalisation. Some problems may arise in feeding a neural network with data spreading over different intervals (both in size and central point). In principle, a well-trained model should adapt to such differences and encode them properly, however, this requires a lot of data and at the end of the story makes the model more difficult to train, less robust and eventually not precise.<br>A widespread best practice to deal with such data is to do feature-wise normalization: for each feature in the input data (a column in the input data matrix), we will subtract the mean of the feature and divide by the standard deviation, so that the feature will be centred around 0 and will have a unit standard deviation.</p><p>Hence we modify the function above as follows,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31925d8df47655415099270e7df42380/href">https://medium.com/media/31925d8df47655415099270e7df42380/href</a></iframe><h3>1. Model building</h3><p>At this stage, we design our model and train it in order to evaluate its performances. Normally, this part is done in a notebook without worrying too much about name conventions, functions, OOP, comments, etc. <br>However, my advice (also here) is to be as much clean as possible, since this can save you from hours of “<em>converting code into something readable</em>” later.</p><h4>Algorithm design</h4><p>Previously performed data analysis should drive this part. For example, a decision tree-based algorithm or an XGBoost would allow you to obtain great results.</p><p>Normally this part is made of a trial-error approach. Often you do not want to train your candidates model on the whole dataset (when you have a lot of data), so one solution might be to random sample your training data and train a bunch of models to compare their performances and choose the best one according to your chosen metric.</p><p>An aside, choosing the right metric for the problem is crucial. Of course, this is problem-dependent, however, here we can state the three properties a good metric has to satisfy:</p><ol><li>It has to be <strong>single-numbered</strong>. You want to make easy comparisons.</li><li>It has to be <strong>satisficing</strong> with respect to some numerical performance property. <em>i.e.</em> It has to measure algorithm numerical performances.</li><li>It has to be <strong>optimising</strong>. <em>i.e.</em> It has to measure algorithm results.</li></ol><p>The typical example is: we pick the model with the highest <em>F1</em>-score and inference time under 10 milliseconds.</p><p>Of course, this is an initial analysis. Usually, you may go through the complete training of a couple of different models before choosing the “right one”.<br>Here, we pretend we have done everything properly and we refer to this great post for details.</p><p><a href="https://medium.com/structuring-your-machine-learning-projects/satisficing-and-optimizing-metric-24372e0a73c">Satisficing and optimizing metric</a></p><p>Let’s say from our analysis we have chosen a Neural Network model. Again, my advice is to write your notebook cells always having in mind that you are going to convert this code in production, so be clean!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16a8205ff4f41585e3025d6e7d21f996/href">https://medium.com/media/16a8205ff4f41585e3025d6e7d21f996/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vm78K5A1Osw1d_P8UGduJg.png" /></figure><p>Once the model is defined and compiled (if you are a PyTorch person, no need for compilation), we are ready to train it on our data.</p><h4>First Training</h4><p>Let’s fit the model on our training data and measure the performance on test. To be rigorous, we should also have a validation set, but we will have time to worry about this later on. In this phase, we just want to end up with a working model and a measure of its performances. This is the overcited <em>quick-and-dirty </em>approach, that has nothing to do with how messy is your code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3c8eb8d06ce5ddb270b7150beb47337/href">https://medium.com/media/a3c8eb8d06ce5ddb270b7150beb47337/href</a></iframe><h4>Model evaluation</h4><p>It is always useful (even more in the regression case) to look at learning curves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lE4mBEFLBNT2qPQT2Z2pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJ305K7UIj1zHGqRt5rVYA.png" /></figure><p>We can see how our model is still minimising the loss function. This would suggest increasing the number of epochs.<br>We have also alternatives, <em>i.e. </em>increasing the modelisation power of our network, that is modifying its architecture, more hidden units and more hidden layers.<br>We will try both in the next section.</p><p>To conclude, an attentive reader may have noticed how the test loss seems to be lower than the training one. This is an effect of the fact that Keras computes the two losses in a slightly different way. I refer to this post for details.</p><p><a href="https://www.pyimagesearch.com/2019/10/14/why-is-my-validation-loss-lower-than-my-training-loss/#:~:text=The%20second%20reason%20you%20may,is%20measured%20after%20each%20epoch">Why is my validation loss lower than my training loss? - PyImageSearch</a></p><h4>Hyperparameter choice and optimisation</h4><p>In the previous section, we ended up with two possible options to improve our model.</p><p>We can try both ways and see which solution gives us the best results on the test-set. We are actually using our test set as a validation one.</p><p>The previous model configuration gave us the plot above. Let’s leave everything unchanged and just increase the number of epochs to 100.<br>The only thing to do is modify the config variable as follows.</p><pre>config = {<br>           &#39;data&#39;: boston_dataset,<br>           &#39;train_test_ratio&#39;: 0.2,<br>           &#39;model_config&#39;: {<br>               &#39;model_name&#39;: &#39;house_pricing_model&#39;,<br>               &#39;layers&#39;: {<br>                        &#39;first_layer&#39;: 12, <br>                        &#39;second_layer&#39;: 5, <br>                        &#39;output_layer&#39;: 1<br>                       },<br>                &#39;activations&#39;: [&#39;relu&#39;, &#39;relu&#39;, None],<br>                &#39;loss_function&#39;: &#39;mse&#39;,<br>                &#39;optimiser&#39;: &#39;adam&#39;,<br>                &#39;metrics&#39;: [&#39;mae&#39;]<br>                },<br>            &#39;training_config&#39;: {<br>                &#39;batch_size&#39;: 10,<br>                &#39;epochs&#39;: 100<br>            }<br>           }</pre><p>Everything else stays the same, we can reinitialise our model and run the train function again. We get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bFS78Nncnu-JFdSC04k5Q.png" /></figure><p>while learning curves look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRtq_AU5s85gRyDAY9vggw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-s7GkPIduy7uYl9CEVTLUQ.png" /></figure><p>Great result! We cannot see overfitting issues and loss stabilises between around 85/90 epochs.</p><p>In order to give some meaning to the value of the error, we have to look at the target variable. df.target.describe() (and the histogram we plotted earlier) gives us the information we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*pkKWuhScw5kdLtKOsxmcDw.png" /></figure><p>We can see how a mean absolute error of ~2.3 corresponds to an error of more or less the 10% on the average of our data.</p><p><em>NOTE</em>: To make our error estimation more robust, we should operate k-fold cross-validation and take as mean absolute error value the average over the folds. We will neglect this here for the sake of readability.</p><p>Let’s try the other option and modify the number of hidden units and hidden layers.</p><pre>config = {<br>           &#39;data&#39;: boston_dataset,<br>           &#39;train_test_ratio&#39;: 0.2,<br>           &#39;model_config&#39;: {<br>               &#39;model_name&#39;: &#39;house_pricing_model&#39;,<br>               &#39;layers&#39;: {<br>                        &#39;first_layer&#39;: 64, <br>                        &#39;second_layer&#39;: 64,<br>                        &#39;third_layer&#39;: 32,<br>                        &#39;output_layer&#39;: 1<br>                       },<br>                &#39;activations&#39;: [&#39;relu&#39;, &#39;relu&#39;, &#39;relu&#39;, None], # Regression problem: no activation in the last layer.<br>                &#39;loss_function&#39;: &#39;mse&#39;,<br>                &#39;optimiser&#39;: &#39;adam&#39;,<br>                &#39;metrics&#39;: [&#39;mae&#39;]<br>                },<br>            &#39;training_config&#39;: {<br>                &#39;batch_size&#39;: 10,<br>                &#39;epochs&#39;: 100<br>            }<br>           }</pre><p>We added a layer and increased the number of hidden units in each layer. Let’s train with such a configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLEQ061L7Nx8VzMX4Z9tJg.png" /></figure><p>Numbers are slightly improved! Let’s look at learning curves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJNTbArG3JjTbKnNEELGqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVLns2n5DF0jlFl5xHRIgg.png" /></figure><p>They are good, but we start to see the nemesis of any data scientist: overfitting. Around epoch 15/20 training loss became systematically lower than test loss, and such divergence grows with epochs.<br>We can lower the number of epochs, or insert a Dropout layer to reduce the overfit. And so on, until we are happy with the result.</p><p>For our purposes, we will stop here and choose the following configuration.</p><pre>config = {<br>           &#39;data&#39;: boston_dataset,<br>           &#39;train_test_ratio&#39;: 0.2,<br>           &#39;model_config&#39;: {<br>               &#39;model_name&#39;: &#39;house_pricing_model&#39;,<br>               &#39;layers&#39;: {<br>                        &#39;first_layer&#39;: 64, <br>                        &#39;second_layer&#39;: 64,<br>                        &#39;third_layer&#39;: 32,<br>                        &#39;output_layer&#39;: 1<br>                       },<br>                &#39;activations&#39;: [&#39;relu&#39;, &#39;relu&#39;, &#39;relu&#39;, None], <br>                &#39;loss_function&#39;: &#39;mse&#39;,<br>                &#39;optimiser&#39;: &#39;adam&#39;,<br>                &#39;metrics&#39;: [&#39;mae&#39;]<br>                },<br>            &#39;training_config&#39;: {<br>                &#39;batch_size&#39;: 10,<br>                &#39;epochs&#39;: 17<br>            }<br>           }</pre><p><strong>Optuna</strong></p><p>Another more efficient option is to look for the best hyperparameter configuration with a library. <a href="https://optuna.org/"><em>Optuna</em></a> is a library that does exactly this, recently they introduced also an experimental feature looking for the best model architecture. My advice is to try it out.</p><p><a href="https://medium.com/optuna/using-optuna-to-optimize-tensorflow-hyperparameters-57b6d4d316a2">Using Optuna to Optimize TensorFlow Hyperparameters</a></p><p>Hyperparameter optimisation is a really fascinating topic and it would require a series of posts on its own, but for this article, let’s follow our guided-example and go on to build the training pipeline.</p><h4>Pipeline construction</h4><p>Since I want to focus on the serving part, here I will keep the training pipeline simple, however, you can make this as involved as you want. For instance, one can build another app to build and train your model.<br>Strictly speaking, one could also train the model in a notebook than save the model file and export it. This can be done, however, I would advise against it, because a notebook has no versioning system, you cannot check whether you introduced some non-compatibility issues, etc.</p><p>Here we will adopt a half-way solution: we will create a script, taking a config file as input (the only one you should modify in the successive versions of your model) and returning a saved model file.<br>Since we put some attention in writing the cells of our notebook, the script is quite easy to create.</p><p>We will make use of an auxiliary library since our script will be executed by a command-line interface and we want to pass the config file path as an argument without touching the script code.</p><p>The script is really brief and very schematic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5e3d66f6f2388bb7b87d8cd451fbf8c/href">https://medium.com/media/e5e3d66f6f2388bb7b87d8cd451fbf8c/href</a></iframe><p>Note that we imported an utils module, which is a collection of the functions we defined above. Note also that this is not the cleanest way to do things, we could (and normally we should) modularise even more, and even better, create classes collecting methods for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4d9405d108e38598f84cbdf4ac2358c/href">https://medium.com/media/b4d9405d108e38598f84cbdf4ac2358c/href</a></iframe><p>As a bonus, you can transform this training script into a command, <em>i.e. </em>you will turn</p><pre>python3 -m estimator train --conf config.json</pre><p>into</p><pre>estimator train --conf config.json</pre><p>To do so, you can read this nice medium post.</p><p><a href="https://christopherdoucette.medium.com/turning-python-scripts-into-cli-commands-aecf56dfda18">Turning Python Scripts into CLI Commands</a></p><p>The config.json file contains all the information to define and train our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2db8c5e93a6a15a26e748b6c68a63d6a/href">https://medium.com/media/2db8c5e93a6a15a26e748b6c68a63d6a/href</a></iframe><h4>Model training</h4><p>Finally, we are ready to run the proper training of our chosen model. Once the model is fitted, we save it to export and serve it to the next-section-coming API.</p><p>This is automatically done by one single command in a command-line shell:</p><pre>python3 -m estimator train --conf config.json</pre><p><em>NOTE</em>: To not make this too long post even longer, here I am not considering one of the greatest features in Keras: callbacks. One can set a metric and monitor it during training in order to automatically stop the fit when your model does not improve over epochs, or save automatically the best metric result, no matter in which epoch it has been reached, etc. A great source for reference is the <a href="https://www.tensorflow.org/guide/keras/custom_callback">official documentation of Tensorflow</a>.</p><h3>2. Deploy</h3><p>Now that your model is trained and saved somewhere locally, we are able to start the fascinating chapter of deployment.</p><p>By this dark and evil word, we simply mean making our model available and reachable (from users or other applications) in order to provide predictions.</p><p>The scheme is simple: we want to put our model somewhere, make it receive <em>requests</em> and give back predictions. In our example, we want to feed the model with houses (more appropriately with feature vectors describing houses) and get as <em>response</em> price predictions for the house fed in.</p><p>Since we do not want to be the only users or our model, we have to choose a protocol that is publicly (or at least to a certain list of users) accessible from outside our local system.</p><p>One of the major ideas in modern computer science is <a href="https://www.sumologic.com/glossary/container/"><em>containerisation</em></a><em>. </em>By this, we mean bundling an application together with all of its related configuration files, libraries and dependencies required for it to run in an efficient and bug-free way across different computing environments. Going on this path, we split our complex applications into packages and then we compose containers together in other to make them without worrying about the system they are going to be executed on.</p><p>A great source to learn about containers is the nice medium post below.</p><p><a href="https://medium.com/cycleplatform/a-brief-introduction-to-containers-d34e64e61bc1">A Brief Introduction to Containers</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvgKQ2SXt8h2yvMu13eZQA.png" /><figcaption>An even poorlier drawn image by the author. We added the numbers referring to the steps below.</figcaption></figure><p>In this spirit, and following the scheme in the figure above, we have to:</p><ol><li>Create an API to serve our model. We will do this by using FastAPI.</li><li>Containerise our API. We will do this by Docker.</li><li>Push the docker image on some service. We are going to use AWS ECR.</li><li>Deploy the docker container containing the app on some service. We will make use of a virtual machine service: AWS EC2.</li></ol><p>Note that these steps are more or less the same as any other software application to be deployed.</p><blockquote>Data scientist are (among other things) developers and must be able to follow the typical <a href="https://en.wikipedia.org/wiki/Software_release_life_cycle">software life-cycle</a>.</blockquote><p>Indeed one can follow these very same steps also and deploy the “hello world” API (<em>i.e. </em>the to-do list). This is actually a very nice exercise and can be used to practice such a procedure. To develop the to-do list API one can refer to the following article.</p><p><a href="https://surikavii.medium.com/making-a-todo-app-from-a-beginners-perspective-part-1-intro-to-fastapi-5006abbcb7a2">Making a Todo app from a beginners perspective. Part: 1 Intro to FastAPI</a></p><p>Do not get scared, these parts are quite straightforward. Here there is no analysis to take into account, no trial-error approach. The objects we are going to define here are mostly a copy-paste of code handed down for generations of fellow programmers.</p><h4>API Creation</h4><p>We are going to use FastAPI, which is one of the possible web frameworks you can use to convert your Python code into an app communicating by HTTP protocol.</p><p>The advantage of FastAPI is that is fast (almost as a compiled language), easy to learn, widely used (a lot of online support), and it builds handy online documentation for your app.</p><p>So let’s build our app.<br>We need to create the following directory structure:</p><pre>├── __init__.py</pre><pre>├── ai</pre><pre>|  ├── __init__.py</pre><pre>|  ├── regressor.py</pre><pre>|  └── services.py</pre><pre>├── main.py</pre><pre>├── model</pre><pre>|  └── model.h5</pre><pre>└── schemas</pre><pre>|  ├── __init__.py</pre><pre>└──└── schemas.py</pre><p>This is not strictly necessary, you can have everything in the same file (may the gods forgive you), or you can use frameworks structuring your Python project for you, <em>e.g.</em> <a href="https://github.com/cookiecutter/cookiecutter">cookie-cutter</a>. However, I strongly advise following a fixed schema to get used to such structures.</p><p>We will explore each file individually.</p><p>Let’s start from the main, which is the file we are going to launch to execute our app.</p><p><strong>main.py</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ec439e822dcd923058b5192b7c5b781/href">https://medium.com/media/1ec439e822dcd923058b5192b7c5b781/href</a></iframe><p>You can see, the code is quite self-explanatory and even without knowing the exact implementation of the function you can say what this app does at high level. It receives data (of type InputData ) and returns a dictionary (actually a type ResponseDataAPI, see function decorator) containing input data and predictions.</p><p>In FastAPI decorators are used to define the HTTP methods, in our app we only need a get (to check the status of the app) and a post (to send the data and obtain predictions).</p><p>We can run the app locally by the terminal command</p><pre>uvicorn main:app --reload</pre><p>Opening a browser and going to the local address <a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a> we will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui">Swagger UI</a>). You can access the alternative documentation page at <a href="http://127.0.0.1:8000/redoc">http://127.0.0.1:8000/redoc</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rzWBma4fxBRaau4romhNPw.png" /><figcaption>This is what you should see. Image by the author.</figcaption></figure><p>There is plenty of functionalities to explore (and a good reference to look at is always the very well written <a href="https://fastapi.tiangolo.com/">FastAPI documentation</a>), here I just want to mention two main aspects:<br><em>1.</em> The API comes automatically with a web interface. This allows you to show the working scheme of your model even to some non-tech fellow. And this comes for free.<br><em>2.</em> You have an URL that can be interrogated with json strings and responds in the same format. This is really useful to go in production, <em>i.e.</em> you can host this app on a web server and start integrating with other apps, that is the key to production procedures.</p><p>This second aspect may be explicitly interrogated by terminal</p><pre>curl -X &#39;POST&#39; \<br>  &#39;<a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/</a>v1/services/predict&#39; \<br>  -H &#39;accept: application/json&#39; \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;[<br>  {<br>    &quot;CRIM&quot;: &quot;float&quot;, <br>    &quot;ZN&quot;: &quot;float&quot;, <br>    &quot;INDUS&quot;: &quot;float&quot;, <br>    &quot;CHAS&quot;: &quot;int&quot;, <br>    &quot;NOX&quot;: &quot;float&quot;, <br>    &quot;RM&quot;: &quot;float&quot;, <br>    &quot;AGE&quot;: &quot;float&quot;, <br>    &quot;DIS&quot;: &quot;float&quot;, <br>    &quot;RAD&quot;: &quot;float&quot;, <br>    &quot;TAX&quot;: &quot;float&quot;,<br>    &quot;PTRATIO&quot;: &quot;float&quot;, <br>    &quot;B&quot;: &quot;float&quot;, <br>    &quot;LSTAT&quot;: &quot;string&quot;<br>  }<br>]&#39;</pre><p>Note we have to provide the examples in a json collecting all the features we have trained the model on. We may have changed the name, but because of a lack of imagination, we left them unchanged with respect to the initial dataset.</p><p>Thus, for instance, to get a prediction, we can give the terminal command</p><pre>curl -X &#39;POST&#39; \<br>  &#39;<a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/</a>v1/services/predict&#39; \<br>  -H &#39;accept: application/json&#39; \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;[<br>  {<br>    &quot;CRIM&quot;: 0.09178, <br>    &quot;ZN&quot;: 0.0, <br>    &quot;INDUS&quot;: 4.05, <br>    &quot;CHAS&quot;: 0, <br>    &quot;NOX&quot;: 0.510, <br>    &quot;RM&quot;: 6.416, <br>    &quot;AGE&quot;: 84.1, <br>    &quot;DIS&quot;: 2.6463, <br>    &quot;RAD&quot;: 5.0, <br>    &quot;TAX&quot;: 296.0,<br>    &quot;PTRATIO&quot;: 16.6, <br>    &quot;B&quot;: 395.50, <br>    &quot;LSTAT&quot;: 9.04<br>  }<br>]&#39;</pre><p>and the API response will be printed on the screen</p><pre>{<br> &quot;inputData&quot;: <br>  [{<br>    &quot;CRIM&quot;: 0.09178, <br>    &quot;ZN&quot;: 0.0, <br>    &quot;INDUS&quot;: 4.05, <br>    &quot;CHAS&quot;: 0, <br>    &quot;NOX&quot;: 0.510, <br>    &quot;RM&quot;: 6.416, <br>    &quot;AGE&quot;: 84.1, <br>    &quot;DIS&quot;: 2.6463, <br>    &quot;RAD&quot;: 5.0, <br>    &quot;TAX&quot;: 296.0,<br>    &quot;PTRATIO&quot;: 16.6, <br>    &quot;B&quot;: 395.50, <br>    &quot;LSTAT&quot;: 9.04<br>  }],<br> &quot;predictions&quot;: [{&quot;Prediction price 0&quot;: 26.900973}]<br>}</pre><p><strong>ai/regressor.py</strong></p><p>This is the file containing the class definition of our model. We define the PriceEstimator class and give a minimal amount of methods. Usually, you do not want someone can train your model from the API, hence there is no train method for this object. There is the predict one thou since you want to expose your model for predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a81639a6043b6949e27a527a007129b/href">https://medium.com/media/9a81639a6043b6949e27a527a007129b/href</a></iframe><p>You can recognise the very same function we used in the data pipeline. The driving force of any programmer should be laziness. <br>In this context, a cleaner approach would be to simply import the same function from the module we have defined earlier, although this, usually, you want to keep the training part of your code and the prediction part well separated.</p><p><strong>ai/services.py</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40154a880c0ee0c2d18fa519d281ea6a/href">https://medium.com/media/40154a880c0ee0c2d18fa519d281ea6a/href</a></iframe><p>This file contains the code to return the prediction and the load of the model from a pretrained saved file. Note how we read the MODEL_FOLDER variable from the environment. This means (to run the app locally) that we have to add the model path to the environment. How you do this depends on the OS, a quick google search will give you the answer. On linux/mac this can be done in a terminal by</p><pre>export MODEL_FOLDER=&#39;path/to/your/model&#39;</pre><p><strong>schemas/schemas.py</strong></p><p>This file is the one defining the custom types (in Python any object is a type) of input and output of our app.</p><p>Everyone knows Python is a dynamically typed programming language, meaning the type of variables is not declared, bu inferred by their value, and can also change during the execution of a program.<br>This behaviour is really handy since you do not bother in defining variable types, in keeping attention to never assign the same variable name to values of different types, etc. However, this is also one of the main reasons why Python is so slow in comparison with some other statically typed language, like C/C++, Go, etc.<br>For a detailed discussion, one can read <a href="http://gallium.inria.fr/~remy/mpri/cours1.pdf">this extremely interesting reference</a> or the <a href="https://en.wikipedia.org/wiki/Type_system">relative Wikipedia page</a>.</p><p>We already pointed out the reason we want to use a web framework like FastAPI is that it is almost as fast as a compiled language, this is reached by slightly modifying such behaviour about type declaration by allowing it.<br>Hence, we will define and set a fixed type for input and output data.</p><p>This is done by the <a href="https://docs.python.org/3/library/typing.html">typing library</a>, which is not a real type declaration, but more a hint. In such a way, we allow the Python interpreter to allocate the right quantity of memory for the “declared” type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51ccaa0e5ac356a8ec38b65081494a58/href">https://medium.com/media/51ccaa0e5ac356a8ec38b65081494a58/href</a></iframe><p>We defined an example that can be shown on the interactive doc page of FastAPI.</p><p>Note how we defined here the types we declare in the main.py functions.</p><h4>Dockerise the FastAPI</h4><p>We are now ready to dockerise our app. <br>We already discussed why containers are crucial in the modern software industry. Here I just wanna synthesise a problem that docker solves.</p><blockquote><em>A</em>: Look how cool my model is. I’ll send you the script, so you can execute on your machine.<br><em>B</em>: Received, however it gives me an error while importing xxx library, I solved by Stack-Overflow, and now my numbers are different than yours.<br><em>A</em>: Come and look at my screen, here it works as expected.</blockquote><p>If A sent B a docker image, this would have never happened.</p><p>Let’s see how to dockerise our API. To dockerize the application, first, you need a Dockerfile</p><p>Dockerfiles describe how to assemble a private filesystem for a container, and can also contain some metadata describing how to run a container based on the image. (Recall the difference between image and containers, <a href="https://phoenixnap.com/kb/docker-image-vs-container">here</a>).</p><p>We will also use a file called requirements.txt, a list of all the libraries we used in the project and their version. We want our app to run without compatibility issues on any machine.</p><p>As said, the following part can be presented really schematically and here I closely follow the excellent post below, just adapting commands to the present case.</p><p><a href="https://medium.com/@meetakoti.kirankumar/deploying-fastapi-web-application-in-aws-a1995675087d">Deploying FastAPI Web Application in AWS</a></p><p><em>i) Create a docker file</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5ba7295ec18417b6a106f57da4e88bf/href">https://medium.com/media/b5ba7295ec18417b6a106f57da4e88bf/href</a></iframe><p>Here we make our app run at the address <a href="http://0.0.0.0:5000/"><em>http://0.0.0.0:5000</em></a>. <br>Note how we defined the model location as an environment variable: this is because our app reads such value from the environment.</p><p><em>ii) Build Docker Image:</em></p><p>This is done by a line command</p><pre>docker build -t price_estimator_api:latest .</pre><p><em>iii) Run the docker image</em></p><p>Now the easy part: let’s run the docker.</p><pre>docker run -p 5000:5000 price_estimator_api:latest</pre><p>You can verify the app running by opening a browser at the page <a href="http://localhost:5000/docs"><em>http://localhost:5000/docs</em></a><em>.</em></p><p>To learn more about Docker, you can look at the official tutorials.</p><p><a href="https://docs.docker.com/get-started/overview/">Docker overview</a></p><h4>Push on Amazon Elastic Container Registry</h4><p>Now that you verified that your app container is running locally, we are ready to move it to some accessible “place”. This can be any server with public (or at least non-local) access. Here we want to use the AWS EC2 service.</p><p>We do not want to bother thinking about machine configuration, scalability, etc. So we will put the docker image on a docker registry, the Amazon Elastic Container Registry (ECR). This is a fully-managed <a href="https://aws.amazon.com/docker/">Docker</a> container registry that makes it easy for developers to store, manage, and deploy Docker container images.</p><p>First, in order to push docker images to ECS, you need to install and configure AWS CLI. Instructions are available on the AWS website.</p><p><a href="https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-mac.html">Installing, updating, and uninstalling the AWS CLI version 2 on macOS</a></p><p>One way to configure the AWS CLI is getting access key ID and Secret Access Key from <strong>Identity and Access Management (IAM) in the AWS console.</strong></p><p>You simply create new access keys and store them for future purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZIM1md6RzCpiHPSo.png" /></figure><p>In a terminal, you can configure access.</p><pre>aws configure</pre><pre>AWS Access Key ID [None]: <strong><em>AKIAIOSFODNN7EXAMPLE</em></strong><br>AWS Secret Access Key [None]:<strong><em>wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY</em></strong><br>Default region name [None]: <strong><em>eu-west-3</em></strong><br>Default output format [None]:<strong><em>json</em></strong></pre><p>You are now ready to access ECR using the following command, provide <strong>region </strong>and <strong>account id</strong> details.</p><pre>aws ecr get-login-password  --region <strong>region</strong> | docker login --username AWS --password-stdin <strong>aws_account_id.</strong>dkr.ecr.<strong>region</strong>.amazonaws.com</pre><p>You should see<strong> “Login Succeeded” </strong>on the console if everything goes well.</p><p>You can now push your image on the AWS registry.<br>First, create a repository.</p><pre>aws ecr create-repository --repository-name price_estimator_api</pre><p>Tag your image in order to push on the registry.</p><pre>docker tag price_api:latest <strong>aws_account_id</strong>.dkr.ecr.<strong>region</strong>.amazonaws.com/price_estimator_api</pre><p>Finally, run the command to push the image on ECR.</p><pre>docker push <strong>aws_account_id</strong>.dkr.ecr.<strong>region</strong>.amazonaws.com/price_estimator_api</pre><h4>Deploy on EC2</h4><p>After pushing the docker image to AWS ECR, we are now ready to create Amazon EC2 instance which can serve your web application. AWS offers many instances in the free tier, I have chosen a Linux instance in this case (you can use other instances as well but do remember to change the configuration accordingly).</p><p><em>i ) Go to Amazon Console; select Amazon Linux EC2 instance.</em></p><p><em>ii) Choose general purpose t2.micro instance type, for example.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_u1WW-CiD9pCu2Ej.png" /></figure><p><em>iii) Change the security settings by adding rules using custom TCP as type and port as 5000 (we exposed that port of the API) and click on review and launch the instance. These configurations are necessary for our web application to run.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ki9YCYS7P6ka9z1F.png" /></figure><p><em>iv) Create a new key pair by selecting from the dropdown “</em>Create a new key pair<em>”, provide a name for the key pair, and download it.</em></p><p>A key pair, consisting of a private key and a public key, is a set of security credentials that you use to prove your identity when connecting to an instance.</p><p>You should able to see the instance running.</p><p>You downloaded the key pair, so a .pem key. Suppose we gave the name priceestimator.pem , we can use such a file to log on to the EC2 by using a secure ssh connection.</p><pre>ssh -i priceestimator.pem ec2-user@<strong>ec2-18-221-11-226.us-east-2.compute.amazonaws.com</strong></pre><p>One logged in, we install the docker on the EC2, configure AWS access to give rights to the machine to access our docker image, and pull the docker container to the machine.</p><p>AWS configuration starts as above,</p><pre>aws configure</pre><pre>AWS Access Key ID [None]: <strong><em>AKIAIOSFODNN7EXAMPLE</em></strong><br>AWS Secret Access Key [None]:<strong><em>wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY</em></strong><br>Default region name [None]: <strong><em>eu-west-3</em></strong><br>Default output format [None]:<strong><em>json</em></strong></pre><p>Then we run the following commands to add ec2 user to perform docker commands in Linux machine.</p><pre>sudo groupadd docker</pre><pre>sudo gpasswd -a ${USER} docker</pre><pre>sudo service docker restart</pre><p>Exit the instance and ssh into the EC2 instance again.</p><pre>ssh -i priceestimator.pem ec2-user@<strong>ec2-18-221-11-226.eu-west-3.compute.amazonaws.com</strong></pre><p>Log into the Amazon ECR registry:</p><pre>aws ecr get-login --region <strong>region</strong> --no-include-email</pre><p>output</p><pre>docker login -u AWS -p &lt;password&gt; -e none https://&lt;aws_account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com</pre><p>Copy the output from the above and run it in the command line. Once you are successfully logged into AWS ECR, you can see “Login Succeeded” in the console.</p><p>Pull the docker image from AWS ECR on the EC2.</p><pre>docker pull <strong>aws_account_id</strong>.dkr.ecr.<strong>region</strong>.amazonaws.com/price_estimator_api:latest</pre><p>Run the docker container in the Linux Machine</p><pre>docker run -p 5000:5000 <strong>aws_account_id</strong>.dkr.ecr.<strong>region</strong>.amazonaws.com/price_estimator_api</pre><p>Finally, we can get the IPv4 Public IP from the instance details page and add port 5000 while launching it in the browser. This will show the API running on EC2. <br>Now you can substitute such an IP address with a more human-readable URL.</p><p>Enjoy!</p><h3>4. Maintenance</h3><p>And finally the dessert: maintaining the deployed app is crucial. A change in data distribution may result in no predictive power of your model.</p><p>Now your model works fine, lucky you. You are happy and ready to repeat the story for another client and another model.</p><p>However, the real estate agency starts to get some houses to sell in a very different location. They use your model and they find your estimate completely wrong! They are angry at your company, your boss starts to tell you off about the awful job you have done.</p><p>How would you handle this?</p><p>Fortunately, by acting as you have done you can easily deploy a new model, by training on new data and make your model more accurate on the new data distribution. Let’s see how.</p><p>What we have done previously is not lost. We can load the current model and use it as a starting point for a new train. We make leverage of previously learnt weights and we simply train our model on new data. If necessary (you want to completely change your model, for some reason) you can also develop a new model. If you coded properly, nothing should change in the whole pipeline.</p><p><strong>Load the current model</strong> <strong>as pretrained</strong> in config.json. Now you can relaunch the training script and get the newly trained model. Change the save model name to keep versioning.</p><p><strong>Save the new model </strong>As before, we save the model in the folder the API is going to read. We can add the date-time reference in the naming convention in order to keep track of versions.</p><p><strong>Modify the Dockerfile </strong>Since we version our app, we modify the Dockerfile to get the right model version to be deployed.</p><p>Finally, <strong>push the Docker image</strong> and make it run as above.</p><p><em>NOTE: </em>It’s usually advisable to write the deploy part as a pipeline, that starts automatically at every push on some git repository. All git control systems offer the possibility to register safely some repository environment variables. One can set some secret AWS credentials there and automatise this part. For more information, look at the following tutorial, for example.</p><p><a href="https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/">Get started with Bitbucket Pipelines | Bitbucket Cloud | Atlassian Support</a></p><h3>Conclusions</h3><p>First of all, let me congratulate you if you have read till here! This post has become a little longer than I expected.</p><p>To sum up, I tried to summarise, working through a concrete example, how the typical data science project develops, to my experience. I would like to warn you: this is not the complete story. There are a lot of points I missed and neglected, a lot of caveats, a lot of different requests, etc.</p><p>For instance, another possibility might be to not bother at all with containers and services and convert our model in some other language, easily runnable online. <br>For a web app, for example, one may convert the model in JavaScript (making use for instance of TensorFlowJS or TorchJS running models on a browser) and then build a website to be hosted on some server. This is an example of a specific case. Indeed, this is accessible through a website, but what if you need an app to access this? Or some other non-human service?</p><p>Docker is a more general and widely used method, this is why I have chosen to present it here.<br>Hence, without being complete, this post aimed to illustrate — in a schematic way — the lifecycle of a machine learning project.<br>I hope this can be useful both to junior data scientists, often feeling lost in this wide world, and to more expert figures that can also give me some hint about the points I surely forgot.</p><p>I hope you enjoyed reading this!</p><blockquote>IMPORTANT: I publish this post also to get suggestions, to discuss and to be made aware of points of weakness in my coding. Please, signal any mistakes/reduntant code! 😫</blockquote><p>🤯 <strong><em>Have you seen what happens if you click the “clap” button multiple times?</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9e0357525cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-design-to-deploy-the-whole-lifepath-of-a-machine-learning-app-e9e0357525cc">From Design to Deploy: The whole lifepath of a Machine Learning app</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Full(Stack) Story of a Text Classifier]]></title>
            <link>https://medium.com/deep-recommender-system/the-full-stack-story-of-a-text-classifier-842abad9ff16?source=rss-5b4c877fa451------2</link>
            <guid isPermaLink="false">https://medium.com/p/842abad9ff16</guid>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[website-design]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Oscar de Felice]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 07:15:14 GMT</pubDate>
            <atom:updated>2022-04-20T13:52:50.132Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://oscar-defelice.github.io/">Hands-on Tutorials</a></h4><h3>The Full (Stack) Story of a Text Classifier</h3><h4>How to build a simple text classifier and deploy it through a web app</h4><figure><a href="https://oscar-defelice.github.io/txt-clf-api.github.io/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLKwLa7QFQa5Lmp5iqLNLQ.png" /></a></figure><p>One nice day an idea came to your mind: I can make big money by selling a machine learning model to a company that might be interested in it.</p><p>You like the idea, and you decide you want to address a company with a press department and sell a text classifier. You feel excited.</p><p>However, at this stage, reality strikes you hard: “<em>I am a data scientist, I can build a great classifier, but when I show my code at managers, they look at it as I would look at hieroglyphs</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*T24cMuwNl3cPtEiJ.jpg" /><figcaption>If you get this reaction, feel lucky. Image created by the author on the base from <a href="https://facciabuco.com/">https://facciabuco.com</a></figcaption></figure><p>Well, your worries are over! Go through this article and you will be able to create and publish your website classifying texts.</p><h4>What are we going to do?</h4><p>In the end, we will build a website like <a href="https://oscar-defelice.github.io/txt-clf-api.github.io/">this</a>, through the following steps</p><ol><li>We create a classifier in Python, making use of a Deep Learning model written with Keras API.</li><li>Convert Keras model (an .h5 file) to a <a href="https://www.tensorflow.org/js">TensorFlow.js</a> file (.json).</li><li>Convert Keras tokeniser to a .json file to be parsed in JavaScript.</li><li>Write a JavaScript program to load the model, the tokeniser, and to write a function to perform inference.</li><li>Write an HTML code to nicely put all of this in a webpage.</li></ol><p>For points one to three, one can make reference to this <a href="https://github.com/oscar-defelice/TextClassifierModels">GitHub repository</a> or to its <a href="https://colab.research.google.com/drive/1nh9QvDu3YgceQ2PH5DZz3pnYbGljtpIF?usp=sharing">Colab version</a>.</p><p>For the others, <a href="https://github.com/oscar-defelice/txt-clf-api.github.io">here another repository</a> containing the relevant code.</p><h3>Let’s build the model in Python</h3><p>As a data scientist, you are not afraid of this (and you can potentially substitute this part with whatever model you like).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*3Xvw9SxcOPVjx-sS.jpg" /><figcaption>Image created by the Author on the base from <a href="https://imgflip.com/">https://imgflip.com/</a></figcaption></figure><p>For these reasons, I am not going too much in-depth with this, one can refer to other excellent publications to see how to build different models in Keras.</p><h4>Load data</h4><p>To write this piece, we used one of the Tensorflow datasets available, in particular the <a href="https://www.tensorflow.org/datasets/catalog/ag_news_subset">AG News subset</a>. It is a dataset made up of 120 000 news labeled in four (balanced) categories, World, Sports, Business, Sci/Tech news.</p><p>We can download the dataset from <a href="https://www.kaggle.com/amananandrai/ag-news-classification-dataset">Kaggle</a> and import train and test sets from csv.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31f4e7a297f810ffe5e9b6b17f09f961/href">https://medium.com/media/31f4e7a297f810ffe5e9b6b17f09f961/href</a></iframe><p>Without performing too much feature engineering (it is not our scope here), let’s simply tokenise Text column and pad sequences to a fixed length.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f3f6d78fb0e3d73b3e075659b59e35/href">https://medium.com/media/42f3f6d78fb0e3d73b3e075659b59e35/href</a></iframe><p>To conclude our ETL process, we just need to one-hot encode labels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8daebb7a0a7d60d2b44a5a8663209e93/href">https://medium.com/media/8daebb7a0a7d60d2b44a5a8663209e93/href</a></iframe><h4>Build the model</h4><p>We are ready to build the classifier model, we define a couple of hyper-parameters and we are ready,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/072042af0ca98b8b258bb048d01b69b0/href">https://medium.com/media/072042af0ca98b8b258bb048d01b69b0/href</a></iframe><p>Hence, the model. We choose a CNN model, as it guarantees both quite a good performance and a short training time. One can use whatever model available, as one of the <a href="https://en.wikipedia.org/wiki/BERT_(language_model)">Bert gang</a>, <a href="https://arxiv.org/abs/1906.08237">XLNET</a>, or some other transformer model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8c8f0ab73cffe2af36cbff61ddae373/href">https://medium.com/media/b8c8f0ab73cffe2af36cbff61ddae373/href</a></iframe><pre>====================================================================</pre><pre>Model: &quot;sequential&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>embedding (Embedding)        (None, 75, 64)            4079296   <br>_________________________________________________________________<br>dropout (Dropout)            (None, 75, 64)            0         <br>_________________________________________________________________<br>conv1d (Conv1D)              (None, 75, 50)            9650      <br>_________________________________________________________________<br>max_pooling1d (MaxPooling1D) (None, 37, 50)            0         <br>_________________________________________________________________<br>dropout_1 (Dropout)          (None, 37, 50)            0         <br>_________________________________________________________________<br>conv1d_1 (Conv1D)            (None, 37, 100)           15100     <br>_________________________________________________________________<br>max_pooling1d_1 (MaxPooling1 (None, 18, 100)           0         <br>_________________________________________________________________<br>dropout_2 (Dropout)          (None, 18, 100)           0         <br>_________________________________________________________________<br>conv1d_2 (Conv1D)            (None, 18, 200)           60200     <br>_________________________________________________________________<br>global_max_pooling1d (Global (None, 200)               0         <br>_________________________________________________________________<br>dropout_3 (Dropout)          (None, 200)               0         <br>_________________________________________________________________<br>dense (Dense)                (None, 100)               20100     <br>_________________________________________________________________<br>activation (Activation)      (None, 100)               0         <br>_________________________________________________________________<br>dropout_4 (Dropout)          (None, 100)               0         <br>_________________________________________________________________<br>dense_1 (Dense)              (None, 4)                 404       <br>_________________________________________________________________<br>activation_1 (Activation)    (None, 4)                 0         <br>=================================================================<br>Total params: 4,184,750<br>Trainable params: 4,184,750<br>Non-trainable params: 0<br>_________________________________________________________________</pre><h4>Training</h4><p>We trained the model above for 7 epochs and a batch size of 64. The results can be displayed easily by making use of classification_report of <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html">sklearn</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c18a38d52e2251abf6850fd0abd3f277/href">https://medium.com/media/c18a38d52e2251abf6850fd0abd3f277/href</a></iframe><p>Hence, the performances are the following,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqWq5sbNzaJ0LoBVOAQNRA.png" /><figcaption>Performances are not bad, also because classes are balanced. Image by Author</figcaption></figure><blockquote>So our model is trained and complete. How to make it running in production? How put it under the hood of a webpage?</blockquote><h3>Convert the model from Keras to Tensorflow.js</h3><p>In order to integrate the model in a web script, we need to convert it into a proper form.</p><p>First, we need to install TensorFlow JS. This is done by the usual command</p><pre>pip install tensorflowjs</pre><p>Once the installation is completed, we can export the Keras model in .h5 format,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4bd43acd55407ee78b209b1120ab58a/href">https://medium.com/media/b4bd43acd55407ee78b209b1120ab58a/href</a></iframe><p>and hence convert it in .json with the Tensorflow js command,</p><pre>tensorflowjs_converter --input_format=keras modelCNN.h5 ./model/</pre><p>This command will produce a model .json file and some weights .bin files (how many depends on model dimensions), these files are the ones that will be loaded in the JavaScript model.</p><h4>The Tokeniser issue</h4><p>To provide predictions, as one can see from the model summary above, we do not feed the model with strings, we need a tokeniser to convert text to vectors*.</p><p><strong><em>*NOTE: </em></strong><em>There is another way: building the model with an Input layer taking </em>tf.strings<em> as input and operate the conversion with a </em>TextVectorizer<em> layer. This, however, implies estimating a huge number of parameters, making the whole model by far heavier, more difficult to train, and eventually less robust.</em></p><p>There are various ways to perform such a conversion, here we used Keras Tokeniser, which simply maps each word in our corpus to an integer. This means to have a dictionary having as keys word in the vocabulary and as values the integer corresponding to each word.</p><p>When we are going to enter the text to be classified in our web page, we need to convert it in a form the model can digest, to do it coherently, we need such a map, so we have to export the tokeniser in a form JavaScript can read.</p><p>JSON format comes to the rescue. The command to export the dictionary is the following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69a157badb41f69dad6bf7cd77e83883/href">https://medium.com/media/69a157badb41f69dad6bf7cd77e83883/href</a></iframe><p>We have all the components we need to build our webpage, so let’s abandon Python and move to build a simple webpage containing our model and taking texts as input, and performing inference on those.</p><h3>TensorFlow JS model</h3><p>We are now ready to build our webpage, by composing a script in JavaScript to serve an HTML webpage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*3lek8t4QaphFPQ6n.png" /><figcaption>Copy and paste: one of the best resources of the FullStack Overflow developer. Image under Creative Commons license from <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fthenounproject.com%2Fterm%2Fcopy-and-paste%2F661787%2F&amp;psig=AOvVaw1C6pZZ0O9jZlFNiwj0lYWP&amp;ust=1604560908229000&amp;source=images&amp;cd=vfe&amp;ved=0CAMQjB1qFwoTCLja3LGt6OwCFQAAAAAdAAAAABAE">Noun Project</a>.</figcaption></figure><p>I am not an expert in web development, so for the HTML part I just took ready stuff on the web and modified it for my purposes, however, for the JavaScript part, TensorFlow JS allows building models, and also train them directly in a browser. A good place to look for more information about is the <a href="https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development">official site of TensorFlow JS</a>, whose documentation is excellent and a brief course is provided.</p><h4>The HTML structure</h4><p>We are going to compose a plain web page, for more fancy appearances, one can write or import a CSS style file to configure the layout of the page.</p><p>The following HTML code imports TensorFlow JS and hence defines an input box where the final user can insert the text he wants to classify. Finally, we define a button to give the command predict.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4673f0d5b1e212608a9ec6e865226b96/href">https://medium.com/media/4673f0d5b1e212608a9ec6e865226b96/href</a></iframe><p>Note that here we focused on the basic stuff, you can beautify to the extent you like by adding options to HTML tags.</p><p>Without standing too much at HTML, we need to notice that the code above just builds the layout of our page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l-GOvBugB1FSU51kAC2KJA.png" /><figcaption>You should get something like this. Image by Author</figcaption></figure><p>To define the model for inference, how to use the input text, what to actually do when clicking the “Predict” button, we need to write another piece of code, the JavaScript part (we store this in a file called model.js as indicated in the HTML page). This is the aim of the next section.</p><h4>Load model in JavaScript</h4><p>The principle scheme is quite easy and analogous to its Python counterpart.</p><p>To predict a user-input text, we need the following</p><ol><li>Encode the text to feed the model making use of the tokeniser map. The result of this part is a numerical vector, being the encoding of the <em>wannabe-classified</em> text.</li><li>Run model inference on the input text vector.</li></ol><p>These two steps are the same we are going to do in JavaScript.</p><p><strong>Load Tokeniser</strong></p><p>First, we need to load the Tokeniser in JavaScript. Recall we exported the word-to-index map as a JSON file exactly for this reason.</p><p>The piece of code importing such a map can be written as follows,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7c768315665081347f331bb16158f9b/href">https://medium.com/media/c7c768315665081347f331bb16158f9b/href</a></iframe><p>where, vocabPath is the path of the JSON file.</p><p>We are not going into details about why we want to use asynchronous functions here, but a partial explanation is that we do not want our webpage to freeze when we wait for JSON loading.</p><p><strong>Use Tokeniser</strong></p><p>We are ready to define a function to encode input texts,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/946e0aae6ed82bb032796e1b26ca690d/href">https://medium.com/media/946e0aae6ed82bb032796e1b26ca690d/href</a></iframe><p>This does exactly what you would do to preprocess a text in Python. The function takes a string as input and returns its vector representation, based on tokeniser. Note that the tokeniser is correctly the one we trained on our data using Keras.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VsFrz6Xhw0vSZWRz" /><figcaption>Can you see the light at the end of the tunnel? Photo by <a href="https://unsplash.com/@adrienolichon?utm_source=medium&amp;utm_medium=referral">Adrien Olichon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Model inference</strong></p><p>What is left? The model!</p><p>Until now, we did not make use of TensorFlow JS. We are going to make up for this right now. Converter Keras model can be loaded in JavaScript very easily,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3915be481a83cfcb4380d3751c16b980/href">https://medium.com/media/3915be481a83cfcb4380d3751c16b980/href</a></iframe><p>where again, modelPath is the location of the model, note how we used the loadLayersModel function built in TensorFlow JS, this returns a model object which will serve us for inference.</p><p>Let’s go back for a second to the HTML, when we defined the button “Predict”, we gave it the instruction onclick=”predict()”, meaning — as one may expect — that on click the function predict has to be executed.</p><p>Hence, we only need to write such a function. Let us put it here and then we will explain its relevant details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/023253608d4ce2d4269caee7f482bcec/href">https://medium.com/media/023253608d4ce2d4269caee7f482bcec/href</a></iframe><p>First of all, tf.tidy is one of the great features of TensorFlow JS. This is a method that executes the functions given as arguments and after the execution, cleans up all intermediate tensors allocated in the process, except those returned by functions. Such behaviour is really important especially in a web execution when you know nothing (or you do not want to think) about the infrastructures that will host your page.</p><p>The first part of the function makes the actual prediction. First, it takes the input text from the webpage input box and stores it in a string variable we called (in an effort of fantasy) text. The text is hence tokenised, and then given to the model making predictions. Of course, we get a vector of probabilities (recall we defined a Neural Network with a softmax activation at the output layer), so we use argmax to get the index of the maximum probability.</p><p>At this stage, we just need to print the prediction on screen. The most immediate way to achieve this is to define a variable populated according to prediction values, being the text to be printed. This is what the switch statement precisely does.</p><p>The only thing we are left with is to print the predictionText in the HTML element we called “prediction”. That’s all!</p><p>Now you have your classifier hosted on a webpage. To publish it, you need a web hosting service, you can pay for a domain or go for a free one, my suggestion is to go for the free <a href="https://pages.github.com/">GitHub pages</a> if you do not need anything too fancy (and the webpage we just built is not).</p><h3>That’s All. Tired Right?😴</h3><p>We are at the end of this long post.</p><p>I hope you enjoyed it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FWuGSL4LFUMQU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Foooh-WuGSL4LFUMQU&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FWuGSL4LFUMQU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="339" frameborder="0" scrolling="no"><a href="https://medium.com/media/e787ab5919c4a986e9adfb5a949eb080/href">https://medium.com/media/e787ab5919c4a986e9adfb5a949eb080/href</a></iframe><p>I think the integration between various environments is interesting and can give inspiration for nice applications of machine learning web interfaces. Here we just built a predictor, but with TensorFlow JS you can also train a whole model in the browser, make transfer learning and even save and download your model weights. I leave you with another example making use of your webcam to perform hand gesture recognition <a href="https://oscar-defelice.github.io/handgesture.github.io/">here</a>. Have fun!</p><blockquote>IMPORTANT: I publish this post also to get suggestions, discussion and to be made aware of points of weakness in my coding. Please, signal any mistakes/reduntant code! 😫</blockquote><p>🤯 <strong><em>Have you seen what happens if you click the “clap” button multiple times?</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=842abad9ff16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deep-recommender-system/the-full-stack-story-of-a-text-classifier-842abad9ff16">The Full(Stack) Story of a Text Classifier</a> was originally published in <a href="https://medium.com/deep-recommender-system">DeepBenBello</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Recommender System]]></title>
            <link>https://medium.com/deep-recommender-system/a-deep-recommender-system-e2b765d27350?source=rss-5b4c877fa451------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2b765d27350</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[triplet-loss]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[content-based-filtering]]></category>
            <dc:creator><![CDATA[Oscar de Felice]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 10:59:11 GMT</pubDate>
            <atom:updated>2022-04-20T13:53:59.915Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to build an hybrid recommender system based on triplet loss, embedding layers and making use of Keras.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Dd35c5cUTg8C8iI9YuibUA.png" /></figure><p>The aim of this post is to describe how one can leverage a deep learning framework to create a hybrid recommender system <em>i.e.</em> a model exploiting both content and collaborative-filter data. The idea is to tackle issues in two different steps: first collaborative filtering and content based model separately, then a combination of the two, to get better results.</p><h3>Introduction</h3><p>Before diving into recommender system, we have been recommended to introduce ourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*yrhJ5WBr-1FCaMu_BKu6QA.png" /></figure><p>We are a team of four good friends with different coding backgrounds, ranging from very limited to advanced coding experience. We all come from Physics studies (different specialisations, though), and we work in different areas. By creating <a href="http://deepbenbello.ai/"><strong>DeepBenBello.ai</strong></a>, we made a little dream come true. We wanted to have something to work on together, to start engaging with tech applications and to create something beautiful. Hence this story is the first of a long series, we hope. Stay tuned!</p><p>Back to the recommender system, the goal is to design and develop an hybrid algorithm based on <a href="https://arxiv.org/pdf/1205.2618.pdf"><em>Bayesian Personalised Ranking triplet loss</em></a><em> </em>and implementing such a system in Keras.</p><h4>What Types of Recommender Systems Exist?</h4><p>As a quick introduction, let’s try to briefly describe the various types of recommender system. We can split recommender systems in two classes:</p><ul><li><strong>Collaborative filtering</strong></li><li><strong>Content based</strong></li></ul><p><strong>Collaborative filtering</strong> assumes that users with similar tastes in the past will have similar tastes in the future. Netflix uses a variant of CF to recommend movies and shows you might like based on similar users’ tastes in similar movies. <strong>Content-based</strong> filtering assumes that a user will like items in the future that share features — like brand, cast, genre, etc. — with items they liked in the past. Amazon uses a variant of CBF to recommend books you might want to read.</p><h3>Encoding and Embeddings</h3><p>Often data are not as simple as we would like them to be. To put them in a format an algorithm can digest (that is <em>numbers</em>) we can make use of different tools.</p><p>Both encoding and embedding map categorical data in numerical vectors. The difference between the two is the fact that an encoder (like <strong>one-hot encoder</strong>) is a predetermined function associating a vector to each data row, while embedding vectors are low dimensional and learned. A neural network learns how to locate objects in an embedding space, placing similar entities close to each other.</p><p>To summarise, an <strong>encoding</strong> maps a categorical feature in a <em>m</em>-dimensional vector, where <em>m </em>is the number of categories of the feature. An <strong>embedding</strong> maps categorical features in an <em>n</em>-dimensional vector, where <em>n</em> is an hyper-parameter of the model.</p><p>A more detailed discussion about embedding can be found in the excellent post below.</p><p><a href="https://towardsdatascience.com/light-on-math-ml-intuitive-guide-to-understanding-glove-embeddings-b13b4f19c010">Light on Math ML: Intuitive Guide to Understanding GloVe Embeddings</a></p><p>The reason we prefer to use embeddings here is because it does not really make sense to treat each categorical value as being completely different from one another (this is <strong>one-hot-encoding</strong>). In our working case, we aim to build an hybrid recommender system to propose movies to users. Imagine you want to take into account user age range to get rid which movies they are more likely to appreciate. Is it correct to consider “equally different” a 29-years old user from a 31-years old and from a 62-years old? Embeddings will solve this issue. Indeed, we can make use of this technique to “learn” the relationships and inner connections between each possible value and our target variable.</p><p>Embeddings are based on a training of a Neural Network with the categorical data, in order to retrieve weights from the Embedding layer. This allows us to have a more significant input when compared to a single One-Hot-Encoding approach, furthermore, we introduce a <em>metric space </em>— that is the<strong><em> Embedding space</em></strong><em> </em>— in<em> </em>where similar entities are close.</p><p>Finally, let’s have a look at our data.</p><h3>The dataset</h3><p>For this application we use the notorious <a href="http://files.grouplens.org/datasets/movielens/"><em>movielens dataset</em></a><em>. </em>We have in mind to build an hybrid recommender system, taking advantage from both users and movies features and from user/movie ratings. These data are stored in three different dataset, users.dat , movies.dat and ratings.dat.</p><p>The <a href="http://files.grouplens.org/datasets/movielens/ml-1m-README.txt"><em>readme</em></a> of the dataset contains a quite exhaustive explanation of the files. User information contains gender, occupation, age range and zip-code (note: we drop the latter as it is plenty of zip-codes referring to just one user), while movie dataset contains (further than movie id) title and genre. Ratings are what will drive the supervised training.</p><p>Ratings dataframe can be reshaped in a (sparse) matrix as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2393a2fce569d4e46ed61c2359496c6/href">https://medium.com/media/c2393a2fce569d4e46ed61c2359496c6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsT43t8mYnCJiAWyiBStGg.png" /><figcaption>As one can see the matrix is sparse, as the majority of couples user-movie is not rated.</figcaption></figure><p>Here how we are going to use the information stored in this matrix. Our training set will be made of <strong>triplets </strong><em>[user, liked movie, not liked movie]</em>. This takes as inspiration a neural network architecture for image recognition, called <a href="https://en.wikipedia.org/wiki/Siamese_neural_network"><em>Siamese Architecture</em></a><em>.</em> According to Wikipedia, Siamese Neural Network is defined as</p><blockquote><strong><em>Siamese neural network</em></strong><em> is an </em><a href="https://en.wikipedia.org/wiki/Artificial_neural_network"><em>artificial neural network</em></a><em> that use the same weights while working in tandem on two different input vectors to compute comparable output vectors. Often one of the output vectors is precomputed, thus forming a baseline against which the other output vector is compared. This is similar to comparing </em><a href="https://en.wikipedia.org/wiki/Fingerprint"><em>fingerprints</em></a><em> or more technical as a distance function for </em><a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing"><em>Locality-sensitive hashing</em></a><em>.</em></blockquote><p>This is often used in conjunction with <a href="https://en.wikipedia.org/wiki/Triplet_loss"><em>Triplet loss</em></a>, again according to Wikipedia:</p><blockquote><strong><em>Triplet loss</em></strong><em> is a </em><a href="https://en.wikipedia.org/wiki/Loss_function"><em>loss function</em></a><em> for </em><a href="https://en.wikipedia.org/wiki/Artificial_neural_network"><em>artificial neural networks</em></a><em> where a baseline (anchor) input is compared to a positive (truthy) input and a negative (falsy) input. The distance from the baseline (anchor) input to the positive (truthy) input is minimized, and the distance from the baseline (anchor) input to the negative (falsy) input is maximized.</em></blockquote><blockquote><em>It is often used for </em><a href="https://en.wikipedia.org/wiki/Similarity_learning"><em>learning similarity</em></a><em> of for the purpose of learning embeddings, like </em><a href="https://en.wikipedia.org/wiki/Word_embedding"><em>word embeddings</em></a><em> and even </em><a href="https://en.wikipedia.org/wiki/Thought_vector"><em>thought vectors</em></a><em>, and </em><a href="https://en.wikipedia.org/wiki/Metric_learning"><em>metric learning</em></a><em>.</em></blockquote><p>In triplet loss basically, we have a triplet as input — (<em>anchor, positive, negative</em>). Anchor can be any image of the person, positive is some other image of the same person and negative is an image of different person. The loss function can be described as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*FnTu9ta7tQEvOl7ZrJp7Eg.png" /></figure><p>where 𝛿<em>(a,p)</em> is the distance between anchor image and positive image. Similarly, 𝛿<em>(a,n)</em> is the distance between anchor and negative image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*H-gKds4bIXuGs7TvuusY5w.png" /></figure><p>In the training phase we try to minimise such a loss.</p><p>A recommender system can be seen in the same way. We have an <em>anchor user, </em>and two recommended items, <em>positive</em> and <em>negative</em>, meaning the recommendation should associate the user to the positive item and penalise the negative one.</p><h3>Bayesian Personalised Ranking</h3><p>As one may notice, the main difference between our recommender system and the image recognition task is the fact that user and items are different things. We need a function to optimise, as the triplet loss one, such that in the training phase we push up the probability of recommending the positive samples and push down the probability of the negative sample by adjusting model parameters.</p><p><a href="https://arxiv.org/abs/1205.2618">Bayesian Personalized Ranking</a> criterion comes to help. The function can be expressed like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Val7boBfo4pncxfta3HJtQ.png" /></figure><p>where 𝜎 denotes the <a href="https://en.wikipedia.org/wiki/Sigmoid_function"><em>sigmoid function</em></a><em> </em>while user, positive item and negative item are represented by their embedding vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WT2-VtOrFXB-5u7K6KXOQ.png" /><figcaption>A poorly drawn slide, showing how minimising BPR Triplet loss function is equivalent to maximising the <em>distance between (Anchor, Positive item) and (Anchor, Negative item).</em></figcaption></figure><p>It is noteworthy that we are now able — in a quite simple way — to leverage user and item features but also to take into account previously expressed feedbacks. This is precisely an hybrid recommender system. I think this may express clearly the power of the embedding tool.</p><h3>The model</h3><p>Let’s put all of this in a neural network model. We are going to use Keras functional API.</p><p>First we need to create a network to be trained. Keras does not have a triplet loss layer, so we have to define a custom one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d9c25035f5b5c1f89c22a688a6bc27c/href">https://medium.com/media/1d9c25035f5b5c1f89c22a688a6bc27c/href</a></iframe><p>Hence we can define the layers adapted to receive user and movie vectors. To do so we need to define an Embedding layer for users and one for items. After that we are ready to define the model. This is done by a function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d755cc131d22157035f6580f2052f7f/href">https://medium.com/media/3d755cc131d22157035f6580f2052f7f/href</a></iframe><p>This gives the model represented in the figure below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csrlDSeMUmXatPaUnMzp8w.png" /><figcaption>Note how item input layers share the same weights.</figcaption></figure><h4>Some comments</h4><p>At this stage, It is good to take a breath and have a look at the code defining the model above.</p><p>We made use of Keras functional API to build the network. Note how we defined layers before applying to other layer objects. This allows us to have weights shared by positive and negative items.</p><p>A further noteworthy aspect of the function above is that it returns actually two models: one to train, the other to predict. This because, as mentioned above, BPR Triplet Loss is not something already implemented in Keras. To be sure the two returned models are actually the same except for the last layer, we can print the `layers` attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQ9tINNg6g7ZWTbenJcN7A.png" /><figcaption>As one may notice, the shared layers have actually the same memory address.</figcaption></figure><p>This is important because we need to train our network for <em>one-shot learning</em> meaning, it has to correctly predict preferences even for a never-seen user or an unknown item.</p><h3>Training the model</h3><p>We are now ready to pass to the train part of our recommender system.</p><h4>Construction of training triplets</h4><p>Before going and train this model we need to build the batches. Recall our training set is made by triplets (<em>user, positive movie, negative movie</em>)<em>.</em></p><p>As one can see from the picture above, the model expects a list of three arrays as input. Corresponding to the feature vectors of users and items.</p><p>Hence, the batch composer function will take information from the users dataset, from movies dataset and from the ratings matrix to compose triplets.</p><p>Thus, the function will return a list containing 3 <em>batch_size</em>-long arrays, representing the triplets. In other words we have a list of objects</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*poL-B4RWNJ2ZkVQ--W01-Q.png" /></figure><p>where <strong><em>A </em></strong>is an array of shape <em>(batch_size, n_user_features)</em>, <strong><em>P</em></strong> and <strong><em>N</em></strong> are both arrays of shape <em>(batch_size, n_item_features)</em>. Each row of the array corresponds to a feature vector. Indeed the triplet referring to the first user (coupled to a movie evaluated positively and to a one negatively ranked) is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qAvndVCPb2HxkjgtjxmYg.png" /></figure><p>In order to get to this result, we defined a function.</p><h4>Translating ratings matrix into triplets</h4><p>The function randomly select a user and among its positive/negative ratings randomly picks two to compose the triplet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fff098ea77d6ad6439b61c67c1a8be7b/href">https://medium.com/media/fff098ea77d6ad6439b61c67c1a8be7b/href</a></iframe><h4>Training</h4><p>Having obtained the training set <em>i.e.</em> a bunch of triplets (user feature vec, liked movie feature vec, not liked movie feature vec), we can train our model on it.</p><p>Once triplets have been composed we can train our model. We have chosen a batch size of 32 and a 10000 iterations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f962e234c4cd0c6bdbc3d0e99cdbdb8/href">https://medium.com/media/5f962e234c4cd0c6bdbc3d0e99cdbdb8/href</a></iframe><p>As one might expect, the triplet loss is close to 1/2 at the beginning (its log is -0.69), going down during the training to a value approximately equal to 0.1.</p><h3>Evaluation and metrics</h3><p>Now the question everyone working in the field has to wonder: <em>How to evaluate our results</em>?</p><p>In our situation, we created a model producing embeddings (<em>i.e. </em>vectors) that we can use to compute distances. In other words, if an item <em>i</em> is likely to be appreciated by an user <em>u</em>, their distance will be small, otherwise they will be separated by a great distance in the embedding space.</p><p>Thus, we need a <strong>threshold: </strong>if the found distance is under the threshold then we recommend the item to the user, if the distance is above the threshold then that item is not recommended. We have to choose this threshold carefully. This is a typical <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">ROC curve problem</a>. For this reason, one metric for evaluation could be Area Under the Curve (AUC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*z77rUfq5YTydgmTBoTn7Mg.png" /><figcaption>The AUC after the training of the model.</figcaption></figure><h3>Predictions: Making actual recommendations</h3><p>The aim of a recommender system is precisely to recommend (likely appreciated) items to users. Thus, given a user and a list of items, we can sort the list by “preference score”.</p><h3>Conclusion</h3><p>This was just a very simple application. The model was not optimised at all, but I think one can build upon this to achieve interesting results. Especially a more careful hyperparameter tuning and a better choice of the Neural Network architecture would improve performances a lot. It could be interesting to see whether with a model to get tuned hyper-parameters we can obtain much better performance.</p><p>Another improvement one can do is to work on the input layers. Data cleaning and maybe enriching considering (for example) geographical data would be beneficial.</p><p>Still, I think this can be a good example of creating a not-so-trivial neural network model to be applied to a concrete problem. It shows quite well the power of Embedding layers.</p><p>It can also work as an example of how nowadays, Deep Learning frameworks really do abstract a lot of the heavy technical stuff for us!</p><p>The full code on which this post is based can be found on my <a href="https://github.com/oscar-defelice">GitHub</a>.</p><h3>Acknowledgements</h3><p>I would like to thank my dear friend and exceptionally talented programmer <a href="https://medium.com/@alessandro.angioi">@alessandro.angioi</a>, for code revision and fruitful discussions.</p><p>🤯 <strong><em>Have you seen what happens if you click the “clap” button multiple times?</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2b765d27350" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deep-recommender-system/a-deep-recommender-system-e2b765d27350">A Deep Recommender System</a> was originally published in <a href="https://medium.com/deep-recommender-system">DeepBenBello</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>