<?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 Leonardo Mauro P. Moraes on Medium]]></title>
        <description><![CDATA[Stories by Leonardo Mauro P. Moraes on Medium]]></description>
        <link>https://medium.com/@leomaurodesenv?source=rss-f4d6e632704c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5OrSo6sjY-mr6grzCH1DUA.jpeg</url>
            <title>Stories by Leonardo Mauro P. Moraes on Medium</title>
            <link>https://medium.com/@leomaurodesenv?source=rss-f4d6e632704c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 14:37:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leomaurodesenv/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[Driving Innovation: Leveraging Machine Learning Platforms]]></title>
            <link>https://medium.com/@leomaurodesenv/driving-innovation-leveraging-machine-learning-platforms-f428ea34c3ab?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f428ea34c3ab</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ml-platform]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 22:27:05 GMT</pubDate>
            <atom:updated>2024-04-12T22:27:05.810Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial Intelligence (AI) is no longer just a fairy tale. We have seen AI changing life and business, such as the implementation of chatbots for customer service and the use of machine learning algorithms for health-care in highly advanced hospitals. As technology continues to advance, AI will likely play an even greater role in shaping the future of various industries. This raises questions like: “<em>How can we leverage data science projects to improve business outcomes in my company?</em>” One practicable answer: You may require a Machine Learning Platform (ML Platform).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxsBU6nL5PP5us1FwMTbMw.png" /><figcaption>Machine Learning Platform. Co-created with <a href="https://ideogram.ai/g/l5EvLIZORCiw06hFrcOrvg/3">Ideogram</a></figcaption></figure><p>Machine Learning Platforms offer numerous benefits for speeding up data science projects. Firstly, they provide a centralized way to access data, via a common database or a feature store. These platforms also offer features for automating repetitive tasks, like training a model or running a batch prediction, thus boosting productivity and efficiency. Furthermore, they facilitate collaboration among data scientists and enable easy sharing of code and models, since everyone writes code in a common framework-way. More advanced platforms can leverage pre-built models and workflows, reducing the time needed to develop and test new models.</p><h3>Seems interesting… How can I start?</h3><p>There are a few well-established platforms and tools on the market, or you can choose to build your in-house solution. Using paid tools can offer benefits such as saving time and resources during the development process, accessing well-tested and validated features, and possibly finding tutorials on the internet. On the other hand, in-house solutions provide a wealth of flexibility and empower you to develop new features without any tool lock-in. Anyway, you can also choose a mixed platform approach.</p><p>When considering a Machine Learning Platform, there are a few names that come to mind, including <a href="https://www.databricks.com/">Databricks</a>, <a href="https://azure.microsoft.com/en-us/free/machine-learning/">Microsoft Azure ML</a>, <a href="https://cloud.google.com/vertex-ai">Google Vertex AI</a>, <a href="https://aws.amazon.com/sagemaker/">Amazon SageMaker</a>, and <a href="https://www.snowflake.com/en/">Snowflake</a>. Furthermore, there is a range of open-source tools for you to create your in-house platform, including <a href="https://kubernetes.io/">Kubernetes</a>, <a href="https://mlflow.org/">MLFlow</a>, <a href="https://dvc.org/">DVC (Data Version Control)</a>, <a href="https://kedro.org/">Kedro</a>, <a href="https://www.kubeflow.org/">Kubeflow</a>, <a href="https://fastapi.tiangolo.com/">FastAPI</a>, <a href="https://www.bentoml.com/">BentoML</a>, and many others. In this blog post, we will cover one paid and one open-source ML Platform. Remember that your platform can and probably will be built using a combination of tools, depending on the suitable technical stack for your company.</p><h3>ML Platforms available on the Market</h3><p>As mentioned, there are a number of machine learning platforms available in the market. Here, I would like to explore the Databricks and <a href="https://www.microsoft.com/pt-br/microsoft-fabric">Microsoft Fabric</a> — the most complete and agnostic solutions in the market. Databricks is a popular machine learning platform that offers a unified analytics and collaboration platform built on Apache Spark. On the other hand, Microsoft Fabric is a platform that provides scalable machine learning infrastructure and tools for developing data products in general. Both platforms have their own strengths, however Databricks is already well-established in the industry, meanwhile Microsoft Fabric is a new player. In the beginning of 2024, Microsoft Fabric shows potential, although it is not yet as mature as Databricks.</p><p>Databricks offers a comprehensive suite of features, like unified data source, experiments tracking, model serving, and workflows for data science. With its scalable infrastructure and powerful collaboration tools, Databricks enables data scientists and engineers to work collaboratively on large-scale machine learning projects, facilitating faster experimentation and iteration. For instance, it provides a <a href="https://docs.databricks.com/en/machine-learning/feature-store/index.html">Feature Store</a> for storing model features, integrates with <a href="https://docs.databricks.com/en/machine-learning/manage-model-lifecycle/index.html">MLFlow</a> for managing model lifecycles, and utilizes <a href="https://docs.databricks.com/en/workflows/index.html">Workflows</a> for scheduling model training and batch predictions. Overall, Databricks offers a great set of features as a ML Platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*uflzAIrin3KL7O-THCsIBw.png" /><figcaption>Azure Databricks architecture. Source: <a href="https://learn.microsoft.com/pt-br/azure/architecture/ai-ml/architecture/batch-scoring-databricks">Azure</a></figcaption></figure><h3>Open-Source ML Platform</h3><p>Given the vast options of open-source tools at our disposal, it becomes complex and easier for a company to curate a selection of them to create their own ML Platform. However, you must consider the effort required to do so. In this blog post, I showcase a simple but very powerful open-source machine learning platform that you can use in your company.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eJJZAdG9DmiBwObI" /><figcaption>Open-source ML Platform Architecture. Draw with <a href="https://github.com/mymlops">MyMLOps</a></figcaption></figure><p>The MLOps community strongly recommends having a way to manage models, such as tracking experiments and using a model registry. Additionally, data versioning is essential, and it is recommended to version all code in Git. In this architecture, I proposed MLFlow as the main tool for model management and DVC for data versioning. Optionally, you can use a pipeline orchestration, such as <a href="https://github.com/spotify/luigi">Luigi</a> and <a href="https://github.com/kedro-org/kedro">Kedro</a>. Moreover, FastAPI can create an API for your model. By using <a href="https://grafana.com/">Grafana</a> and <a href="https://prometheus.io/">Prometheus</a>, it provides model observability and monitoring. In this way, you have a cloud-agnostic ML Platform Architecture.</p><h3>Conclusion</h3><p>ML Platforms are decisive tools for any data science team. They simplify the process of training, experimentation, and serving models. While the market offers numerous options, selecting the right platform depends on individual needs, preferences, and the specific requirements of the project. You must consider a few considerations for your ML Platform: Ensure compatibility with your current technical stack; Offer a robust scale infrastructure for handling your use cases; and cost-benefit ratio.</p><p><strong>Extra References</strong></p><ul><li><a href="https://www.featurestore.org/">Feature Store tools list</a></li><li><a href="https://github.com/kelvins/awesome-mlops">Awesome MLOps tools</a></li><li><a href="https://github.com/visenger/awesome-mlops">Awesome MLOps news</a></li><li><a href="https://www.gartner.com/reviews/market/data-science-and-machine-learning-platforms">Gartner ML Platform list</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f428ea34c3ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identity Document Recognition — Understanding the Basics of Image Classification]]></title>
            <link>https://medium.com/@leomaurodesenv/identity-document-recognition-understanding-the-basics-of-image-classification-9217ad27ea91?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9217ad27ea91</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 00:16:06 GMT</pubDate>
            <atom:updated>2023-10-18T15:40:13.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>Identity Document Recognition — Understanding the Basics of Image Classification</h3><p>Identity documents play a crucial role in our lives, providing a means to verify our identity and access many services. However, with the increasing number of identity theft cases and illegal activities, it is essential to implement robust systems for identity document classification. This process involves automatically categorizing different types of identity documents, such as passports, driver’s licenses, and national identification cards, to ensure security and efficiency in identity recognition processes. In this blog post, we will discuss the basics of image classification for real-world identity document images and its important setup aspects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KnlMeXlZQiokJDO5" /><figcaption>Photo by <a href="https://unsplash.com/@nicolegeri?utm_source=medium&amp;utm_medium=referral">Nicole Geri</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><h3>Techniques Used in Document Image Classification</h3><p>There are several techniques used in document image classification. One popular technique is image classification using deep learning models. Another technique is layout analysis, which involves analyzing the layout and structure of the document to identify its type. Additionally, traditional feature extraction involves extracting specific features from an image such as color, shape or texture, to classify the document.</p><p><strong>Focus</strong>. In this blog post, we will build a robust image classification model using deep learning specifically designed for the classification of identity documents from the basics of image classification. Nevertheless, the following codes/notes can be applied to other classification cases as well.</p><h3>Real-world Use Case</h3><p>Currently, our customers request or send us various types of documents. From these documents, we extract several important information for them. For this information to be correctly extracted, an automatic identity document type classification process is necessary. The challenge is to classify at least the RG (Brazilian regional identification) and CPF (Brazilian national identification) documents, using their images, through machine learning. <strong>Note</strong>. Since the model code is not limited to specific set of image classes, this use case can be expanded to other types of documents as well.</p><p>In this blog post, we will explore the BID dataset. <a href="https://github.com/ricardobnjunior/Brazilian-Identity-Document-Dataset">BID (Brazilian Identity Document)</a> dataset is a collection of 28,800 document images. It is composed of images of Brazilian identification documents divided into eight classes: both front and back faces of driver’s license (CNH), CNH front face, CNH back face, Brazilian national identity (CPF) front face, CPF back face, Brazilian regional identity (RG) front face, RG back face, and RG front and back faces. It counts 3,600 samples for each class.</p><p>For simplicity, we will use a subset of the dataset (70MB), not the full (8GB).</p><pre># Download the dataset<br># install the &quot;gdown&quot; library<br>!pip install gdown<br><br># full dataset<br># !gdown 1Oi88TRcpdjZmJ79WDLb9qFlBNG8q2De6<br><br># subset dataset<br>!gdown 144EqqmMtCziua9iYo-3afUEvZrJVxUXU</pre><h3>Cleaning the Dataset</h3><p>In this dataset we have eight types of identity documents. I select three types for this blog post experiment: CNH_Frente, CPF_Frente and RG_Frente. I also removed unused files, such as “*_ocr.txt” and “*_segmentation.jpg”. These files are explored on other types of document analysis; they are: (i) Optical character recognition (OCR) for text and values extraction, and (ii) Segmentation for document layout extraction. Remaining only the useful identity document images for our use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*IIg6sq_1GzxST77dhrhJZg.png" /><figcaption>BID dataset image sample.</figcaption></figure><h3>Machine Learning Modeling</h3><p>In this use case, we will apply <a href="https://keras.io/">Keras framework</a> in the implementation. Keras is a high-level neural network API written in Python and designed to run on top of other deep learning frameworks, such as TensorFlow or Theano. With its user-friendly interface, Keras simplifies the process of building and training deep learning models.</p><p>The initial task is to define the model architecture. Throughout this use case, we will explore preprocessing, data augmentation, image feature extraction and classification techniques. Keras provides a variety of layers, such as normalization for preprocessing, image flipping for data augmentation, dense and convolutional layers for feature extraction and classification, that can be stacked together to form the model.</p><p>Initially we perform the data preprocessing to rescale the images to fit our model. Later, let’s conduct augmentation on the data to avoid overfitting, to make the model robust for real-world use cases, and to increase the amount of data in the training set. We will use three types of augmentation: <a href="https://keras.io/api/layers/preprocessing_layers/image_augmentation/">image rotation, flipping and zoom adjustment</a>.</p><pre># data normalization<br># -- resizing for a fixed size<br># -- value rescaling between [0, 1]<br>resize_and_rescale = tf.keras.Sequential([<br>  layers.Resizing(img_height, img_width),<br>  layers.Rescaling(1./255)<br>])<br><br># data augmentation<br>data_augmentation = keras.Sequential([<br>  layers.RandomFlip(&quot;horizontal_and_vertical&quot;),<br>  layers.RandomRotation(0.1),<br>  layers.RandomZoom(0.05),<br>])</pre><p><strong>Note</strong>. Data Augmentation is disabled at test/validation time, so input images will only be upscaled during calls to Model.fit on the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*zOTKh5wlG62vjJSXCXDd7g.png" /><figcaption>Image samples after the Data Preprocessing and Augmentation</figcaption></figure><p>After defining the preprocessing steps, you need to compose your neural network by combining the feature extraction layers and the feedforward layers for image classification. We will employ a set of convolutional layers and pooling layers to perform the feature extraction. Convolutional layers are designed for visual processing tasks, mimicking how the human visual cortex works. It is commonly used for image and video recognition, as well as in computer vision applications. The convolutional layers extract features from the images, followed by pooling layers to reduce dimensionality of the features and extract the visual patterns.</p><p>In the meantime, let’s proceed with implementing a feedforward neural network using dense and dropout layers. A feedforward neural network is a type of artificial neural network used for common classification applications. Dense layers are layers where all neurons in the current layer are connected to all neurons in the next layer, allowing for complex patterns to be learned. Dropout layers are used to prevent overfitting by randomly setting a fraction of input units to zero at each training step.</p><pre>model = Sequential([<br>  # preprocessing<br>  data_augmentation,<br>  resize_and_rescale,<br><br>  # convolutional layers<br>  layers.Conv2D(64, 3, padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>  layers.MaxPooling2D(),<br>  layers.Conv2D(32, 3, padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>  layers.MaxPooling2D(),<br>  layers.Conv2D(16, 3, padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>  layers.MaxPooling2D(),<br><br>  # feedfoward layers<br>  layers.Flatten(),<br>  layers.Dropout(0.3),<br>  layers.Dense(256, activation=&#39;relu&#39;),<br>  layers.Dropout(0.3),<br>  layers.Dense(128, activation=&#39;relu&#39;),<br>  layers.Dropout(0.3),<br>  layers.Dense(num_classes)<br>])</pre><p><strong>Note</strong>. Given that the model features data augmentation and dropout layers, its convergence is expected to be slower, i.e., more training epochs are required. However, it will be more adaptive to real-world data.</p><p>Next, we can train the model using our training dataset. To avoid overtraining, we will employ an early stopping method. Early stopping is a technique used in machine learning to prevent a model from overfitting the training data. It involves monitoring the model’s performance on a separate validation set and stopping the training process when the performance on the validation set starts to degrade. I instructed the model to pause after every ten steps and evaluate if there is a drop in loss of at least 0.001. If not, the training process will be halted.</p><pre># early stopping, to avoid overfitting<br>early_stopping = keras.callbacks.EarlyStopping(<br>  patience=10,<br>  min_delta=0.001,<br>  restore_best_weights=True,<br>)<br><br># training<br>history = model.fit(<br>  train_ds,<br>  epochs=200,<br>  validation_data=val_ds,<br>  callbacks=[early_stopping]<br>)</pre><p><strong>Note</strong>. Using the early stopping method, the model was trained in only 30 epochs, in less than one minute. Of course, considering I only used a subset of the entire dataset for learning purposes of this blog post.</p><h3>Model Performance</h3><p>Once the model is trained, we can evaluate its performance on the validation dataset. Keras allows you to compute metrics such as accuracy, precision, recall, or F1 score, depending on the type of problem you are working on. This evaluation step is crucial to assess how well the model generalizes to unseen data. Our model reached 97.70% of accuracy in training set and 95.24% of accuracy in validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*ji4E5lDXoNqf4UE4Sk55_w.png" /><figcaption>Model performance across training epochs.</figcaption></figure><h3>Conclusion</h3><p>Identity document recognition is a valuable classification model that can help organizations manage their digital documents more efficiently. It involves categorizing documents based on their content, layout or structure, using deep learning techniques. In this blog post, I presented how to build a robust classification model using the basics of image classification. Each of the steps (normalization, data augmentation, feature extraction and classification network) are customizable, you can change and improve it in different ways. In any case, we achieved an impressive accuracy rate of over 95% in categorizing three documents for our specific use case. You can see the complete code in the <strong>Jupyter Notebook</strong>:</p><p><a href="https://github.com/leomaurodesenv/kaggle/blob/main/jupyter/identity-document-image-classification.ipynb">kaggle/jupyter/identity-document-image-classification.ipynb at main · leomaurodesenv/kaggle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9217ad27ea91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficiently Setting up VS Code for Data Science Development on Windows with WSL]]></title>
            <link>https://medium.com/@leomaurodesenv/efficiently-setting-up-vs-code-for-data-science-development-on-windows-with-wsl-47a7ef0d74b8?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a7ef0d74b8</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 21:20:55 GMT</pubDate>
            <atom:updated>2023-07-03T21:20:55.699Z</atom:updated>
            <content:encoded><![CDATA[<p>In the year 2023, the Windows Operating System (OS) continues to dominate desktop computers, representing 57.37% market share (<a href="https://www.gizmochina.com/2023/03/07/windows-losing-market-share-us-historic-low-57/">source</a>). However, despite its widespread adoption, Windows has been observed to be less user-friendly for Data Scientists and general developers compared to Linux-based systems. Additionally, it often presents limitations in terms of available integrations and development tools. This raises an important question: How can we efficiently set up a Data Science development environment on Windows? VS Code and WSL are a powerful combination to resolve this question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/0*lk5tBya0mgU-TA8b.png" /><figcaption>Visual Studio Code (source: <a href="https://code.visualstudio.com/">Windows Visual Studio Code</a>)</figcaption></figure><p>Visual Studio Code (VS Code) is a popular, lightweight, and feature-rich integrated development environment (IDE) that offers excellent support for various programming languages, including those commonly used in Data Science, such as Python, R, and Julia. Moreover, VS Code offers a wide range of extensions specifically designed for Data Science, providing features such as code formatting, linting, debugging, and integration with popular data manipulation and visualization libraries.</p><p>By integrating Windows Subsystem for Linux (WSL), which provides a compatibility layer for running Linux distributions on Windows, Data Scientists can take advantage of the benefits offered by Linux-based systems without completely migrating to a different operating system. WSL allows users to run native Linux commands and access the Linux file system from within Windows, effectively bridging the gap between Windows OS and the Linux ecosystem.</p><blockquote>The flexibility and extensibility of VS Code, combined with the compatibility and accessibility provided by WSL, make this combination a powerful choice for Data Scientists to efficiently develop on Windows OS.</blockquote><h3>1. Install the Windows Subsystem for Linux (WSL)</h3><p>To install WSL, you need open Windows PowerShell with Administrator access using the right-click option “Run as Administrator”.</p><pre># 1. Install WSL using the command<br>$ wsl --install<br><br># 2. Install Ubuntu on your WSL<br>$ wsl --install -d ubuntu<br><br># 3. Set up your Ubuntu user credentials<br>#    Follow the instructions<br><br># 4. Update your Ubuntu machine<br>$ sudo apt update &amp;&amp; sudo apt upgrade</pre><p>If you face any issue, access these official tutorials:</p><ul><li><a href="https://learn.microsoft.com/en-us/windows/wsl/install">Install Linux on Windows with WSL</a></li><li><a href="https://learn.microsoft.com/en-us/windows/wsl/setup/environment">Set up a WSL development environment</a></li><li><a href="https://ubuntu.com/tutorials/install-ubuntu-on-wsl2-on-windows-10#1-overview">Install Ubuntu on WSL2 on Windows 10</a></li></ul><h3>1.1 Windows Terminal [Optional]</h3><p>To enhance your experience with multiple terminals like Windows PowerShell, WSL, and WSL Ubuntu, consider installing Windows Terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*trTtt4-32H9UqG6QViS5mg.png" /><figcaption>Windows Terminal, showing WSL Ubuntu distro</figcaption></figure><p>You can download via Windows Store, or through this <a href="https://apps.microsoft.com/store/detail/windows-terminal/9N0DX20HK701">link</a>.</p><h3><em>1.2 Install Python on WSL Ubuntu [Optional]</em></h3><p>You can follow these steps to set up Python on your WSL Ubuntu machine.</p><pre># 1. Install Python 3.10<br>$ sudo apt install python3.10<br>$ sudo apt install python3.10-venv<br><br># 2. Install Python Pip<br>$ sudo apt install python3-pip</pre><h3>2. Install the Visual Studio Code (VS Code)</h3><p>To install VS Code, download and install Visual Studio Code for Windows from the official website.</p><ol><li>Download VS Code from <a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a></li><li>Follow the steps to configure the VS Code.</li></ol><h3>3. Integrating Visual Studio Code with WSL</h3><p>Now, you can integrate your VS Code with WSL Ubuntu.</p><ol><li>Click on the “Extensions” icon on the left sidebar. In the search bar, type the name of the extension you want to install.</li><li>Install the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl">WSL</a> extension</li><li>Install the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack">Remote Development</a> extension pack</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpeN3PZCz8H9JXg6r64zYg.png" /><figcaption>VS Code, WSL extension</figcaption></figure><p><strong>Done</strong>. Happy coding!</p><h3>Conclusion</h3><p>By following these steps, you can efficiently set up Windows OS for Data Science development using VS Code with WSL and take advantage of the best of both worlds. You can also take advantage of Visual Studio Code’s powerful extensions and debugging features, as well as use the Linux-based features to streamline your workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ktgjs0V6HJ-sbrVLddv7RA.png" /><figcaption>VS Code, running Python commands on WSL</figcaption></figure><h3>Troubleshooting Reference [Extra]</h3><p>Troubleshooting is the process of identifying and resolving problems or issues that occur in systems and software. Troubleshooting can be helpful when facing difficulties during installation or execution of steps. Here is a list of useful troubleshooting references:</p><ul><li><a href="https://learn.microsoft.com/en-us/windows/wsl/troubleshooting">Troubleshooting Windows Subsystem for Linux</a></li><li>Forum — <a href="https://learn.microsoft.com/en-us/answers/questions/853140/wsl-2-internet-connectivity-is-gone">WSL 2 internet connectivity issue</a></li><li>GitHub — <a href="https://github.com/microsoft/WSL/issues/5420">WSL 2 keeps overwriting resolv.conf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a7ef0d74b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up your Git Bash/ZSH terminals on Windows]]></title>
            <link>https://medium.com/@leomaurodesenv/setting-up-your-git-bash-zsh-terminals-on-windows-fa94871f440d?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa94871f440d</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[developement]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 00:27:19 GMT</pubDate>
            <atom:updated>2023-03-15T00:27:19.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Command-line tool" src="https://cdn-images-1.medium.com/max/1024/0*Ykq0iCJPgrvDgB2x" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Git Bash and ZSH are command-line interfaces that allow users to interact with their operating system using text commands. Although Windows comes with its own command prompt, many developers prefer to use Git Bash or ZSH because they offer a more powerful set of features. Turning into powerful tools for developers.</p><blockquote>This tutorial provides a comprehensive guide with essential steps and tips for implementing a great terminal for development on Windows machines.</blockquote><h3>Setup Git Bash</h3><p>To setup Git Bash on Windows, follow these steps:</p><ol><li>Download the Git for Windows installer from the <a href="https://git-scm.com/downloads">official website</a>.</li><li>Run the installer and select the desired components. Make sure the “Git Bash” option is selected.</li><li>Follow the rest of the installer prompts to complete the installation.</li></ol><p>Once Git Bash is installed, you can access it by right-clicking in a folder and selecting “Git Bash Here” from the context menu. This will open a Git Bash terminal window in that folder.</p><h3>Setup ZSH</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*4j5wCZMd8UA0kHy6UnuMig.png" /><figcaption>Git Bash / ZSH on Windows by <a href="https://walterteng.com/using-zsh-on-windows">Walter Teng</a>.</figcaption></figure><p>To setup ZSH on Git Bash, follow these steps:</p><p>1. Download the latest ZSH package from the <a href="https://packages.msys2.org/package/zsh?repo=msys&amp;variant=x86_64">MSYS2 package repository</a>. The file will be named something like “<a href="https://repo.msys2.org/msys/x86_64/zsh-5.8-5-x86_64.pkg.tar.zst"><em>zsh-5.8–5-x86_64.pkg.tar.zst</em></a><em>”</em>.</p><p>2. Install an extractor that can open TAR and ZST archives such as <a href="https://www.7-zip.org/">7-Zip</a> and <a href="https://github.com/facebook/zstd">facebook/zstd</a> (named something like “<a href="https://github.com/facebook/zstd/releases/download/v1.5.2/zstd-v1.5.2-win64.zip"><em>zstd-v1.5.2-win64.zip</em></a>”). First, use <em>zstd</em> to extract the TAR file. Later, use 7-Zip to extract the files into the Git Bash directory.</p><pre># Open Git Bash<br># Navigate to zstd file<br>$ cd ~/../zstd-v1.5.4-win64<br><br># Decompress the .zst file<br>$ ./zstd --decompress ~/Downloads/zsh-5.8-5-x86_64.pkg.tar.zst<br><br># The TAR file will be created in the ~/Downloads/ directory<br>$ ls ~/Downloads/ | grep .tar</pre><p>3. Extract the archive’s file using the 7-Zip (which should include <em>etc</em> and <em>usr</em> folders) into your Git Bash installation directory. This directory is usually located at “<em>C:\\Program Files\\Git</em>”. If asked, merge the contents of the folder (no files should be overwritten).</p><p>4. Open Git Bah and test the ZSH.</p><pre># Testing ZSH<br>$ zsh</pre><p>5. Configure ZSH as default command-line shell.</p><pre># Create/edit the ~/.bashrc file<br>$ notepad ~/.bashrc<br><br># Add the following content<br>if [ -t 1 ]; then<br>  exec zsh<br>fi<br><br># Save the file and close the Git Bash</pre><p>Once ZSH is installed and set as the default shell, you can access it by opening the Git Bash. Now, your Git Bash will open a ZSH terminal.</p><h3>Setup oh-my-zsh (optional)</h3><p><a href="https://github.com/ohmyzsh/ohmyzsh/">oh-my-zsh</a> is a popular open-source framework for managing ZSH terminal. It includes a large number of plugins and themes, as well as a set of default configurations that can help you get started with ZSH. Using oh-my-zsh can help simplify and streamline your development, making it easier and more powerful than ever.</p><p>1. Installing oh-my-zsh, execute the following command on Git Bash.</p><pre># Install oh-my-zsh<br>sh -c &quot;$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)&quot;</pre><p>Additional packages</p><ul><li>There is a set of <a href="https://github.com/ohmyzsh/ohmyzsh/wiki/Themes">zsh themes</a> available.</li><li>There is <a href="https://github.com/zsh-users/zsh-syntax-highlighting">syntax highlighting</a> tools.</li><li>There is <a href="https://github.com/zsh-users/zsh-completions">additional commands</a>.</li><li>and much more!</li></ul><h3>Conclusion</h3><p>In summary, Git Bash and ZSH are powerful command-line interfaces that offer a more flexible and feature-rich alternative to the Windows command prompt. By following the steps outlined in this tutorial, you can easily set up Git Bash and ZSH on your Windows machine and start using them for your development work.</p><h3>Reference</h3><ul><li><a href="https://walterteng.com/using-zsh-on-windows">Using zsh on Windows</a></li><li><a href="https://gist.github.com/fworks/af4c896c9de47d827d4caa6fd7154b6b">Zsh / Oh-my-zsh on Windows Git Bash</a></li><li><a href="https://dominikrys.com/posts/zsh-in-git-bash-on-windows/">Installing Zsh (and oh-my-zsh) in Windows Git Bash</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa94871f440d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing AutoML Tools in Titanic Dataset — Machine Learning]]></title>
            <link>https://medium.com/wearesinch/comparing-automl-tools-in-titanic-dataset-machine-learning-87ae3b23228a?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/87ae3b23228a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 11:46:43 GMT</pubDate>
            <atom:updated>2023-02-09T23:48:34.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparing AutoML Tools in Titanic Dataset — Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aj9Pi-kIXe6DLBvQBkLn8A.png" /></figure><p><strong>What is AutoML?</strong> Automated Machine Learning (AutoML) is the process of automating the tasks of applying machine learning to problems. Machine learning lifecycle is composed of several steps including, but not limited to, data selection, data preprocessing, data mining, model evaluation, model fine-tuning, and deployment [Adapted from Fayyad, 96]. Thus, AutoML is the process of automatizing one or more steps from the machine learning lifecycle. In this way, we can improve the efficiency of machine learning experiments and accelerate research on the problem.</p><p><strong>How can we use AutoML?</strong> Okay, let’s use AutoML. The problem is that there are multiple Python packages, so how can I choose the right package for my project? It is not very clear how to do that; and it is a time-consuming experience for all of them. In this blog post, we are going to explore a set of 11 (eleven) well-known Python packages for AutoML.</p><h3>Experimentation Setup</h3><p>For this AutoML benchmark, we used the dataset from <a href="https://www.kaggle.com/competitions/titanic">Titanic — Machine Learning from Disaster</a> competition, simply called the Titanic dataset. This is a competition to use machine learning to create a classification model that predicts which passengers survived the sinking of the Titanic. The titanic dataset is composed of twelve columns of categorical and numerical data, such as “Pclass”, “Name”, “Sex”, “Fare”, “Cabin”, “Embarked”, etc. Since many of the AutoML packages do not process categorical data, I performed a simple preprocessing to remove and transform the columns.</p><p>The train set counts just 891 samples. We are going to use this set to train and validate our AutoML packages. The results of the test will then be sent to the competition. We are going to normalize the train set using an Encoder and Imputer (for missing data). I encoded the columns “Sex”, “Embarked” to numerical columns, and executed the Imputer into the columns “Pclass”, “Sex”, “SibSp”, “Parch”, “Fare”, “Age”, “Embarked”. You can access the Jupyter Notebook code from the public link at the end of the blog post.</p><blockquote>Note, a few codes are written in markdown in the Jupyter Notebook, because it uses incompatible packages for the other packages. But they all have the installation and run code.</blockquote><h3># Lazy Predict</h3><p>[<a href="https://github.com/shankarpandala/lazypredict">GitHub</a>, <a href="https://lazypredict.readthedocs.io/">Documentation</a>] Lazy Predict helps build a lot of basic models (from scikit-learn and similar libraries) without much code, and helps understand which models work better without any parameter tuning. In other words, Lazy Predict is a good library to test multiple solutions at once quickly. It only includes preprocessing and model training; thus, it does not perform any fine-tuning.</p><pre># Lazy Predict<br>from lazypredict.Supervised import LazyClassifier<br><br>automl = LazyClassifier()<br>results, _ = automl.fit(X_train, X_train, y_train, y_train)</pre><h3># hyperopt-sklearn</h3><p>[<a href="https://github.com/hyperopt/hyperopt-sklearn">GitHub</a>, <a href="http://hyperopt.github.io/hyperopt-sklearn/">Documentation</a>] hyperopt-sklearn (hyperparameter optimization for scikit-learn) is hyperopt-based model selection among machine learning algorithms in scikit-learn. In contrast with Lazy Predict, hyperopt-sklearn can perform hyperparameter tuning in the models, but it does not perform data preprocessing automatically.</p><pre># hyperopt-sklearn<br>from hpsklearn import HyperoptEstimator<br><br>automl = HyperoptEstimator()<br>automl.fit(X_train, y_train)</pre><h3># auto-sklearn</h3><p>[<a href="https://github.com/automl/auto-sklearn">GitHub</a>, <a href="https://automl.github.io/auto-sklearn/master/">Documentation</a>] auto-sklearn is a toolkit on top of scikit-learn estimator. In summary, it combines data preprocessing, feature preprocessing and classifier evaluation. Note, it does not train simple models, auto-sklearn ensemble models to get better performance. It is good for competitions, but not for production models.</p><pre># auto-sklearn<br>from autosklearn.classification import AutoSklearnClassifier<br><br>automl = AutoSklearnClassifier()<br>automl.fit(X_train, y_train)</pre><h3># TPOT</h3><p>[<a href="https://github.com/EpistasisLab/tpot">GitHub</a>, <a href="http://epistasislab.github.io/tpot/">Documentation</a>] TPOT stands for Tree-based Pipeline Optimization Tool. It optimizes machine learning pipelines using genetic programming. It looks like a combination of hyperopt-sklearn fine-tuning and auto-sklearn data preprocessing, however, it does not ensemble the models — it keeps models simple and interpretable. Nice tool for high performance and simple modeling.</p><pre># TPOT<br>from tpot import TPOTClassifier<br><br>automl = TPOTClassifier()<br>automl.fit(X_train, y_train)</pre><h3># MLJAR</h3><p>[<a href="https://github.com/mljar/mljar-supervised">GitHub</a>, <a href="https://supervised.mljar.com/">Documentation</a>] mljar-supervised abstracts the common way to preprocess the data, construct the machine learning models, and perform hyperparameter tuning to find the best model. Also, it supports explainability and automatic exploratory data analysis. It contains more features than TPOT, but it is more complex too. Also, it can support textual data, but it was developed for tabular data only.</p><pre># MLJAR<br>from supervised.automl import AutoML<br><br>automl = AutoML(mode=&quot;Compete&quot;)<br>automl.fit(X_train, y_train)</pre><h3># FLAML</h3><p>[<a href="https://github.com/microsoft/FLAML">GitHub</a>, <a href="https://microsoft.github.io/FLAML/">Documentation</a>] FLAML is a package that finds accurate machine learning models automatically. It frees users from selecting learners and hyperparameters for each learner. It can also be used to tune generic hyperparameters for MLOps workflows, models, algorithms, computing experiments, software configurations and so on. It contains many features as MLJAR has, without explainability. Also, it can process textual data and can work with online learning as well.</p><pre># FLAML<br>from flaml import AutoML<br><br>automl = AutoML()<br>automl.fit(X_train, y_train, task=&quot;classification&quot;)</pre><h3># AutoGluon</h3><p>[<a href="https://github.com/awslabs/autogluon">GitHub</a>, <a href="https://auto.gluon.ai/">Documentation</a>] AutoGluon automates machine learning tasks enabling you to easily achieve strong predictive performance in your applications. This package is focused on training, evaluation, fine-tuning, and deployment. It can works with textual data, tabular data, image, time series, and even multi-modal data. It is the most robust and generic AutoML tool so far.</p><pre># AutoGluon<br>from autogluon.tabular import TabularPredictor<br><br>automl = TabularPredictor(label=&quot;Survived&quot;, path=&quot;titanic-autogluon&quot;)<br>automl.fit(train) # pd.DataFrame as parameter</pre><h3># H2O</h3><p>[<a href="https://github.com/h2oai/h2o-3">GitHub</a>, <a href="https://h2o.ai/">Documentation</a>] H2O is an in-memory platform for distributed, scalable machine learning. It provides implementations of many popular algorithms; but it didn’t use scikit-learn implementations, it contains its own implementations. It can reach nice results, but it only works with its own pre-built algorithms and models.</p><pre># H2O<br>import h2o<br><br># Start the H2O cluster (locally)<br>h2o.init()<br># Get H2O data frame<br>hf_train = h2o.H2OFrame(train)<br><br># Run the AutoML<br>automl = H2OAutoML()<br>automl.train(x=x_columns, y=&quot;Survived&quot;, training_frame=hf_train)</pre><h3># AutoKeras</h3><p>[<a href="https://github.com/keras-team/autokeras">GitHub</a>, <a href="https://autokeras.com/">Documentation</a>] AutoKeras is a package based on Keras, a Deep Learning library. AutoKeras can perform AutoML into different types of data, such as tabular, image or even textual data. Deep Learning models tend to be good with real data.</p><pre># AutoKeras<br>import autokeras as ak<br><br>automl = ak.StructuredDataClassifier()<br>automl.fit(X_train, y_train, epochs=10)</pre><h3># MLBox</h3><p>[<a href="https://github.com/AxeldeRomblay/MLBox">GitHub</a>, <a href="https://mlbox.readthedocs.io/en/latest/">Documentation</a>] MLBox provides data preprocessing, feature selection, hyperparameter optimization and model evaluation. It contains several state-of-the-art competition models, such as Deep Learning, Stacking, LightGBM. Also, a few interpretation functions to analyze our results. It works only with tabular data.</p><pre># MLBox<br># Init MLBox<br>from mlbox.preprocessing import *<br>from mlbox.optimisation import *<br>from mlbox.prediction import *<br><br># Reading data<br>rd = Reader(sep = &quot;,&quot;)<br>df = rd.train_test_split(paths, &quot;Survived&quot;)<br><br># AutoML<br>opt = Optimiser(scoring = &quot;accuracy&quot;, n_folds = 5)<br>params = opt.optimise(space, df, 15)<br><br># Making Predictions<br>prd = Predictor()<br>prd.fit_predict(params, df)</pre><h3># PyCaret</h3><p>[<a href="https://github.com/pycaret/pycaret">GitHub</a>, <a href="https://pycaret.org/">Documentation</a>] PyCaret is a low-code machine learning library that automates machine learning lifecycle. It is an end-to-end machine learning and model management tool that makes you more productive and speeds up the experiment cycle exponentially; AutoML is just one of the features. This is the most complete package on this list.</p><pre># PyCaret<br>from pycaret import classification<br><br>s = classification.setup(train, target = &quot;Survived&quot;)<br>best = classification.compare_models()<br>classification.plot_model(best)</pre><h3>Conclusion</h3><p>In this blog post, I presented and roughly evaluated eleven well-known Python packages for AutoML. Most of them work with tabular data, but few stand out due to their ability to work with textual data, images, time series, and even multi-modal projects.</p><p>It is important to note that I have not fully explored all the packages, so we could use more of their features to achieve better results. Anyway, they all achieved good results, averaging 76% F1-score.</p><figure><img alt="Experiments results" src="https://cdn-images-1.medium.com/max/679/1*mQ3jPFnf4t4QeYnnhUiuqA.png" /><figcaption>AutoML Tools — Packages evaluation</figcaption></figure><p>In summary, I liked most Lazy Predict, TPOT, MLJAR, FLAML, AutoGluon, AutoKeras and PyCaret. Of course, each of them has their own advantages and disadvantages. <em>See the complete code in the </em><strong><em>Jupyter Notebook</em></strong><em>:</em></p><p><a href="https://www.kaggle.com/code/leomauro/automl-benchmark-titanic-disaster">AutoML Benchmark - Titanic Disaster</a></p><h3>Reference</h3><p>Fayyad, Usama, Gregory Piatetsky-Shapiro, and Padhraic Smyth. <a href="https://ojs.aaai.org/index.php/aimagazine/article/view/1230">From data mining to knowledge discovery in databases</a>. AI magazine 17.3 (1996): 37–37.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87ae3b23228a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wearesinch/comparing-automl-tools-in-titanic-dataset-machine-learning-87ae3b23228a">Comparing AutoML Tools in Titanic Dataset — Machine Learning</a> was originally published in <a href="https://medium.com/wearesinch">Sinch Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Emotion Detection in Brazilian Tweets]]></title>
            <link>https://medium.com/wearesinch/multi-emotion-detection-in-brazilian-tweets-8e3481b8017b?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3481b8017b</guid>
            <category><![CDATA[brazil]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[tweet]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Fri, 05 Aug 2022 21:15:36 GMT</pubDate>
            <atom:updated>2022-10-17T18:24:22.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multi-Emotion Detection in Brazilian Tweets — Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBu9TXNy0lW9MBUpTmPo2g.png" /></figure><p>Have you ever watched Ultron in Avengers movie? Imagine a Machine capable of understanding, comprehending and answering according to environment and people actions; this is the big dream of Natural Language Processing (NLP) — 👀 not destroy the world but understand the natural language (text, audio).</p><p>But how can a machine (or even we) understand text? Semantic is a first guess. Semantic is the study of meanings: word meaning, sentence meaning, whole text meaning, and so on. One of the areas of semantics is sentiment analysis. In sentiment analysis, we want to identify the sentiment of the author through the written text. Also, in some cases, we can detect multiple sentiments in a sentence. For example, “Oh thanks boss, I’m so happy about this promotion.” can be labeled as “positive”, “joy”, or even “surprise” sentiments. Imagine understanding the sentiments of a tweet. In this blog-post, we are going to develop a solution to detect multiple sentiments in a tweet.</p><p><strong>Problem statement</strong>. Given a tweet (small text), we must assign nine emotional labels to it.</p><h3>Multi-Emotion Detection Problem</h3><p>According to Plutchik’s Wheel of Emotions (1986), emotions can be based on four basic emotional axes, the emotion pairs (or axes) are joy x sadness, anger x fear, trust x disgust and surprise x anticipation; also, a extra label named neutral (none of previous sentiments). We are going to explore the <a href="https://www.kaggle.com/datasets/fernandojvdasilva/stock-tweets-ptbr-emotions">Brazilian Stock Market Tweets with Emotions</a> dataset to identify these emotions in Brazilian stock market tweets. This dataset holds 4,517 tweets labeled with these nine sentiments.</p><p>In Machine Learning area, we can see this problem as multilabel classification task where we must assign a set of emotional labels (called classes) for each tweet. There are a few ways to tackle this problem: <strong>(i)</strong> transform each class vector into a single class, that is, each vector (combination of sentiments) will be a class for a given sentence; <strong>(ii)</strong> develop a binary classifier for each class (so nine binary classifiers), where each classifier predicts absence or presence of a class; or <strong>(iii)</strong> specific case for this dataset, develop four multiclass classifiers, one for each sentiment axis, if they all return 0 it is considered as neutral. Note, the strategy (ii) and (iii) usually performs better, but for simplicity (and for being generic for any multilabel task) we are going to implement the first strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ybw4j3WBnN3L5gcwJhkTIQ.png" /><figcaption>Multilabel classification strategies</figcaption></figure><h3>Algorithm Development</h3><p>We are going to implement the first multilabel strategy using: <strong>(1)</strong> preprocessing for text normalization; <strong>(2)</strong> TF-IDF for feature extraction (transform the normalized texts into vectors); and <strong>(3)</strong> Decision Tree for sentiment classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*2noNWClBndmT-xyzlCMUvg.png" /><figcaption><em>Multilabel algorithm developed</em></figcaption></figure><p><strong>(1) Preprocessing</strong>, we are going to perform two simple normalization (i) lower the text and (ii) remove the accents. I create a class for this preprocessor:</p><pre>import pandas as pd<br>from unidecode import unidecode<br>from sklearn.base import TransformerMixin, BaseEstimator</pre><pre>class <strong>SimpleTextPreprocessor</strong>(BaseEstimator, TransformerMixin):<br>    <em>&quot;&quot;&quot;</em><br><em>    Text preprocessing includes steps:</em><br><em>        - Lower case</em><br><em>        - Remove accents</em><br><em>    &quot;&quot;&quot;</em><br>    def __init__(self):<br>        pass<br><br>    def fit(self, X, y=None):<br>        return self<br><br>    def transform(self, X, *_):<br>        data = pd.Series(X) if <strong>not</strong> isinstance(X, pd.Series) else X<br>        data = data.apply(self._preprocess_text)<br>        return data<br><br>    def _preprocess_text(self, text):<br>        <em># handed functions</em><br>        pre_text = text.lower()<br>        pre_text = unidecode(pre_text)<br>        return pre_text</pre><p><strong>(2) TF-IDF</strong> (Term Frequency-Inverse Document Frequency) is an approach based on word count, in which the vector of a tweet is represented by the importance of the words present in it.</p><p><strong>(3) Decision Tree</strong> is a supervised learning algorithm designed for classification or regression tasks. Its algorithm predicts the labels of a tweet by learning decision rules inferred from the attributes of the data (in our case, on the values of the columns of the vectors resulting from the TF-IDF).</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.pipeline import Pipeline<br><br>pipeline = Pipeline(steps=[<br>    (&#39;normalize&#39;, <strong>SimpleTextPreprocessor</strong>()), <br>    (&#39;features&#39;, <strong>TfidfVectorizer</strong>(<br>        ngram_range=(1, 2), analyzer=&#39;word&#39;,<br>        sublinear_tf=True, max_features=3_000,<br>        max_df=0.9, preprocessor=None<br>    )),<br>    (&#39;classifier&#39;, <strong>DecisionTreeClassifier</strong>(random_state=1))<br>])</pre><h3>Experiments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*NF8oyqBeEGUQvCZaM7KFlQ.png" /><figcaption>Experiment results</figcaption></figure><p>We can notice that the overall accuracy of the model is 63.77% using a simple pre-processing. However, the performance of the sentiment classes (apart from the neutral class) were not good; which suggests that the model focused on the majority class (neutral) and “forgot” the other classes. Anyway, we can notice that it was able to detect some feelings (in addition to neutral) in the tweets, such as “anger” and “disgust.”</p><h3>Conclusion</h3><p>In this blog-post, we developed one solution for classifying multiple sentiments in a tweet based on multilabel classification, using Text Preprocessing, TF-IDF and Decision Tree. With this solution, we reached 63.77% of accuracy in predicting the correct set of labels for a tweet.</p><p>As future work, (i) we can explore binary classification techniques, or different multilabel strategies; (ii) we can explore symbolic solutions and identify the most important words/expressions for each feeling; or (iii) explore more advanced machine learning techniques, such as BERT. <em>See the complete code in the </em><strong><em>Jupyter Notebook</em></strong><em>:</em></p><p><a href="https://www.kaggle.com/code/leomauro/nlp-multi-emotion-detection-in-tweets">NLP - Multi-Emotion Detection in Tweets</a></p><h3>Reference</h3><ol><li><a href="https://www.euppublishing.com/doi/abs/10.3366/cor.2020.0203">Fernando J. Vieira da Silva, et al. Stock market tweets annotated with emotions (2020)</a></li><li><a href="https://link.springer.com/chapter/10.1007/978-3-319-16354-3_5">Lars Buitinck, et al. Multi-emotion Detection in User-Generated Reviews (2015)</a></li><li>Plutchik R. and H. Kellerman. Emotion: Theory, Research and Experience (1986)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3481b8017b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wearesinch/multi-emotion-detection-in-brazilian-tweets-8e3481b8017b">Multi-Emotion Detection in Brazilian Tweets</a> was originally published in <a href="https://medium.com/wearesinch">Sinch Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Question Answering — Document Retriever (Machine Learning)]]></title>
            <link>https://medium.com/wearesinch/automatic-question-answering-document-retriever-machine-learning-f4f473387739?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4f473387739</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 22:26:24 GMT</pubDate>
            <atom:updated>2022-06-07T22:26:24.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automatic Question Answering — Document Retriever (Machine Learning)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XdGFXf9SigDxXMA2HPKYw.png" /></figure><p>Have you ever used Google or Wikipedia to sake your curiosity? I often use these systems to search a topic or get quick information. I can imagine that you do the same. In this blog post, we are going to create a system like them, called Question Answering (QA) system. A good QA system allow users to extract knowledge from data in a natural way by asking questions.</p><p>QA is an Artificial Intelligence (AI) task that answers users’ questions (natural language queries) using a large collection of documents; by document you can understand as web pages, Word documents, PDF documents, FAQs, and so on. In summary, QA systems query many documents to extract an answer to user questions; this consists of two main models: (1) document retriever — retrieve the most useful documents that may contain the answer to a given question; (2) document reader — a machine reader carefully examines the retrieved contexts and identify the correct answer. In this blog post, we are going to explore the Document Retriever using AI techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TbH4FWDzfh7O7v46.png" /><figcaption>Source: <a href="https://qa.fastforwardlabs.com/methods/background/2020/04/28/Intro-to-QA.html">Intro to Automated Question Answering</a></figcaption></figure><p>Let’s see the Document Retriever from Wikipedia, just to better understand our goal:</p><pre>import wikipedia as wiki<br><br>k = 5<br>question = &quot;What are the tourist hotspots in Portugal?&quot;<br><br>results = wiki.search(question, results=k)<br>print(&#39;Question:&#39;, question)<br>print(&#39;Pages:&#39;, results)</pre><pre>----- Output</pre><pre>Question: What are the tourist hotspots in Portugal?<br>Pages: [ <br>  &#39;Tourist attraction&#39;, &#39;Portugal&#39;,<br>  &#39;Goa&#39;, &#39;Tourism&#39;, &#39;Algarve&#39;<br>]</pre><p>We can notice a few things:</p><ul><li>The question is made in pure natural language; and</li><li>We must inform the number <strong>k</strong> of documents to be retrieved.</li></ul><p>Thus, the Document Retriever must be able to (1) process natural language, usually using Natural Language Processing (NLP) techniques; and (2) sort the most useful documents based on a question.</p><h3>Document Retriever</h3><p>Document Retriever in QA is usually implemented using <a href="https://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction">TF-IDF</a> or <a href="https://opensourceconnections.com/blog/2015/10/16/bm25-the-next-generation-of-lucene-relevation/">BM25</a>, which matches keywords between the question and the documents representing them as sparse vectors. Conversely, we can also use dense embeddings, like <a href="https://radimrehurek.com/gensim/models/word2vec.html">Word2Vec</a> and BERT. In this case, synonyms or paraphrases that consist of completely different words, but with similar meaning, may still be mapped to vectors close to each other.</p><p>This model can be implemented in two steps: (1) transform the question and the documents into vectors; and, in sequence, (2) compute the similarity between them and return the <strong>k</strong> most likely documents with the answer. For the first task, we can use TF-IDF, Word2Vec, etc. At last, for the second task, we can use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html#sklearn.neighbors.NearestNeighbors">Nearest Neighbors</a> algorithm.</p><h3>Development</h3><p>We will evaluate our model using the <a href="https://www.kaggle.com/code/leomauro/nlp-document-retrieval-for-question-answering">Stanford Question Answering Dataset</a>. It contains over 100k questions and answers. Also, for simplicity, let’s explore only the TF-IDF implementation, but you can see an implementation using Word2Vec as well in the Jupyter Notebook (linked in the end of the blog post).</p><p>“TF-IDF, short for term frequency–inverse document frequency, is a numerical statistic that is intended to reflect how important a word is to a document […] It is often used as a weighting factor in searches of information retrieval, text mining, and user modeling.” [<a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">Wikipedia</a>]</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer</pre><pre>tfidf_configs = {<br>    &#39;lowercase&#39;: True,<br>    &#39;analyzer&#39;: &#39;word&#39;,<br>    &#39;stop_words&#39;: &#39;english&#39;,<br>    &#39;binary&#39;: True,<br>    &#39;max_df&#39;: 0.9,<br>    &#39;max_features&#39;: 10_000<br>}<br><br>embedding = TfidfVectorizer(**tfidf_configs)</pre><p>The TF-IDF setups are: (I) English preprocessing; (II) Analyze at word-level; (III) Binary importance, means that the same word is only computed once per document to avoid counting the same word several times; and (IV) Sparse vector size is 10k, so the not-frequent words will be ignored.</p><pre>from sklearn.neighbors import NearestNeighbors<br><br>retriever_configs = {<br>    &#39;n_neighbors&#39;: 3,<br>    &#39;metric&#39;: &#39;cosine&#39;<br>}<br><br>retriever = NearestNeighbors(**retriever_configs)</pre><p>Meanwhile, the Nearest Neighbors setups are: (I) Compute the similarity between the question and document vectors using the cosine function — the most popular function to work with NLP problems; and (II) retrieve the 3 most likely documents to answer the question.</p><p><strong>OK.</strong> How good is this model? Retrieving only one document, the model reached a low accuracy of 43.22%. Note, this is a difficult problem because we have many documents (~18k documents) and some are similar each other, thereby it becomes complicated to retrieve exactly the right one. In contrast, retrieving the top-3 documents the model was able to reach a high accuracy of 98.92% (hitting 86,650 cases out of 87,599).</p><h3>Conclusion</h3><p>Question Answering systems are capable of respond users’ questions using Natural Language Processing algorithms, they consist of Document Retriever and Document Reader techniques. In this blog post, we discussed how to elaborate a Document Retriever and evaluated the strategy using a real dataset. As mentioned, this is a complex problem, due to the high number of documents. Nevertheless, our baseline solution reached a high accuracy of 98.92%. Besides this approach, we also have other popular models to work with document retrieval such as BM25 and DPR. <strong><em>Jupyter Notebook:</em></strong></p><p><a href="https://www.kaggle.com/code/leomauro/nlp-document-retrieval-for-question-answering">NLP - Document Retrieval for Question Answering</a></p><h3>Reference</h3><ol><li><a href="https://qa.fastforwardlabs.com/methods/background/2020/04/28/Intro-to-QA.html">Intro to Automated Question Answering</a></li><li><a href="https://aclanthology.org/2020.emnlp-main.550/">Dense Passage Retrieval (DPR) for Open-Domain Question Answering</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4f473387739" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wearesinch/automatic-question-answering-document-retriever-machine-learning-f4f473387739">Automatic Question Answering — Document Retriever (Machine Learning)</a> was originally published in <a href="https://medium.com/wearesinch">Sinch Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Anomaly Detection algorithms for Streaming Data — Machine Learning]]></title>
            <link>https://medium.com/wearesinch/simple-anomaly-detection-algorithms-for-streaming-data-machine-learning-92cfaeb6f43b?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/92cfaeb6f43b</guid>
            <category><![CDATA[real-time-streaming-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[outliers]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 21:17:35 GMT</pubDate>
            <atom:updated>2023-02-08T21:41:48.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simple Anomaly Detection algorithms for Streaming Data — Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kh3wXbIA2oKHc8qiIy3v0g.png" /><figcaption>by <a href="https://www.linkedin.com/in/leomaurodesenv/">Leonardo Mauro P. Moraes</a></figcaption></figure><h3>Abstract</h3><p>Have you ever heard about Anomaly Detection for Streaming Data? Basically, Streaming Data is data that is continuously generated over time. For example, the number of songs downloaded per time, internet usage per time, travel time on a road along the day. As you can see, this data changes over time. Meanwhile, Anomaly Detection refers to Machine Learning techniques to detect suddenly peaks or drop-offs in the data.</p><p>See some practical examples for this kind of machine learning technique: (1) detect high time travel on roads to offer another alternative route; (2) detect trend topics in Twitter volume data; (3) detect peaks in CPU usage to automatically provide more cloud computers. In general, you can detect anomalies/outliers in any kind of Streaming Data.</p><p>In this article, we are going to learn two simple techniques to detect anomalies in near real-time streaming data: <em>Moving Average</em> and <em>Exponential Moving Average</em>. To demonstrate the generality of the models, we are going to explore four different types of Streaming Data.</p><blockquote>The <strong>code</strong> is available at the end of the article.</blockquote><p><strong>What are the algorithms requirements?</strong></p><ul><li>Predictions must be made online; they cannot look ahead</li><li>Algorithms must run automatically and unsupervised</li><li>Algorithms must learn continuously and adapt to dynamic environments</li></ul><h3>Moving Average</h3><p>Moving Average is a common type of average used in Streaming Data problems. Moving Average is a calculation used to analyze/smooth data by creating a new series of averages from subsets of the data points. In other words, this technique simply averages the <em>n</em> latest data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*DlqZEbmiWv7kcCh6IHt17Q.png" /><figcaption>Moving Average formula</figcaption></figure><p><em>See this one-minute video for better understanding:</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FxWTakzxIaxA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DxWTakzxIaxA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FxWTakzxIaxA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2790f13a47bec4055dc39c09aea66b4/href">https://medium.com/media/a2790f13a47bec4055dc39c09aea66b4/href</a></iframe><p>In this way, a new averaged data results from the average of the previous <em>n</em> data points. This calculation happens for every data point in your dataset. Thus, the algorithm needs a parameter <em>n</em> to indicate how many periods it will use to compute the average. Here, we used the “averaged data” as “expected value”, thereby we can compare the current value with the expectation.</p><p>Meanwhile, how can we predict whether a value is an anomaly or not? To achieve this, we define a dynamic range from the “expected value” <strong><em>x_value</em></strong>. The range is computed from the standard deviation <strong><em>std</em></strong> from the <em>n</em> lastest points. Thus, the range of a non-anomaly is from (<strong><em>x_value</em></strong> - <strong>std</strong>) to (<strong><em>x_value</em></strong><em> </em>+ <strong><em>std</em></strong>). So, if the value is in the range, it is not an anomaly; but if the value is out of the range, it is an anomaly/outlier.</p><p><strong>Note</strong>. At this moment, we have created a simple and powerful algorithm to detect anomalies in Streaming Data. However, the simpleness of this algorithm is only able to treat simple Streaming Data where the data increases and decreases uniformly or with small changes over time. While, we have the <em>Exponential Moving Average</em> algorithm that is able to fit to more changes in the data, such as seasonal data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqMnK8tBCmS6O-I_9YbuPA.png" /><figcaption>Types of Streaming Data</figcaption></figure><h3>Exponential Moving Average</h3><p>Exponential Moving Average is a weighted average algorithm that focuses on the most recent data by assigning more weight and significance to the most recent data; roughly, it is a Moving Average with weights. “An exponentially weighted moving average reacts more significantly to recent data changes than a simple moving average, which applies an equal weight to all observations in the period.” (Infopedia)</p><p>Also, the Exponential Moving Average needs a parameter called <em>alpha</em> (or smoothing factor) which determines the importance of the last record, and it’s decaying for the next records. For example, if <em>alpha=0.5</em>: record-1 has 50% importance, record-2 has 30% importance, and so on. Thus, the algorithm allows smoothing the “expected value”, prioritizing the most recent data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*EL2PYKUFOCf2lAr55dRhbw.png" /><figcaption>Exponential Moving Average formula</figcaption></figure><p>Finally, the anomaly detection happens in the same way as the Moving Average. So, we just have to compute the standard deviation and define a range for non-anomaly data points as seen before. Experiments with real data showed that the Exponential Moving Average performs better than Moving Average in data with high variance (e.g., many peaks); also, it learns faster due to its smoothing factor.</p><h3>Discussion</h3><p>We learned two simple algorithms to automatically detect anomalies in Streaming Data. If you want to see the robustness of these algorithms, consider accessing Jupyter Notebook on Kaggle. The notebook presents the implementation of both algorithms, as well as experiments in real data, such as detect outliers in CPU utilization and network usage.</p><blockquote><strong>Curiosity. </strong>In finance, moving average techniques are stock indicators commonly used in technical analysis. The reason for calculating the moving average of a stock is to help smooth out the price data by creating a constantly updated average price. (<a href="https://www.investopedia.com/terms/m/movingaverage.asp">Investopedia</a>)</blockquote><h3>Kaggle — Jupyter Notebooks</h3><p>We have the first notebook describing and detailing the techniques; the second is just an evaluation in another dataset; and the last one is an extension with new algorithm developed by <a href="https://www.kaggle.com/neomatrix369">Mani Sarkar</a>.</p><ul><li><a href="https://www.kaggle.com/leomauro/anomaly-detection-streaming-data/">leomauro/anomaly-detection-streaming-data/</a></li><li><a href="https://www.kaggle.com/leomauro/anomaly-detection-streaming-data-evaluation">leomauro/anomaly-detection-streaming-data-evaluation/</a></li><li><a href="https://www.kaggle.com/neomatrix369/anomaly-detection-streaming-data-extended/">neomatrix369/anomaly-detection-streaming-data-extended/</a></li></ul><h3>References</h3><ul><li><a href="https://otexts.com/fpp2/moving-averages.html">Moving averages (Rob J Hyndman et al.)</a></li><li><a href="https://www.investopedia.com/terms/m/movingaverage.asp">Moving Average (MA) (investopedia)</a></li><li><a href="https://www.investopedia.com/terms/e/ema.asp">Exponential Moving Average (EMA) (investopedia)</a></li><li><a href="https://people.duke.edu/~rnau/411avg.htm">Moving average and exponential smoothing models (Robert Nau)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92cfaeb6f43b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wearesinch/simple-anomaly-detection-algorithms-for-streaming-data-machine-learning-92cfaeb6f43b">Simple Anomaly Detection algorithms for Streaming Data — Machine Learning</a> was originally published in <a href="https://medium.com/wearesinch">Sinch Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A high-accuracy framework for binary text classification — Machine  Learning]]></title>
            <link>https://medium.com/wearesinch/a-high-accuracy-framework-for-binary-text-classification-machine-learning-2e6128c6879c?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6128c6879c</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Thu, 01 Jul 2021 13:34:48 GMT</pubDate>
            <atom:updated>2021-07-01T14:55:49.212Z</atom:updated>
            <content:encoded><![CDATA[<h3>A high-accuracy framework for binary text classification — Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_NEmZzuNbeUBp21G" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>written with </em><a href="https://www.linkedin.com/in/raphael-da-silva/"><em>Raphael Silva</em></a><em>.</em></p><h3>Abstract</h3><p>Have you ever heard of binary classification problems? Binary classification is an Artificial Intelligence task in which the algorithm must identify whether something belongs to a given class or no. Typical binary classification problem includes decisions of yes or no (do or do not). See some examples: (i) medical testing to determine if a patient has certain disease or no; (ii) Identify if an email is spam; or (iii) classify the sentiment polarity of a text as positive or negative.</p><p>In this article, we present our solution (a framework) to work with multiple binary classification problems with high accuracy and provide an API (Application Programming Interface) to consume it. Most of the services offered by Sinch are related to texts and messages, such as WhatsApp, SMS (Short Message Service), and others. Thus, our framework was developed to work with text classification problems. However, this framework can be expanded for any binary classification problem if the modeling and encoding stages are adapted.</p><p>As mentioned, we offer services for messaging. Thus, we process a lot of messages from different channels, and we had the need to create a single solution to address many different issues from varied channels. We decided to provide an internal API to be consumed by our services. We have been using the binary text classifier framework for: (1) detecting automatic message reply, e.g., “Hi, I’ll be back soon”; (2) filter out-scope messages, e.g., spam messages or messages from other contexts; (3) detect if the user is dissatisfied, i.e., the bot is not helping the user, (so the system can switch the service to a human, a process called offloading), and other cases.</p><h3>Solution</h3><p>Ok, but how does it work? It is called a framework because it is a software abstraction which provides a generic functionality; therefore, it can be used for diverse binary text classification problems without hard modifications. Our framework is split into two main procedures: (i) machine learning; and (ii) the API itself; let us detail each of these steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*EABUKuF7B5kNn9n79zHMJw.png" /><figcaption>The framework structure</figcaption></figure><p>Consider that we have a binary text classification problem, for example, detect spam emails. First, we must develop the Machine Learning algorithm that will predict whether an email is a spam or not. The first procedure is responsible for designing this algorithm executing a series of steps: (i) collect and preprocess the data (remove duplicates, null values, and oversampling the minor classes); (ii) learn the features (extract words, characters, and n-grams for elaborate a refined bag-of-word model); (iii) train the estimator, i.e., the Machine Learning algorithm (we’ve used a Neural Network with over three million parameters); (iv) evaluate the algorithm using a test dataset (usually the test represents 20% of the total data); finally, (v) save the model (create dumps of the model). Now, we have a trained estimator to detect spam emails. Note that this approach also can be executed for other binary text classification problems.</p><p>We just go forward to the next procedure after finding a good model and reaching good results. See the f1-score results on some of our binary problems: (1) in automatic message detection, we reached 99.7%; (2) in filter out-scope messages, we also got 99.7%; and (3) in detect if the user is dissatisfied, the most difficult problem, we got 76.8%. As you can see, this framework shows high performance in our cases and presented promising results.</p><p>The second procedure is responsible for exposing the trained model via API. The API maintains a list of all trained models and their files (the dumps) and exposes them using a unique identifier (ID) for each model. In this way, our services can consume these models by calling this API and informing the unique ID of the classifier. In summary, this API is created by the following steps: (i) add the saved models into the unique ID list; (ii) create a Docker container with all models’ files; and (iii) deploy the container in the cloud, we’re using Google Cloud Platform (GCP); thereby, we have one API that can be used to consume several classifiers. In our benchmarks, each message is processed in ~0.1 second. In addition, the API is product agnostic, which means that the same classifier can be used in many products.</p><h3>Discussion</h3><p>We presented our framework to work with any binary text classification problem. As stated, the framework is generic and have some steps and parameters to train different kind of models. In some of our cases, we achieve over than 99% in f1-score. Besides, the model is deployed in an API that can process each message in ~0.1 seconds. If you wish, please contact us to know more about it.</p><p><strong>Future work</strong>. Our classifiers only comprehend Portuguese because they are trained using bag-of-words features and the datasets we used are in that language. Therefore, to enable the classifiers for all Sinch customers — in many languages, we are incorporating language agnostic sentence embedding (features), which can understand more than 100 languages. Follow us, to know more in our next post.</p><p>If you want to work with us or know more about, please contact me:</p><p><a href="https://www.linkedin.com/in/leomaurodesenv/">Leonardo Mauro P. Moraes - Machine Learning Engineer - Sinch | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6128c6879c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wearesinch/a-high-accuracy-framework-for-binary-text-classification-machine-learning-2e6128c6879c">A high-accuracy framework for binary text classification — Machine  Learning</a> was originally published in <a href="https://medium.com/wearesinch">Sinch Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searching for Similar Songs on Spotify — Data Science]]></title>
            <link>https://medium.com/wearesinch/searching-for-similar-songs-on-spotify-data-science-c7e3faeb66f0?source=rss-f4d6e632704c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7e3faeb66f0</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[music]]></category>
            <dc:creator><![CDATA[Leonardo Mauro P. Moraes]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 14:53:16 GMT</pubDate>
            <atom:updated>2023-02-08T01:22:50.886Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Searching for S</strong>imilar Songs on Spotify — Data Science</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zn5DGEfCJEBAtfKX" /><figcaption>Photo by <a href="https://unsplash.com/@cdx2?utm_source=medium&amp;utm_medium=referral">C D-X</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Idealized by </em><a href="https://www.linkedin.com/in/guilherme-muzzi-da-rocha-85384aab/"><em>Guilherme Muzzi</em></a><em>.</em></p><h3>Case Study</h3><p>Have you ever asked yourself how can we recommend similar songs based on a listened song? In this article, we describe a simple method to do that.</p><p><strong>Similarity</strong> is an answer. Similarity measures how much two songs are similar, in order to create a fine recommendation for the users based on previously listened songs. In this study, we compared songs based on broader features, such as acousticness and danceability.</p><blockquote><strong>Disclaimer.</strong> This is a simple case study of similarity. There are many state-of-art algorithms for song recommendation. However, this algorithm is an interesting and generic approach that can be used in many other situations. It can also be used as a base test for your experiments.</blockquote><h3>Dataset</h3><p>First, we need the data. In this sense, we used the <a href="https://www.kaggle.com/geomack/spotifyclassification">Spotify Song Attributes</a> dataset, which contains 2017 songs from GeorgeMcIntire’s playlist,<strong> </strong>with songs attributes from Spotify’s API.</p><p>Each song has a set of interesting attributes, such as acousticness, danceability, energy, instrumentalness, loudness, etc. In this sense, a song is represented by a set of attributes, <em>i.e.,</em> its characteristics.</p><h3>Similarity</h3><p>Okay, now we have the data. But what is similarity?</p><p>Similarity is a measure that calculates how much two objects have similar shapes, values, or distances. If we observe our songs as data points, we can measure the similarity of two songs using a distance function. Wait… what? A distance function is a function <em>f(x1, x2) </em>that measures how much <em>x1</em> and <em>x2</em> are close - so how much they are similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*NdHyWS9c5kUL_pjL5MTW1A.png" /><figcaption>Distance function in a Cartesian space</figcaption></figure><p>See the image above. The yellow ball is more similar to the blue ball because they are closer when compared to the other green balls. So, a distance function is used to compare the distance between the balls to find the most similar one. There are many distance functions; in our case study, we used <a href="https://en.wikipedia.org/wiki/Euclidean_distance">Euclidean distance</a>, represented by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/0*27D-SNLoErLkwkG4" /><figcaption>Euclidean distance formula</figcaption></figure><h3>Algorithm</h3><p>How can we search for similar songs in our dataset?</p><p>In this case, we applied the <a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm"><em>k-nearest neighbors (k-NN)</em></a> algorithm. The <em>k-NN</em> searches for the similar elements based on a query point at the center; for example, “this song is similar to this”. Basically, the <em>k-NN:</em></p><ol><li>Measures the distance from the query point for all songs.</li><li>Sort the songs based on proximity.</li><li>Return the <em>k</em> most similar songs.</li></ol><h3>Song Recommendation</h3><p>Now, we have a set of ~2000 songs and a <em>k-NN</em> algorithm that searches for <em>k</em> similar songs, using Euclidean distance as similarity function. Let’s try!</p><p>We randomly selected <a href="https://www.youtube.com/watch?v=5NPBIwQyPWE">Avril Lavigne — Complicated</a> as a query point.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5NPBIwQyPWE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5NPBIwQyPWE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5NPBIwQyPWE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a127f1d9aa043b02022aeaf7e2c785cd/href">https://medium.com/media/a127f1d9aa043b02022aeaf7e2c785cd/href</a></iframe><p>And the <em>k-NN</em> returned the three most similar songs: (1) <a href="https://www.youtube.com/watch?v=7F8PgqXm36Q">DOLF — Fuck It All Up</a>; (2) <a href="https://www.youtube.com/watch?v=E3IChv3B364">Sam F — Limitless</a>; and (3) <a href="https://www.youtube.com/watch?v=a3HPpu2Gsog">ASTR — Blue Hawaii</a>; respectively. If you check the query point and the other songs, they are pretty similar — they have similar acousticness, energy, and rhythm.</p><blockquote><strong>Discussion.</strong> However, the third (ASTR — Blue Hawaii) is not so similar to the query point. This can happen if we have a small amount of data, or if we do not know enough about the song to know what it is.</blockquote><p>But, we successfully elaborated a simple song recommendation algorithm.</p><h3>Other Queries</h3><p>Is that it? No, we can also apply our algorithm to answer other queries, such as: (1) “What is the most active, cheerful song?” or (2) “What is the less active, or not energized song?”. In this way, we have to create a synthetic query point.</p><p>To create a synthetic query point, we only have to set the attributes we want to. For example, to answer the first question, we can set the values of danceability, energy, and valence to the highest value possible. We then create a query point to the song with the highest value.</p><p>This query returned <a href="https://www.youtube.com/watch?v=Kgjkth6BRRY">Gwen Stefani — Hollaback Girl</a> as the most cheerful song.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKgjkth6BRRY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKgjkth6BRRY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKgjkth6BRRY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d25b0a41f93b875a59d2641381a0277d/href">https://medium.com/media/d25b0a41f93b875a59d2641381a0277d/href</a></iframe><p>And the opposite query (danceability, energy, and valence to the lowest value possible) returned <a href="https://www.youtube.com/watch?v=PZddaC_gBHE">Nikolaus Harnoncourt — Mozart: Requiem in D Minor, K. 626: VIII. Lacrimosa</a> is the less energized song.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPZddaC_gBHE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPZddaC_gBHE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPZddaC_gBHE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7405766daa43c5d4c1aaea962f17699d/href">https://medium.com/media/7405766daa43c5d4c1aaea962f17699d/href</a></iframe><p><strong>Conclusion</strong></p><p>Similarity functions are powerful approaches to execute queries in datasets in order to retrieve similar elements based on a query point. In this way, we can use similarity to create a simple recommendation algorithm. Furthermore, we can explore many other things, such as (1) change the distance function, (2) modify the algorithm, or (3) create other synthetic query points.</p><p>If you are interesting in this topic, explore our Code, Jupyter Notebook in: <a href="https://www.kaggle.com/leomauro/spotify-songs-similarity-search">https://www.kaggle.com/leomauro/spotify-songs-similarity-search</a></p><p>If you want to work with or know more about, please contact me:</p><p><a href="https://www.linkedin.com/in/leonardo-mauro/">Leonardo Mauro P. Moraes - Artficial Intelligence Analyst​ - Wavy Global | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7e3faeb66f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wearesinch/searching-for-similar-songs-on-spotify-data-science-c7e3faeb66f0">Searching for Similar Songs on Spotify — Data Science</a> was originally published in <a href="https://medium.com/wearesinch">Sinch Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>