<?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 Steve Mutuvi on Medium]]></title>
        <description><![CDATA[Stories by Steve Mutuvi on Medium]]></description>
        <link>https://medium.com/@stevemutuvi?source=rss-25849db11a79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9Uh7sJyUYwIvMrDyH4aR3Q.jpeg</url>
            <title>Stories by Steve Mutuvi on Medium</title>
            <link>https://medium.com/@stevemutuvi?source=rss-25849db11a79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:11:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stevemutuvi/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[Using Aspect-Based Sentiment Analysis to Understand User-Generated Content]]></title>
            <link>https://heartbeat.comet.ml/using-aspect-based-sentiment-analysis-to-understand-user-generated-content-2cfd5d3e25bb?source=rss-25849db11a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cfd5d3e25bb</guid>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Steve Mutuvi]]></dc:creator>
            <pubDate>Thu, 16 May 2019 14:19:44 GMT</pubDate>
            <atom:updated>2021-09-27T18:20:22.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Xwhqh7VzvKbQetwacWOew.jpeg" /></figure><h3>Introduction</h3><p>User-generated content has increased significantly in the recent past. Much of this content is text-based, generated mainly via online forums and social media platforms, an will often contain users’ opinions about organizations or hot-button issues.</p><p>Businesses exist to provide goods and/or services, which means that communication and relationships with customers are crucial elements of their success. Analyzing customer feedback—either customer reviews or complaints—shared on online or social medium platforms can provide key insights necessary to optimize customer service. In fact, there <a href="https://stackla.com/resources/blog/42-statistics-about-user-generated-content-you-need-to-know/">a lot of statistics </a>that suggest this kind of analysis via user-generated content is a key part of any brand strategy.</p><p>Despite the perceived benefits, it’s still a great challenge for businesses to parse and organize this large amount of unstructured data into more digestible and actionable insights. Unstructured textual data coming from disparate sources in the form of natural language is especially difficult to analyze manually. However, machine learning-based opinion mining techniques have the potential to enable automatic extraction of opinions and their corresponding polarities from such user-generated content. This approach is known as <strong>aspect-based sentiment analysis (ABSA)</strong>.</p><p>Formally, <a href="https://medium.com/@nitesh10126/aspect-based-sentiment-analysis-in-product-reviews-unsupervised-way-fb0b38ead501">Sentiment analysis or opinion mining</a> is the computational study of people’s opinions, sentiments, evaluations, attitudes, moods, and emotions. Aspect-based sentiment analysis involves two sub-tasks; firstly, detecting the <em>opinion or aspect terms </em>in the given text data, and secondly, finding the <em>sentiment</em> corresponding to the aspect terms detected.</p><p>In this article, we’ll demonstrate the building of a <a href="https://heartbeat.comet.ml/the-7-nlp-techniques-that-will-change-how-you-communicate-in-the-future-part-i-f0114b2f0497">natural language processing</a> (NLP) pipeline to extract meaningful insights from a large volume of customer reviews. This is in an attempt to automate the process of understanding opinions about a given subject from user-generated text.</p><blockquote>The latest in deep learning — from a source you can trust. <a href="https://www.deeplearningweekly.com/?utm_campaign=dlweekly-newsletter-expertise1&amp;utm_source=heartbeat">Sign up for a weekly dive into all things deep learning</a>, curated by experts working in the field.</blockquote><h3>Dataset</h3><p>We’ll use the restaurant reviews dataset generated during the <a href="http://alt.qcri.org/semeval2016/">2016 SemEval</a> annual competition. The competition targeted development of computational techniques for extraction from customer reviews of aspect terms mentioned and their associated sentiment scores.</p><p>We start by importing the required library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78416ad80b8b8695a0756ccd143a4180/href">https://medium.com/media/78416ad80b8b8695a0756ccd143a4180/href</a></iframe><p>The training dataset is loaded using the pandas read_csv() function. We also show the first 5 rows of the dataset using the head() function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/896e58594e072bfe5b7246837561f2b8/href">https://medium.com/media/896e58594e072bfe5b7246837561f2b8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*DAcxIy5fnVyTAnsCueaMkw.png" /><figcaption>First 5 records of the dataset</figcaption></figure><p>The aspect_category and the sentiment are the target variables for the aspect and the sentiment classifiers respectively. We can obtain the total number of aspect categories using the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c690b8cb1b94286a76b17824055a5079/href">https://medium.com/media/c690b8cb1b94286a76b17824055a5079/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*rb0VrajoysE47g2p9yKcJg.png" /><figcaption>Aspect Categories</figcaption></figure><p>In our case, we have a total of 13 aspect categories.</p><h3>Model Training</h3><p>Using the Keras Library, we’ll build and train neural networks for both aspect category and sentiment classification. <a href="https://heartbeat.fritz.ai/introduction-to-deep-learning-with-keras-c7c3d14e1527">Keras</a> is a neural networks API that enables fast experimentation through a high-level, user-friendly, modular and extensible API. Keras was developed and is maintained by <a href="https://twitter.com/fchollet?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Francois Chollet</a> and can run on both CPU and GPU.</p><h4>Defining the Neural Network Architecture</h4><p>Let’s start by defining the aspect classifier architecture:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c48494f822ffe2ca84dbfd918023ac99/href">https://medium.com/media/c48494f822ffe2ca84dbfd918023ac99/href</a></iframe><p>We’ll use a fully-connected network structure with three layers. We first create a Sequential object and use the add function to add layers to our model. The Dense class is used to define a fully-connected layer, where each neuron in the network receives input from all the neurons in the previous layer.</p><p>The input shape is set to 6000, which is the maximum size of vocabulary created using word embedding, with relu used as the non-linear activation function. Nonlinear functions transform data such that the resulting transformed points can effectively be classified into different classes. The output layer comprises 13 neurons, one for each class. The softmax activation function used in our model returns the probabilities of each class—the target class will have the highest probability.</p><p>Once the architecture is specified, we need to configure the learning process by specifying an optimizer, a loss function, and accuracy metrics. “Learning” simply means finding a combination of model parameters that minimize a<br>loss function for a given set of training data samples and their corresponding targets. Since the problem at hand is multi-class classification, categorical <a href="https://datascience.stackexchange.com/questions/20296/cross-entropy-loss-explanation">cross entropy loss</a> was specified as the loss function.</p><h4>Vector Representations of Words</h4><p>To encode the reviews in vectors we use a word embedding technique known as the <a href="https://machinelearningmastery.com/gentle-introduction-bag-words-model/"><em>Bag-of-Words (BoW)</em></a>. In this approach, we use tokenized words for each observation and find out the frequency of each token:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03fb4b52557fddb85f2d3cfba0b4e713/href">https://medium.com/media/03fb4b52557fddb85f2d3cfba0b4e713/href</a></iframe><p>We need to encode the aspect category column as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7ca2f42985b2e83bade87cf9ae35bd4/href">https://medium.com/media/e7ca2f42985b2e83bade87cf9ae35bd4/href</a></iframe><p>The above three steps are repeated for the sentiment classifier. The output layer for this classifier will, however, be initialized with the value 3 since there are 3 types of sentiments—namely positive, neutral, and negative.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54e243c477af6353cdb170e26d5e801f/href">https://medium.com/media/54e243c477af6353cdb170e26d5e801f/href</a></iframe><h4>The Training Process</h4><p>Our two models are ready to be trained. To train, we’ll use the fit()function on our models with the training data (reviews_tokenized), target data (encoded_y), the number of epochs, and verbose parameters. Verbose helps us see the training progress for each epoch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90c010ce3dee0dd3e8c83d9f3cc50b08/href">https://medium.com/media/90c010ce3dee0dd3e8c83d9f3cc50b08/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*OxXGL81vj8P_ZSZjmkanqw.png" /><figcaption>Training progress</figcaption></figure><p>The accuracy of our models can be improved further by <a href="https://heartbeat.comet.ml/tuning-machine-learning-hyperparameters-40265a35c9b8">hyperparameters.</a></p><p>Finally, we test our models using a list of reviews, as shown below. Minor pre-processing, which includes changing the reviews to lowercase, is done on the reviews.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a4abd7e1e61bb8bacb666df80fd6118/href">https://medium.com/media/2a4abd7e1e61bb8bacb666df80fd6118/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*ddCj8tGcSnsk83hMkqOLlQ.png" /><figcaption>Test Reviews Results</figcaption></figure><p>The models performed fairly well in classifying our test reviews.</p><h3>Conclusion</h3><p>Aspect-based sentiment analysis (ABSA) can help businesses become <a href="https://www.salesforce.com/blog/2019/01/how-to-create-a-customer-centric-experience.html">customer-centric</a> and place their customers at the heart of everything they do. It’s about listening to customers, understanding their voices, analyzing their feedback, and learning more about customer experiences, as well as their expectations for products or services.</p><p>While the use of computation approaches in mining customer opinions have proven to be quite promising, more needs to be done to improve the performance of these models. A plausible approach to improving the performance would be to use advanced word representation techniques, specifically <em>contextual</em> <a href="https://heartbeat.comet.ml/using-a-keras-embedding-layer-to-handle-text-data-2c88dc019600">word embedding</a>.</p><p><em>Contextual</em> word representations derived from pre-trained bidirectional language models (biLMs) have recently been shown to provide significant improvements to the state-of-the-art for a wide range of NLP tasks. Among the popular contextual word embedding techniques is Google’s <a href="https://ai.googleblog.com/2018/11/open-sourcing-bert-state-of-art-pre.html">Bidirectional Encoder Representations from Transformer (BERT)</a>.</p><p><em>Contextual</em> representation is characterized by generating a representation of each word based on the other words in the sentence. Therefore, the performance of the classification model is expected to improve significantly as a result of the rich contextual representations learned from the user-generated content.</p><p><strong>Discuss this post on </strong><a href="https://news.ycombinator.com/edit?id=19930693"><strong>Hacker News</strong></a><strong> and </strong><a href="https://www.reddit.com/r/MachinesLearn/comments/bpf2i8/using_aspectbased_sentiment_analysis_to/"><strong>Reddit</strong></a><strong>.</strong></p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cfd5d3e25bb" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/using-aspect-based-sentiment-analysis-to-understand-user-generated-content-2cfd5d3e25bb">Using Aspect-Based Sentiment Analysis to Understand User-Generated Content</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Machine Learning Model Evaluation]]></title>
            <link>https://heartbeat.comet.ml/introduction-to-machine-learning-model-evaluation-fa859e1b2d7f?source=rss-25849db11a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa859e1b2d7f</guid>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Steve Mutuvi]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 14:08:29 GMT</pubDate>
            <atom:updated>2021-09-24T20:42:15.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPjZ1Lu2LCiMuYlMRxuOGQ.jpeg" /></figure><p>Machine learning continues to be an increasingly integral component of our lives, whether we’re applying the techniques to research or business problems. Machine learning models ought to be able to give accurate predictions in order to create real value for a given organization.</p><p>While <a href="https://medium.com/r?url=https%3A%2F%2Fheartbeat.fritz.ai%2Ftraining-an-image-classification-convolutional-neural-net-to-detect-plant-disease-using-fast-ai-a9f5315ed59">training a model</a> is a key step, how the model generalizes on unseen data is an equally important aspect that should be considered in every machine learning pipeline. We need to know whether it actually works and, consequently, if we can trust its predictions. Could the model be merely memorizing the data it is fed with, and therefore unable to make good predictions on future samples, or samples that it hasn’t seen before?</p><p>In this article, we explain the techniques used in evaluating how well a machine learning model generalizes to new, previously unseen data. We’ll also illustrate how common model evaluation metrics are implemented for classification and <a href="https://heartbeat.comet.ml/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0">regression problems</a> using Python.</p><h3>Model Evaluation Techniques</h3><p>The above issues can be handled by evaluating the performance of a machine learning model, which is an integral component of any data science project. Model evaluation aims to estimate the generalization accuracy of a model on future (unseen/out-of-sample) data.</p><p>Methods for evaluating a model’s performance are divided into 2 categories: namely, <a href="https://www.datarobot.com/wiki/training-validation-holdout/">holdout</a> and <a href="https://towardsdatascience.com/cross-validation-70289113a072">Cross-validation</a>. Both methods use a test set (i.e data not seen by the model) to evaluate model performance. It’s not recommended to use the data we used to build the model to evaluate it. This is because our model will simply remember the whole training set, and will therefore always predict the correct label for any point in the training set. This is known as <a href="https://elitedatascience.com/overfitting-in-machine-learning">overfitting</a>.</p><h4>Holdout</h4><p>The purpose of holdout evaluation is to test a model on different data than it was trained on. This provides an unbiased estimate of learning performance.</p><p>In this method, the dataset is <em>randomly</em> divided into three subsets:</p><ol><li><strong>Training set</strong> is a subset of the dataset used to build predictive models.</li><li><strong>Validation set</strong> is a subset of the dataset used to assess the performance of the model built in the training phase. It provides a test platform for fine-tuning a model’s parameters and selecting the best performing model. Not all modeling algorithms need a validation set.</li><li><strong>Test set</strong>, or unseen data, is a subset of the dataset used to assess the likely future performance of a model. If a model fits to the training set much better than it fits the test set, overfitting is probably the cause.</li></ol><p>The holdout approach is useful because of its speed, simplicity, and flexibility. However, this technique is often associated with high variability since differences in the training and test dataset can result in meaningful differences in the estimate of accuracy.</p><blockquote>The latest in deep learning — from a source you can trust. <a href="https://www.deeplearningweekly.com/?utm_campaign=dlweekly-newsletter-expertise1&amp;utm_source=heartbeat">Sign up for a weekly dive</a> into all things deep learning, curated by experts working in the field.</blockquote><h4>Cross-Validation</h4><p><a href="https://machinelearningmastery.com/k-fold-cross-validation/">Cross-validation</a> is a technique that involves partitioning the original observation dataset into a training set, used to train the model, and an independent set used to evaluate the analysis.</p><p>The most common cross-validation technique is <a href="https://medium.com/datadriveninvestor/k-fold-cross-validation-6b8518070833">k-fold cross-validation</a>, where the original dataset is partitioned into k equal size subsamples, called folds. The k is a user-specified number, usually with 5 or 10 as its preferred value. This is repeated k times, such that each time, one of the k subsets is used as the test set/validation set and the other k-1 subsets are put together to form a training set. The error estimation is averaged over all k trials to get the total effectiveness of our model.</p><p>For instance, when performing five-fold cross-validation, the data is first partitioned into 5 parts of (approximately) equal size. A sequence of models is trained. The first model is trained using the first fold as the test set, and the remaining folds are used as the training set. This is repeated for each of these 5 splits of the data and the estimation of accuracy is averaged over all 5 trials to get the total effectiveness of our model.</p><p>As can be seen, every data point gets to be in a test set exactly once and gets to be in a training set k-1 times. This significantly reduces bias, as we’re using most of the data for fitting, and it also significantly reduces variance, as most of the data is also being used in the test set. Interchanging the training and test sets also adds to the effectiveness of this method.</p><h3>Model Evaluation Metrics</h3><p>Model evaluation metrics are required to quantify model performance. The choice of evaluation metrics depends on a given machine learning task (such as classification, regression, ranking, clustering, topic modeling, among others). Some metrics, such as <a href="https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c">precision-recall</a>, are useful for multiple tasks. Supervised learning tasks such as classification and regression constitutes a majority of machine learning applications. In this article, we focus on metrics for these two supervised learning models.</p><h3>Classification Metrics</h3><p>In this section we will review some of the metrics used in classification problems, namely:</p><ul><li>Classification Accuracy</li><li>Confusion matrix</li><li>Logarithmic Loss</li><li>Area under curve (AUC)</li><li>F-Measure</li></ul><h4>Classification Accuracy</h4><p>Accuracy is a common evaluation metric for classification problems. It’s the number of correct predictions made as a ratio of all predictions made. We use sklearn module to compute the accuracy of a classification task, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/371164dafdaff38790da1c9115b57f4b/href">https://medium.com/media/371164dafdaff38790da1c9115b57f4b/href</a></iframe><p>The classification accuracy is <strong>88%</strong> on the validation set.</p><p>By using cross-validation, we’d be “testing” our machine learning model in the “training” phase to check for overfitting and to get an idea about how our machine learning model will generalize to independent data (test data set).</p><p>Cross-validation techniques can also be used to compare the performance of different machine learning models on the same data set and can also be helpful in selecting the values for a model’s parameters that maximize the accuracy of the model—also known as parameter tuning.</p><h4>Confusion Matrix</h4><p>A confusion matrix provides a more detailed breakdown of correct and incorrect classifications for each class. We use the <a href="http://archive.ics.uci.edu/ml/datasets/iris">Iris dataset</a> to classify and compute the confusion matrix for the predictions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93c16f65a5c33a4a85e54db31efa28dc/href">https://medium.com/media/93c16f65a5c33a4a85e54db31efa28dc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*3m5Cjkc5-drL8KrVvtnmCw.png" /></figure><p>The short explanation of how to interpret a confusion matrix is as follows: The diagonal elements represent the number of points for which the predicted label is equal to the true label, while anything off the diagonal was mislabeled by the classifier. Therefore, the higher the diagonal values of the confusion matrix the better, indicating many correct predictions.</p><p>In our case, the classifier predicted all the 13 setosa and 18 virginica plants in the test data perfectly. However, it incorrectly classified 4 of the versicolor plants as virginica.</p><h4>Logarithmic Loss</h4><p>Logarithmic loss (logloss) measures the performance of a classification model where the prediction input is a probability value between 0 and 1. Log loss increases as the predicted probability diverges from the actual label. The goal of machine learning models is to minimize this value. As such, smaller logloss is better, with a perfect model having a log loss of 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60101a6494f5785614f9c68a8765bd0b/href">https://medium.com/media/60101a6494f5785614f9c68a8765bd0b/href</a></iframe><h4>Area under Curve (AUC)</h4><p>Area under ROC Curve is a performance metric for measuring the ability of a <a href="https://heartbeat.comet.ml/binary-classification-using-keras-in-r-ef3d42202aaa">binary classifier </a>to discriminate between positive and negative classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da964b609aece5fb57458af4400fce5f/href">https://medium.com/media/da964b609aece5fb57458af4400fce5f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*L6KQRhvz1WT2L5MmRDRbAQ.png" /></figure><p>In the example above, the AUC is relatively close to 1 and greater than 0.5. A perfect classifier will have the ROC curve go along the Y axis and then along the X axis.</p><h4>F-Measure</h4><p>F-measure (also F-score) is a measure of a test’s accuracy that considers both the <a href="https://en.wikipedia.org/wiki/Precision_(information_retrieval)">precision</a> and the <a href="https://en.wikipedia.org/wiki/Recall_(information_retrieval)">recall</a> of the test to compute the score. Precision is the number of correct positive results divided by the total predicted positive observations. Recall, on the other hand, is the number of correct positive results divided by the number of all relevant samples (total actual positives).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c8a813aeec1c09ae14b340d27400bb3/href">https://medium.com/media/4c8a813aeec1c09ae14b340d27400bb3/href</a></iframe><h3>Regression Metrics</h3><p>In this section we review 2 of the most common metrics for evaluating regression problems namely, Root Mean Squared Error and Mean Absolute Error.</p><p>The Mean Absolute Error (or MAE) is the sum of the absolute differences between predictions and actual values. On the other hand, Root Mean Squared Error (RMSE) measures the average magnitude of the error by taking the square root of the average of squared differences between prediction and actual observation.</p><p>The Python code snippet below shows how the two regression metrics can be implemented.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05139d3fdae8267e9559a14bb807d837/href">https://medium.com/media/05139d3fdae8267e9559a14bb807d837/href</a></iframe><h3>Conclusion</h3><p>Ideally, the estimated performance of a model tells us how well it performs on unseen data. Making predictions on future data is often the main problem we want to solve. It’s important to understand the context before choosing a metric because each machine learning model tries to solve a problem with a different objective using a different dataset.</p><p>This article has attempted to explain the common evaluation metrics for classification and regression machine learning problems, providing short Python snippets to show how they can be implemented.</p><p><strong>Discuss this post on </strong><a href="https://news.ycombinator.com/item?id=19674289"><strong>Hacker News</strong></a><strong> and </strong><a href="https://www.reddit.com/r/MachinesLearn/comments/bdv27q/introduction_to_machine_learning_model_evaluation/?ref=share&amp;ref_source=link"><strong>Reddit</strong></a><strong>.</strong></p><p><em>Editor’s Note:</em><a href="http://heartbeat.fritz.ai/"><em> Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa859e1b2d7f" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/introduction-to-machine-learning-model-evaluation-fa859e1b2d7f">Introduction to Machine Learning Model Evaluation</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Bus Ticket Sales Using Machine Learning]]></title>
            <link>https://heartbeat.comet.ml/predicting-bus-ticket-sales-using-machine-learning-dd2fcfe15392?source=rss-25849db11a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd2fcfe15392</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[catboost]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Steve Mutuvi]]></dc:creator>
            <pubDate>Tue, 26 Mar 2019 14:22:10 GMT</pubDate>
            <atom:updated>2021-10-01T17:15:54.837Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Machine Learning to Predict Bus Ticket Sales</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0noIBxlHm8pfKM-1Gjzpw.jpeg" /></figure><h3>Introduction</h3><p>Sales are the lifeblood of a business. <a href="https://heartbeat.comet.ml/sales-forecasting-using-facebooks-prophet-f9ae0214f196">Sales forecasting</a> is, therefore, a crucial part of any business’s financial planning.</p><p>In this tutorial, we look at one specific sales forecasting example: public bus ticket sales. Accurately predicting the demand for bus ticket sales can enable commuter companies to make informed decisions regarding their operations. The companies are able to gauge customer demand for certain rides, to manage resources and vehicles more efficiently, to offer promotions and sell other services more effectively, such as micro-insurance, or even improve customer service by being able to efficiently communicate alerts and other useful information.</p><h3>The Dataset</h3><p>The data used in this article is obtained from <a href="https://zindi.africa/about">Zindi</a>, a data science competition platform with the mission of building the data science ecosystem in Africa. The dataset comprises historic ticket purchasing details for 14 bus routes into Nairobi from October 2017 to April 2018, and includes information such as place or origin, the scheduled time of departure, the channel used for the purchase, the type of vehicle, the capacity of the vehicle, and the assigned seat number.</p><h3>Data Pre-processing</h3><p><a href="https://heartbeat.comet.ml/data-preprocessing-and-visualization-implications-for-your-machine-learning-model-8dfbaaa51423">Data pre-processing</a> is an important step that describes any type of processing performed on raw data. The quality of data and the useful information that can be derived from it determine how a model can best learn from the data.</p><p>Data pre-processing includes cleaning, normalization, transformation, feature extraction, and selection among others. The end result of data pre-processing is the final training data which form the experience that the algorithm uses to learn.</p><p>We begin by importing the required libraries and at the same time suppressing pandas warnings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5eddb64e590ee9c858b9e9cb3da57f0/href">https://medium.com/media/c5eddb64e590ee9c858b9e9cb3da57f0/href</a></iframe><p>The raw data is read using pandas in order to derive the target variable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bf5d59cb78500aa36e598a5aea261a5/href">https://medium.com/media/6bf5d59cb78500aa36e598a5aea261a5/href</a></iframe><p>The dataset consists of a list of tickets each identified by the ride_id. To derive the target variable, we need to aggregate the list to know how many passengers there are for a given ride_id. The aggregate function defined below removes any duplicate data, and groups and counts the number of tickets per ride.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bb7aa9d638a2534f9551155c744ed17/href">https://medium.com/media/8bb7aa9d638a2534f9551155c744ed17/href</a></iframe><p>The aggregated data is then saved in a comma-separated values (CSV) file format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcef2152438c5336c76b9814d9e4d794/href">https://medium.com/media/bcef2152438c5336c76b9814d9e4d794/href</a></iframe><p>In order to proceed with the next phase of model training, we read the aggregated training data and list the first five (5) records using panda’s read_csv()and head()functions respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e3e36719afe4352374d23d41a68ed2/href">https://medium.com/media/c9e3e36719afe4352374d23d41a68ed2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*xTtDayXxKpzsvi6r-C_R4w.png" /></figure><h4>Feature Engineering</h4><p><a href="https://heartbeat.comet.ml/introduction-to-automated-feature-engineering-using-deep-feature-synthesis-dfs-3feb69a7c00b">Feature engineering</a> involves defining new features from the existing features in a dataset. The quality of results produced by a machine learning model is heavily dependent on the quality of the features in the dataset used to train that model. Creating new features helps in providing more information to the model about the target variable, which in turn improves the model’s performance.</p><p>We create additional features, namely travel_month,isEndWeek, isMorning and isEndMonth. These features are important, as it’s common for people to travel more in certain months, times of the day, and over the weekend.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fbb6eb7857e679f85c3dd0330067e31/href">https://medium.com/media/9fbb6eb7857e679f85c3dd0330067e31/href</a></iframe><p>The feature extraction and selection process are also performed on the test data. The reason for having the test set is to ensure the model does not <a href="https://machinelearningmastery.com/overfitting-and-underfitting-with-machine-learning-algorithms/">overfit</a> (memorizing the data it has seen).</p><p>We drop the travel_date, travel_dow(day of the week), hour_booked and TOM (time of the month), as these features were only necessary for deriving the best features. The inplace = true and axis = 1ensure the underlying data is affected column-wise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af2d62f7a50d16ea14a12f744c36075c/href">https://medium.com/media/af2d62f7a50d16ea14a12f744c36075c/href</a></iframe><p>The features and target variables of our training set need to be separated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca7d6441163c3896504f06ffb68c770e/href">https://medium.com/media/ca7d6441163c3896504f06ffb68c770e/href</a></iframe><h3><strong>Model Training</strong></h3><p>With our data ready, it’s time to train our model. We settled on <a href="https://github.com/catboost/catboost">CatBoost</a>, which is a machine learning algorithm based on <a href="https://heartbeat.comet.ml/boosting-your-machine-learning-models-using-xgboost-d2cabb3e948f">gradient boosting</a> over <a href="https://heartbeat.comet.ml/introduction-to-decision-tree-learning-cd604f85e236">decision trees</a>. Among the main advantages of this algorithm include support for both numerical and categorical features and its superior quality compared with other gradient boosting decision tree (GBDT) libraries. It also includes out of the box support for both numerical and categorical features.</p><p>Predicting the number of tickets sold is a regression problem. <a href="https://heartbeat.comet.ml/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0">Regression</a> is a technique used to predict continuous (dependent) variables given a set of independent variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed20451566430bffdff99c2abc9b420f/href">https://medium.com/media/ed20451566430bffdff99c2abc9b420f/href</a></iframe><h3>Prediction on Test Data</h3><p>Just like in the training set, we need to prepare the test data for evaluation of the model to determine how the model performs on unseen data—and it gives us some indication as to whether the model generalizes or not.</p><p>We read the data using panda’s read_csv() function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/887196e778182e12b4a783a11b9aba65/href">https://medium.com/media/887196e778182e12b4a783a11b9aba65/href</a></iframe><p>Just like with training data, we subject the test data to the feature engineering process. New features are created, categorical values encoded, and insignificant features dropped.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/787be3193ff9d696426b22e7d2c5c28b/href">https://medium.com/media/787be3193ff9d696426b22e7d2c5c28b/href</a></iframe><p>After the processing phase, the prediction is then performed on the test data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e57f31e926c693fab7152bb316e334b/href">https://medium.com/media/4e57f31e926c693fab7152bb316e334b/href</a></iframe><h4>Submission File</h4><p>The final step involves preparation of the submission file for submission to <a href="https://zindi.africa/">zindi.africa</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aa7aba7e736919bf4ceac54bf1a46b8/href">https://medium.com/media/1aa7aba7e736919bf4ceac54bf1a46b8/href</a></iframe><p>With a mean absolute error of <strong>3.7352</strong>, our solution ended up in top 15% on the leaderboard.</p><h3>Conclusion</h3><p>The resulting model can be used by bus operators to anticipate customer demand for certain rides, to manage resources and vehicles more efficiently, to offer promotions and sell other services more effectively, such as micro-insurance, or even improve customer service by being able to send alerts and other useful information to customers.</p><p>In addition, the statistics related to ticket sales can be leveraged by local municipal governments to assess the number of vehicles and passengers visiting cities at any given time for infrastructure resource planning.</p><p>And all of these processes can be improved with the power of machine learning!</p><p><strong>Discuss this post on </strong><a href="https://news.ycombinator.com/edit?id=19493894"><strong>Hacker News</strong></a><strong> and </strong><a href="https://www.reddit.com/r/MachineLearning/comments/b5s7k3/using_machine_learning_to_predict_bus_ticket_sales/?ref=share&amp;ref_source=link"><strong>Reddit</strong></a><strong>.</strong></p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd2fcfe15392" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/predicting-bus-ticket-sales-using-machine-learning-dd2fcfe15392">Predicting Bus Ticket Sales Using Machine Learning</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Text Classification Model using Flask and Vue.js]]></title>
            <link>https://heartbeat.comet.ml/deploying-a-text-classification-model-using-flask-and-vue-js-25b9aa7ff048?source=rss-25849db11a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/25b9aa7ff048</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[heartbeat]]></category>
            <dc:creator><![CDATA[Steve Mutuvi]]></dc:creator>
            <pubDate>Tue, 26 Feb 2019 15:17:46 GMT</pubDate>
            <atom:updated>2021-09-27T18:46:16.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a Text Classification Model Using Flask and Vue.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mwm0xGQsg7DfAH5cDfBCOw.jpeg" /></figure><h3>Introduction</h3><p>Successful machine learning models are developed to serve and bring value to an end user. Whether the end user is a customer or domain expert, the full value of data science is only realized by operationalizing the workflow and exposing model predictions and insights to the end user. End users consume and interact with models in different contexts—via a web application, mobile application, or a command line API request.</p><p>It’s worth noting that no model is perfect and a successful model is an evolving one. This means the model can be improved through an iterative process that involves continually gaining user feedback and new data, re-training, and re-deploying over and over again. Performing the iterative process often shortens <a href="https://heartbeat.comet.ml/the-lifecycle-of-mobile-machine-learning-models-759bff75ec3f">the machine learning cycle</a>, resulting in better models and more impact.</p><p>Integrating a machine learning model into an existing production environment in order to start using it to make practical business decisions based on data can be extremely demanding. This is because considerable effort is required for related tasks such as routing and domain configuration, load balancing, environment installation, and more.</p><h3>Turning the Spam Message Classifier into a Web Application</h3><p>To help illustrate this difficult process, we’ll deploy a spam classification model as a REST API with <a href="http://flask.pocoo.org/">Flask</a> and a <a href="https://vuejs.org/">Vue.js</a> webapp that connects and makes calls to the API. The web application consists of a simple web page with a form field that lets us enter a text message. Upon submitting the message to the web application, the appropriate API endpoint is called, which in turn processes and returns to the frontend the result—classifying the text as either spam or not spam.</p><p>The spam classification model used in this article was trained and evaluated in <a href="https://heartbeat.comet.ml/using-transfer-learning-and-pre-trained-language-models-to-classify-spam-549fc0f56c20">my previous </a>article using the <a href="https://jobs.zalando.com/tech/blog/zalando-research-releases-flair/?gh_src=4n3gxh1">Flair Library</a>, a simple framework for state-of-the-art Natural Language Processing build on top of <a href="https://heartbeat.comet.ml/introduction-to-pytorch-for-deep-learning-5b437cea90ac">PyTorch</a>.</p><p><a href="https://heartbeat.comet.ml/using-transfer-learning-and-pre-trained-language-models-to-classify-spam-549fc0f56c20">Using Transfer Learning and Pre-trained Language Models to Classify Spam</a></p><h4>Implementing the Flask API</h4><p><strong>API</strong> stands for Application Program Interface, which can be defined as a set of methods of communication between various software components. In other words, an API allows computer programs to communicate amongst themselves or with the underlying operating system. A common architectural approach to designing web services is REST (REpresentational State Transfer).</p><p>Central to the concept of RESTful API is the notion of resources that are represented by Uniform Resource Locators (URLs). The clients send requests to these URLs using the methods defined by the HTTP protocol, and possibly as a result of that the state of the affected resource changes.</p><p>While REST is independent of any underlying protocol and is not necessarily tied to HTTP, most common REST implementations use HTTP as the application protocol. It takes advantage of the HTTP protocol to provide CRUD (Create, Read, Update, and Delete), with CRUD behavior mapping to the HTTP protocol method verbs—namely Post, Get, Put and Delete.</p><p>Flask is a lightweight <a href="https://wsgi.readthedocs.io/">WSGI</a> web application framework designed to make getting started with APIs quick and easy, with the ability to scale up to complex applications.</p><p>Flask can be installed using the pip command as follows;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fe07fc9db221551f1b923b9b6239f1f/href">https://medium.com/media/4fe07fc9db221551f1b923b9b6239f1f/href</a></iframe><p>The code below creates a server that listens to web traffic, run functions to process the requests raised, and finally sends a response back to the requester.</p><p>We start by importing the required Python libraries. The flask-cors extension is used for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a29e790684531c7093e8a20d34f321c6/href">https://medium.com/media/a29e790684531c7093e8a20d34f321c6/href</a></iframe><p>Once we import flask, we need to create an instance of the flask class for our web app, specify the secret_key needed to maintain sessions in our Flask application, and enable CORS for all routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1c6f051cf78b9fc245193ca2b4837da/href">https://medium.com/media/c1c6f051cf78b9fc245193ca2b4837da/href</a></iframe><p>We now implement the functions that will handle the API calls:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dfa59dfd6366cd1fcda9b2f0f85bfb7/href">https://medium.com/media/4dfa59dfd6366cd1fcda9b2f0f85bfb7/href</a></iframe><p>The input_predict_text() function receives the text input from the web application, and using the text classifier (best-model.pt) loaded from the models folder, predicts and returns the result in Json format. The get_results function, on the other hand, prepares the output to be displayed on the Vue.js frontend.</p><blockquote>Passionate about machine learning? Same! We’re curating each week’s biggest stories, best tutorials, and latest research so you don’t have to. <a href="https://www.deeplearningweekly.com/?utm_campaign=dlweekly-newsletter-timesaver4&amp;utm_source=heartbeat">Sign up for weekly updates delivered to your inbox</a>.</blockquote><h3>Vue.js Frontend</h3><p><a href="https://vuejs.org/">Vue.js</a> is an open source progressive JavaScript framework used to develop interactive web interfaces and single page applications. Vue.js’s popularity has been on an upward trajectory in the recent past, adding 45.3k stars in 2018, making it the most popular JavaScript project on GitHub.</p><h4>Installing Vue.Js</h4><p>The <a href="https://github.com/vuejs/vue-cli"><strong>Vue CLI</strong></a> (Command Line Interface) provides a quick, easy, and robust way to get started with developing Vue projects. Therefore, we need to have CLI installed, which is done using the following command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/787eb1c06aa0d46d840cfd7751b73ce5/href">https://medium.com/media/787eb1c06aa0d46d840cfd7751b73ce5/href</a></iframe><p>Once done, you can use the following command to create a new project using Webpack. The command performs an initial project setup and scaffolding, thus generating the initial project folder and files:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/235b8bc4c5657c48dcea65b04a0bc09c/href">https://medium.com/media/235b8bc4c5657c48dcea65b04a0bc09c/href</a></iframe><p>We implement the GET and POST method as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/134db652565524ace3fd5badfdbd0351/href">https://medium.com/media/134db652565524ace3fd5badfdbd0351/href</a></iframe><h4><strong>Axios</strong></h4><p><a href="https://github.com/axios/axios">Axios</a> is an impressive HTTP client library that enables us to asynchronously issue HTTP requests to interact with the Flask REST endpoints. The addNewTask() function uses Axios to post the provided input data to the /api/task endpoint, while getTasks() obtains the results returned by the API.</p><p>The output of our final solution is as follows;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*8335ziNyzDx6sBub0agk_A.png" /></figure><p>The complete source code can be downloaded from <a href="https://github.com/smutuvi/flask_vue_ML.git">GitHub</a>.</p><h3>Conclusion</h3><p>In order to get the most value out of machine learning models, it’s important to deploy them into production as seamlessly as possible so that end users can start using them to make practical decisions. Putting a model into production means having the model accessible to anyone to perform machine learning tasks—for instance, <a href="https://heartbeat.comet.ml/using-a-keras-embedding-layer-to-handle-text-data-2c88dc019600">text classification</a>. Virtually every organization is looking to leverage machine learning and build deeper and richer predictive analytics into their applications.</p><p>While most attention has been paid to the actual building of machine learning models, information on how to operationalize the models remains scant. This article aims to provide information on how to move a model into production. In this article, we’ve illustrated how to deploy a spam classification model as a REST API using Flask and how to develop a Vue webapp that can connect to the API, post, retrieve, and display the results of the text classification task. The approach can easily be adapted to deploy and manage analytical models in other domains such as <a href="https://heartbeat.comet.ml/the-5-computer-vision-techniques-that-will-change-how-you-see-the-world-1ee19334354b">computer vision</a>.</p><p><strong>Discuss this post on </strong><a href="https://news.ycombinator.com/item?id=19257133"><strong>Hacker News</strong></a><strong> and </strong><a href="https://heartbeat.fritz.ai/deploying-a-text-classification-model-using-flask-and-vue-js-25b9aa7ff048"><strong>Reddit</strong></a><strong>.</strong></p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25b9aa7ff048" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/deploying-a-text-classification-model-using-flask-and-vue-js-25b9aa7ff048">Deploying a Text Classification Model using Flask and Vue.js</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training an Image Classification Convolutional Neural Net to Detect Plant Disease Using fast.ai]]></title>
            <link>https://heartbeat.comet.ml/training-an-image-classification-convolutional-neural-net-to-detect-plant-disease-using-fast-ai-a9f5315ed59?source=rss-25849db11a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9f5315ed59</guid>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Steve Mutuvi]]></dc:creator>
            <pubDate>Thu, 14 Feb 2019 15:09:40 GMT</pubDate>
            <atom:updated>2021-09-29T18:15:15.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TwSnwUAU8xCarvIfxkHeg.jpeg" /></figure><h3>Image Classification and Convolutional Neural Networks</h3><p>Over the past few years, deep learning techniques have dominated <a href="https://heartbeat.comet.ml/the-5-computer-vision-techniques-that-will-change-how-you-see-the-world-1ee19334354b">computer vision</a>. One of the computer vision application areas where deep learning excels is image classification<strong> </strong>with<strong> </strong><a href="https://heartbeat.comet.ml/a-beginners-guide-to-convolutional-neural-networks-cnn-cf26c5ee17ed">Convolutional Neural Networks</a> (CNNs)<strong>. </strong>The goal of image classification is to classify a specific image according to a set of possible categories. State-of-the-art image classifiers often result from transfer learning approaches based on pre-trained convolutional neural networks<strong>.</strong></p><p>In this article, we illustrate the training of a plant disease classification model using the Fastai library.</p><h3>The Fastai Library</h3><p>The fastai library simplifies and enables the training of fast and accurate neural nets using modern best practices. It’s an excellent initiative by <a href="https://twitter.com/jeremyphoward">Jeremy Howard</a> and his team aimed at democratizing deep learning and making it easier for everyone to build deep learning models.</p><p>Fastai is a wrapper for <a href="https://heartbeat.comet.ml/introduction-to-pytorch-for-deep-learning-5b437cea90ac">PyTorch</a>, which makes it easier to access recommended best practices for training deep learning models, while at the same time making all the underlying PyTorch functionality directly available to developers.</p><p>The main reason why fastai has been successful is the use of transfer learning techniques. <a href="https://heartbeat.comet.ml/using-transfer-learning-and-pre-trained-language-models-to-classify-spam-549fc0f56c20">Transfer learning</a> involves the use of a pre-trained model, that has been trained on a large collection of data and finally repurposed for ones&#39; specific needs. Fastai library has <a href="https://docs.fast.ai/">awesome documentation</a> to help you navigate through their library functions with live examples on how to use them.</p><h3>Training a Plant Disease Classifier</h3><h4>The Dataset</h4><p>The data used in this article is obtained from the <a href="https://www.crowdai.org/challenges/plantvillage-disease-classification-challenge/dataset_files">PlantVillage Disease Classification Challenge</a> organized by <a href="http://www.crowdai.org/">CrowdAi</a>. The goal of this challenge was to develop algorithms that can accurately diagnose a disease based on a plant image. <a href="https://plantvillage.psu.edu/">PlantVillage</a> is a not-for-profit project by Penn State University in the US and EPFL (Ecole polytechnique fédérale de Lausanne) in Switzerland.</p><p>The organizations empower smallholder farmers to increase yield by leveraging Artificial Intelligence to provide offline expert level knowledge and extension advice. PlantVillage has already collected and continue to collect tens of thousands of images of diseased and healthy crops.</p><p>The same dataset of diseased plant leaf images and corresponding labels comprising 38 classes of crop disease can also be found in <a href="https://github.com/spMohanty/PlantVillage-Dataset">spMohanty’s GitHub</a> account.</p><blockquote>Editor’s Note: You can also check out our <a href="https://heartbeat.comet.ml/community-spotlight-nuru-a-mobile-app-by-plantvillage-to-detect-crop-disease-in-africa-28d142bf63d5">community spotlight</a> on how Plant Village uses on-device machine learning to detect plant disease in remote parts of East Africa</blockquote><h4>Training the Model</h4><p>We use the <a href="https://docs.fast.ai/vision.html#vision">vision</a> module of the Fastai library to train an image classification model which can recognize plant diseases at state-of-the-art accuracy. While training of the model can be done locally using a laptop, we use <a href="https://colab.research.google.com/">Google Colab</a> which gives us more compute power, access to a GPU, and an easy-to-use Jupyter notebook environment for building machine learning and deep learning models.</p><p>We begin by placing the following three lines at the start of the notebook to ensure that any edits made to libraries are reloaded automatically, and also that any charts or images displayed are displayed within the notebook. These are not Python codes but special directives for Jupyter Notebook itself. The % is one of the magic commands supported in Jupyter Lab that adds extra functionality to our Jupyter Lab notebooks (and isn’t limited to the core language).</p><pre>%reload_ext autoreload<br>%autoreload 2<br>%matplotlib inline</pre><p>The next step is to import the required libraries. The fastai module and any other module can easily be installed using the pip command.</p><pre>!pip install fastai #installs the fastai library</pre><pre>import numpy as np<br>from fastai import *<br>from fastai.vision import *<br>from pathlib import Path</pre><h4>Loading and looking at the Data</h4><p>We download the colored (original RGB) images using the following command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1403226dcc07682bc7bf07ec6d3d235/href">https://medium.com/media/d1403226dcc07682bc7bf07ec6d3d235/href</a></iframe><p>Whenever we approach a problem, the first thing to do is to take a look at the data in order to better understand what the problem is and what the data looks like before we can figure out how to solve the problem. Taking a look at the data means understanding how the data directories are structured, what the labels are, and what some of the sample images look like.</p><p>In this particular dataset, the folder name represents the class label of all the images present within that folder. We need to extract the label names from the folder name automatically. Fortunately, fastai library provides the <a href="https://docs.fast.ai/vision.data#ImageDataBunch.from_folder">ImageDataBunch.from_folder</a> function that enables automatic extraction of the label names from the folder name. In addition, the ImageDataBunch class makes it easy to create the training and validation sets with images and labels. Once the data is loaded, we can also normalize the data by using .normalize to ImageNet parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d32406c2d31c087c38df12e2e848881/href">https://medium.com/media/7d32406c2d31c087c38df12e2e848881/href</a></iframe><p>The .show_batch() function of the ImageDataBunch class can be used to view a random sample of images from the given data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7849673a7cbf1293ca745475b0c63621/href">https://medium.com/media/7849673a7cbf1293ca745475b0c63621/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*SUm9NZF7AVSlSx6glB69ZA.png" /></figure><p>You’ll notice that the images appear to have been zoomed and cropped in a reasonably nice way. Fastai provides a rich image transformation library, whose main purpose is data augmentation when training computer vision models. The library can, however, be used for other general transformation tasks such as default center cropping.</p><p>DataBunch has a property called c which helps determine the number of classes—an important piece of information, especially for classification problems. We print the class labels and the number of classes as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb730ac7424f188c015cb0d57ba9e8bd/href">https://medium.com/media/eb730ac7424f188c015cb0d57ba9e8bd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrAnuqUxtfY_z1iXqkmIkQ.png" /></figure><h4>Transfer learning using a Pre-trained model: ResNet 50</h4><p>Now that our data is ready, it’s time to fit a model. To create the model we will use the function create_cnn from Learner class and feed a pre-trained model, in this case, <a href="https://medium.com/@14prakash/understanding-and-implementing-architectures-of-resnet-and-resnext-for-state-of-the-art-image-cf51669e1624">ResNet 50</a>, from the models class. The model we are building will take images as input and outputs the predicted probability of each category, with accuracy being used as the measure of performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a84dc9700aac46bd7f26ad532c0ff4d/href">https://medium.com/media/0a84dc9700aac46bd7f26ad532c0ff4d/href</a></iframe><p>We use the method fit_one_cycle to train the model for 4 epochs (4 cycles through the data).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4f2119c7d5e50c56fc3070b0a3df9a5/href">https://medium.com/media/d4f2119c7d5e50c56fc3070b0a3df9a5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*Skmy2Q3lCDmE4H86ZU1ljg.png" /></figure><p>The set of weights generated from the training process can be saved for re-use using the .save function of the learner class. In our case, we save it as ‘stage-1’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b2c4dc0ea359cafaffc22c2a05cab22/href">https://medium.com/media/8b2c4dc0ea359cafaffc22c2a05cab22/href</a></iframe><h3>Conclusion</h3><p>To achieve global food security, society needs to increase food production by an <a href="https://arxiv.org/abs/1511.08060">estimated 70%</a> in order to feed an expected population size of over 9 billion people by 2050. One way of achieving this target is to reduce infectious crop diseases, which often result in a reduction of the potential yield by an average of 40% and sometimes even more—especially for small-scale farmers in the developing world.</p><p>The widespread adoption of smartphones around the globe provides the potential of turning our phones into valuable disease diagnostics tools, enabling farmers to recognize diseases from images captured using the device’s camera.</p><p><strong>Discuss this post on </strong><a href="https://news.ycombinator.com/item?id=19163029"><strong>Hacker News</strong></a><strong> and </strong><a href="https://www.reddit.com/r/MachinesLearn/comments/aqlcfm/training_an_image_classification_convolutional/"><strong>Reddit</strong></a><strong>.</strong></p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9f5315ed59" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/training-an-image-classification-convolutional-neural-net-to-detect-plant-disease-using-fast-ai-a9f5315ed59">Training an Image Classification Convolutional Neural Net to Detect Plant Disease Using fast.ai</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Transfer Learning and Pre-trained Language Models to Classify Spam]]></title>
            <link>https://heartbeat.comet.ml/using-transfer-learning-and-pre-trained-language-models-to-classify-spam-549fc0f56c20?source=rss-25849db11a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/549fc0f56c20</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[heartbeat]]></category>
            <dc:creator><![CDATA[Steve Mutuvi]]></dc:creator>
            <pubDate>Thu, 31 Jan 2019 14:56:28 GMT</pubDate>
            <atom:updated>2021-09-22T15:17:20.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jR6U6w4XuQ-flGhE3jKo2w.jpeg" /></figure><p><a href="https://heartbeat.fritz.ai/transfer-learning-how-it-may-help-to-enable-ai-on-every-smartphone-de696f019e36">Transfer learning</a>, an approach where a model developed for a task is reused as the starting point for a model on a second task, is an important approach in machine learning. Prior knowledge from one domain and task is leveraged into a different domain and task. Transfer learning, therefore, draws inspiration from human beings, who are capable of transferring and leveraging knowledge from what they have learned in the past for tackling a wide variety of tasks.</p><p>In <a href="https://heartbeat.fritz.ai/the-5-computer-vision-techniques-that-will-change-how-you-see-the-world-1ee19334354b">computer vision</a>, great advances have been made using transfer learning approach, with pre-trained models being used as a starting point. This has sped up training and improved the performance of deep learning models. This is attributed to the availability of huge datasets like <a href="http://www.image-net.org/">ImageNet</a>, that have enabled the development of state-of-the-art pre-trained models used for transfer learning.</p><p>Until recently, the <a href="https://heartbeat.fritz.ai/the-7-nlp-techniques-that-will-change-how-you-communicate-in-the-future-part-i-f0114b2f0497">natural language processing</a> community was lacking its ImageNet equivalent. But development of transfer learning techniques in NLP continues to gain traction. In NLP, transfer learning techniques are mainly based on pre-trained language models, which repurpose and reuse deep learning models trained in high-resource languages and domains.</p><p>The pre-trained models are then fine-tuned for downstream tasks, often in low-resource settings. The downstream tasks include part-of-speech tagging, text classification, and <a href="https://heartbeat.fritz.ai/natural-language-in-ios-12-customizing-tag-schemes-and-named-entity-recognition-caf2da388a9f">named-entity recognition</a>, among others.</p><h3><strong>Contextualized Embeddings</strong></h3><p><a href="https://heartbeat.fritz.ai/coreml-with-glove-word-embedding-and-recursive-neural-network-part-2-d72c1a66b028">Word embedding</a> plays a critical role in the realization of transfer learning in NLP. The intuition behind word embeddings is that words are represented as low-dimensional vectors that capture both the syntax and semantics of the text corpus. Words with similar meanings tend to occur in similar context.</p><p>The word representations are learned by exploiting vast amounts of text corpora. A popular implementation of word embeddings is the <a href="https://skymind.ai/wiki/word2vec">Word2Vec</a> model which has two training options—<a href="https://www.researchgate.net/figure/Illustration-of-the-Skip-gram-and-Continuous-Bag-of-Word-CBOW-models_fig1_281812760">Continuous Bag of Words and the Skip-gram model</a>. Word embeddings are often used as the first data processing layer in a deep learning model.</p><p>One limitation of standard word embedding techniques such as Word2Vec, fasttext, and Glove is that they aren’t able to better disambiguate between the correct sense of a given word. In other words, each instance of a given word ends up having the same representation regardless of the context in which it appears.</p><p>Recently, contextual word embeddings such as <a href="https://allennlp.org/elmo">Embeddings from Language Models (ELMo)</a> and <a href="https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270">Bidirectional Encoder Representations from Transformers (BERT)</a> have emerged. These techniques generate embeddings for a word based on the context in which the word appears, thus generating slightly different embeddings for each of word’s occurrence.</p><p>ELMo uses a combination of independently trained left-to-right and right-to-left <a href="https://heartbeat.fritz.ai/a-beginners-guide-to-implementing-long-short-term-memory-networks-lstm-eb7a2ff09a27">LSTMs</a> to generate features for downstream tasks. On the other hand, BERT representations are jointly conditioned on both the left and right context and use the <a href="http://ai.googleblog.com/2017/08/transformer-novel-neural-network.html">Transformer</a>, a neural network architecture based on a self-attention mechanism. The Transformer has been shown to have superior performance in modeling long-term dependencies in the text, compared to <a href="https://heartbeat.fritz.ai/detecting-the-language-of-a-persons-name-using-pytorch-rnn-29a9090c20f2">recurrent neural network</a> architecture.</p><p>The integration of the contextual word embeddings into neural architectures has led to <strong>consistent improvements in important NLP tasks</strong> such as <a href="https://heartbeat.fritz.ai/training-a-sentiment-analysis-core-ml-model-28823b21322c">sentiment analysis</a>, question answering, reading comprehension, textual entailment, semantic role labeling, coreference resolution, or dependency parsing.</p><p>Language model embeddings can be used as features in a target model or a language model can be fine-tuned on target task data. Training a model on a large-scale dataset and then fine-tuning the Pre-trained model for a target task (transfer learning, if you’ll recall), can particularly be beneficial to low-resource languages where labeled data is limited.</p><blockquote><a href="https://www.deeplearningweekly.com/?utm_campaign=dlweekly-newsletter-expertise3&amp;utm_source=heartbeat">A newsletter for machine learners — by machine learners.</a> Sign up to receive our weekly dive into all things ML, curated by our experts in the field.</blockquote><h3><strong>The Flair Library</strong></h3><p><a href="https://jobs.zalando.com/tech/blog/zalando-research-releases-flair/?gh_src=4n3gxh1">Flair</a> is a library for state-of-the-art NLP developed by <a href="https://research.zalando.com/">Zalando Research</a>. It’s built in Python on top of the <a href="https://heartbeat.fritz.ai/introduction-to-pytorch-for-deep-learning-5b437cea90ac">PyTorch framework</a>. Flair allows for the application of state-of-the-art NLP models to text, such as named entity recognition (NER), part-of-speech tagging (PoS), sense disambiguation, and classification.</p><p>It is multilingual and allows you to use and combine different word and document embeddings, including the BERT embeddings, ELMo embeddings, and their proposed <a href="https://drive.google.com/file/d/17yVpFA7MmXaQFTe-HDpZuqw9fJlmzg56/view?usp=sharing">Flair embeddings</a>. In addition, Flair allows you to train your own language model, targeted to your language or domain, and apply it to the downstream task.</p><h3>Spam Classification using Flair</h3><p>While email continues to be the dominant medium for digital communications for both consumer and business uses, unsolicited bulk emails (i.e. spam) make up for <a href="https://www.statista.com/statistics/420391/spam-email-traffic-share/">approximately 53.5%</a> (as of September 2018) of the global email traffic.</p><p>Machine learning-based spam filtering approaches have been applied with success to automatically classify spam and non-spam emails. A crucial component in such approaches is word embeddings, typically trained over very large collections of unlabeled data to assist learning and generalization.</p><p>Contextualized word embeddings have been shown to significantly improve the performance of text classifier because they are able to capture word semantics in context. This means that the same word can have different embeddings depending on its contextual use, thus disambiguating words and addressing polysemy which affects the accuracy of text classification models.</p><p>The following implementation illustrates how to use the Flair library to train a language model and fine-tune it to classify spam.</p><h3>Getting started</h3><p>We begin by installing the Flair library using the <strong>pip command.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45fca392b8fcb06b86b7f00810c33a55/href">https://medium.com/media/45fca392b8fcb06b86b7f00810c33a55/href</a></iframe><p>The required Python libraries are then imported</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b56c7a17932e68a68bad98bd7561bc2f/href">https://medium.com/media/b56c7a17932e68a68bad98bd7561bc2f/href</a></iframe><h3>Loading and Pre-processing the Data</h3><p>We use the <a href="http://www.dt.fee.unicamp.br/~tiago/smsspamcollection/">SMS Spam Collection</a>, a public dataset of SMS labeled messages that have been collected for mobile phone spam research. The data is read using pandas and basic <a href="https://heartbeat.fritz.ai/data-preprocessing-and-visualization-implications-for-your-machine-learning-model-8dfbaaa51423">preprocessing</a> is done—namely removing duplicates, ensuring the labels are prefixed with __label__, and splitting the dataset into train, dev and test sets using the 80/10/10 split.</p><p>Flair’s classification dataset needs to be formatted based on Facebook’s <a href="https://fasttext.cc/docs/en/supervised-tutorial.html">FastText format</a>, which requires labels to be defined at the beginning of each line starting with the prefix __label__.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea563760c527a15d0571b6e799ae19d/href">https://medium.com/media/eea563760c527a15d0571b6e799ae19d/href</a></iframe><p>The next step is to train the model. All the required libraries and datasets are loaded into a corpus object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4538aaf84b5e823aa704cfbb8cd3a16/href">https://medium.com/media/b4538aaf84b5e823aa704cfbb8cd3a16/href</a></iframe><p>Finally, we load the pre-trained model and use it to predict if a message is spam or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d5d4fd807fc915eb411eba813d262e9/href">https://medium.com/media/4d5d4fd807fc915eb411eba813d262e9/href</a></iframe><h3>Model Evaluation</h3><p>The model achieved a <strong>F-score of 0.9845</strong> after 10 epochs, using default parameters. <a href="https://deepai.org/machine-learning-glossary-and-terms/f-score">F-score</a> calculates metrics globally by counting the total true positives, false negatives, and false positives.</p><p>It is a measure of a test’s accuracy that considers both the <a href="https://en.wikipedia.org/wiki/Precision_(information_retrieval)">precision</a> and the <a href="https://en.wikipedia.org/wiki/Recall_(information_retrieval)">recall</a> of the test to compute the score. Precision is the fraction of relevant instances among the retrieved instances, while recall is the fraction of relevant instances that have been retrieved over the total amount of relevant instances. In classification tasks for which every test case is guaranteed to be assigned to exactly one class, micro-F is equivalent to accuracy. This won’t be the case in multi-label classification.</p><h3>Baseline Model</h3><p>The <a href="https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0">logistic regression</a> baseline model achieved a <strong>f-score of 0.9668, </strong>which was marginally lower than that of Flair model above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b017550880ac36c39b0da9062317d11/href">https://medium.com/media/7b017550880ac36c39b0da9062317d11/href</a></iframe><h3>Discussion</h3><p>Machine learning models are data intensive and require access to large annotated data to train good predictive NLP models. The required annotated data will in most cases not be available beforehand for many domains or language. <a href="https://heartbeat.fritz.ai/it-all-boils-down-to-training-data-c7e3c2df1e6b">Annotation of such datasets </a>is a time-consuming, expensive exercise and a challenging task. But sufficient and accurately labeled is a key determinant of model’s prediction accuracy.</p><p>In view of these challenges, transfer learning via pre-trained language models is a promising approach to addressing these challenges.</p><p><strong>Discuss this post on </strong><a href="https://news.ycombinator.com/item?id=19051579"><strong>Hacker News</strong></a><strong> and </strong><a href="https://www.reddit.com/r/MachinesLearn/comments/alqr1v/using_transfer_learning_and_pretrained_language/"><strong>Reddit</strong></a><strong>.</strong></p><p><em>Editor’s Note:</em><a href="http://heartbeat.fritz.ai/"><em> Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=549fc0f56c20" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/using-transfer-learning-and-pre-trained-language-models-to-classify-spam-549fc0f56c20">Using Transfer Learning and Pre-trained Language Models to Classify Spam</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Depression from Routine Survey Data using Keras]]></title>
            <link>https://heartbeat.comet.ml/predicting-depression-from-routine-survey-data-using-keras-f72a71e4cfe8?source=rss-25849db11a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/f72a71e4cfe8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[heartbeat]]></category>
            <dc:creator><![CDATA[Steve Mutuvi]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 15:05:26 GMT</pubDate>
            <atom:updated>2021-10-01T19:17:52.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0nVDzgohmsL8mvNNfEdhhQ.jpeg" /></figure><p>Depression is among the most prominent mental illnesses, affecting more than 300 million people globally, according to the <a href="https://www.who.int/news-room/fact-sheets/detail/depression">World Health Organization</a> (WHO). Beyond the potentially devastating personal and social effects of depression, the economic costs related to this mental health issue have substantially increased in recent years. In fact, it’s currently estimated to cost the global economy over $1 trillion USD each year.</p><p>In this tutorial, we’ll build a simple neural network model using <a href="https://heartbeat.fritz.ai/introduction-to-deep-learning-with-keras-c7c3d14e1527">Keras</a> to predict individuals that are likely to be depressed from routine survey data. Keras is a high-level neural networks API written in <strong>Python</strong>, and it can run on top of TensorFlow, CNTK, or Theano. We evaluate the accuracy of the model and compare it to a binary classification baseline model based on a random forest algorithm.</p><h3><strong>Getting Started</strong></h3><h4><strong>Loading the Required Dependencies</strong></h4><p>We begin by loading the required dependencies to process data and build the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cd332243027bd0fbf0f983c6c4bddf0/href">https://medium.com/media/4cd332243027bd0fbf0f983c6c4bddf0/href</a></iframe><h4>Reading and Understanding the Data</h4><p>We’re using the <a href="https://zindi.africa/competitions/busara-mental-health-prediction-challenge/data">Busara’s Mental Health dataset</a>, which can be downloaded from the <a href="https://zindi.africa/about">Zindi</a> data science competition platform. Zindi is a platform where you can access datasets to solve African problems. We read the train.csv and test.csv files using pandas. The train.csv contains the data that we’ll use to train the model, while test.csv is the dataset we’ll apply to our model to make predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f0be6bb4790104f3956bbc76df25ac7/href">https://medium.com/media/7f0be6bb4790104f3956bbc76df25ac7/href</a></iframe><p>Using the dataframes’s shape property, we establish that the train set comprises 1143 rows and 75 columns, among them the target column (‘depressed’) which has values as 0,1.</p><h4><strong>Data Cleaning and Processing</strong></h4><p>Poor data quality due to missing data is always a challenge in machine learning. Handling missing data is therefore an important step in ensuring that ML models produce more accurate and valid prediction results. The function below computes and prints the percentage of missing values for each column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06f02bc33b63f52e9a9a254cd8ebbfdb/href">https://medium.com/media/06f02bc33b63f52e9a9a254cd8ebbfdb/href</a></iframe><p>A good rule of the thumb is that a column with 50% missing values can be excluded. For our training dataset, 4 columns exceed the 50% threshold and, therefore, we drop them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f70d44bce8ffa2e1944df17138ecf5ab/href">https://medium.com/media/f70d44bce8ffa2e1944df17138ecf5ab/href</a></iframe><p>Because we’re building a simple neural network using Keras, which only understands numbers, we convert the column survey_date, which is displayed as text, to numeric format using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html">SKlearn</a>. This involves creating a label (category) encoder object, fitting the encoder to the survey_date column, and finally applying the fitted encoder to the column to transform categories into integers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c7b0fcd41612ff673ddee3b24dcef2/href">https://medium.com/media/96c7b0fcd41612ff673ddee3b24dcef2/href</a></iframe><p>Now that we’ve processed our data to a considerable level, it’s time to specify the input and target variables. Our input will be every column except the depressed column, since that’s what we’re attempting to predict—hence, it’s our target variable.</p><p>We also handle any missing values in the columns with less that 50% null values using SKlearn’s Imputer class. The data is then split into train and test sets, and a random seed of 5 is specified for the purpose of reproducing the results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f008045c67d52acc39a3cd7c44ab459/href">https://medium.com/media/6f008045c67d52acc39a3cd7c44ab459/href</a></iframe><h3>Creating the Classification Model</h3><p>We build a simple neural network classification model using the Keras library. Keras is a user-friendly neural network library written in Python that defines models as a sequence of layers.</p><p>Using the add function, we add two input layers and an output layer, all of the type Dense, meaning that the layers are fully connected. Each input layer has 36 neurons, and the first layer expects 70 inputs while the output layer has 1 neuron to predict the outcome. We use the sigmoid function on the output layer to ensure our network output is between 0 and 1, while the relu function is used in the input layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9905068968cf15d3dc9c8f54341d2b7/href">https://medium.com/media/d9905068968cf15d3dc9c8f54341d2b7/href</a></iframe><h4><strong>Compile the Model</strong></h4><p>Now that the model is defined, we can compile it. In our case, TensorFlow backend is used for compiling, and it involves automatically choosing the best way to represent the network for training and making predictions. Training a network simply means finding the best set of weights to make predictions for this problem.</p><p>We therefore specify the loss function to be used to evaluate a set of weights, the optimizer used to search through different weights for the network, and metrics to evaluate the model’s performance. For a binary classification problem like this one, we use binary_crossentropy for the logarithmic loss, adam for gradient descent, and accuracy for the metric parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e95236227b2c7317092190889c40ec1/href">https://medium.com/media/0e95236227b2c7317092190889c40ec1/href</a></iframe><h4><strong>Fit the Model</strong></h4><p>Having created and compiled our model, it’s time to train or fit the model on our loaded data by calling the fit() function. The model will iterate 100 times through the dataset, as defined by the epochs<strong> </strong>argument. The batch_size argument sets the number of instances that are evaluated before a weight update in the network is performed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83a9a9ca50103ba8465b973543c1ea3b/href">https://medium.com/media/83a9a9ca50103ba8465b973543c1ea3b/href</a></iframe><h4><strong>Evaluate the Model</strong></h4><p>We finally evaluate the model for our test data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/963c505f26930b577bcca9ae7ca4d679/href">https://medium.com/media/963c505f26930b577bcca9ae7ca4d679/href</a></iframe><p>The model achieved accuracy of 86.51%. This accuracy is slightly higher than that of the random forest baseline model below, whose accuracy evaluated to 85.98%.</p><h4>Baseline Model</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e13d0e20aeb7bffaf67ca5448762f6c/href">https://medium.com/media/8e13d0e20aeb7bffaf67ca5448762f6c/href</a></iframe><h4>Conclusion</h4><p>Mental health is a key component of public health more broadly. It’s a key determinant of overall health and socio-economic development. Governments globally continue to heavily invest and put in place measures and strategies for mitigating the burden of mental health problems and disorders, such as depression.</p><p>Early prediction and detection of depression is an essential step towards implementing effective prevention and clinical intervention strategies. Statistical models, like the one developed in this tutorial, can provide an alternative approach to the medical science approaches for detecting depression, which mainly rely on analyzing self-reported patient data.</p><p>Our model could be incorporated into public health information systems to screen for risk factors for depression. It could also be used by various organizations, especially non-governmental organizations (NGOs) that routinely conduct surveys related to mental health.</p><p><strong>Discuss this post on </strong><a href="https://news.ycombinator.com/item?id=18815677"><strong>Hacker News</strong></a><strong> and </strong><a href="https://www.reddit.com/r/MachinesLearn/comments/ac6mb7/predicting_signs_of_depression_from_survey_data/"><strong>Reddit</strong></a><strong>.</strong></p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f72a71e4cfe8" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/predicting-depression-from-routine-survey-data-using-keras-f72a71e4cfe8">Predicting Depression from Routine Survey Data using Keras</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>