<?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 Joel Franklin Stalin Vijayakumar on Medium]]></title>
        <description><![CDATA[Stories by Joel Franklin Stalin Vijayakumar on Medium]]></description>
        <link>https://medium.com/@joel_34096?source=rss-39a45d0a8c0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fJrP7p2ashkOh6YFK5q6hw.jpeg</url>
            <title>Stories by Joel Franklin Stalin Vijayakumar on Medium</title>
            <link>https://medium.com/@joel_34096?source=rss-39a45d0a8c0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:31:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joel_34096/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[ML System Design Part 1: Introduction and Overview]]></title>
            <link>https://medium.com/@joel_34096/ml-system-design-part-1-introduction-and-overview-9c5b4c5e6598?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5b4c5e6598</guid>
            <category><![CDATA[ml-system-design]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 03:22:38 GMT</pubDate>
            <atom:updated>2026-07-04T03:22:38.248Z</atom:updated>
            <content:encoded><![CDATA[<p>How to think through the key stages of building, deploying, and maintaining machine learning systems in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mC2wZDD2UfINsFFzuKusKA.png" /></figure><p>This is Part 1 of my ML System Design series, where I break down the core concepts behind designing production-ready machine learning systems.</p><p>Machine learning system design is not just about choosing a model.</p><p>A production-grade ML system includes many moving parts: data pipelines, model training, serving infrastructure, evaluation workflows, and monitoring systems. The goal is not only to build a model that performs well during development, but also to make sure it works reliably for real users over time.</p><p>A complete ML system typically includes:</p><ul><li>Data infrastructure to collect, store, and process data</li><li>Serving infrastructure to make predictions available to users</li><li>Evaluation pipelines to measure model performance</li><li>Monitoring systems to detect failures and performance degradation</li></ul><p>In this article, we will walk through the major stages of ML system design:</p><ol><li>Clarifying requirements</li><li>Framing the problem as an ML task</li><li>Data preparation</li><li>Model development</li><li>Evaluation</li><li>Deployment and serving</li><li>Monitoring</li></ol><p>Let’s look at each stage one by one.</p><h3>1. Clarifying Requirements</h3><p>The first step in ML system design is understanding what the system is expected to achieve.</p><p>This means clarifying the business objective, the features the system should support, the available data sources, the expected scale, and any constraints around latency, cost, accuracy, or reliability.</p><p>At this stage, we should ask questions such as:</p><ul><li>What business problem are we solving?</li><li>Who are the users of the system?</li><li>What data is available?</li><li>What is the expected traffic or scale?</li><li>Are there latency or performance requirements?</li><li>How will success be measured?</li></ul><p>Clarifying requirements early helps avoid building a technically impressive model that does not solve the right problem.</p><h3>2. Framing the Problem as an ML Task</h3><p>Once the business objective is clear, the next step is to translate it into a machine learning problem.</p><p>This usually involves three steps:</p><h3>Defining the ML Objective</h3><p>The ML objective should directly support the business objective.</p><p>For example:</p><ul><li>In an ad click prediction system, if the business goal is to increase user clicks, the ML objective may be to maximize click-through rate.</li><li>In a friend recommendation system, if the business goal is to help users grow their network, the ML objective may be to maximize the number of formed connections.</li><li>In a video streaming app, if the business goal is to increase engagement, the ML objective may be to maximize total watch time.</li></ul><p>The key idea is that the ML objective should be measurable and aligned with the business goal.</p><h3>Specifying Inputs and Outputs</h3><p>After defining the ML objective, we need to clearly define what the model receives as input and what it produces as output.</p><p>For example, in a harmful content detection system:</p><ul><li>Input: a user-generated post</li><li>Output: whether the post is harmful or not</li></ul><p>This step makes the problem concrete and helps guide data collection, labeling, model selection, and evaluation.</p><h3>Choosing the Right ML Category</h3><p>Most machine learning problems can be broadly grouped into three categories: supervised learning, unsupervised learning, and reinforcement learning.</p><h4>Supervised Learning</h4><p>In supervised learning, the model is trained on labeled data, meaning the training examples include the correct answers.</p><p>Many real-world ML problems fall into this category because labeled data often leads to stronger predictive performance.</p><p>Common supervised learning tasks include:</p><ul><li>Regression</li><li>Classification</li></ul><h4>Unsupervised Learning</h4><p>In unsupervised learning, the training data does not include correct answers.</p><p>The goal is to identify meaningful patterns in the data. This is commonly used for clustering, anomaly detection, and discovering hidden structures in datasets.</p><h4>Reinforcement Learning</h4><p>In reinforcement learning, an agent learns by interacting with an environment through trial and error.</p><p>The agent takes actions, receives feedback in the form of rewards or penalties, and gradually learns which actions lead to better outcomes.</p><h3>Common Supervised Learning Tasks</h3><p>Within supervised learning, two of the most common task types are regression and classification.</p><h4>Regression</h4><p>Regression is the task of predicting a continuous numeric value.</p><p>Examples include:</p><ul><li>Predicting house prices</li><li>Forecasting sales</li><li>Estimating delivery time</li></ul><h4>Classification</h4><p>Classification is the task of predicting a discrete class label.</p><p>Classification can be further divided into:</p><ul><li>Binary classification, where there is only one class</li><li>Multiclass classification, where there are more than one possible classes</li></ul><p>Examples include spam detection, fraud detection, and image classification.</p><h3>3. Data Preparation</h3><p>High-quality ML systems depend on high-quality data.</p><p>Data preparation usually involves two major processes:</p><ul><li>Data engineering</li><li>Feature engineering</li></ul><h3>Data Engineering</h3><p>Data engineering is the practice of designing and building pipelines to collect, store, retrieve, and process data.</p><p>One of the most important concepts in data engineering is ETL, which stands for:</p><ul><li>Extract</li><li>Transform</li><li>Load</li></ul><p>In the extract step, data is collected from different sources.</p><p>In the transform step, the data is cleaned, mapped, and converted into a useful format.</p><p>In the load step, the transformed data is loaded into a target destination such as a database, data warehouse, or file system.</p><p>Structured data is usually stored in relational databases, some NoSQL databases, and data warehouses. Unstructured data is often stored in NoSQL databases and data lakes.</p><h3>Feature Engineering</h3><p>Feature engineering is the process of converting raw data into useful model inputs.</p><p>It includes:</p><ul><li>Selecting predictive features from raw data</li><li>Extracting meaningful signals</li><li>Handling missing values</li><li>Scaling numerical values</li><li>Encoding categorical variables</li></ul><p>Good feature engineering can significantly improve model performance, especially in traditional machine learning systems.</p><h3>Handling Missing Values</h3><p>Missing values are common in real-world datasets.</p><p>There are two common ways to handle them: deletion and imputation.</p><h3>Deletion</h3><p>In deletion, we remove data that contains too many missing values.</p><p>This can be done in two ways:</p><ul><li>Delete rows where too many values are missing</li><li>Delete columns where a feature has too many missing values</li></ul><p>The drawback is that deletion reduces the amount of available training data.</p><h3>Imputation</h3><p>In imputation, we fill in missing values instead of removing them.</p><p>Common approaches include filling missing values with:</p><ul><li>A default value</li><li>The mean</li><li>The median</li><li>The mode</li></ul><p>Imputation allows us to preserve more data, but it can also introduce noise if the filled values do not accurately represent the true data.</p><h3>Feature Scaling</h3><p>Feature scaling is the process of transforming numerical features so they have a standard range or distribution.</p><p>This is especially useful for models that are sensitive to the scale of input features.</p><p>Common feature scaling techniques include normalization, standardization, and log scaling.</p><h3>Normalization</h3><p>Normalization scales feature values into a fixed range, usually between 0 and 1.</p><p>The formula is:</p><pre>z = (x - x_min) / (x_max - x_min)</pre><p>Normalization does not change the shape of the feature’s distribution. It only rescales and repositions the values.</p><h3>Standardization</h3><p>Standardization transforms values so that the feature has a mean of 0 and a standard deviation of 1.</p><p>The formula is:</p><pre>z = (x - mean) / standard deviation</pre><p>This is useful when features have different units or scales.</p><h3>Log Scaling</h3><p>Log scaling is used to reduce skewness in a feature.</p><p>The formula is:</p><pre>z = log(x)</pre><p>Skewness refers to the asymmetry of a probability distribution around its mean. Log scaling can make highly skewed features easier for the model to learn from and mainly helps with right skewed data.</p><h3>4. Model Development</h3><p>Model development is the process of selecting an appropriate machine learning model and training it to solve the task.</p><p>This stage includes model selection, model training, and handling issues such as class imbalance.</p><h3>Model Selection</h3><p>A good model selection process usually starts simple and becomes more complex only when needed.</p><p>A practical approach is:</p><ol><li>Establish a simple baseline</li><li>Experiment with simple models</li><li>Move to more complex models if necessary</li><li>Use an ensemble of models when higher accuracy is required</li></ol><p>Starting with a simple baseline is important because it gives us a reference point. Without a baseline, it is difficult to know whether a more complex model is actually adding value.</p><h3>Model Training</h3><p>Model training involves several steps:</p><ol><li>Collect raw data</li><li>Identify features and labels</li><li>Select a sampling strategy</li><li>Split the data into training, validation, and test sets</li><li>Address class imbalance if needed</li><li>Choose an appropriate loss function</li><li>Train the model</li><li>Fine-tune or retrain as needed</li></ol><p>Depending on the problem, we may train a model from scratch or fine-tune an existing model.</p><p>For large-scale models, distributed training may be required.</p><p>The two main types of distributed training are:</p><ul><li>Data parallelism</li><li>Model parallelism</li></ul><p>In data parallelism, the dataset is split across multiple machines or devices. In model parallelism, different parts of the model are distributed across machines or devices.</p><h3>Addressing Class Imbalance</h3><p>Class imbalance occurs when one class appears much more frequently than another.</p><p>For example, in fraud detection, fraudulent transactions may represent only a tiny percentage of the total data. If the model is trained without addressing this imbalance, it may learn to predict the majority class most of the time.</p><p>There are two common ways to address class imbalance.</p><h3>Resampling the Training Dataset</h3><p>We can either:</p><ul><li>Oversample the minority class</li><li>Undersample the majority class</li></ul><p>Oversampling increases the number of minority class examples, while undersampling reduces the number of majority class examples.</p><h3>Altering the Loss Function</h3><p>Another approach is to penalize the model more when it makes mistakes on the minority class.</p><p>This is done by assigning a higher weight to minority class examples in the loss function.</p><h3>5. Evaluation</h3><p>Evaluation helps us understand how well the model performs.</p><p>There are two major types of evaluation:</p><ul><li>Offline evaluation</li><li>Online evaluation</li></ul><h3>Offline Evaluation</h3><p>Offline evaluation happens during model development.</p><p>We evaluate the model on an evaluation dataset by comparing its predictions against ground truth labels.</p><p>The choice of metric depends on the task.</p><p>For classification problems, common metrics include:</p><ul><li>Accuracy</li><li>Precision</li><li>Recall</li><li>F1 score</li><li>ROC-AUC</li><li>Confusion matrix</li></ul><p>For regression problems, common metrics include:</p><ul><li>Mean Squared Error</li><li>Root Mean Squared Error</li><li>Mean Absolute Error</li></ul><p>For ranking problems, common metrics include:</p><ul><li>Precision@k</li><li>Recall@k</li><li>Mean Reciprocal Rank</li><li>Mean Average Precision</li><li>nDCG</li></ul><p>For natural language processing tasks, common metrics include:</p><ul><li>BLEU</li><li>ROUGE</li></ul><p>Offline evaluation is useful because it allows us to compare models before deploying them to production.</p><h3>Online Evaluation</h3><p>Online evaluation measures how the model performs after deployment.</p><p>These metrics are usually tied to business objectives.</p><p>For example:</p><ul><li>In ad click prediction, online metrics may include click-through rate and revenue lift.</li><li>In video recommendation, online metrics may include total watch time, click-through rate, and number of completed videos.</li><li>In friend recommendation, online metrics may include the number of friend requests sent and accepted per day.</li></ul><p>Online evaluation is important because a model that performs well offline may not always perform well in production.</p><h3>6. Deployment and Serving</h3><p>Deployment and serving involve making the model available to users.</p><p>This stage includes model compression, production testing, and prediction pipeline design.</p><h3>Model Compression</h3><p>Model compression reduces the size or computational cost of a model while trying to preserve performance.</p><p>Common techniques include knowledge distillation, pruning, and quantization.</p><h3>Knowledge Distillation</h3><p>Knowledge distillation trains a smaller model, called the student, to mimic a larger model, called the teacher.</p><p>The goal is to get much of the performance of the larger model while using fewer resources.</p><h3>Pruning</h3><p>Pruning removes or reduces the least useful parameters in a model.</p><p>This can make the model smaller and faster.</p><h3>Quantization</h3><p>Quantization uses fewer bits to represent model parameters.</p><p>This reduces model size and can improve inference speed. Quantization can be applied during training or after training.</p><h3>Testing Models in Production</h3><p>Before fully rolling out a new model, it is important to test it with real production traffic.</p><p>Common production testing techniques include:</p><ul><li>Shadow deployment</li><li>A/B testing</li><li>Canary release</li><li>Interleaving experiments</li><li>Bandit-based experiments</li></ul><h3>Shadow Deployment</h3><p>In shadow deployment, the new model runs in parallel with the existing model.</p><p>Each incoming request is sent to both models, but only the existing model’s prediction is shown to the user.</p><p>This allows teams to observe how the new model behaves on real traffic without affecting the user experience.</p><p>The drawback is cost, since predictions are generated by both models.</p><h3>A/B Testing</h3><p>In A/B testing, a portion of traffic is routed to the new model, while the remaining traffic continues to use the existing model.</p><p>This allows teams to compare the two models using real user behavior.</p><p>A/B testing is commonly used to measure whether the new model improves business metrics such as clicks, conversions, revenue, or engagement.</p><h3>Prediction Pipelines</h3><p>There are two common types of prediction pipelines:</p><ul><li>Batch prediction</li><li>Online prediction</li></ul><h3>Batch Prediction</h3><p>In batch prediction, the model generates predictions periodically and stores the results in a database.</p><p>For example, a recommendation system may precompute:</p><pre>user_id -&gt; recommended_items</pre><p>When the user visits the website, the system can simply perform a fast database lookup.</p><p>The advantage is speed. Since predictions are precomputed, the system does not need to run the model in real time for every request.</p><p>However, batch prediction has two major drawbacks.</p><p>First, it is less responsive to changing user preferences.</p><p>Second, it only works when we know the input in advance. For example, in a language translation system, we cannot precompute translations because the input depends entirely on what the user types.</p><h3>Online Prediction</h3><p>In online prediction, predictions are generated as soon as requests arrive.</p><p>This makes the system more responsive to real-time user behavior.</p><p>The main drawback is latency. If the model takes too long to generate predictions, the user experience may suffer.</p><h3>7. Monitoring</h3><p>Monitoring is essential after deployment.</p><p>It helps us understand why a model may fail in production and whether its performance is degrading over time.</p><p>One of the most common issues in production ML systems is data distribution shift.</p><p>Data distribution shift happens when the data seen by the model in production differs from the data it saw during training.</p><p>For example, user behavior may change over time, new types of content may appear, or external conditions may affect the input data.</p><p>There are several ways to deal with data distribution shift:</p><ol><li>Train the model on large and diverse datasets so it is exposed to a wider range of patterns. Any data points encountered in production likely come from this learned training distribution.</li><li>Regularly retrain the model using labeled data from the new production distribution.</li><li>Evaluate the model on future time periods. For example, train on January and February data, then test on March and April data to understand how the model performs under changing conditions.</li></ol><p>Monitoring ensures that the model continues to perform well after deployment, not just during development.</p><h3>Conclusion</h3><p>Machine learning system design is a complete engineering discipline.</p><p>It is not enough to train a model and measure its accuracy once. A real-world ML system requires clear requirements, careful problem framing, reliable data pipelines, strong evaluation methods, scalable deployment, and continuous monitoring.</p><p>The key stages are:</p><ul><li>Clarify the business and system requirements</li><li>Frame the problem as a machine learning task</li><li>Prepare high-quality data and features</li><li>Select and train the right model</li><li>Evaluate the model offline and online</li><li>Deploy the model safely</li><li>Monitor performance over time</li></ul><p>A successful ML system is not just one that performs well in a notebook.</p><p>It is one that continues to deliver reliable value in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5b4c5e6598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating your own Python Package]]></title>
            <link>https://medium.com/swlh/creating-your-own-python-package-1cc92d186554?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cc92d186554</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Sun, 31 May 2020 06:59:15 GMT</pubDate>
            <atom:updated>2020-06-02T20:01:20.505Z</atom:updated>
            <content:encoded><![CDATA[<h4>Object-oriented programming made simple</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahwL7Fy4GCrffxEnyWQWcw.jpeg" /></figure><p>Object-oriented programming is a type of programming in which programmers define the data type of a data structure and also the type of operations that can be applied to the data structure.</p><p>Let’s first look at the basics of object-oriented programming. <strong>Class</strong> is a blueprint for the object. <strong>Object</strong> is simply a collection of attributes(variables) and methods (functions). <strong>Attributes</strong> are the characteristics of an object. <strong>Methods</strong> are the tasks performed on the object.</p><p>Let’s understand this with an example. ‘Shirts’ can be considered as a Class. ‘Shirt1’ and ‘Shirt2’ are different objects of the Class ‘Shirts’. ‘Color’, ‘Size’, and ‘Price’ are the attributes of each object of the Class ‘Shirt’. ‘Doubling the price’, and ‘Changing color’ are the methods performed on each object of the Class ‘Shirt’. The syntax is as given below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd8f6cd14dccbe2c13eb226cee021a0d/href">https://medium.com/media/dd8f6cd14dccbe2c13eb226cee021a0d/href</a></iframe><p>The output of the above snippet of code is as given below :-</p><pre><strong>red<br>32<br>500<br>yellow<br>28<br>1000</strong></pre><p>Python is an object-oriented programming language. The various in-built packages in Python are all built on the concept of object-oriented programming. Now we’ll create our own python package that calculates the mean, standard deviation and plots the histogram of any user input data. The snippet of code is as given below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4210c540df614bf2c5f408515a19f861/href">https://medium.com/media/4210c540df614bf2c5f408515a19f861/href</a></iframe><p>We create an object of class ‘guassian’ by specifying the mean and standard deviation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9f7c0509d320bc3b443bf59b8a9b154/href">https://medium.com/media/a9f7c0509d320bc3b443bf59b8a9b154/href</a></iframe><p>We can also create an object of class ‘guassian’ by reading the data from a text file. In text file, each line is a number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c469f5e2fdb2c05dc50daa2fc3e0e27/href">https://medium.com/media/9c469f5e2fdb2c05dc50daa2fc3e0e27/href</a></iframe><p>The histogram is as plotted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*Zhptz8v0Ph4oXQ_S4DfHvA.png" /><figcaption>Right-skewed distribution</figcaption></figure><p>Let’s look at ‘<strong>Magic Methods</strong>’. Magic methods are special methods that you can define in your classes. The rules of operation are as specified by user. We look at 2 magic methods below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7039de17e1a218e9f9707edcf2f5f841/href">https://medium.com/media/7039de17e1a218e9f9707edcf2f5f841/href</a></iframe><p><strong>__add__ </strong>method returns the addition of 2 objects of a class.<br><strong>__repr__ </strong>method returns the object representation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/322b6aca15187206ae28568ea4548b80/href">https://medium.com/media/322b6aca15187206ae28568ea4548b80/href</a></iframe><p><strong>__add__ </strong>method adds the 2 objects ‘guassian_one’ and ‘guassian_two’. The means are added as sum of means and the standard deviations are added as square root of sum of squares of standard deviations.</p><p><strong>__repr__ </strong>method returns the ‘guassian_three’ representation in the following format :- <strong>mean 7, standard deviation 10.63</strong></p><p>We have created our own python package that can read user input data, calculate mean and standard deviation, plot the histogram and can add 2 sets of data.</p><p>Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cc92d186554" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/creating-your-own-python-package-1cc92d186554">Creating your own Python Package</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Means Clustering for Image Classification]]></title>
            <link>https://medium.com/@joel_34096/k-means-clustering-for-image-classification-a648f28bdc47?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a648f28bdc47</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[image-classifier]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Thu, 02 Jan 2020 23:55:38 GMT</pubDate>
            <atom:updated>2020-01-02T23:55:38.620Z</atom:updated>
            <content:encoded><![CDATA[<h4>Yes! K-Means Clustering can be used for Image Classification of MNIST dataset. Here’s how.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIWBk7IQ1uv2-BlfjXkD8Q.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/geralt-9301/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1036469">Gerd Altmann</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1036469">Pixabay</a></figcaption></figure><p>K-means clustering is an unsupervised learning algorithm which aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest centroid. The algorithm aims to minimize the squared Euclidean distances between the observation and the centroid of cluster to which it belongs.</p><p>K-Means clustering is not limited to the consumer information and population scientist. It can be used for Imagery analysis as well. Here we would use K-Means clustering to classify images of MNIST dataset.</p><h4>Getting to know the data</h4><p>The MNIST dataset is loaded from keras.</p><pre># Importing the dataset from keras</pre><pre><strong>from keras.datasets import mnist</strong></pre><pre><strong>(x_train, y_train), (x_test, y_test) = mnist.load_data()</strong></pre><p>The MNIST dataset is a benchmark dataset in the machine learning community which consists of 28 x 28 pixel images of digits from 0 to 9. Let us get to know more about the dataset.</p><pre># Checking the ‘type’</pre><pre><strong>print(type(x_train))<br>print(type(x_test))<br>print(type(y_train))<br>print(type(y_test))</strong></pre><p>All of them are numpy arrays.</p><pre># Checking the shape</pre><pre><strong>print(x_train.shape)<br>print(x_test.shape)<br>print(y_train.shape)<br>print(y_test.shape)</strong></pre><p>The output is (60000,28,28), (10000,28,28), (60000,1), (10000,1). The ‘x_train’ and ‘x_test’ consist of 60000 and 10000 monochrome images respectively . The pixel size of each image is 28 x 28.</p><p>Every input image has an output which is the number displayed in the image. Thus ‘y_train’ and ‘y_test’ are of size (60000,1) and (10000,1).</p><pre><strong>plt.gray()</strong> # B/W Images</pre><pre><strong>plt.figure(figsize = (10,9))</strong> # Adjusting figure size</pre><pre># Displaying a grid of 3x3 images</pre><pre><strong>for i in range(9):<br> plt.subplot(3,3,i+1)<br> plt.imshow(x_train[i])</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*7hgyxv6RDmxV0Gj_xmvHZw.png" /></figure><p>Initially all the images were of different pixel sizes. Through <strong>Image Scaling</strong> they have been reduced to a common pixel size of 28 x 28. The details of the image are lost due to reduction in pixel size and hence the images are blurred.</p><pre># Printing examples in &#39;y_train&#39;</pre><pre><strong>for i in range(5):<br>  print(y_train[i])</strong></pre><p>The output is 5,0,4,1,9. The ‘y_train’ and ‘y_test’ are digits from 0 to 9 which indicate the number displayed in image.</p><h4>Preprocessing the Data</h4><pre># Checking the minimum and maximum values of x_train</pre><pre><strong>print(x_train.min())<br>print(x_train.max())</strong></pre><p>The minimum and maximum values are 0 and 255 respectively. In the RGB color space the red, green and blue use 8 bits each which have integer values from 0 to 255. So the total number of possible colors is 256*256*256 = 16777216. Sounds astonishing?</p><p>Since the dataset contains a range of values from 0 to 255, the dataset has to be normalized. <strong>Data Normalization</strong> is an important preprocessing step which ensures that each input parameter (pixel, in this case) has a similar data distribution. This fastens the process of covergence while training the model. Also Normalization makes sure no one particular parameter influences the output significantly.</p><p>Data normalization is done by subtracting the mean from each pixel and then dividing the result by the standard deviation. The distribution of such data would resemble a Gaussian curve centered at zero. For image inputs we need the pixel numbers to be positive. So the image input is divided by 255 so that input values are in range of [0,1].</p><pre># Data Normalization</pre><pre># Conversion to float</pre><pre><strong>x_train = x_train.astype(‘float32’) <br>x_test = x_test.astype(‘float32’)</strong></pre><pre># Normalization</pre><pre><strong>x_train = x_train/255.0<br>x_test = x_test/255.0</strong></pre><p>Now we again check the minimum and maximum values of input.</p><pre># Checking the minimum and maximum values of x_train</pre><pre><strong>print(x_train.min())<br>print(x_train.max())</strong></pre><p>The minimum and maximum values are 0 and 1 respectively. The input data is in range of [0,1].</p><p>The input data have to be converted from 3 dimensional format to 2 dimensional format to be fed into the K-Means Clustering algorithm. Hence the input data has to be reshaped.</p><pre># Reshaping input data</pre><pre><strong>X_train = x_train.reshape(len(x_train),-1)<br>X_test = x_test.reshape(len(x_test),-1)</strong></pre><p>Now let us check the shape of ‘X_train’ and ‘X_test’.</p><pre># Checking the shape</pre><pre><strong>print(X_train.shape)<br>print(X_test.shape)</strong></pre><p>The output is (60000,784) and (10000,784). (28 x 28 = 784)</p><p>Now that preprocessing of data is done, we move ahead to building of model with Mini Batch K-Means.</p><h4>Building the model</h4><p><strong>Mini Batch K-Means</strong> works similarly to the K-Means algorithm. The difference is that in mini-batch k-means the most computationally costly step is conducted on only a random sample of observations as opposed to all observations. This approach can significantly reduce the time required for the algorithm to find convergence with only a small cost in quality.</p><pre><strong>from sklearn.cluster import MiniBatchKMeans</strong></pre><pre><strong>total_clusters = len(np.unique(y_test))</strong></pre><pre># Initialize the K-Means model</pre><pre><strong>kmeans = MiniBatchKMeans(n_clusters = total_clusters)</strong></pre><pre># Fitting the model to training set</pre><pre><strong>kmeans.fit(X_train)</strong></pre><p>The model has been fit to the training data. Now we run the <strong>kmeans.labels_</strong></p><pre><strong>kmeans.labels_</strong></pre><p>The images are classified into clusters based on similarity of pixel values. Each image is assigned a cluster label value given by kmeans.labels_. So kmeans.labels_ is an array of length 60000 as there are 60000 images in the training set.</p><p>But the kmeans.labels_ only denotes the cluster to which the image belongs to. It doesn’t denote the number displayed in image. Hence we write a separate function to retrieve the necessary information from kmeans.labels_</p><pre><strong>def retrieve_info(cluster_labels,y_train):</strong><br> ‘’’<br> Associates most probable label with each cluster in KMeans model<br> returns: dictionary of clusters assigned to each label</pre><pre>‘’’</pre><pre># Initializing</pre><pre><strong>reference_labels = {}</strong></pre><pre># For loop to run through each label of cluster label</pre><pre><strong>for i in range(len(np.unique(kmeans.labels_))):</strong></pre><pre><strong>index = np.where(cluster_labels == i,1,0)<br>  num = np.bincount(y_train[index==1]).argmax()<br>  reference_labels[i] = num</strong></pre><pre><strong>return reference_labels</strong></pre><p>Let us look at ‘reference_labels’.</p><pre><strong>print(reference_labels)</strong></pre><p>The output is :-<br> {0: 8, 1: 1, 2: 2, 3: 1, 4: 6, 5: 7, 6: 4, 7: 3, 8: 0, 9: 9} ( i.e A cluster label of 0 is a cluster of images of 8, a cluster label of 1 is a cluster of images of 1 and so on).</p><p>It can be seen that cluster labels of 1 and 3 both denote the cluster of images of 1 and none of the cluster labels denote the cluster of images of 5. These can be solved by optimizing which would be discussed later in the article.</p><p>We run the ‘retrieve_info’ function and process it to get ‘number_labels’ which denotes the number displayed in image.</p><pre><strong>reference_labels = retrieve_info(kmeans.labels_,y_train)</strong></pre><pre><strong>number_labels = np.random.rand(len(kmeans.labels_))</strong></pre><pre><strong>for i in range(len(kmeans.labels_)):</strong></pre><pre><strong>  number_labels[i] = reference_labels[kmeans.labels_[i]]</strong></pre><p>Now we print the predicted ‘number_label’ and the actual label for the first 20 training examples.</p><pre># Comparing Predicted values and Actual values</pre><pre><strong>print(number_labels[:20].astype(‘int’))<br>print(y_train[:20])</strong></pre><p>The output is :- <br> [8 0 9 1 4 2 1 8 1 4 3 1 3 6 1 7 2 8 1 7]<br> [5 0 4 1 9 2 1 3 1 4 3 5 3 6 1 7 2 8 6 9]</p><pre># Calculating accuracy score</pre><pre><strong>from sklearn.metrics import accuracy_score</strong></pre><pre><strong>print(accuracy_score(number_labels,y_train))</strong></pre><p>The accuracy score is about 55%.</p><p>Now let us optimize the algorithm for better results.</p><h4>Optimizing the Algorithm</h4><p>The performance of model is measured by the following 3 metrics :- Inertia, Homogeneity score and Accuracy score.</p><p><strong>Inertia</strong> is a measure of how internally coherent clusters are. It is inversely proportional to sum of squares of distances between data points and their respective cluster’s centroid. Higher the number of clusters, lower is the inertia score.</p><p>In clustering, a data point can belong to more than one cluster with some probability or likelihood value. The data points at the borderline of clusters can belong to more than 1 cluster. <strong>Homogeneity</strong> is a measure of data points of a particular cluster belonging to a single class.</p><p><strong>Accuracy score</strong> is the percentage of correctly predicted values.</p><p>We define a function that calculates metrics for the model.</p><pre># Function to calculate metrics for the model</pre><pre><strong>def calculate_metrics(model,output):<br> print(‘Number of clusters is {}’.format(model.n_clusters))<br> print(‘Inertia : {}’.format(model.inertia_))<br> print(‘Homogeneity :       {}’.format(metrics.homogeneity_score(output,model.labels_)))<br></strong></pre><p>Now we run the model for different values of ‘number of clusters’.</p><pre><strong>from sklearn import metrics</strong></pre><pre><strong>cluster_number = [10,16,36,64,144,256]</strong></pre><pre><strong>for i in cluster_number:</strong></pre><pre><strong>total_clusters = len(np.unique(y_test))</strong></pre><pre># Initialize the K-Means model</pre><pre><strong>kmeans = MiniBatchKMeans(n_clusters = i)</strong></pre><pre># Fitting the model to training set</pre><pre><strong>kmeans.fit(X_train)</strong></pre><pre># Calculating the metrics<br> <br><strong>calculate_metrics(kmeans,y_train)</strong></pre><pre># Calculating reference_labels</pre><pre><strong>reference_labels = retrieve_info(kmeans.labels_,y_train)</strong></pre><pre># ‘number_labels’ is a list which denotes the number displayed in image</pre><pre><strong>number_labels = np.random.rand(len(kmeans.labels_))</strong></pre><pre><strong>for i in range(len(kmeans.labels_)):<br> <br> number_labels[i] = reference_labels[kmeans.labels_[i]]<br> <br>print(‘Accuracy score : {}’.format(accuracy_score(number_labels,y_train)))</strong></pre><pre><strong>print(‘\n’)</strong></pre><p>The output is as given below :-</p><p>Number of clusters is 10 <br>Inertia : 2374596.25 <br>Homogeneity : 0.44577826488898536 <br>Accuracy score : 0.5496</p><p>Number of clusters is 16 <br>Inertia : 2242527.25 <br>Homogeneity : 0.5248907780235825 <br>Accuracy score : 0.6086</p><p>Number of clusters is 36 <br>Inertia : 1964164.875 <br>Homogeneity : 0.6916427302065263 <br>Accuracy score : 0.7745</p><p>Number of clusters is 64 <br>Inertia : 1810550.125 <br>Homogeneity : 0.7442898553384553 <br>Accuracy score : 0.82385</p><p>Number of clusters is 144 <br>Inertia : 1632715.875 <br>Homogeneity : 0.8060049496038609 <br>Accuracy score : 0.8646333333333334</p><p>Number of clusters is 256 <br>Inertia : 1515926.875 <br>Homogeneity : 0.8384350512732647 <br>Accuracy score : 0.8941</p><p>It can be observed that as the number of clusters increases,</p><blockquote>(1 The inertia score decreases because sum of squares of distances between data points and their respective cluster’s centroid decreases and clusters become more internally coherent.</blockquote><blockquote>(2 The homogeneity score increases the clusters become more differentiable and number of data points having a single class label is high.</blockquote><blockquote>(3 The accuracy score increases. The reason will be discussed later in the article.</blockquote><p>The accuracy is highest for ‘number of clusters’ = 256. Hence we run the model on the testing set for number of clusters = 256.</p><pre># Testing model on Testing set</pre><pre># Initialize the K-Means model</pre><pre><strong>kmeans = MiniBatchKMeans(n_clusters = 256)</strong></pre><pre># Fitting the model to testing set</pre><pre><strong>kmeans.fit(X_test)</strong></pre><pre># Calculating the metrics</pre><pre><strong>calculate_metrics(kmeans,y_test)</strong></pre><pre># Calculating the reference_labels</pre><pre><strong>reference_labels = retrieve_info(kmeans.labels_,y_test)</strong></pre><pre># ‘number_labels’ is a list which denotes the number displayed in image</pre><pre><strong>number_labels = np.random.rand(len(kmeans.labels_))</strong></pre><pre><strong>for i in range(len(kmeans.labels_)):<br> <br> number_labels[i] = reference_labels[kmeans.labels_[i]]<br> <br>print(‘Accuracy score : {}’.format(accuracy_score(number_labels,y_test)))</strong></pre><pre><strong>print(‘\n’)</strong></pre><p>The output is as given below :-</p><p>Number of clusters is 256<br> Inertia : 246126.453125 <br>Homogeneity : 0.8574948835978999 <br>Accuracy score : 0.903</p><p>The accuracy score on training and testing set are very similar and close to 90% which suggests the model is not overfitting the training data and can be generalized well to new data.</p><p>A question to ponder is that <strong>why do we need 256 clusters when there are only 10 digits</strong>. This is because there can be multiple ways to write a particular number. The orientation and style of writing a number can be different and thus the algorithm views them as drastically different images. Hence we need more than 1 cluster to represent the images of a particular number.</p><p>The above point can be verified by Visualizing the centroids of each cluster.</p><h4>Visualization of Cluster Centroids</h4><p>Each cluster has a centroid which is the most representative point of the cluster. If we can visualize the cluster centroid, we can get an idea of the other images in the cluster.</p><pre># Cluster centroids is stored in ‘centroids’</pre><pre><strong>centroids = kmeans.cluster_centers_</strong></pre><p>Let us look at the shape of ‘centroids’.</p><pre><strong>centroids.shape</strong></pre><p>The ‘centroids’ is of shape (256,784). There are 256 cluster centroids and each cluster centroid has 784 features.</p><p>We reshape the centroids from 2 dimensional format to 3 dimensional format so that we can view them as images.</p><pre><strong>centroids = centroids.reshape(256,28,28)</strong></pre><p>We had normalized the data. So now we nullify the normalization effect by multiplying by 255.</p><pre><strong>centroids = centroids * 255</strong></pre><p>Now let us visualize the cluster centroids.</p><pre><strong>plt.figure(figsize = (10,9))</strong></pre><pre><strong>bottom = 0.35</strong></pre><pre><strong>for i in range(16):<br> plt.subplots_adjust(bottom)<br> plt.subplot(4,4,i+1)<br> plt.title(‘Number:{}’.format(reference_labels[i]),fontsize = 17)<br> plt.imshow(centroids[i])</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*74gsJD12WERt0OjQEtOrMA.png" /></figure><p>Each image is a cluster centroid image. It can be seen that there are 5 clusters which denote the number 4. The style and orientation of all 5 cluster centroid images are different.</p><p>Suppose there are 2 images A and B which denote 2 different numbers but have the same style. If the number of clusters was less, the 2 images A and B would be clustered together. This decreases the accuracy of the model.</p><p>A particular number can be written in different styles and orientations. Increasing the number of clusters helps to assign a separate cluster to each style and orientation. This improves the accuracy of the model.</p><h4>Predicting number displayed in user input image</h4><p>The K-Means clustering model runs successfully on the MNIST data with an accuracy of 90%. But can it be used to predict other hand written images? Let us try to find out.</p><p>The below given image is an image of number 4 created in Microsoft Paint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*8szxAJphXNQTlo03SkOChQ.png" /></figure><p>The pixel size of the image is 819 x 460. It is reduced to a pixel size of 28 x 28 as all other images in MNIST data set.</p><pre># Reading the image</pre><pre><strong>image = plt.imread(‘number_4.jpg’)<br>plt.imshow(image)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*-4DxkGxXAeLTGwmR8DZhVg.png" /><figcaption>The image is blurry because it has been reduced from 819 x 460 to 28 x 28.</figcaption></figure><pre><strong>image.shape</strong></pre><p>The shape is (28, 28, 3) which suggests it is a RGB image as there are 3 channels. The RGB image is converted to monochrome image as all images in MNIST data set are monochrome images.</p><pre># RGB image is converted to Monochrome image</pre><pre><strong>from skimage import color<br>from skimage import io</strong></pre><pre><strong>image = color.rgb2gray(io.imread(‘number_4.jpg’))</strong></pre><p>The ‘image’ is reshaped into a single row vector to be fed into K-Means clustering algorithm.</p><pre># Reshaping into a row vector</pre><pre><strong>image = image.reshape(1,28*28)</strong></pre><p>The shape of the ‘image’ is (1,784).</p><p>The MNIST data set is imported.</p><pre># Importing the dataset from keras</pre><pre><strong>from keras.datasets import mnist</strong></pre><pre><strong>(x_train, y_train), (x_test, y_test) = mnist.load_data()</strong></pre><p>Let us check the minimum and maximum pixel values of ‘x_train’ and ‘image’.</p><pre><strong>print(x_train.min())<br>print(x_train.max())<br>print(image.min())<br>print(image.max())</strong></pre><p>The minimum and maximum pixel values of ‘x_train’ and ‘image’ are (0,255) &amp; (0,0.5) respectively. This suggests normalization is required for ‘x_train’ but not for ‘image’.</p><pre># Normalization of ‘x_train’</pre><pre><strong>x_train = x_train.astype(‘float32’)<br>x_train = x_train/255.0</strong></pre><p>‘x_train’ is reshaped from 3 dimensional format to 2 dimensional format.</p><pre># Reshaping of ‘x_train’</pre><pre><strong>x_train = x_train.reshape(60000,28*28)</strong></pre><p>The model is trained.</p><pre># Training the model</pre><pre><strong>kmeans = MiniBatchKMeans(n_clusters=256)<br>kmeans.fit(x_train)</strong></pre><p>The ‘retrieve_info’ function is run and processed to get ‘number_labels’ which denotes the number displayed in image.</p><pre><strong>reference_labels = retrieve_info(kmeans.labels_,y_train)</strong></pre><pre><strong>number_labels = np.random.rand(len(kmeans.labels_))</strong></pre><pre><strong>for i in range(len(kmeans.labels_)):</strong></pre><pre><strong>  number_labels[i] = reference_labels[kmeans.labels_[i]]</strong></pre><p>The cluster into which the image is classified into is predicted.</p><pre><strong>predicted_cluster = kmeans.predict(image)</strong></pre><p>The number in the image is predicted.</p><pre><strong>number_labels[[predicted_cluster]]</strong></pre><p>The output is 4. The model has successfully predicted the number displayed in ‘image’.</p><p>Happy Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a648f28bdc47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pros & Cons of Dimensionality Reduction]]></title>
            <link>https://medium.datadriveninvestor.com/pros-cons-of-dimensionality-reduction-f843cad3953a?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f843cad3953a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Thu, 02 Jan 2020 00:33:53 GMT</pubDate>
            <atom:updated>2020-01-03T07:21:21.392Z</atom:updated>
            <content:encoded><![CDATA[<h4>Compression and Visualization of Iris data using Principle Component Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwenU3V3y9P4j9rfmj6krw.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/manfredrichter-4055600/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2219594">Manfred Richter</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2219594">Pixabay</a></figcaption></figure><p>We would be working on the famous Iris flower data set.</p><p>The necessary packages are imported.</p><pre># Importing the necessary packages</pre><pre><strong>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</strong></pre><p>The Iris data set is imported from sklearn.datasets</p><pre># Importing the data set</pre><pre><strong>from sklearn import datasets</strong></pre><pre><strong>iris_data = datasets.load_iris()</strong></pre><p>Let’s get to know ‘iris_data’.</p><pre><strong>iris_data.keys()</strong></pre><p>Output is dict_keys([‘data’, ‘target’, ‘target_names’, ‘DESCR’, ‘feature_names’, ‘filename’]).</p><p>‘<strong>data</strong>’ :- As the name suggests, it’s the data.<br>‘<strong>target</strong>’ :- Integer encoding of output labels. 0 denotes ‘setosa’, 1 denotes ‘versicolor’ and 2 denotes ‘virginica’.<br>‘<strong>target_names</strong>’ :- The output labels namely [‘setosa’, ‘versicolor’, ‘virginica’].<br>‘<strong>DESCR</strong>’ :- Description of the dataset.<br>‘<strong>feature_names</strong>’ :- The input features namely [‘sepal length’, ‘sepal width’, ‘petal length’, ‘petal width’].<br>‘<strong>filename</strong>’ :- Path of the file.</p><p>Let’s create a dataframe of ‘iris_data’.</p><pre># Create a dataframe of the ‘iris_data’</pre><pre><strong>iris = pd.DataFrame(data = iris_data[‘data’], columns = iris_data[‘feature_names’])</strong></pre><pre># Displays first 5 columns of ‘iris’</pre><pre><strong>iris.head()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*XYlvlJcrigjsJcuxBNOatg.png" /></figure><pre># Displays properties of each column</pre><pre><strong>iris.describe()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*EfG_RuBrd_WzsYXSOvq08w.png" /></figure><p>It can be observed that the count of all columns is 150 and the minimum values of all columns is a non zero number which suggests <strong>there are no missing values</strong>.</p><h4>Visualizing The Data</h4><pre><strong>sns.pairplot(iris)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*jozdlqBi2hmib4jEzGvR2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*LEiINT6LkeCF2C-2SPHd-g.png" /></figure><p>‘sepal length’, ‘petal length’ and ‘petal width’ are highly correlated with each other.</p><pre><strong>sns.heatmap(iris.corr())</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*O_SUcckOhp8dKEyyK-5zcQ.png" /></figure><pre># &#39;pairs&#39; is a list of combinations of iris columns</pre><pre><strong>pairs = []</strong></pre><pre><strong>for i in range(len(iris.columns)):<br>  for j in range(i+1,len(iris.columns)):<br>    pairs.append((iris.columns[i],iris.columns[j]))</strong></pre><pre><strong>pairs</strong></pre><p>The output is <br>[(‘sepal length (cm)’, ‘sepal width (cm)’), <br>(‘sepal length (cm)’, ‘petal length (cm)’), <br>(‘sepal length (cm)’, ‘petal width (cm)’), <br>(‘sepal width (cm)’, ‘petal length (cm)’),<br> (‘sepal width (cm)’, ‘petal width (cm)’),<br> (‘petal length (cm)’, ‘petal width (cm)’)]</p><pre><strong>a = 1<br>left = 0.01</strong></pre><pre><strong>plt.figure(figsize = (15,9))</strong> # Adjusting figure size</pre><pre><strong>for i,j in pairs:</strong></pre><pre><strong>  sns.set(font_scale=1.3)</strong> # Adjusting font size<br>  <strong>plt.subplots_adjust(left)</strong> # Adjusting spacing between subplots<br> <br>  <strong>plt.subplot(2,3,a)</strong> # Subplot No.</pre><pre>  <strong>sns.scatterplot(iris[i],iris[j],hue = iris_data[‘target’],palette= [“C0”, “C1”, “C2”])</strong> # Plotting the scatter plot<br>  <br><strong>a = a+1</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrFVlRT_LhUr-jw-2ZzQ5w.png" /><figcaption>Legend :- 0 denotes ‘Setosa’. 1 denotes ‘Versicolor’. 2 denotes ‘Virginica’.</figcaption></figure><p>In each scatter plot, 3 well-separated clusters can be seen. There is a slight overlap between the orange (‘Versicolor’) and green (‘Virginica’) points. Otherwise the clusters are well differentiable. <strong>This suggests K-Means Clustering model would be the best choice for the iris dataset</strong>. <strong>Thus visualizing the data not only helps in getting to know the data but also with the selection of model.</strong></p><p><a href="https://www.datadriveninvestor.com/2019/03/25/a-programmers-guide-to-creating-an-eclectic-bookshelf/">A Programmer&#39;s Guide to Creating an Eclectic Bookshelf | Data Driven Investor</a></p><h4>Elbow Method</h4><p>The elbow method helps to decide the optimum number of clusters.</p><pre><strong>from sklearn.cluster import KMeans</strong></pre><pre># K-Means model is run for different values of ‘number of clusters’</pre><pre><strong>clusters = list(range(1,10))</strong></pre><pre># ‘inertia’ stores the inertia score of K-Means model</pre><pre><strong>inertia = []</strong></pre><pre># ‘for’ loop to run K-Means model for each value of ‘number of clusters’</pre><pre><strong>for i in clusters:<br> kmeans = KMeans(n_clusters = i)<br> kmeans.fit(iris)<br> inertia.append(kmeans.inertia_)</strong></pre><pre># A graph is plotted with ‘number of clusters’ on x-axis and ‘inertia score’ on y-axis</pre><pre><strong>plt.figure(figsize = (10,8))<br>plt.plot(clusters,inertia,marker = ‘o’,linestyle = ‘dashed’)<br>plt.xlabel(‘Number of clusters’)<br>plt.ylabel(‘Inertia score’)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*5OOd4TYWRsEJhxL-T14HRQ.png" /></figure><p>The inertia score decreases sharply till ‘number of clusters’ = 3. After that there is no significant decrease. Hence the optimum value of ‘number of clusters’ is 3. It is called the elbow method because there is an elbow formation at the optimum value.</p><p><strong>Principal Component Analysis (PCA) Reduction<br>Principal component analysis</strong> (<strong>PCA</strong>) is a statistical procedure that uses an orthogonal transformation to convert a set of observations of possibly correlated variables into a set of values of linearly uncorrelated variables called <strong>principal components</strong>. Some information is lost in the process of dimensionality reduction.</p><p>In the dataset ‘iris’, 3 features (‘sepal length’, ‘petal length’ and ‘petal width’) out of 4 features are correlated with each other. So PCA would work well on the ‘iris’ dataset.</p><pre># Importing PCA</pre><pre><strong>from sklearn.decomposition import PCA</strong></pre><pre># Perform PCA</pre><pre><strong>pca = PCA(n_components = 2)<br>pc = pca.fit_transform(iris)</strong></pre><p>The ‘iris’ dataset with 4 features has been reduced to ‘pc’ with 2 features.</p><pre><strong>pc.shape</strong></pre><p>The shape is of (150,2).</p><p>Let’s train the model on the reduced dataset ‘pc’.</p><pre><strong>kmeans = KMeans(n_clusters = 3)<br>kmeans.fit(pc)</strong></pre><p>Let’s visualize the reduced 2 dimensional data by plotting the color plot.</p><pre># Define step size of mesh</pre><pre><strong>h = 0.02</strong></pre><pre># Generate mesh grid</pre><pre><strong>x_min, x_max = pc[:,0].min() — 1, pc[:,0].max() + 1<br>y_min, y_max = pc[:,1].min() — 1, pc[:,1].max() + 1<br>xx, yy = np.meshgrid(np.arange(x_min,x_max,h), np.arange(y_min,y_max,h))</strong></pre><pre># Obtain labels for each point in the mesh using our trained model on reduced data set</pre><pre><strong>Z = kmeans.predict(np.c_[xx.ravel(),yy.ravel()])</strong></pre><pre># Put the result into a color plot</pre><pre><strong>Z = Z.reshape(xx.shape)</strong></pre><pre># Define color plot</pre><pre><strong>cmap = plt.cm.Paired</strong></pre><pre># Plotting color plot figure (Decision Boundary)</pre><pre><strong>plt.clf()<br>plt.figure(figsize=(10,9))<br>plt.imshow(Z,interpolation = ‘nearest’,extent=(xx.min(),xx.max(),yy.min(),yy.max()),<br> cmap = cmap,aspect = ‘auto’,origin = ‘lower’)</strong></pre><pre># Plotting the points</pre><pre><strong>sns.scatterplot(pc[:,0],pc[:,1],hue = iris_data[‘target’],palette=[“C0”, “C1”, “C2”],legend = False)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*lTwri7BI7m5sGTux78wPXw.png" /></figure><p>The scattered points have been classified into 3 colors based on ‘iris_data[‘target’]’ information (actual output). The regions have been classified into 3 colors based on the prediction of trained model (predicted output).</p><p>Few red ( Versicolor) and green ( Virginica) points have been misclassified by the trained model.</p><h4>Comparison of ‘without PCA’ and ‘with PCA’</h4><p>The comparison is made based on the following 4 metrics :- Accuracy, Homogeneity score, Completeness score and V-Measure score.</p><pre><strong>from sklearn import metrics</strong></pre><pre># Training model on actual data</pre><pre><strong>kmeans1 = KMeans(n_clusters=3)<br>kmeans1.fit(iris)</strong></pre><pre># Training model on reduced data</pre><pre><strong>kmeans2 = KMeans(n_clusters=3)<br>kmeans2.fit(pc)</strong></pre><pre># Importing Metrics</pre><pre><strong>from sklearn.metrics import homogeneity_score<br>from sklearn.metrics import completeness_score<br>from sklearn.metrics import v_measure_score</strong></pre><pre># Calculating Accuracy</pre><pre><strong>models = [kmeans1,kmeans2]<br>accuracy = []</strong></pre><pre><strong>for i in models:<br>  h = 0<br>  correct_label = 0<br>  for j in range(i.n_clusters):<br>    index = np.where(iris_data[&#39;target&#39;] == h)<br>    correct_label = correct_label + (i.labels_[index] == i.labels_[index].max()).sum()<br>    h = h + 1<br>  accuracy.append(correct_label/len(i.labels_))</strong></pre><pre># Printing the metrics</pre><pre><strong>k = 0<br>for i in models:<br>  print(&#39;Accuracy : {}&#39;.format(accuracy[k]))<br>  print(&#39;Homogeneity score  {}:&#39;.format(metrics.homogeneity_score(iris_data[&#39;target&#39;],i.labels_)))<br>  print(&#39;Completeness score {}:&#39;.format(metrics.completeness_score(iris_data[&#39;target&#39;],i.labels_)))<br>  print(&#39;V-Measure {}:&#39;.format(metrics.v_measure_score(iris_data[&#39;target&#39;],i.labels_)))<br>  print(&#39;\n&#39;)<br>  k = k+1</strong></pre><blockquote>(1 Without PCA<br> Accuracy : 0.7466666666666667<br> Homogeneity score : 0.7514854021988338 <br>Completeness score : 0.7649861514489815 <br>V-Measure : 0.7581756800057784</blockquote><blockquote>(2 With PCA<br> Accuracy : 0.74 <br>Homogeneity score : 0.736419288125285<br> Completeness score : 0.7474865805095325 <br>V-Measure : 0.7419116631817838</blockquote><p>There is a small decrease in Accuracy, Homogeneity, Completeness and V-Measure score after dimensionality reduction. <strong>This suggests reducing the dimensionality of data does not affect the model evaluation metrics significantly. The important information of data is still preserved. Dimensionality reduction also has the added advantage of two-dimensional visualization of the data.</strong></p><p>Happy New Year! Happy Reading!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f843cad3953a" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/pros-cons-of-dimensionality-reduction-f843cad3953a">Pros &amp; Cons of Dimensionality Reduction</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis of Movie Reviews in NLTK Python]]></title>
            <link>https://medium.com/swlh/sentiment-analysis-of-movie-reviews-in-nltk-python-4af4b76a6f3?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4af4b76a6f3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 02:22:12 GMT</pubDate>
            <atom:updated>2020-01-01T02:22:12.511Z</atom:updated>
            <content:encoded><![CDATA[<h4>A gentle introduction to sentiment analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7YAdZYL64W_Mjd1CgoiOw.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/tookapic-1386459/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=932926">tookapic</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=932926">Pixabay</a></figcaption></figure><p>Sentiment Analysis is the process of computationally identifying and categorizing opinions expressed in a piece of text, especially in order to determine whether the writer’s attitude towards a particular topic, product, etc. is positive, negative, or neutral.</p><p>This is a simple project of classifying the movie reviews as either positive or negative. We would be working on the ‘movie_reviews’ dataset in ntlk.corpus package.</p><p>The necessary packages are imported.</p><pre><strong>import nltk<br>from nltk.corpus import movie_reviews</strong></pre><p>Let us explore the package ‘movie_reviews’.</p><pre># A list of all the words in &#39;movie_reviews&#39;</pre><pre><strong>movie_reviews.words()</strong></pre><p>The output is [‘plot’, ‘:’, ‘two’, ‘teen’, ‘couples’, ‘go’, ‘to’, …]</p><pre># Prints total number of words in &#39;movie_reviews&#39;</pre><pre><strong>len(movie_reviews.words())</strong></pre><p>Total number of words is 1583820.</p><pre><strong>movie_reviews.categories()</strong></pre><p>The output is [‘neg’, ‘pos’]. There are two categories :- ‘neg’ and ‘pos’ which implies negative and positive reviews respectively.</p><pre># Displays frequency of words in ‘movie_reviews’</pre><pre><strong>nltk.FreqDist(movie_reviews.words())</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*i2xC4BwXxfadpt92lVuerw.png" /><figcaption>Frequency of a sample of words in ‘movie_reviews’</figcaption></figure><pre># Prints frequency of the word &#39;happy&#39;.</pre><pre><strong>nltk.FreqDist(movie_reviews.words())[&#39;happy&#39;]</strong></pre><p>The frequency of the word ‘happy’ is 15.</p><pre># Displays frequency of 15 most common words in ‘movie_reviews’</pre><pre><strong>nltk.FreqDist(movie_reviews.words()).most_common(15)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*Ai5wj8KBNyj-QgavqRPdhw.png" /></figure><p>The punctuation characters [‘,’ , ‘.’ , ‘-’] are treated as separate words.</p><p>Each of the movie review has a file id associated with it. The file id is the identification factor of movie review.</p><pre># Prints all file ids</pre><pre><strong>movie_reviews.fileids()</strong></pre><pre># Prints file ids of positive reviews</pre><pre><strong>movie_reviews.fileids(‘pos’)</strong></pre><pre># Prints file ids of negative reviews.</pre><pre><strong>movie_reviews.fileids(‘neg’)</strong></pre><p>The words in a particular movie review can be printed if the file id is known.</p><pre># Prints all words in movie_review with file id ‘neg/cv001_19502.txt’</pre><pre><strong>movie_reviews.words(‘neg/cv001_19502.txt’)</strong></pre><p>The output is [‘the’, ‘happy’, ‘bastard’, “‘“, ‘s’, ‘quick’, ‘movie’, …].</p><p>Now that we explored, let us get into the project.</p><pre># all_words is a dictionary which contains the frequency of words in ‘movie_reviews’</pre><pre><strong>all_words = nltk.FreqDist(movie_reviews.words())</strong></pre><p><strong>len(all_words) = 39768 </strong>gives the total number of distinct words in ‘movie_reviews’</p><p>We define a ‘feature_vector’ which contains the first 4000 words of ‘all_words’. <strong>We don’t include all the words in ‘all_words’ to save computational power and time and thus we compromise on results.</strong></p><pre># Defining the feature_vector</pre><pre><strong>feature_vector = list(all_words)[:4000]</strong></pre><p>Let us try to manually analyze the sentiment of one movie review.</p><pre># Initialization</pre><pre><strong>feature = {}</strong></pre><pre># One movie review is chosen</pre><pre><strong>review = movie_reviews.words(‘neg/cv954_19932.txt’)</strong></pre><pre># ‘True’ is assigned if word in feature_vector can also be found in review. Otherwise ‘False’</pre><pre><strong>for x in range(len(feature_vector)):<br> feature[feature_vector[x]] = feature_vector[x] in review</strong></pre><pre># The words which are assigned ‘True’ are printed</pre><pre><strong>[x for x in feature_vector if feature[x] == True]</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*tEnIgwZTdBJI_oqStcAJ5Q.png" /><figcaption>Entire word list is not displayed due to screenshot constraint</figcaption></figure><p>Negative words like ‘unfortunately’ ,’accidentally’, can be seen in the output which suggests the sentiment is ‘negative’. <strong>Better results can be achieved if the 4000 words defined in ‘feature_vector’ be on extreme ends (either positive or negative).</strong></p><p>Now let us try to analyze the sentiments of movie reviews using Machine Learning.</p><pre># Document is a list of (words of review, category of review)</pre><pre><strong>document = [(movie_reviews.words(file_id),category) for file_id in movie_reviews.fileids() for category in movie_reviews.categories(file_id)]</strong></pre><pre><strong>document</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*zXXKH5bQnn2ysMW2RkoS6w.png" /><figcaption>Entire list could not be displayed due to screenshot constraint</figcaption></figure><pre># we define a function that finds the features</pre><pre><strong>def find_feature(word_list):</strong></pre><pre># Initialization</pre><pre><strong>feature = {}</strong></pre><pre># For loop to find the feature. ‘True’ is assigned if word in feature_vector can also be found in review. Otherwise ‘False’</pre><pre><strong>for x in feature_vector:<br> feature[x] = x in word_list</strong></pre><pre>return feature</pre><p>Let us check the function ‘find_feature’.</p><pre># Checking the function ‘find_feature’</pre><pre><strong>find_feature(document[0][0])</strong></pre><p>document[0][0] is the list of words of first movie review.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*qago4gHeIhRXW_kR7B9UKw.png" /><figcaption>All the words could not be displayed due to screen shot constraint</figcaption></figure><p>The ‘find_feature’ function works fine.</p><pre># Feature_sets stores the ‘feature’ of every review</pre><pre><strong>feature_sets = [(find_feature(word_list),category) for (word_list,category) in document]</strong></pre><p>Now we create machine learning models.</p><pre># The necessary packages and classifiers are imported</pre><pre><strong>from nltk.classify.scikitlearn import SklearnClassifier<br>from sklearn.svm import SVC<br>from sklearn import model_selection</strong></pre><p>The data set is split into Training and Test sets.</p><pre># Splitting into training and testing sets</pre><pre><strong>train_set,test_set = model_selection.train_test_split(feature_sets,test_size = 0.25)</strong></pre><p>We check the size of Train and Test sets.</p><pre><strong>print(len(train_set))<br>print(len(test_set))</strong></pre><p>train_set is of size 1500 and test_set is of size 500.</p><p>We train the model on Training set.</p><pre># The model is trained on Training data.</pre><pre><strong>model = SklearnClassifier(SVC(kernel = ‘linear’))<br>model.train(train_set)</strong></pre><p>We test the trained model on Test set.</p><pre># The trained model is tested on Testing data and accuracy is calculated</pre><pre><strong>accuracy = nltk.classify.accuracy(model, test_set)</strong></pre><pre><strong>print(‘SVC Accuracy : {}’.format(accuracy))</strong></pre><p>The Test set accuracy is 63%.</p><p><strong>The test set accuracy can be further improved by choosing a more appropriate ‘feature_vector’, increasing the size of ‘feature_vector’ (only 4000 words have been included to save computational power and time), SVM Hyper parameter tuning and combining multiple classification algorithms.</strong></p><p>Happy Learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4af4b76a6f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/sentiment-analysis-of-movie-reviews-in-nltk-python-4af4b76a6f3">Sentiment Analysis of Movie Reviews in NLTK Python</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing — Tokenizing, Stop words & Stemming]]></title>
            <link>https://medium.com/swlh/natural-language-processing-tokenizing-stop-words-stemming-a6a72a4b8571?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a72a4b8571</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Fri, 27 Dec 2019 19:25:01 GMT</pubDate>
            <atom:updated>2019-12-28T08:36:43.399Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started With Natural Language Processing</h3><h4>A gentle introduction to NLTK library of Python with simple examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViK9OhgSd5Es4parmQpoOg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/StartupStockPhotos-690514/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=593313">StartupStockPhotos</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=593313">Pixabay</a></figcaption></figure><p>The necessary packages are imported.</p><pre><strong># Importing the necessary packages</strong></pre><pre><strong>import nltk<br>from nltk.tokenize import sent_tokenize, word_tokenize<br>from nltk import PunktSentenceTokenizer<br>from nltk.corpus import stopwords<br>from nltk.stem import PorterStemmer</strong></pre><pre><strong>from nltk.corpus import stopwords</strong></pre><p>Let us understand the function of each package.</p><pre><strong>from nltk.tokenize import word_tokenize, sent_tokenize</strong></pre><p>‘<strong>word_tokenize</strong>’ gives an output as a list of words in the input sentence.</p><pre># Example usage of ‘word_tokenize’</pre><pre><strong>a = ‘Spending today complaining about yesterday will not make tomorrow any better’</strong></pre><pre><strong>word_tokenize(a)</strong></pre><p>The output is [‘Spending’, ‘today’, ‘complaining’, ‘about’, ‘yesterday’, ‘will’, ‘not’, ‘make’, ‘tomorrow’, ‘any’, ‘better’].</p><p>Given below is the snippet of code that serves the same function as ‘word_tokenize’ <strong>(Optional)</strong></p><pre><strong>def word(a):<br> return a.split(‘ ‘)</strong></pre><pre><strong>a = ‘Spending today complaining about yesterday will not make tomorrow any better’</strong></pre><pre><strong>word(a)</strong></pre><p>‘<strong>sent_tokenize</strong>’ gives a list of sentences as output in the input paragraph.</p><pre>Example usage of &#39;sent_tokenize&#39;</pre><pre><strong>a = ‘Today is a good day. I would like to do more. Would you like to join me? It is gonna be fun’<br>sent_tokenize(a)</strong></pre><p>The output is [‘Today is a good day.’, ‘I would like to do more.’, ‘Would you like to join me?’, ‘It is gonna be fun’]</p><p>‘sent_tokenize’ is an instance of ‘<strong>PunktSentenceTokenizer</strong>’.</p><pre># Example usage of PunktSentenceTokenizer</pre><pre># Importing the PunktSentenceTokenizer</pre><pre><strong>from nltk import PunktSentenceTokenizer</strong></pre><pre># Defining the training and sample text</pre><pre><strong>train_txt = ‘Mr. Mike met Shane. The appointment was critical. Mr. Mike was in serious condition’<br>sample_txt = ‘Mr. Watson met Mark. The appointment was critical. Mr. Watson was in serious condition’</strong></pre><pre># Training the PunktSentenceTokenizer on &#39;train_nxt&#39;</pre><pre><strong>custom_tokenizer = PunktSentenceTokenizer(train_txt)</strong></pre><pre>#Tokenizing the sample_txt using the trained PunkSentenceTokenizer</pre><pre><strong>tokenized = custom_tokenizer.tokenize(sample_txt)</strong></pre><pre><strong>tokenized</strong></pre><p>The output is [‘Mr. Watson met Mark.’, ‘The appointment was critical.’, ‘Mr. Watson was in serious condition’].</p><p>‘sent_tokenizer’ is pretrained. It doesn’t require training text and can tokenize straightaway. But it is not much helpful if the text to be tokenized is very different and uncommon. The tokenization may not be perfect. In that case, ‘PunktSentenceTokenizer’ is a better option. The tokenizer is first trained on a training text which is similar to the text to be tokenized. Then the trained tokenizer is used for tokenizing.</p><p>Given below is the snippet of code that serves the same function as ‘sent_tokenize’ <strong>(Optional)</strong></p><pre># Defining the sentence tokenizer function. There are 3 end punctuations :- &#39;?&#39;,&#39;!&#39;,&#39;.&#39;. All 3 end punctuations are replaced with &#39;.&#39;</pre><pre><strong>def sentence(a):<br> a.replace(‘?’,’.’).replace(‘!’,’.’)<br> return a.split(‘.’)</strong></pre><pre># Defining the text to be tokenized</pre><pre><strong>a = ‘Today is a good day. I would like to do more. Would you like to join me? It is gonna be fun’</strong></pre><pre><strong>sentence(a)</strong></pre><p>The set of ‘<strong>stopwords</strong>’ is predefined in the nltk library of python.</p><pre><strong>from nltk.corpus import stopwords</strong></pre><pre><strong>print(set(stopwords.words(&#39;english&#39;)))</strong></pre><p>‘Stopwords’ are commonly used words in a particular language. They don’t help in classification of text as they are commonly and widely used. Hence in order to save computational power and time, the stopwords are filtered which is an important preprocessing step for natural language processing applications.</p><pre><strong>from nltk.stem import PorterStemmer</strong></pre><p><strong>Stemming</strong> is the process of reducing a word to its word stem or to the roots of words known as a lemma. It is a kind of normalization for words.</p><pre># Example usage of ‘PorterStemmer’</pre><pre># Defining a list of words to be stemmed.</pre><pre><strong>a = [‘lift’,’lifts’,’lifting’,’lifter’,’lifted’]</strong></pre><pre># Defining an empty list to stored the stemmed words.</pre><pre><strong>a_stemmed = []</strong></pre><pre># Defining an instance of class PorterStemmer()</pre><pre><strong>ps = PorterStemmer()</strong></pre><pre><strong>for x in a:<br> a_stemmed.append(ps.stem(x))</strong></pre><pre><strong>print(a_stemmed)</strong></pre><p>The output is [‘lift’, ‘lift’, ‘lift’, ‘lifter’, ‘lift’]. ‘lift’, ‘lifts’, ‘lifting’, and ‘lifted’ have all been reduced to ‘lift’.</p><p>The <strong>POS tagger</strong> is used for part of speech tagging. The following line of code gives the list of POS tags.</p><pre><strong>nltk.help.upenn_tagset()</strong></pre><ul><li>CC coordinating conjunction</li><li>CD cardinal digit</li><li>DT determiner,the,a,an</li><li>EX existential, there (like: “there is” … think of it like “there exists”)</li><li>FW foreign word</li><li>IN preposition/subordinating conjunction</li><li>JJ adjective, ‘big’</li><li>JJR adjective, comparative ‘bigger’</li><li>JJS adjective, superlative ‘biggest’</li><li>LS list marker, 1)</li><li>MD modal could, will</li><li>NN noun, singular ‘desk’</li><li>NNS noun, plural ‘desks’</li><li>NNP proper noun, singular ‘Harrison’</li><li>NNPS proper noun, plural ‘Americans’</li><li>PDT predeterminer, ‘all the kids’</li><li>POS possessive ending, parent’s</li><li>PRP personal pronoun I, he, she</li><li>PRP$ possessive pronoun my, his, hers</li><li>RB adverb, very/silently,</li><li>RBR adverb, comparative better</li><li>RBS adverb, superlative best</li><li>RP adverbial particle, give up</li><li>TO, to go ‘to’ the store.</li><li>UH interjection, errrrrrrrm</li><li>VB verb, base form take</li><li>VBD verb, past tense took</li><li>VBG verb, gerund/present participle taking</li><li>VBN verb, past participle taken</li><li>VBP verb, sing. present, non-3d take</li><li>VBZ verb, 3rd person sing. present takes</li><li>WDT wh-determiner, which</li><li>WP wh-pronoun, who/what</li><li>WP$ possessive wh-pronoun, whose</li><li>WRB wh-abverb, where/when</li></ul><pre># Example usage of POS Tagger</pre><pre># Defining a sample text</pre><pre><strong>sample_txt = &#39;European authorities fined Google a record $5.1 billion on Wednesday for abusing its power in the mobile phone market and ordered the company to alter its practices&#39;</strong></pre><pre># Word tokenizing</pre><pre><strong>word = nltk.word_tokenize(sample_txt)</strong></pre><pre># POS Tagging</pre><pre><strong>tag = nltk.pos_tag(word)</strong></pre><pre><strong>tag</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*PUSC6ceOxTm_A5_ZbJNdJQ.png" /></figure><p><strong>Named Entity Recognition</strong> seeks to locate and classify named entities in text into pre-defined categories such as the names of persons, organizations, locations, expressions of times, quantities, monetary values, percentages, etc.</p><p>Named Entity Type and Examples<br>ORGANIZATION :- Companies, Agencies, Institutions. Google, Microsoft.<br>PERSON :- People including fictional. Mike, Jessica.<br>LOCATION :- Non-GPE Locations, mountain ranges, bodies of water. Mount Everest.<br>DATE :- Absolute or relative dates or periods. June, 2008–06–29.<br>TIME :- Times smaller than a day. three fifty a m, 2:30 p.m.<br>MONEY :- Monetary values including unit. 50 million Canadian Dollars, GBP 10.65<br>PERCENT :- Percentage including ‘%’. twenty five pct, 18.75 %.<br>FACILITY :- Buildings, airports, highways, bridges. Washington Monument, Stonehenge.<br>GPE — Countries, cities, states. Bangalore, India.</p><pre># Example usage of Named Entity Recognition</pre><pre># Defining a sample text</pre><pre><strong>sample_txt = ‘Amit Shah asserted the government will ensure that the non-Muslim refugees from Pakistan, Bangladesh and Afghanistan get Indian nationality and live in the country with honour.’</strong></pre><pre># Word tokenizing</pre><pre><strong>words = nltk.word_tokenize(sample_txt)</strong></pre><pre># POS tagging</pre><pre><strong>tagged = nltk.pos_tag(words)</strong></pre><pre># Named entity recognition</pre><pre><strong>named_entity = nltk.ne_chunk(tagged,binary = False)</strong></pre><pre><strong>print(named_entity)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*lUkXIioUBH-iDDelCknRbQ.png" /></figure><p>The main aim of <strong>Chunking</strong> is to group words into phrases as per the regularized expression defined. Let us chunk using the given below regularized expression :-</p><blockquote>&lt;RB.?&gt;*&lt;VB.?&gt;*&lt;NNP&gt;*&lt;NN&gt;?</blockquote><blockquote>RB = Adverb<br>VB = Verb<br>NNP = Singular Proper noun<br>NN = Singular Noun</blockquote><blockquote>+ = Match 1 or more<br>? = Match 0 or 1 repetitions<br>* = Match 0 or more repetitions<br>. = Any character except a new line</blockquote><blockquote>RB.? = Any tense of Adverb (RBR, RBS)<br>VB.? = Any tense of Verb (VBD, VBG, VBN, VBP, VBZ)</blockquote><pre># Example usage of Chunking</pre><pre><strong>from nltk.corpus import state_union</strong></pre><pre># Defining the training and sample text</pre><pre><strong>train_text = state_union.raw(‘2005-GWBush.txt’)<br>sample_txt = state_union.raw(‘2006-GWBush.txt’)</strong></pre><pre># Training the tokenizer and tokenizing the sample text</pre><pre><strong>custom_tokenizer = PunktSentenceTokenizer(train_text)<br>tokenized = custom_tokenizer.tokenize(sample_txt)</strong></pre><pre># Defining function which chinks as per the regularized expression</pre><pre><strong>def process_content():<br> for i in tokenized[7:9]:<br>  words = nltk.word_tokenize(i)<br>  tagged = nltk.pos_tag(words)</strong></pre><pre><strong>  chunkgram = r’’’chunk: {&lt;RB.?&gt;*&lt;VB.?&gt;*&lt;NNP&gt;*&lt;NN&gt;?}’’’<br>  chunkparser = nltk.RegexpParser(chunkgram)<br>  chunked = chunkparser.parse(tagged)</strong></pre><pre><strong>print(chunked)</strong></pre><pre><strong>process_content()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*sZrbrAb0R6nHRSX6FJ8x4w.png" /></figure><p><strong>Chinking</strong> helps to remove words from phrases that we don’t want. The following regularized expression is used for Chinking.</p><blockquote><strong>{&lt;.*&gt;+} <br> }&lt;VB.?|IN|DT|TO&gt;+{</strong></blockquote><p>The main difference here is the ‘}{‘ vs the ‘{}’. ‘}{‘ means we are removing from the chink one or more verbs, prepositions, determiners, or the word ‘to’.</p><pre># Example usage of Chinking</pre><pre># Defining the training and sample text</pre><pre><strong>train_text = state_union.raw(‘2005-GWBush.txt’)<br>sample_txt = state_union.raw(‘2006-GWBush.txt’)</strong></pre><pre># Training the tokenizer and tokenizing the sample text</pre><pre><strong>custom_tokenizer = PunktSentenceTokenizer(train_text)<br>tokenized = custom_tokenizer.tokenize(sample_txt)</strong></pre><pre># Defining function which chinks as per the regularized expression</pre><pre><strong>def process_content():<br> for i in tokenized[0:3]:<br>  words = nltk.word_tokenize(i)<br>  tagged = nltk.pos_tag(words)<br>  </strong></pre><pre><strong>  chunkgram = r’’’chunk: {&lt;.*&gt;+} <br>  }&lt;VB.?|IN|DT|TO&gt;+{‘’’<br>  chunkparser = nltk.RegexpParser(chunkgram)<br>  chunked = chunkparser.parse(tagged)</strong></pre><pre><strong>  print(chunked)</strong></pre><pre><strong>process_content()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*EFQF_VOuj6rIxHBWu3m6yw.png" /></figure><p>From the above output, it can be observed that none of the chunks contain verbs, prepositions, determiners, or the word ‘to’.</p><p>All the basics (<strong>Word tokenizer, Sentence tokenizer, Stop words, Stemming, POS Tagging, Named entity recognition, Chunking and Chinking</strong>) have been covered and now can start working on a Natural Language Processing project.</p><p>Happy Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a72a4b8571" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/natural-language-processing-tokenizing-stop-words-stemming-a6a72a4b8571">Natural Language Processing — Tokenizing, Stop words &amp; Stemming</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning in Bioinformatics]]></title>
            <link>https://medium.datadriveninvestor.com/machine-learning-in-bioinformatics-d81b1b3eaba2?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d81b1b3eaba2</guid>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Sat, 14 Dec 2019 20:36:01 GMT</pubDate>
            <atom:updated>2019-12-22T19:38:26.165Z</atom:updated>
            <content:encoded><![CDATA[<h4>Classification of genes &amp; Performance comparison of common classifiers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKCgg6SvX8JCj17Q9ulK3Q.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/qimono-1962238/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1811955">Arek Socha</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1811955">Pixabay</a></figcaption></figure><p>Bioinformatics is a field of study that uses computation to extract knowledge from biological data. It includes the collection, storage, retrieval, manipulation and modeling of data for analysis, visualization or prediction. Here we would use machine learning to classify genes of E. Coli bacteria.</p><p>Let us understand the basics of Genetics. DNA or deoxyribonucleic acid is the hereditary material in humans and almost all other organisms. The DNA is made up of four chemical bases: Adenine(A), Guanine(G), Cytosine(C), and Thymine(T). Adenine pairs up with Thymine and Guanine pairs up with Cytosine. Each base is also attached to a sugar molecule and a phosphate molecule. A base, sugar, and phosphate together form the nucleotide.</p><p>Genes are made up of very long nucleotide sequences. Genes can be classified into 2 categories (Promoter &amp; Non-Promoter) based on the nucleotide sequence.</p><p><a href="https://www.datadriveninvestor.com/2019/03/03/editors-pick-5-machine-learning-books/">DDI Editor&#39;s Pick: 5 Machine Learning Books That Turn You from Novice to Expert | Data Driven Investor</a></p><p>It is impractical to look at the long nucleotide sequences. Hence we would be looking at the short nucleotide sequence(57 sequences) of genes of E. Coli bacteria and predict whether the gene is Promoter or Non-Promoter.</p><p>The data set ‘genes’ is of <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/molecular-biology/promoter-gene-sequences/">UIC machine learning data base</a>.</p><p>The necessary packages are imported.</p><pre># Importing the necessary packages</pre><pre><strong>import numpy as np<br>import pandas as pd</strong></pre><p>The data is read into ‘genes’.</p><pre># Import UCI molecular biology (promoter gene sequences) dataset</pre><pre><strong>url = ‘</strong><a href="https://archive.ics.uci.edu/ml/machine-learning-databases/molecular-biology/promoter-gene-sequences/promoters.data&#39;"><strong>https://archive.ics.uci.edu/ml/machine-learning-databases/molecular-biology/promoter-gene-sequences/promoters.data&#39;</strong></a><strong><br>columns = [‘Class’,’id’,’Sequence’] </strong># Naming the columns<strong><br>genes = pd.read_csv(url,names = columns) </strong># Reading the data</pre><p>Let us explore the dataset.</p><pre><strong>genes.shape</strong> # Prints the shape of ‘df’</pre><p>The ‘genes’ dataframe is of shape (106,3) which implies 106 cases and 3 columns.</p><pre><strong>genes.nunique()</strong> # Prints number of unique elements in each column</pre><p>Class :- 2, id :- 106, Sequence :- 106</p><p>There are 2 unique classes, 106 unique ids and 106 unique sequences. We know there are 106 cases. So each of the ‘id’ and ‘Sequence’ is unique.</p><pre><strong>genes[‘Class’].unique()</strong> # Prints the unique elements in ‘Class’ column</pre><p>The 2 unique classes are labelled as ‘+’ (Promoter) and ‘-’ (Non-Promoter).</p><pre><strong>genes.head()</strong> # Displays first 5 rows of ‘genes’ dataframe</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*Z3_pZGo6TZScmi2UEm178Q.png" /></figure><p>Some of the ‘Sequences’ begin with ‘\t’ special character which denotes a tab space. The preprocessing step would be to remove these special characters so that there are only bases(a,g,c,t).</p><pre># Removing ‘\t’ in ‘Sequence’ column</pre><pre><strong>for i in range(genes.shape[0]):<br> genes[‘Sequence’][i] = genes[‘Sequence’][i].replace(‘\t’, ‘’)</strong></pre><p>Let us verify this by checking the sequence and length of sequence of 5 randomly selected sequences.</p><pre><strong>for i in np.random.randint(0,106,5):<br> print(genes[‘Sequence’][i])<br> print(len(genes[‘Sequence’][i]))<br> print(‘\n’)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*1xD226FGsRxVpDzG00xICw.png" /></figure><p>‘\t’ characters have been removed and length of each sequence is 57.</p><p>Only the ‘Sequence’ column is important in classifying the gene. Let us make a dataframe of the ‘Sequence’ column.</p><pre># Initializing a dataframe ‘nucleotide_sequence’ of size (106,57)</pre><pre><strong>nucleotide_sequence = pd.DataFrame(np.random.randn(106,57))</strong></pre><pre># Storing each base of ‘Sequence’ in ‘nucleotide_sequence’</pre><pre><strong>for i in range(genes.shape[0]):<br> nucleotide_sequence.loc[i] = list(genes[‘Sequence’][i])</strong></pre><pre># Storing &#39;Class&#39; column of &#39;Sequence&#39; as a column in &#39;nucleotide_sequence&#39;</pre><pre><strong>nucleotide_sequence[&#39;Class&#39;] = genes[&#39;Class&#39;]</strong></pre><p>Let us look at the dataframe ‘nucleotide_sequence’</p><pre><strong>nucleotide_sequence.head() </strong># Displays first 5 rows of ‘nucleotide_sequence’ dataframe</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*zDLEA2FSU8rJIz5tNYiqfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*HuuVva21uX5iCCxf9jT3LA.png" /></figure><pre><strong>plt.figure(figsize=(8,8)) <br>plt.xticks(fontsize=20) <br>plt.yticks(fontsize=20) <br>plt.xlabel(&#39;Class&#39;,fontsize=20) <br>plt.ylabel(&#39;count&#39;,fontsize=20) <br>sns.countplot(nucleotide_sequence[&#39;Class&#39;])</strong> # Displays count of each element in &#39;Class&#39; column</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*8sq3AH8HMtbX9n_1SdTklA.png" /></figure><p>There are equal number of Promoters and Non-Promoters in the dataset given.</p><p>Machine learning algorithms can be applied only on numerical values. Hence we convert the string characters of ‘nucleotide_sequence’ into numerical values using ‘get_dummies’ function.</p><pre># Switch to numerical data using pd.get_dummies() function</pre><pre><strong>numerical_nucleotide = pd.get_dummies(nucleotide_sequence)</strong></pre><p>Let us print the ‘numerical_nucleotide’ dataframe.</p><pre><strong>print(numerical_nucleotide.head()) </strong># Prints first 5 rows of &#39;numerical_nucleotide&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*UFpOKB2F26xvqLN2vOy2eA.png" /></figure><p>There are 2 class columns :- ‘Class_+’ and ‘Class_-’. The class label ‘Promoter’ or ‘Non-Promoter’ can be found by just looking at one of the column (either ‘Class+’ or ‘Class-’). So one of them is dropped and the other is renamed as ‘Class’.</p><pre># Remove one of the class columns and rename the other to simply ‘Class’</pre><pre><strong>numerical_nucleotide.drop(‘Class_-’,axis = 1,inplace = True)<br>numerical_nucleotide.rename(columns = {‘Class_+’:’Class’},inplace = True)</strong></pre><p>Now let us print the ‘numerical_nucleotide’ dataframe.</p><pre><strong>print(numerical_nucleotide.head()) </strong># Prints first 5 rows of &#39;numerical_nucleotide&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*btMMCfN_fqE2avlG5ybYRA.png" /></figure><p>Below given is the snippet of code that serves the same purpose as get_dummies() function (<strong>Optional</strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/944914fa576310da2cff8636a8ec2134/href">https://medium.com/media/944914fa576310da2cff8636a8ec2134/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*9v5nxStouOv6nxgMLtgWJw.png" /></figure><p>Now that we have processed the data, the next step is train the data using machine learning classifiers.</p><p>The dataset is split into training and test sets.</p><pre># Import train_test_split</pre><pre><strong>from sklearn.model_selection import train_test_split</strong></pre><pre># X is input and y is output</pre><pre><strong>X = numerical_nucleotide.drop(‘Class’,axis = 1)<br>y = numerical_nucleotide[‘Class’]</strong></pre><pre># Split into train and test sets</pre><pre><strong>X_train,X_test,y_train,y_test = train_test_split(X,y)</strong></pre><p>The necessary classifiers and metrics are imported.</p><pre># Performance comparison of 9 classifiers</pre><pre><strong>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.neural_network import MLPClassifier<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier<br>from sklearn.naive_bayes import GaussianNB<br>from sklearn.svm import SVC<br>from sklearn.metrics import classification_report,accuracy_score<br>from sklearn import model_selection</strong></pre><p>The Cross validation scores of the classifiers are calculated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef35e63581afe9ad6e6e3a2b03bc51ad/href">https://medium.com/media/ef35e63581afe9ad6e6e3a2b03bc51ad/href</a></iframe><p>The Cross validation scores of classifiers are displayed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62149c871d30a4e4a99357f573838179/href">https://medium.com/media/62149c871d30a4e4a99357f573838179/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*_Yo59E5HboySGOmTtQAFTA.png" /></figure><blockquote>Classifier rankings based on Cross validation scores :-<br>(1 Neural Net (MLP Classifier) &amp; SVM Linear<br>(2 Naive Bayes<br>(3 AdaBoost<br>(4 SVM rbf<br>(5 K Nearest Neighbors<br>(6 Decision Tree<br>(7 Random Forest<br>(8 SVM Sigmoid</blockquote><p>Neural Net (MLP Classifier) &amp; SVM Linear have the best cross validation score of 0.9625. But it is not right to generalize the performance of classifier on new unseen data based on cross validation score. Hence we check the performance of classifier models on the test set.</p><pre><strong>for i in range(len(models)):<br> a = models[i].fit(X_train,y_train) </strong># Fitting the model<strong><br> y_predict = a.predict(X_test) </strong># Predicting using trained model<strong><br> print(accuracy_score(y_predict,y_test))<br> print(classification_report(y_predict,y_test))</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*UhBbACkfFpMNgavojQK82w.png" /><figcaption>K-Nearest Neighbors</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*W7OLx3fMQyhVgL2PumyQng.png" /><figcaption>Neural Net (MLP Classifier)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*yGFtQwFPT5z4s7q8KZRmdw.png" /><figcaption>Decision Tree</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*lVWlXBpMTBMR1PHtjPw1Hw.png" /><figcaption>Random Forest</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*o0dw9XFP2Dtd8GVWLYiBrw.png" /><figcaption>AdaBoost</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*eI8yhyL3z05L7cJ8t-gm8Q.png" /><figcaption>Naive Bayes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*R78Uue98aEv3L88GCN7E2g.png" /><figcaption>SVM Linear</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*nnZUPXDIz4EaBgG-kkWS7Q.png" /><figcaption>SVM rbf</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*7iWuHPqHiNm4FajOJkFCsw.png" /><figcaption>SVM Sigmoid</figcaption></figure><blockquote>Classifier rankings based on Test scores :-<br>(1 Neural Net (MLP Classifier), Naive Bayes &amp; SVM Linear<br>(2 K-Nearest Neighbors &amp; SVM rbf<br>(3 AdaBoost &amp; SVM Signoid<br>(4 Decision Tree<br>(5 Random Forest</blockquote><p>Neural Net (MLP Classifier), Naive Bayes &amp; SVM Linear have the highest accuracy score and f1-score.</p><p>The performance of the classifier models can be further improved by hyperparameter tuning. If you are curious, please do read <a href="https://medium.com/datadriveninvestor/hyperparameter-tuning-with-deep-learning-grid-search-8630aa45b2da">hyperparameter tuning of Neural Networks</a>.</p><p>Happy Reading!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d81b1b3eaba2" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/machine-learning-in-bioinformatics-d81b1b3eaba2">Machine Learning in Bioinformatics</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperparameter Tuning with Deep Learning Grid Search]]></title>
            <link>https://medium.datadriveninvestor.com/hyperparameter-tuning-with-deep-learning-grid-search-8630aa45b2da?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8630aa45b2da</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[grid-search]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 06:25:10 GMT</pubDate>
            <atom:updated>2020-01-02T00:24:12.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>Diabetes Prediction with Neural Network in Keras</h3><h4>Hyperparameter Tuning with GridSearchCV</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Y4sdXvV5fsusDo6zZPTcbg.jpeg" /></figure><p>This machine learning project is about Diabetes Prediction. We would be working on <a href="https://www.kaggle.com/uciml/pima-indians-diabetes-database">kaggle pima indians diabetes</a> dataset.</p><p>The necessary packages are imported.</p><pre><strong># Importing the necessary packages</strong></pre><pre>import pandas as pd<br>import numpy as np<br>import keras</pre><p>The dataset is read into ‘df’ dataframe.</p><pre><strong># Reading the file</strong></pre><pre>df = pd.read_csv(‘/kaggle/input/pima-indians-diabetes-database/diabetes.csv’)</pre><p>Let us understand the dataframe ‘df’.</p><pre>df.shape <strong># Shape of ‘df’</strong></pre><p>The size is (768,9) which suggests there are 768 cases and 9 columns.</p><pre>df.columns <strong># Prints columns of ‘df’</strong></pre><p>The columns are [‘Pregnancies’, ‘Glucose’, ‘BloodPressure’, ‘SkinThickness’, ‘Insulin’, ‘BMI’, ‘DiabetesPedigreeFunction’, ‘Age’, ‘Outcome’]</p><pre>df.describe() <strong># Displays properties of each column</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*ixmkfJ5iCWyNcDgI11pliw.png" /></figure><p>All the columns have count = 768 which suggests there are no missing values. The mean of ‘Outcome’ is 0.35 which suggests there are more ‘Outcome’ = 0 than ‘Outcome’ = 1 cases in the given dataset.</p><p>The dataframe ‘df’ is converted into numpy array ‘dataset’</p><pre>dataset = df.values</pre><p>The ‘dataset’ is split into input X and output y</p><pre>X = dataset[:,0:8]<br>y = dataset[:,8].astype(‘int’)</pre><h4>Standardization</h4><p>It can be observed that mean value of columns are very different. Hence the dataset is to be standardized so that no inappropriate weightage is given to any feature.</p><pre><strong># Standardization</strong></pre><pre>a = StandardScaler()<br>a.fit(X)<br>X_standardized = a.transform(X)</pre><p>Now let us look at mean and standard deviation of ‘X_standardized’.</p><pre>pd.DataFrame(X_standardized).describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*xABcgm-UdLm5Q_4J5m6ztw.png" /></figure><p>Mean of all columns is around 0 and Standard deviation of all columns is around 1. The data has been standardized.</p><p><a href="https://www.datadriveninvestor.com/2019/01/23/which-is-more-promising-data-science-or-software-engineering/">Which is More Promising: Data Science or Software Engineering? | Data Driven Investor</a></p><h4><strong>Tuning of Hyperparameters :- Batch Size and Epochs</strong></h4><pre><strong># Importing the necessary packages</strong></pre><pre>from sklearn.model_selection import GridSearchCV, KFold<br>from keras.models import Sequential<br>from keras.layers import Dense<br>from keras.wrappers.scikit_learn import KerasClassifier<br>from keras.optimizers import Adam</pre><p>The neural architecture and optimization algorithm are defined. The neural network consists of 1 input layer, 2 hidden layers with rectified linear unit activation function and 1 output layer with sigmoid activation function. Adams optimization is chosen as the optimization algorithm for the neural network model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*ae78I89LoFIkPrW5sQRnEg.png" /></figure><p>We run the grid search for 2 hyperparameters :- ‘batch_size’ and ‘epochs’. The cross validation technique used is K-Fold with the default value k = 3. The accuracy score is calculated.</p><pre><strong># Create the model</strong></pre><pre>model = KerasClassifier(build_fn = create_model,verbose = 0)</pre><pre><strong># Define the grid search parameters</strong></pre><pre>batch_size = [10,20,40]<br>epochs = [10,50,100]</pre><pre><strong># Make a dictionary of the grid search parameters</strong></pre><pre>param_grid = dict(batch_size = batch_size,epochs = epochs)</pre><pre><strong># Build and fit the GridSearchCV</strong></pre><pre>grid = GridSearchCV(estimator = model,param_grid = param_grid,cv = KFold(),verbose = 10)<br>grid_result = grid.fit(X_standardized,y)</pre><p>The results are summarized. The best accuracy score and the best values of hyperparameters are printed.</p><pre><strong># Summarize the results</strong></pre><pre>print(‘Best : {}, using {}’.format(grid_result.best_score_,grid_result.best_params_))<br>means = grid_result.cv_results_[‘mean_test_score’]<br>stds = grid_result.cv_results_[‘std_test_score’]<br>params = grid_result.cv_results_[‘params’]<br>for mean, stdev, param in zip(means, stds, params):<br>  print(‘{},{} with: {}’.format(mean, stdev, param))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*BOaXMYDAkXDo8nsevCRi0A.png" /></figure><p>The best accuracy score is 0.7604 for ‘batch_size’ = 40 and ‘epochs’ = 10. So we choose ‘batch_size’ = 40 and ‘epochs’ = 10 while tuning other hyperparameters.</p><h4>Tuning of Hyperparameters:- Learning rate and Drop out rate</h4><p>The learning rate plays an important role in optimization algorithm. If the learning rate is too large, the algorithm may diverge and thus can’t find the local optima. If the learning rate is too small, the algorithm may take many iterations to converge which results in high computational power and time. Thus we need an optimum value of learning rate which is small enough for the algorithm to converge and large enough to fasten the converging process. The learning rate helps with ‘Early Stopping’ which is a regularization method where the training set is trained as long as test set accuracy is increasing.</p><p>Drop out is a regularization method that reduces the complexity of the model and thus prevents overfitting the training data. By dropping an activation unit out, we mean temporarily removing it from the network, along with all its incoming and outgoing connections. Dropout rate can take values between 0 and 1. 0 implies no activation units are knocked out and 1 implies all the activation units are knocked out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b7f4aee31d629581c807837138cb96f/href">https://medium.com/media/6b7f4aee31d629581c807837138cb96f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*rNjy_dYu3k4CsteZZKqIDQ.png" /></figure><p>The best accuracy score is 0.7695 for ‘dropout_rate’ = 0.1 and ‘learning_rate’ = 0.001. So we choose ‘dropout_rate’ = 0.1 and ‘learning_rate’ = 0.001 while tuning other hyperparameters.</p><h4>Tuning of Hyperparameters:- Activation Function and Kernel Initializer</h4><p>Activation functions introduce non-linear properties to the neural network such that non-linear complex functional mappings between input and output can be established. If we do not apply the activation function, then the output would be a simple linear function of the input.</p><p>The neural network needs to start with some weights and then iteratively update them to better values. Kernel initializer decides the statistical distribution or function to be used for initializing the weights.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db8a2b0d6f2e91352d963e0d8337c5ab/href">https://medium.com/media/db8a2b0d6f2e91352d963e0d8337c5ab/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*y-IFYrRG7rsIGSYIA8tGBg.png" /></figure><p>The best accuracy score is 0.7591 for ‘activation_function’ = tanh and ‘kernel_initializer’ = uniform. So we choose ‘activation_function’ = tanh and ‘kernel_initializer’ = uniform while tuning other hyperparameters.</p><h4>Tuning of Hyperparameter :-Number of Neurons in activation layer</h4><p>The complexity of the data has to be matched with the complexity of the model. The number of neurons in activation layer decides the complexity of the model. Higher the number of neurons in activation layer, higher is the degree of non-linear complex functional mappings between input and output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99f3cf2275c6f1324c40da864d7acfc1/href">https://medium.com/media/99f3cf2275c6f1324c40da864d7acfc1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*1eT-FMSugM9hVoXH_0vvyQ.png" /></figure><p>The best accuracy score is 0.7591 for number of neurons in first layer = 16 and number of neurons in second layer = 4.</p><blockquote><strong>The optimum values of Hyperparameters are as follows :-</strong><br>Batch size = 40<br>Epochs = 10<br>Dropout rate = 0.1<br>Learning rate = 0.001<br>Activation function = tanh<br>Kernel Initializer = uniform<br>No. of neurons in layer 1 = 16<br>No. of neurons in layer 2 = 4</blockquote><h4>Training model with optimum values of Hyperparameters</h4><p>The model is trained using optimum values of hyperparameters found in previous section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6b8160c7b106288b07b1ebe8c9300bc/href">https://medium.com/media/e6b8160c7b106288b07b1ebe8c9300bc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*DqVF-Y7SxSnt6w1vFfJQUg.png" /></figure><p>We get an accuracy of 77.6% and F1 scores of 0.84 and 0.65.</p><p>The hyperparameter optimization was carried out by taking 2 hyperparameters at once. We may have missed the best values. The performance can be further improved by finding the optimum values of hyperparameters all at once given by the code snippet below. Note:- This process is computationally expensive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5535377eb42a949d92a5156907c3e0e/href">https://medium.com/media/e5535377eb42a949d92a5156907c3e0e/href</a></iframe><p>Happy Reading! Happy Learning!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8630aa45b2da" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/hyperparameter-tuning-with-deep-learning-grid-search-8630aa45b2da">Hyperparameter Tuning with Deep Learning Grid Search</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock Market Clustering with K-Means Clustering in Python]]></title>
            <link>https://medium.datadriveninvestor.com/stock-market-clustering-with-k-means-clustering-in-python-4bf6bd5bd685?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf6bd5bd685</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 00:50:02 GMT</pubDate>
            <atom:updated>2019-12-09T08:43:03.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*n_ocmMIVMsHJ9-p4K96SJQ.jpeg" /></figure><p>This machine learning project is about clustering similar companies with K-means clustering algorithm. The similarity is based on daily stock movements.</p><p>The necessary packages are imported.</p><pre><strong>from pandas_datareader import data <br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import datetime<br>import numpy as np<br>import plotly.graph_objects as go</strong></pre><p>A dictionary ‘companies_dict’ is defined where ‘key’ is company’s name and ‘value’ is company’s stock code. 28 companies are considered.</p><pre><strong>companies_dict = {<br>    &#39;Amazon&#39;:&#39;AMZN&#39;,<br>    &#39;Apple&#39;:&#39;AAPL&#39;,<br>    &#39;Walgreen&#39;:&#39;WBA&#39;,<br>    &#39;Northrop Grumman&#39;:&#39;NOC&#39;,<br>    &#39;Boeing&#39;:&#39;BA&#39;,<br>    &#39;Lockheed Martin&#39;:&#39;LMT&#39;,<br>    &#39;McDonalds&#39;:&#39;MCD&#39;,<br>    &#39;Intel&#39;:&#39;INTC&#39;,<br>    &#39;Navistar&#39;:&#39;NAV&#39;,<br>    &#39;IBM&#39;:&#39;IBM&#39;,<br>    &#39;Texas Instruments&#39;:&#39;TXN&#39;,<br>    &#39;MasterCard&#39;:&#39;MA&#39;,<br>    &#39;Microsoft&#39;:&#39;MSFT&#39;,<br>    &#39;General Electrics&#39;:&#39;GE&#39;,<br>    &#39;Symantec&#39;:&#39;SYMC&#39;,<br>    &#39;American Express&#39;:&#39;AXP&#39;,<br>    &#39;Pepsi&#39;:&#39;PEP&#39;,<br>    &#39;Coca Cola&#39;:&#39;KO&#39;,<br>    &#39;Johnson &amp; Johnson&#39;:&#39;JNJ&#39;,<br>    &#39;Toyota&#39;:&#39;TM&#39;,<br>    &#39;Honda&#39;:&#39;HMC&#39;,<br>    &#39;Mistubishi&#39;:&#39;MSBHY&#39;,<br>    &#39;Sony&#39;:&#39;SNE&#39;,<br>    &#39;Exxon&#39;:&#39;XOM&#39;,<br>    &#39;Chevron&#39;:&#39;CVX&#39;,<br>    &#39;Valero Energy&#39;:&#39;VLO&#39;,<br>    &#39;Ford&#39;:&#39;F&#39;,<br>    &#39;Bank of America&#39;:&#39;BAC&#39;}</strong></pre><p>Stock market data is extracted from yahoo finance. The time period considered is from ‘2015–01–01’ to ‘2017–12–31’. The stock movement of companies would be compared based on these 6 parameters :- ‘High’, ‘Low’, ‘Open’, ‘Close’, ‘Volume’, ‘Adj Close’.</p><p>‘High’ :- Highest price during the day.<br>‘Low’ :- Lowest price during the day.<br>‘Open’ :- Opening price of the day.<br>‘Close’ :- Closing price of the day.<br>‘Volume’ :- Total number of shares of stock traded during the day.<br>‘Adj Close’ :- The closing price is amended to account for any corporate actions to give the ‘Adjusted closing’ price.</p><pre><strong>data_source = ‘yahoo’</strong> # Source of data is yahoo finance.<br><strong>start_date = ‘2015–01–01’ <br>end_date = ‘2017–12–31’<br>df = data.DataReader(list(companies_dict.values()),<br> data_source,start_date,end_date)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moc1rREvkrTU_HzUtJcMFw.png" /></figure><p>Numpy arrays are more convenient. So ‘stock_open’ and ‘stock_close’ are defined as follows :-</p><pre><strong>stock_open = np.array(df[‘Open’]).T </strong># stock_open is numpy array of transpose of df[&#39;Open&#39;]<strong><br>stock_close = np.array(df[‘Close’]).T </strong># stock_close is numpy array of transpose of df[&#39;Close&#39;]</pre><p>‘movement’ is defined as difference of opening and closing prices of a particular day. Positive movement suggests to go long on stock(buy) and negative movement suggests to short the stock(sell).</p><pre><strong>movements = stock_close — stock_open</strong></pre><p>‘sum_of_movement’ of a company is defined as sum of differences of closing and opening prices of all days.</p><pre><strong>sum_of_movement = np.sum(movements,1)</strong></pre><p>The company and its ‘sum_of_movement’ is printed.</p><pre><strong>for i in range(len(companies)):<br> print(‘company:{}, Change:{}’.format(df[‘High’].columns[i],sum_of_movement[i]))</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*l6r1iAo5IZEopgPcVzYX4w.png" /></figure><p>‘AAPL’, ‘NOC’, ‘BA’, ‘LMT’, ‘MCD’, ‘INTC’, ‘IBM’, ‘TXN’, ‘MA’, ‘MSFT’, ‘GE’, ‘SYMC’, ‘AXP’, ‘PEP’, ‘KO’, ‘JNJ’, ‘MSBHY’, ‘XOM’, ‘CVX’, and ‘VLO’ have positive ‘sum_of_movement’. Hence it is advisable to go long(buy) on these stocks.</p><p>‘AMZN’ ,’WBA’, ‘NAV’, ‘TM’, ‘HMC’, ‘SNE’, ‘F’ and ‘BAC’ have negative ‘sum_of_movement’. Hence it is advisable to short(sell) the stocks.</p><p><strong>VISUALIZING THE DATA (Can skip this section. Just basic plots and their interpretations)</strong></p><p>The variation of opening prices of 2 companies(Amazon and Apple) have been plotted below.</p><pre><strong>plt.figure(figsize = (20,10)) <br>plt.subplot(1,2,1) <br>plt.title(‘Company:Amazon’,fontsize = 20)<br>plt.xticks(fontsize = 10)<br>plt.yticks(fontsize = 20)<br>plt.xlabel(‘Date’,fontsize = 15)<br>plt.ylabel(‘Opening price’,fontsize = 15)<br>plt.plot(df[‘Open’][‘AMZN’])<br>plt.subplot(1,2,2) <br>plt.title(‘Company:Apple’,fontsize = 20)<br>plt.xticks(fontsize = 10)<br>plt.yticks(fontsize = 20)<br>plt.xlabel(‘Date’,fontsize = 15)<br>plt.ylabel(‘Opening price’,fontsize = 15)<br>plt.plot(df[‘Open’][‘AAPL’])</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zkxaLbUEWsROVrHGbvHz1w.png" /></figure><p>Amazon’s opening price has increased from 200 to 1200 while Apple’s opening price has increased from 110 to 180. Also Amazon has relatively better steady increase. Thus Amazon has better growth than Apple in the given time period.</p><p><a href="https://www.datadriveninvestor.com/2019/02/21/best-coding-languages-to-learn-in-2019/">Best Coding Languages to Learn in 2019 | Data Driven Investor</a></p><p>Let us plot the opening and closing prices of Amazon in the time period from ‘2015–01–02’ to ‘2015–01–23’.</p><pre><strong>plt.figure(figsize = (20,10))</strong> # Adjusting figure size<br><strong>plt.title(‘Company:Amazon’,fontsize = 20)</strong><br><strong>plt.xticks(fontsize = 10)<br>plt.yticks(fontsize = 20)<br>plt.xlabel(‘Date’,fontsize = 20)<br>plt.ylabel(‘Price’,fontsize = 20)<br>plt.plot(df.iloc[0:30][‘Open’][‘AMZN’],label = ‘Open’)</strong> # Opening prices of first 30 days are plotted against date<br><strong>plt.plot(df.iloc[0:30][‘Close’][‘AMZN’],label = ‘Close’)</strong> # Closing prices of first 30 days are plotted against date<br><strong>plt.legend(loc=’upper left’, frameon=False,framealpha=1,prop={‘size’: 22})</strong> # Properties of legend box</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omEGRXF7AGQE2rccWVaCng.png" /></figure><p>There is an overall increase in ‘Open’ and ‘Close’ prices over the 30 day time period which shows the company in a positive light.</p><p>‘Movement’ as defined earlier is difference of closing and opening prices of a particular day. The variation of ‘movement’ of amazon in the time period from 2015–01–02 to 2015–02–13 is plotted below.</p><pre><strong>plt.figure(figsize = (20,8)) <br>plt.title(&#39;Company:Amazon&#39;,fontsize = 20)<br>plt.xticks(fontsize = 18)<br>plt.yticks(fontsize = 20)<br>plt.xlabel(&#39;Date&#39;,fontsize = 20)<br>plt.ylabel(&#39;Movement&#39;,fontsize = 20)<br>plt.plot(movements[0][0:30])</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EJH3DkqcSr3KgqP5-Nojg.png" /></figure><p>A positive ‘movement’ is desirable which suggests the price has increased during the day.</p><p>Another important parameter is ‘Volume’. The ‘Volume’ of stocks traded in the time period from ‘2015–01–02’ to ‘2017–12–31’ has been plotted below.</p><pre><strong>plt.figure(figsize = (20,10)) <br>plt.title(‘Company:Amazon’,fontsize = 20)<br>plt.xticks(fontsize = 18)<br>plt.yticks(fontsize = 20)<br>plt.xlabel(‘Date’,fontsize = 20)<br>plt.ylabel(‘Volume’,fontsize = 20)<br>plt.plot(df[‘Volume’][‘AMZN’],label = ‘Open’)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDIYWQNNw8znyiv5Ax7-tw.png" /></figure><p>The peaks suggest there are high volumes of stocks traded on certain days. This may be due to restructuring of company’s management, change of ownership, yearly announcements, new ventures and other factors which affect the image of company in the minds of market participants.</p><p>The candlestick chart for the first 60 days of Amazon has been plotted below.</p><pre><strong>fig = go.Figure(data=[go.Candlestick(x=df.index,<br> open=df.iloc[0:60][‘Open’][‘AMZN’],<br> high=df.iloc[0:60][‘High’][‘AMZN’],<br> low=df.iloc[0:60][‘Low’][‘AMZN’],<br> close=df.iloc[0:60][‘Close’][‘AMZN’])])<br>fig.show()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQVq5kLGyrDKm7MUfFFirw.png" /></figure><p>Candlestick pattern is an important tool of technical analysis of stocks to predict particular market movements. The candlestick patterns will be discussed in subsequent articles.</p><h4><strong>NEED FOR NORMALIZATION</strong></h4><p>Let us plot the variation of ‘movement’ of Amazon and Apple.</p><pre><strong>plt.figure(figsize = (20,8)) <br>ax1 = plt.subplot(1,2,1)<br>plt.title(‘Company:Amazon’,fontsize = 20)<br>plt.xticks(fontsize = 18)<br>plt.yticks(fontsize = 20)<br>plt.xlabel(‘Date’,fontsize = 20)<br>plt.ylabel(‘Movement’,fontsize = 20)<br>plt.plot(movements[0]) <br>plt.subplot(1,2,2,sharey = ax1)<br>plt.title(‘Company:Apple’,fontsize = 20)<br>plt.xticks(fontsize = 18)<br>plt.yticks(fontsize = 20)<br>plt.xlabel(‘Date’,fontsize = 20)<br>plt.ylabel(‘Movement’,fontsize = 20)<br>plt.plot(movements[1])</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGyYnbJZUtRFJYPu-e4Phw.png" /></figure><p>Stock prices of Amazon and Apple have different scales. Thus x units of change in stock price of Amazon is not the same as x units of change in stock price of Apple. Some companies are worth a lot more than other companies. Hence the data has to be normalized.</p><p>The goal of Normalization is to change the value of numeric columns in the dataset to a common scale without distorting differences in the range of values. It is required only when features have different ranges like in the present scenario.</p><p>‘norm_movements’ is defined as normalized version of ‘movements’. The Normalizer() rescales each row of ‘movements’ independently.</p><pre><strong>normalizer = Normalizer() </strong># Define a Normalizer<strong><br>norm_movements = normalizer.fit_transform(movements) </strong># Fit and transform</pre><p>The minimum, maximum and mean value of ‘norm_movements’ is printed.</p><pre><strong>print(norm_movements.min())<br>print(norm_movements.max())<br>print(norm_movements.mean())</strong></pre><p>The minimum, maximum and mean value of ‘norm_movements’ are -0.259, 0.26 and 0.001. All values are in range (-1,1) and mean is close to 0.</p><p>Now let us plot the variation of ‘norm_movements’ of Amazon and Apple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOQ3LGgqtdpq4ElY12SGwA.png" /></figure><p>The normalized movements of Amazon and Apple are in similar range.</p><h4><strong>CREATING A PIPELINE</strong></h4><p>Now we create a pipeline that normalizes the data and then applies K-Means clustering algorithm to cluster companies with similar daily stock movements.</p><pre># Import the necessary packages<br><strong>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import Normalizer<br>from sklearn.cluster import KMeans</strong></pre><pre># Define a normalizer<br><strong>normalizer = Normalizer()</strong></pre><pre># Create Kmeans model<br><strong>kmeans = KMeans(n_clusters = 10,max_iter = 1000)</strong></pre><pre># Make a pipeline chaining normalizer and kmeans<br><strong>pipeline = make_pipeline(normalizer,kmeans)</strong></pre><pre># Fit pipeline to daily stock movements<br><strong>pipeline.fit(movements)</strong></pre><pre><strong>labels = pipeline.predict(movements)</strong></pre><p>The companies and their cluster number is printed.</p><pre><strong>df1 = pd.DataFrame({‘labels’:labels,’companies’:list(companies)}).sort_values(by=[‘labels’],axis = 0)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*s72BQfUOsySx7_jwVPdmag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*Nl9O3c1fF9lxi7QV7ZWSMw.png" /></figure><p>Soft drink manufacturers like Pepsi and Coca Cola, oil corporations like Chevron and Exxon, automotive manufacturers like Ford, Toyota, Honda, technology companies like Amazon, Apple, Microsoft, Intel and defence industries like Lockheed Martin, Boeing, Northrop Grumman are clustered together.</p><p>If the pipeline is run again, we get different cluster formation results as the beginning step of initialization of centroids is random in K-Means clustering.</p><p><strong>kmeans.inertia_ </strong>gives the cost function score of K-Means clustering. As number of clusters go up, the inertia score would go down.</p><h4><strong>PCA REDUCTION</strong></h4><p>The high dimensional data ‘norm_movement’ with 755 features(755 days) is reduced to a 2 dimensional data with 2 features(2days) and then k-means clustering is applied. This way we can plot the clustered companies on a two dimensional graph.</p><p>Given below is the pipeline which normalizes, reduces (PCA reduction) and applies K-Means clustering algorithm.</p><pre># Define a normalizer<strong><br>normalizer = Normalizer()</strong></pre><pre># Reduce the data<strong><br>reduced_data = PCA(n_components = 2)</strong></pre><pre># Create Kmeans model<strong><br>kmeans = KMeans(n_clusters = 10,max_iter = 1000)</strong></pre><pre># Make a pipeline chaining normalizer, pca and kmeans<strong><br>pipeline = make_pipeline(normalizer,reduced_data,kmeans)</strong></pre><pre># Fit pipeline to daily stock movements<strong><br>pipeline.fit(movements)</strong></pre><pre># Prediction<strong><br>labels = pipeline.predict(movements)</strong></pre><pre># Create dataframe to store companies and predicted labels<br><strong>df2 = pd.DataFrame({&#39;labels&#39;:labels,&#39;companies&#39;:list(companies_dict.keys())}).sort_values(by=[&#39;labels&#39;],axis = 0)</strong></pre><p>Now let&#39;s look at the clustered companies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*SUcyJzNFai7S_39ZczFglg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*M341exLs6qULzC0PRWXouw.png" /></figure><p>The cluster formation with PCA reduction is different from the cluster formation without PCA reduction. The cons of PCA reduction is some details are lost. The results are not very accurate. The pros of PCA reduction is less computational power and easy visualization.</p><p>The decision boundary is plotted below.</p><pre><strong>from sklearn.decomposition import PCA</strong></pre><pre># Reduce the dat<strong>a<br>reduced_data = PCA(n_components = 2).fit_transform(norm_movements)</strong></pre><pre># Define step size of mesh<strong><br>h = 0.01</strong></pre><pre># Plot the decision boundary<strong><br>x_min,x_max = reduced_data[:,0].min()-1, reduced_data[:,0].max() + 1<br>y_min,y_max = reduced_data[:,1].min()-1, reduced_data[:,1].max() + 1<br>xx,yy = np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))</strong></pre><pre># Obtain labels for each point in the mesh using our trained model<strong><br>Z = kmeans.predict(np.c_[xx.ravel(),yy.ravel()])</strong></pre><pre># Put the result into a color plot<strong><br>Z = Z.reshape(xx.shape)</strong></pre><pre># Define color plot<strong><br>cmap = plt.cm.Paired</strong></pre><pre># Plotting figure<strong><br>plt.clf()<br>plt.figure(figsize=(10,10))<br>plt.imshow(Z,interpolation = ‘nearest’,extent=(xx.min(),xx.max(),yy.min(),yy.max()),cmap = cmap,aspect = ‘auto’,origin = ‘lower’)</strong></pre><pre><strong>plt.plot(reduced_data[:,0],reduced_data[:,1],’k.’,markersize = 5)</strong></pre><pre># Plot the centroid of each cluster as a white X<strong><br>centroids = kmeans.cluster_centers_<br>plt.scatter(centroids[:,0],centroids[:,1],marker = ‘x’,s = 169,linewidths = 3,color = ‘w’,zorder = 10)</strong></pre><pre><strong>plt.title(‘K-Means clustering on stock market movements (PCA-Reduced data)’)<br>plt.xlim(x_min,x_max)<br>plt.ylim(y_min,y_max)<br>plt.show()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*QezBre6NBl_HmK3jKLcvJg.png" /><figcaption>Each black point represents a company. Each white cross represents the centroid of respective cluster.</figcaption></figure><p>Happy Reading!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf6bd5bd685" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/stock-market-clustering-with-k-means-clustering-in-python-4bf6bd5bd685">Stock Market Clustering with K-Means Clustering in Python</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Credit Card Fraud Detection using Local Outlier Factor and Isolation Forest in Python]]></title>
            <link>https://medium.datadriveninvestor.com/credit-card-fraud-detection-using-local-outlier-factor-and-isolation-forest-in-python-56edd0a44af5?source=rss-39a45d0a8c0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/56edd0a44af5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[outliers]]></category>
            <dc:creator><![CDATA[Joel Franklin Stalin Vijayakumar]]></dc:creator>
            <pubDate>Mon, 02 Dec 2019 12:38:15 GMT</pubDate>
            <atom:updated>2020-01-02T00:26:15.312Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning in Credit Card Fraud Detection</h3><h4>Anomaly detection with Local outlier factor and Isolation forest algorithms</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUQfPAGN2oHAVLBWFsAAHA.jpeg" /></figure><p>This machine learning project is about detecting fraudulent credit card transactions. The data set ‘creditcard.csv’ can be downloaded from <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud">kaggle credit card fraud detection</a>.</p><p>The necessary packages are imported.</p><pre><strong>import numpy as np<br>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from sklearn.metrics import classification_report, accuracy_score<br>from sklearn.ensemble import IsolationForest<br>from sklearn.neighbors import LocalOutlierFactor</strong></pre><h4><strong>READING THE DATA</strong></h4><p>The data is loaded into ‘df’ dataframe.</p><pre><strong>df = pd.read_csv(‘creditcard.csv’)</strong></pre><h4><strong>VISUALIZING AND UNDERSTANDING THE DATA</strong></h4><p>Understanding the data is important as we get an intuitive feeling for the data which helps to identify the necessary preprocessing steps.</p><pre><strong>df.shape</strong> # Prints the shape of ‘df’</pre><p>The ‘df’ data frame is of shape (284807,31) which implies 284807 cases and 31 columns.</p><p>This is a very large data frame. It is computationally expensive. Hence the data frame is downsampled to one-tenth of previous size by dropping rows. <strong>Though training the model with large data samples gives better results, it is at the cost of computational power and time</strong>.</p><pre><strong>df = df.sample(frac=0.1)</strong> # Size of data frame is reduced</pre><p>Now data frame ‘df’ is of shape (24831,31)</p><pre><strong>df.columns</strong> # Prints columns of data frame ‘df’</pre><p>The columns have [‘Time’, ‘V1’, ‘V2’, ‘V3’, ‘V4’, ‘V5’, ‘V6’, ‘V7’, ‘V8’, ‘V9’, ‘V10’,<br> ‘V11’, ‘V12’, ‘V13’, ‘V14’, ‘V15’, ‘V16’, ‘V17’, ‘V18’, ‘V19’, ‘V20’,<br> ‘V21’, ‘V22’, ‘V23’, ‘V24’, ‘V25’, ‘V26’, ‘V27’, ‘V28’, ‘Amount’,<br> ‘Class’].</p><p>‘Time’ and ‘Amount’ denote time and amount of transaction respectively. ‘Class’ denotes whether transaction is fraudulent or not. ‘V1’ to ‘V28’ are reduced features of transaction details which can’t be disclosed.</p><pre><strong>df.nunique()</strong> # Prints total number of unique elements in each column</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*Ea3x57Oo0DUr88l51mBprA.png" /><figcaption>All columns could not be displayed due to screen size constraint.</figcaption></figure><p>The ‘class’ column is a categorical variable which has 2 unique elements :- 0 and 1. 0 denotes non-fraudulent transaction and 1 denotes fraudulent transaction.</p><pre><strong>df.describe()</strong> # Displays details of each column</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*9saeN6vPPkXAGEC6pEvsiQ.png" /><figcaption>All columns could not be displayed due to screen size constraint</figcaption></figure><p>The count of each column is 28481 which suggests <strong>there are no missing values</strong>.</p><p>The mean value of ‘Class’ column is 0.00197 which suggests there are more cases of ‘Class’ = 0 ( non-fraudulent transactions).</p><pre><strong>df[df[‘Class’] == 1][‘Class’].count()</strong> # Prints total number of fraudulent transactions</pre><p>0.19 percent (56 of 28481) are fraudulent transactions which suggests <strong>this is an Anomaly Detection problem</strong>.</p><p>Minimum value of ‘Time’ and ‘Amount’ is positive which suggests <strong>there are no negative values in ‘Time’ and ‘Amount’</strong>.</p><pre><strong>plt.figure(figsize=(12,8))</strong><br><strong>sns.heatmap(df.corr())</strong> # Heatmap of correlation between columns of ‘df’.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*5mv8z0nlOAORFMhauC4yvg.png" /></figure><p>‘Class’ is less correlated with ‘Amount’ and ‘Time’ which suggests it is hard to predict whether transaction is fraudulent or not from ‘Amount’ and ‘Time’ details of transaction.</p><p>‘Class’ is negatively correlated with ‘V3’, ‘V7’, ‘V10’, ‘V12’, ‘V14’, ‘V17’ and positively correlated with ‘V2’, ‘V4’, ‘V11’. The other correlations are relatively small.</p><p>There are no significant correlations between the reduced features (‘V1’ to V’28&#39;). Therefore <strong>we don’t drop any of the columns as they are fairly unrelated to each other</strong>.</p><blockquote>Summary :- Since there are no missing values, no columns to be dropped and no incorrect data, there are no preprocessing steps required and we proceed to training the model.</blockquote><h4><strong>TRAINING THE MODEL</strong></h4><p>The data set has been preprocessed and is ready to be trained. A comparison is made between 2 models :- Linear Outlier Factor &amp; Isolation Forest.</p><p>The local outlier factor is an unsupervised outlier detection method. It calculates the anomaly score of each sample. It measures the local deviation of density of a given sample with respect to its neighbors. The anomaly score depends on how isolated the sample is with respect to surrounding neighborhood.</p><p>The Isolation forest is an unsupervised algorithm for anomaly detection that works on principle of isolating anomalies. Instead of trying to build a model of normal instances, it explicitly isolates anomalous points in the dataset. It is a very fast algorithm with a low memory demand.</p><p>The outlier fraction is to be calculated.</p><pre><strong>fraud = df[df[‘Class’] == 1]</strong> # Number of fraudulent transactions<br><strong>valid = df[df[‘Class’] == 0]</strong> # Number of valid transactions<br><strong>outlier_fraction = len(fraud)/float(len(valid))</strong></pre><p>The outlier fraction is 0.00197</p><p><strong>Input and Output</strong></p><pre><strong>X = df.drop(‘Class’,axis = 1) </strong># X is input<br><strong>y = df[‘Class’]</strong> # y is output</pre><p><strong>Performance of Local Outlier Factor model</strong></p><pre><strong>a = LocalOutlierFactor(n_neighbors = 20,contamination = outlier_fraction)</strong><br><strong>y_prediction1 = a.fit_predict(X)</strong> # Fitting the model.<br><strong>y_prediction1[y_prediction1 == 1] = 0</strong> # Valid transactions are labelled as 0.<br><strong>y_prediction1[y_prediction1 == -1] = 1</strong> # Fraudulent transactions are labelled as 1.<br><strong>errors1 = (y_prediction1 != y).sum()</strong> # Total number of errors is calculated.<br><strong>print(errors1)<br>print(accuracy_score(y_prediction1,y))<br>print(classification_report(y_prediction1,y))</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*gDMWyZpusvAGHIK6fOSG9A.png" /></figure><p>Total number of errors = 107. Accuracy = 99.62%. Accuracy is not a good metric for anomaly detection. It is important to look at precision, recall and f1-score. The precision=0.02, recall=0.02 and f1-score=0.92 are very low. This suggests there is 2% chance of actually predicting a fraudulent transaction and there is 2% chance for a predicted fraudulent transaction to be actually true.</p><p><strong>Performance of Isolation Forest</strong></p><pre><strong>b = IsolationForest(max_samples = len(X),contamination = outlier_fraction).fit(X)</strong> # Fitting the model.<br><strong>y_prediction2 = b.predict(X)</strong> # Prediction using trained model.<br><strong>y_prediction2[y_prediction2 == 1] = 0</strong> # Valid transactions are labelled as 0.<br><strong>y_prediction2[y_prediction2 == -1] = 1</strong> # Fraudulent transactions are labelled as 1.<br><strong>errors2 = (y_prediction2 != y).sum()</strong> # Total number of errors is calculated.<br><strong>print(errors2)<br>print(accuracy_score(y_prediction2,y))<br>print(classification_report(y_prediction2,y))</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*9h1Q0iDnO5Qv5xITESyQoA.png" /></figure><p>Total number of errors = 77. Accuracy = 99.73%. Precision = 0.3, Recall = 0.29 and f1-score = 0.29 are better than that of previous Local outlier factor model.</p><p>Isolation forest is a better anomaly detection algorithm than Local outlier factor for the given data set.</p><p>Happy Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56edd0a44af5" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/credit-card-fraud-detection-using-local-outlier-factor-and-isolation-forest-in-python-56edd0a44af5">Credit Card Fraud Detection using Local Outlier Factor and Isolation Forest in Python</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>