<?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 Kamal khumar on Medium]]></title>
        <description><![CDATA[Stories by Kamal khumar on Medium]]></description>
        <link>https://medium.com/@kamalkhumar22?source=rss-3b5d58dc183f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ji4ClKasbDs5ENTzl06ATg.jpeg</url>
            <title>Stories by Kamal khumar on Medium</title>
            <link>https://medium.com/@kamalkhumar22?source=rss-3b5d58dc183f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:59:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kamalkhumar22/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[Easy way to handle multiple machine learning pipelines]]></title>
            <link>https://faun.pub/easy-way-to-handle-multiple-machine-learning-pipelines-15c8ac1e9a94?source=rss-3b5d58dc183f------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c8ac1e9a94</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[rfe]]></category>
            <category><![CDATA[atom]]></category>
            <dc:creator><![CDATA[Kamal khumar]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 07:25:38 GMT</pubDate>
            <atom:updated>2021-06-25T13:03:28.933Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will explain the RFE, Sampling and ATOM module for processing multiple pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wZPrb94d8oM7Nwsx" /><figcaption>Photo by <a href="https://unsplash.com/@franki?utm_source=medium&amp;utm_medium=referral">Franki Chamaki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What is RFE and how to use it!</h4><p><strong>Recursive Feature Elimination</strong>, or RFE for short, is a popular feature selection algorithm.</p><p>RFE is popular because it is easy to configure and use and because it is effective at selecting those features (columns) in a training dataset that are more or most relevant in predicting the target variable.</p><p>There are two important configuration options when using RFE: the choice in the number of features to select and the choice of the algorithm used to help choose features. Both of these hyperparameters can be explored, although the performance of the method is not strongly dependent on these hyperparameters being configured well(Source: <a href="https://machinelearningmastery.com/rfe-feature-selection-in-python/">machinelearningmastery</a>).</p><pre>from sklearn.feature_selection import RFE <br>from sklearn.svm import SVC</pre><p>We can import RFE from <strong>sklearn.feature_selection</strong> module and here we are using the <strong>Support Vector Classifier</strong> algorithm as the estimator.</p><p>The dataset has 5 features excluding the target feature from which we are going to select 3 more relevant ones.</p><pre>estimator = SVC(kernel = &quot;linear&quot;)<br>selector = RFE(estimator, n_features_to_select = 3, step = 1)<br>selector = selector.fit(X, y)</pre><p>Here, <strong>n_features_to_select </strong>is the parameter used to select the no.of features.</p><pre>print(selector.support_)<br>print(selector.ranking_)</pre><p>These statements will return the selected features. And the output is,</p><pre>array([ True, False,  True, False,  True])<br>array([1, 2, 1, 3, 1])</pre><p>We can get the result both in boolean format and based on ranking.</p><h4>Sampling and its types</h4><p>We don’t get the perfect balanced data every time, sometimes we may encounter imbalanced data and here are the techniques to handle the imbalanced data.</p><p><strong>Oversampling </strong>— Duplicating the samples from the minority class</p><p><strong>Undersampling</strong> — Deleting the samples from the majority class.</p><p>In other words, Both oversampling and undersampling involve introducing a bias to select more samples from one class than from another, to compensate for an imbalance that is either already present in the data, or likely to develop if a purely random sample were taken (Source: <a href="https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis">Wikipedia</a>).</p><p>Let’s jump on to the code</p><pre>from collections import Counter<br>from imblearn.over_sampling import RandomOverSampler<br>from imblearn.under_sampling import RandomUnderSampler</pre><p>Imbalance-learn(imblearn) is a readily available python package with which we are going to balance the dataset.</p><pre>print(Counter(y))</pre><pre>Counter({1:1000 , 0: 100})</pre><p>Initially, the ratio of the data is 1:10, we are going to try oversampling the data.</p><pre><em># define oversampling strategy</em><br>oversample = RandomOverSampler(sampling_strategy = &#39;minority&#39;)<br><br><em># fit and apply the transform</em><br>X_over, y_over = oversample.fit_resample(X, y)<br><br><em># summarize class distribution</em><br>print(Counter(y_over))</pre><p>After oversampling the minority class the result is,</p><pre>Counter({0: 1000, 1: 1000})</pre><p>Now, let’s try undersampling</p><pre><em># define oversampling strategy</em><br>undersample = RandomUnderSampler(sampling_strategy = &#39;majority&#39;)<br><br><em># fit and apply the transform</em><br>X_under, y_under = undersample.fit_resample(X, y)<br><br><em># summarize class distribution</em><br>print(Counter(y_under))</pre><p>The result of undersampling the majority class is</p><pre>Counter({0: 100, 1: 100})</pre><p>An additional point to note is that we can sample a part of the data instead of the whole. We can do that by passing a float value to the <strong>sampling_strategy </strong>parameter.</p><pre><em># define oversampling strategy</em><br>undersample = RandomUnderSampler(sampling_strategy = 0.7)<br><br><em>#A floating point value can be specified to indicate the ratio of majority class to be under sampled.</em><br><br><br><em># fit and apply the transform</em><br>X_size, y_size = undersample.fit_resample(X, y)<br><br><em># summarize class distribution</em><br>print(Counter(y_size))</pre><p>Here only 70% of the majority class data will be undersampled and the output will be like,</p><pre>Counter({1: 300, 0: 100})</pre><p><strong>Let’s start with the ATOM</strong></p><pre>pip install -U atom-ml</pre><p>Call the <strong>ATOMClassifier</strong> function from the atom class to get started</p><pre>from atom import ATOMClassifier<br><br>atom = ATOMClassifier(X, y, test_size = 0.2, verbose = 2)</pre><p>The output is,</p><pre>&lt;&lt; ================== ATOM ================== &gt;&gt;<br>Algorithm task: binary classification.<br><br>Dataset stats ====================== &gt;&gt;<br>Shape: (569, 6)<br>Scaled: False<br>Outlier values: 27 (1.0%)<br>---------------------------------------<br>Train set size: 456<br>Test set size: 113<br>---------------------------------------<br>|    | dataset   | train     | test     |<br>|---:|:----------|:----------|:---------|<br>|  0 | 212 (1.0) | 166 (1.0) | 46 (1.0) |<br>|  1 | 357 (1.7) | 290 (1.7) | 67 (1.5) |</pre><p>The next step is feature selection and training the model. We are going to select 4 features from the dataset and train the model with Random Forest.</p><pre>atom.feature_selection(&quot;RFE&quot;, solver = &quot;RF&quot;, n_features = 4)</pre><pre>atom.run(models =&quot;RF&quot;, metric = &quot;balanced_accuracy&quot;)</pre><p>The output for this is,</p><pre>Fitting FeatureSelector...</pre><pre>Performing feature selection ...<br> --&gt; The RFE selected 4 features from the dataset.<br>   &gt;&gt;&gt; Dropping feature mean_smoothness (rank 2).</pre><pre>Training ===================================== &gt;&gt;<br>Models: RF<br>Metric: balanced_accuracy</pre><pre>Results for Random Forest:         <br>Fit ---------------------------------------------<br>Train evaluation --&gt; balanced_accuracy: 1.0<br>Test evaluation --&gt; balanced_accuracy: 0.8981<br>Time elapsed: 0.251s<br>-------------------------------------------------<br>Total time: 0.251s<br><br><br>Final results ========================= &gt;&gt;<br>Duration: 0.252s<br>------------------------------------------<br>Random Forest --&gt; balanced_accuracy: 0.8981</pre><p><strong>atom.branch</strong> will show use the current branch we are in and its pipelines</p><pre>Branch: master<br> --&gt; Pipeline: <br>   &gt;&gt;&gt; FeatureSelector<br>     --&gt; strategy: RFE<br>     --&gt; solver: RandomForestClassifier(n_jobs=1)<br>     --&gt; n_features: 4<br>     --&gt; max_frac_repeated: 1.0<br>     --&gt; max_correlation: 1.0<br>     --&gt; kwargs: {}<br> --&gt; Models: RF</pre><p>Now, let’s create a new branch called oversample, oversample the dataset and train the model.</p><pre><em># Creating a new branch</em><br>atom.branch = &quot;oversample&quot;</pre><pre><em># Balancing the dataset by over sampling</em><br>atom.balance(strategy = &quot;randomoversampler&quot;)</pre><pre># <em>Training the model</em><br>atom.run(models = &quot;RF_os&quot;, metric = &quot;balanced_accuracy&quot;)</pre><p><em>_os </em>is the tag added to the algorithm to differentiate it from others<em>. </em>The result is,</p><pre>New branch oversample successfully created!</pre><pre>Oversampling with RandomOverSampler...<br> --&gt; Adding 124 samples to class: 0.</pre><pre>Training ===================================== &gt;&gt;<br>Models: RF_os<br>Metric: balanced_accuracy</pre><pre>Results for Random Forest:         <br>Fit ---------------------------------------------<br>Train evaluation --&gt; balanced_accuracy: 1.0<br>Test evaluation --&gt; balanced_accuracy: 0.8832<br>Time elapsed: 0.269s<br>-------------------------------------------------<br>Total time: 0.269s<br><br><br>Final results ========================= &gt;&gt;<br>Duration: 0.270s<br>------------------------------------------<br>Random Forest --&gt; balanced_accuracy: 0.8832</pre><p>Now, let’s check this branch details using <strong>atom.branch</strong>,</p><pre>Branch: oversample<br> --&gt; Pipeline: <br>   &gt;&gt;&gt; FeatureSelector<br>     --&gt; strategy: RFE<br>     --&gt; solver: RandomForestClassifier(n_jobs=1)<br>     --&gt; n_features: 4<br>     --&gt; max_frac_repeated: 1.0<br>     --&gt; max_correlation: 1.0<br>     --&gt; kwargs: {}<br>   &gt;&gt;&gt; Balancer<br>     --&gt; strategy: randomoversampler<br>     --&gt; kwargs: {}<br> --&gt; Models: RF_os</pre><p>Similarly, we can create another branch called undersample, undersample the dataset and train the model. The branch details will be like,</p><pre>Branch: undersample<br> --&gt; Pipeline: <br>   &gt;&gt;&gt; FeatureSelector<br>     --&gt; strategy: RFE<br>     --&gt; solver: RandomForestClassifier(n_jobs=1)<br>     --&gt; n_features: 4<br>     --&gt; max_frac_repeated: 1.0<br>     --&gt; max_correlation: 1.0<br>     --&gt; kwargs: {}<br>   &gt;&gt;&gt; Balancer<br>     --&gt; strategy: randomundersampler<br>     --&gt; kwargs: {}<br> --&gt; Models: RF_us</pre><p>The <strong>scoring</strong> function generates the scores of all the pipelines with which we can identify the one which suites our needs.</p><pre>atom.scoring()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0kTt4qAt42pMlnzzPP9cg.png" /></figure><p>And we can also get the PRC graph,</p><pre>atom.plot_prc()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*cjzYtb9ndTBzliH0P8GgCw.png" /></figure><p>You can check the full code <a href="https://www.kaggle.com/kamalkhumar/handling-multiple-pipelines-using-atom">here</a>.</p><p>Thanks for reading!</p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c8ac1e9a94" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/easy-way-to-handle-multiple-machine-learning-pipelines-15c8ac1e9a94">Easy way to handle multiple machine learning pipelines</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiclass Classification with Image Augmentation]]></title>
            <link>https://kamalkhumar22.medium.com/multiclass-classification-with-image-augmentation-834c16122a3b?source=rss-3b5d58dc183f------2</link>
            <guid isPermaLink="false">https://medium.com/p/834c16122a3b</guid>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[multiclass-classification]]></category>
            <category><![CDATA[image-augmentation]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Kamal khumar]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 10:07:32 GMT</pubDate>
            <atom:updated>2020-10-11T12:45:51.104Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article explains the basics of multiclass image classification and how to perform image augmentation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkhQmX6qEs17A4Rca54pIg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@marcus_wallis">Marcus Wallis</a><strong> </strong>on <a href="https://unsplash.com/s/photos/rock-paper-scissors">Unsplash</a></figcaption></figure><p>What is Image Augmentation?</p><p>Image Augmentation, a solution to the <strong>problem of limited data</strong>. Image augmentation is a technique that can be used to artificially <strong>expand the size of a training dataset</strong> by creating modified versions of images in the dataset. Image Augmentation encompasses a suite of techniques that enhance the size and quality of training images such that better Deep Learning models can be built using them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*VUaSURSH3jUk6eEu9x7F9Q.gif" /><figcaption>Image Augmentation</figcaption></figure><h3>Installation of Tensorflow</h3><h3>Prerequisites</h3><ul><li>Linux, macOS, Windows</li><li>Python ≥ 3.7</li></ul><h3>Install TensorFlow</h3><p><strong>CPU-only</strong></p><pre>pip install “tensorflow&gt;=1.15.2,&lt;2.0”<br><strong>or</strong> <br>conda install tensorflow’&gt;=1.15.2,&lt;2.0.0&#39;</pre><p><strong>GPU support</strong></p><pre>pip install “tensorflow-gpu&gt;=1.15.2,&lt;2.0”<br><strong>or</strong> <br>conda install tensorflow-gpu’&gt;=1.15.2,&lt;2.0.0&#39;</pre><h3>Sanity Check</h3><pre><strong>&gt;&gt; </strong>import<strong> tensorflow </strong>as<strong> tf<br></strong>&gt;&gt; <strong>tf</strong>.__version__<br>&#39;2.3.0&#39;</pre><p>Now, we are going to use <a href="https://www.kaggle.com/sanikamal/rock-paper-scissors-dataset">Rock Paper Scissors Dataset</a> from Kaggle to perform multiclass image classification.</p><h3>Let’s jump into it !!!</h3><h3>1. Dataset exploration</h3><p>The dataset has three directories namely train, test and validation. Here, train and test have three classes of image and validation has a list of images to be tested.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/939de57246b301475bb43cda67b62609/href">https://medium.com/media/939de57246b301475bb43cda67b62609/href</a></iframe><p>The output is,</p><pre>Train set --&gt;  [&#39;paper&#39;, &#39;scissors&#39;, &#39;rock&#39;]<br>Test set --&gt;  [&#39;paper&#39;, &#39;scissors&#39;, &#39;rock&#39;]<br>Validation set --&gt;  [&#39;paper8.png&#39;, &#39;paper1.png&#39;, &#39;scissors-hires1.png&#39;]</pre><h3>2. Dataset Sample</h3><p>Let’s display a random image of each class from the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b730dd5b8fc3c50d67aa8abcbd2e08d/href">https://medium.com/media/6b730dd5b8fc3c50d67aa8abcbd2e08d/href</a></iframe><p>So, the images are,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*3cvnM7UffgdwL4Uk_nL4bg.png" /></figure><h3>3. Defining the CNN model</h3><p>This model comprises of five different types of layer,</p><ul><li><strong>Convolution Layer</strong>: This layer will extract important features from the image</li><li><strong>Pooling Laye</strong>r: This layer reduces the spatial volume of the input image after convolution by isolating the important features</li><li><strong>Flatten Layer: </strong>Flattens the input into a single-dimensional array</li><li><strong>Hidden Layer</strong>: Also called a dense layer, connects the network from a layer to another layer</li><li><strong>Output Layer</strong>: It is the final layer consisting of neurons equals to the no.of classes</li></ul><p>Here, we have three classes of the image, so, the output layer should have three neurons.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe6adfe573f379236171ce0d48857d79/href">https://medium.com/media/fe6adfe573f379236171ce0d48857d79/href</a></iframe><p>And, the summary of the model is,</p><pre>Model: &quot;sequential&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>conv2d (Conv2D)              (None, 148, 148, 32)      896       <br>_________________________________________________________________<br>max_pooling2d (MaxPooling2D) (None, 74, 74, 32)        0         <br>_________________________________________________________________<br>conv2d_1 (Conv2D)            (None, 72, 72, 64)        18496     <br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 36, 36, 64)        0         <br>_________________________________________________________________<br>conv2d_2 (Conv2D)            (None, 34, 34, 128)       73856     <br>_________________________________________________________________<br>max_pooling2d_2 (MaxPooling2 (None, 17, 17, 128)       0         <br>_________________________________________________________________<br>conv2d_3 (Conv2D)            (None, 15, 15, 128)       147584    <br>_________________________________________________________________<br>max_pooling2d_3 (MaxPooling2 (None, 7, 7, 128)         0         <br>_________________________________________________________________<br>flatten (Flatten)            (None, 6272)              0         <br>_________________________________________________________________<br>dense (Dense)                (None, 512)               3211776   <br>_________________________________________________________________<br>dense_1 (Dense)              (None, 1)                 513       <br>=================================================================<br>Total params: 3,453,121<br>Trainable params: 3,453,121<br>Non-trainable params: 0<br>_________________________________________________________________</pre><h3>4. Model compilation &amp; Callback function</h3><p>For this model, we use <em>adam </em>optimizer and <em>categorical_crossentropy</em> as the loss function.<br>The callback function here will stop the training of the model on epoch end when it reaches the accuracy &gt;95%.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed555b01cd05cb7eb7dc6fbbca84c6e3/href">https://medium.com/media/ed555b01cd05cb7eb7dc6fbbca84c6e3/href</a></iframe><h3>5. Generators</h3><h4>Training Generator with Image augmentation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/162efffdedd9ac8d148802b8ba735b54/href">https://medium.com/media/162efffdedd9ac8d148802b8ba735b54/href</a></iframe><pre>Found 2520 images belonging to 3 classes.</pre><h4>Validation Generator</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3784fce2ed5bf4be83af9ee996e30cc7/href">https://medium.com/media/3784fce2ed5bf4be83af9ee996e30cc7/href</a></iframe><pre>Found 372 images belonging to 3 classes.</pre><h3>6. Fitting the model</h3><p>As we are using generators in place of <em>model.fit</em> we need to use <em>model .fit_generator</em> function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2b4dc60a13782099401529f9d03dd0c/href">https://medium.com/media/e2b4dc60a13782099401529f9d03dd0c/href</a></iframe><pre>Epoch 1/10<br>126/126 - 46s - loss: 1.0141 - accuracy: 0.4591 - val_loss: 0.4937 - val_accuracy: 0.9301<br>Epoch 2/10<br>126/126 - 27s - loss: 0.5067 - accuracy: 0.7968 - val_loss: 0.0886 - val_accuracy: 0.9785<br>Epoch 3/10<br>126/126 - 27s - loss: 0.2712 - accuracy: 0.9056 - val_loss: 0.1290 - val_accuracy: 0.9624<br>Epoch 4/10<br>126/126 - 27s - loss: 0.1608 - accuracy: 0.9393 - val_loss: 0.1045 - val_accuracy: 0.9597<br>Epoch 5/10<br><br>Reached &gt;95% accuracy so cancelling training!<br>126/126 - 26s - loss: 0.1408 - accuracy: 0.9512 - val_loss: 0.0784 - val_accuracy: 0.9677</pre><h3>7. Visualizing the model training</h3><p>Let’s distribute the model’s accuracy and loss across the epoch</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab74493cf32c37cbc2dfba5c728782d/href">https://medium.com/media/5ab74493cf32c37cbc2dfba5c728782d/href</a></iframe><p>And the resultant graphs are,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*ary8ye3WZjhf-ZmUrN6Cdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*T2-Q8lTKIEy9Kgb1IJZfsQ.png" /></figure><p>We can see that the accuracy increases and the loss drops for every epoch</p><h3>8. Prediction</h3><h4>Preparation of test data</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f13f425fd5dd9fd6808e87f3af99dd25/href">https://medium.com/media/f13f425fd5dd9fd6808e87f3af99dd25/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*qCWH3klTsFV8cQFka0ildQ.png" /></figure><h4>Test Generator</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dca5803d5e8dd0fad2ca01dea49a0659/href">https://medium.com/media/dca5803d5e8dd0fad2ca01dea49a0659/href</a></iframe><pre>Found 33 validated image filenames.</pre><h4>Model prediction</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5efbc9635d0d8909d3fce7bba1474c5b/href">https://medium.com/media/5efbc9635d0d8909d3fce7bba1474c5b/href</a></iframe><h4>Label Mapping</h4><p>To identify the labels of the image, <em>class_indices </em>function is used</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3be142c44ebc4999e1c9f98106a1122d/href">https://medium.com/media/3be142c44ebc4999e1c9f98106a1122d/href</a></iframe><pre>{0: &#39;paper&#39;, 1: &#39;rock&#39;, 2: &#39;scissors&#39;}</pre><h4>Plotting the prediction</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccebde879c52c3371238de92c84e6629/href">https://medium.com/media/ccebde879c52c3371238de92c84e6629/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*GQatFtcQ7h9MP4tgWmETOQ.png" /></figure><h4>Model performance on unseen images</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f4b47d500c7ce214afcadf2bd416782/href">https://medium.com/media/9f4b47d500c7ce214afcadf2bd416782/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*MxfWCzkPfwBh6SpZ_YGPtA.png" /></figure><h4>Model accuracy on unseen images</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e3dcaa5418bffb0866764d22620cd74/href">https://medium.com/media/4e3dcaa5418bffb0866764d22620cd74/href</a></iframe><pre>Accuracy of the model on test data is 93.94%</pre><p>The full code is available <a href="https://www.kaggle.com/kamalkhumar/multiclass-classification-with-image-augmentation">here</a></p><p>Thanks for reading !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=834c16122a3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AmpliGraph — What is it?]]></title>
            <link>https://medium.com/featurepreneur/ampligraph-what-is-it-8b243800818c?source=rss-3b5d58dc183f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b243800818c</guid>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kamal khumar]]></dc:creator>
            <pubDate>Thu, 08 Oct 2020 06:54:38 GMT</pubDate>
            <atom:updated>2020-10-11T05:59:02.810Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>AmpliGraph — What is it?</strong></h3><blockquote>This blog explains, what is AmpliGraph and how to use it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*XeXQks82N_psJ8O9WXB2Aw.png" /></figure><p><strong>What is AmpliGraph?</strong></p><p><strong>AmpliGraph</strong> is a suite of neural machine learning models for relational Learning, a branch of machine learning that deals with supervised learning on knowledge graphs.</p><p>Use <strong>AmpliGraph</strong> if you need to:</p><ul><li>Discover new knowledge from an existing knowledge graph.</li><li>Complete large knowledge graphs with missing statements.</li><li>Generate stand-alone knowledge graph embeddings.</li><li>Develop and evaluate a new relational model.</li></ul><p>AmpliGraph’s machine learning models generate <strong>knowledge graph embeddings</strong>, vector representations of concepts in metric space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJ-zEj-9_TVGZmrxTRvPZQ.png" /></figure><p>It then combines embeddings with model-specific scoring functions to predict unseen and novel links:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwaVbdVCjLT518a58RXzrw.png" /></figure><p>Data-Flow in knowledge graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*TOuZ1fw6-XWFbLevuVjiCA.png" /></figure><p><strong>AmpliGraph API</strong> includes the following submodules:</p><ul><li><a href="https://docs.ampligraph.org/en/1.3.2/ampligraph.datasets.html">Datasets</a></li><li><a href="https://docs.ampligraph.org/en/1.3.2/ampligraph.latent_features.html">Models</a></li><li><a href="https://docs.ampligraph.org/en/1.3.2/ampligraph.evaluation.html">Evaluation</a></li><li><a href="https://docs.ampligraph.org/en/1.3.2/ampligraph.discovery.html">Discovery</a></li><li><a href="https://docs.ampligraph.org/en/1.3.2/ampligraph.utils.html">Utils</a></li></ul><h3>Installation</h3><h3>Prerequisites</h3><ul><li>Linux, macOS, Windows</li><li>Python ≥ 3.7</li></ul><h3>Provision a Virtual Environment</h3><p>Create and activate a virtual environment (conda)</p><pre>conda create --name ampligraph python=3.7<br>source activate ampligraph</pre><h3>Install AmpliGraph</h3><p>Install the latest stable release from pip:</p><pre>pip install ampligraph</pre><p>If instead, you want the most recent development version, you can clone the repository and install from source as below (also see the <a href="https://docs.ampligraph.org/en/1.3.2/dev.html">How to Contribute guide</a> for details):</p><pre>git clone <a href="https://github.com/Accenture/AmpliGraph.git">https://github.com/Accenture/AmpliGraph.git</a><br>cd AmpliGraph<br>git checkout develop<br>pip install -e .</pre><h3>Sanity Check</h3><pre>&gt;&gt; <strong>import</strong> <strong>ampligraph</strong><br>&gt;&gt; ampligraph.__version__<br>&#39;1.3.2&#39;</pre><p>Now we are going to use <a href="https://ampligraph.s3-eu-west-1.amazonaws.com/datasets/GoT.csv">Game of Thrones</a> data to plot the Ampligraph</p><blockquote>Please note: This isn’t the <em>greatest</em> dataset for demonstrating the power of knowledge graph embeddings, but is small, intuitive and should be familiar to most users.</blockquote><h3>Let’s get Started with AmpliGraph</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F4748677&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Ftype-typing-keyboard-computer-fast-typing-gif-4748677&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fimages%2Fc7dc8d0139b1e61ccdc15f3f16e80b99%2Fraw&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/20e2c1b5db432996cbfe8a641c13c6c2/href">https://medium.com/media/20e2c1b5db432996cbfe8a641c13c6c2/href</a></iframe><h3>1. Dataset exploration</h3><p>First things first! Let&#39;s import the required libraries and retrieve some data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/802cce5147fb1bd57768d9f8327b7770/href">https://medium.com/media/802cce5147fb1bd57768d9f8327b7770/href</a></iframe><p>The Output is,</p><pre>array([[‘Smithyton’, ‘SEAT_OF’, ‘House Shermer of Smithyton’], [‘House Mormont of Bear Island’, ‘LED_BY’, ‘Maege Mormont’], [‘Margaery Tyrell’, ‘SPOUSE’, ‘Joffrey Baratheon’], [‘Maron Nymeros Martell’, ‘ALLIED_WITH’, ‘House Nymeros Martell of Sunspear’], [‘House Gargalen of Salt Shore’, ‘IN_REGION’, ‘Dorne’]], dtype=object)</pre><h3>2. Defining train and test datasets</h3><p>As is typical in machine learning, we need to split our dataset into training and test (and sometimes validation) datasets. What differs from the standard method of randomly sampling N points to make up our test set, is that our data points are two entities linked by some relationship, and we need to take care to ensure that all entities are represented in train and test sets by at least 1 triple. To accomplish AmpliGraph provides the train_test_split_no_unseen function.</p><p>We’ll stick to common practice and divide our training and test set in an 80/20 split.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b5ff0e80bc25099b7f7147b136fe44f/href">https://medium.com/media/0b5ff0e80bc25099b7f7147b136fe44f/href</a></iframe><h3>3. Training a model</h3><p>AmpliGraph has implemented several Graph embedding models (TransE, ComplEx, DistMult, HolE), but to begin with, we’re just going to use the ComplEx model (with default values).</p><p>Let’s go through the parameters to understand what’s going on:</p><ul><li><strong>k</strong> : the dimensionality of the embedding space</li><li><strong>eta</strong> (η): the number of negative, or false triples that must be generated at training runtime for each positive, or true triple</li><li><strong>batches_count</strong> : the number of batches in which the training set is split during the training loop. If you are having into low memory issues than settings this to a higher number may help.</li><li><strong>epochs</strong> : the number of epochs to train the model for.</li><li><strong>optimizer</strong> : the Adam optimizer, with a learning rate of 1e-3 set via the <em>optimizer_params</em> kwarg.</li><li><strong>loss</strong> : pairwise loss, with a margin of 0.5 sets via the <em>loss_params</em> kwarg.</li><li><strong>regularizer</strong> : Lp regularization with p=2, i.e. l2 regularization. λ = 1e-5, set via the <em>regularizer_params</em> kwarg.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b3bdb51ce62b25f1ea90ea4e350e8fc/href">https://medium.com/media/5b3bdb51ce62b25f1ea90ea4e350e8fc/href</a></iframe><h3><strong>4. Fitting the model</strong></h3><p>Once you run the next cell the model will train.</p><p>On a modern laptop, this should take ~3 minutes (although your mileage may vary, especially if you’ve changed any of the hyper-parameters above).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5717bd9ee886ff13c70828b53b344159/href">https://medium.com/media/5717bd9ee886ff13c70828b53b344159/href</a></iframe><pre>Average Loss:   0.021658: 100%|██████████| 200/200 [01:28&lt;00:00,  2.25epoch/s]</pre><h3>5. Evaluating a model</h3><p>Now it’s time to evaluate our model on the test set to see how well it’s performing.</p><p>For this, we’ll use the evaluate_performance function and let’s look at the arguments to this function:</p><ul><li><strong>X</strong> - the data to evaluate. We&#39;re going to use our test set to evaluate.</li><li><strong>model</strong> - the model we previously trained.</li><li><strong>filter_triples</strong> - will filter out the false negatives generated by the corruption strategy.</li><li><strong>use_default_protocol</strong> - specifies whether to use the default corruption protocol. If True, then subj and obj are corrupted separately during evaluation.</li><li><strong>verbose</strong> - will give some nice log statements. Let&#39;s leave it on for now.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24d51e5c99d930d1138329ea3cc3963b/href">https://medium.com/media/24d51e5c99d930d1138329ea3cc3963b/href</a></iframe><pre>WARNING - DeprecationWarning: use_default_protocol will be removed in future. Please use corrupt_side argument instead.</pre><pre>100%|██████████| 635/635 [00:02&lt;00:00, 288.28it/s]</pre><p>The <strong><em>ranks</em></strong> returned by the evaluate_performance function indicate the rank at which the test set triple was found when performing link prediction using the model.</p><p>For example, given the triple:</p><pre>&lt;House Stark of Winterfell, IN_REGION The North&gt;</pre><p>The model returns a rank of 7. This tells us that while it’s not the highest likelihood true statement (which would be given a rank 1), it’s pretty likely.</p><h3>6. Metrics</h3><p>Let’s compute some evaluate metrics and print them out.</p><p>We’re going to use the mrr_score (mean reciprocal rank) and hits_at_n_score functions.</p><ul><li><strong><em>mrr_score</em></strong>: The function computes the mean of the reciprocal of elements of a vector of rankings ranks.</li><li><strong><em>hits_at_n_score</em></strong>: The function computes how many elements of a vector of rankings ranks make it to the top n positions.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85e321a3dffe90b13312d77e81c9bac1/href">https://medium.com/media/85e321a3dffe90b13312d77e81c9bac1/href</a></iframe><p>And the output is,</p><pre>MRR: 0.30<br>Hits@10: 0.41<br>Hits@3: 0.33<br>Hits@1: 0.24</pre><h3>7. Predicting New Links</h3><p>Link prediction allows us to infer missing links in a graph. This has many real-world use cases, such as predicting connections between people in a social network, interactions between proteins in a biological network, and music recommendation based on prior user taste.</p><p>In our case, we’re going to see which of the following candidate statements (that we made up) are more likely to be true:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e072e3e208b7e03e7eb3a058f7ff085c/href">https://medium.com/media/e072e3e208b7e03e7eb3a058f7ff085c/href</a></iframe><pre>100%|██████████| 22/22 [00:00&lt;00:00, 159.31it/s]</pre><p>We transform the scores (real numbers) into probabilities (bound between 0 and 1) using the expit transform.</p><p>Note that the probabilities are not calibrated in any sense.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d09d8a7ea862f74225632079fb574462/href">https://medium.com/media/d09d8a7ea862f74225632079fb574462/href</a></iframe><p>The resulting DataFrame,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*VIYQcORe0ZsDBFpLJp5gXQ.png" /></figure><h3>8. Visualizing Embeddings with Tensorboard projector</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55715dbac1a6a3177089756569bc61cb/href">https://medium.com/media/55715dbac1a6a3177089756569bc61cb/href</a></iframe><p>If all went well, we should now have several files in the AmpliGraph<a href="https://colab.research.google.com/drive/1rylqOnm992AdP9z1aW8metlKpPuBTRGD#">/tutorials/GoT_embeddings</a> directory:</p><pre>GoT_embeddings/<br>    ├── checkpoint<br>    ├── embeddings_projector.tsv<br>    ├── graph_embedding.ckpt.data-00000-of-00001<br>    ├── graph_embedding.ckpt.index<br>    ├── graph_embedding.ckpt.meta<br>    ├── metadata.tsv<br>    └── projector_config.pbtxt</pre><p>To visualize the embeddings in Tensorboard, run the following from your command line inside AmpliGraph/tutorials:</p><pre>tensorboard --logdir=./visualizations</pre><p>.. and once your browser opens up you should be able to see and explore your embeddings as below (PCA-reduced, two components):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*YLShfpuKaHgMnZJ8rMbjzQ.png" /></figure><h3>Conclusion</h3><p>In summary, AmpliGraph Graphs are at the crossroads of <strong>Data Base</strong> and <strong>Artificial intelligence</strong> to provide smart insights (or <em>Knowledge</em>) from very different types of data. Decision-makers can store all business knowledge as a set of connected vectors and use artificial neural networks to reason using this information.</p><p>The source code of AmpliGraph Library is available <a href="https://github.com/Accenture/AmpliGraph">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b243800818c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/ampligraph-what-is-it-8b243800818c">AmpliGraph — What is it?</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text summarization using spaCy]]></title>
            <link>https://medium.com/analytics-vidhya/text-summarization-using-spacy-ca4867c6b744?source=rss-3b5d58dc183f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca4867c6b744</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[text-analysis]]></category>
            <category><![CDATA[text-summarization]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[spacy]]></category>
            <dc:creator><![CDATA[Kamal khumar]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 07:05:13 GMT</pubDate>
            <atom:updated>2020-08-02T15:49:08.293Z</atom:updated>
            <content:encoded><![CDATA[<h4>The article explains, What is spacy, Advantages of spacy and how to perform text summarization with it.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HoFdy564ZFQG1pZHc6pFg.png" /><figcaption>Photo by <a href="https://commons.wikimedia.org/wiki/File:SpaCy_logo.svg">Artichok3</a></figcaption></figure><h3>What is spaCy?</h3><p>spaCy is a free, open-source advanced natural language processing library, written in the programming languages Python and Cython. spaCy mainly used in the development of production software and also supports deep learning workflow via statistical models of PyTorch and TensorFlow.</p><h3>Why spaCy?</h3><p>spaCy provides a fast and accurate syntactic analysis, named entity recognition and ready access to word vectors. We can use the default word vectors or replace them with any you have. spaCy also offers tokenization, sentence boundary detection, POS tagging, syntactic parsing, integrated word vectors, and alignment into the original string with high accuracy.</p><h3>Text Summarization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*YGj5iXEAm_271tIUCpIO7g.png" /><figcaption>Fig 2: Text Summarization</figcaption></figure><p>Text summarization can broadly be divided into two categories — <strong>Extractive Summarization</strong> and <strong>Abstractive Summarization</strong>.</p><ol><li><strong>Extractive Summarization:</strong> These methods rely on extracting several parts, such as phrases and sentences, from a piece of text and stack them together to create a summary. Therefore, identifying the right sentences for summarization is of utmost importance in an extractive method.</li><li><strong>Abstractive Summarization:</strong> These methods use advanced NLP techniques to generate an entirely new summary. Some parts of this summary may not even appear in the original text.</li></ol><p>In this article, we will be focusing on the <strong>extractive summarization</strong> technique.</p><h3>Step: 1 Installation instructions</h3><p>To install <em>spaCy</em>, simply type the following:</p><pre>pip install -U spacy</pre><p>To begin with import <em>spaCy</em> and other necessary modules:</p><pre>import spacy<br>from spacy.lang.en.stop_words import STOP_WORDS<br>from string import punctuation<br>from collections import Counter<br>from heapq import nlargest</pre><p>Next, load the model (English) into spaCy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*HghTt2VutllnleSBc4OJRQ.png" /><figcaption>Fig 3: Loading the model</figcaption></figure><p>The text we are about to handle is “<em>Introduction to Machine Learning”</em> and the string is stored in the variable<em> doc.</em></p><p>And the string is,</p><pre>Machine learning (ML) is the scientific study of algorithms and statistical models that computer systems use to progressively improve their performance on a specific task. Machine learning algorithms build a mathematical model of sample data, known as “training data”, in order to make predictions or decisions without being explicitly programmed to perform the task. Machine learning algorithms are used in the applications of email filtering, detection of network intruders, and computer vision, where it is infeasible to develop an algorithm of specific instructions for performing the task. Machine learning is closely related to computational statistics, which focuses on making predictions using computers. The study of mathematical optimization delivers methods, theory and application domains to the field of machine learning. Data mining is a field of study within machine learning and focuses on exploratory data analysis through unsupervised learning. In its application across business problems, machine learning is also referred to as predictive analytics.</pre><p>Now, pass the string <em>doc</em> into the <em>nlp</em> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*gUTVWNeqsMWIBzta5qsr2w.png" /><figcaption>Fig 4: Tokenization</figcaption></figure><p>To find the number of sentences in the given string the following function is used,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*Rop0R5bD4N9A_OG2o3PjXw.png" /><figcaption>Fig 5: No. of sentence</figcaption></figure><pre>7</pre><p>Next, two lists are created for parts-of-speech and stop words to validate each token followed by filtering of the necessary tokens and save them in the <em>keywords</em> list.</p><h3>Step: 2 Filtering tokens</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lu5cyjN9lEnLm8uDjaAocA.png" /><figcaption>Fig 6: Keyword filtering</figcaption></figure><p>Calculate the frequency of each token using the “<em>Counter”</em> function, store it in <em>freq_word </em>and to view top 5 frequent words, <em>most_common </em>method can be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Tk8kfbgfZ546K7LmDYXpDg.png" /><figcaption>Fig 7: Token frequency</figcaption></figure><p>The desired output would be,</p><pre>[(‘learning’, 8), (‘Machine’, 4), (‘study’, 3), (‘algorithms’, 3), (‘task’, 3)]</pre><p>This frequency can be normalised for better processing and it can be done by dividing the token’s frequencies by the maximum frequency.</p><h3>Step: 3 Normalization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*zk4MaBZzkZBt_z3SYnKsxw.png" /><figcaption>Fig 8: Normalising token frequency</figcaption></figure><p>The normalised list is,</p><pre>[(‘learning’, 1.0), (‘Machine’, 0.5), (‘study’, 0.375), (‘algorithms’, 0.375), (‘task’, 0.375)]</pre><p>This is the major part where each sentence is weighed based on the frequency of the token present in each sentence. The result is stored as a key-value pair in <em>sent_strength</em> where keys are the sentences in the string <em>doc</em> and the values are the weight of each sentence.</p><h3>Step: 4 Weighing sentences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*RrqbxyeDgQcq5zZQABsDuQ.png" /><figcaption>Fig 9: Weighing the sentence</figcaption></figure><p>And the output is,</p><pre>{Machine learning (ML) is the scientific study of algorithms and statistical models that computer systems use to progressively improve their performance on a specific task.: 4.125, <br>Machine learning algorithms build a mathematical model of sample data, known as “training data”, in order to make predictions or decisions without being explicitly programmed to perform the task.: 4.625, <br>Machine learning algorithms are used in the applications of email filtering, detection of network intruders, and computer vision, where it is infeasible to develop an algorithm of specific instructions for performing the task.: 4.25, <br>Machine learning is closely related to computational statistics, which focuses on making predictions using computers.: 2.625, <br>The study of mathematical optimization delivers methods, theory and application domains to the field of machine learning.: 3.125, <br>Data mining is a field of study within machine learning, and focuses on exploratory data analysis through unsupervised learning.: 4.25, In its application across business problems, machine learning is also referred to as predictive analytics.: 2.25}</pre><p>Finally, <em>nlargest</em> function is used to summarize the string, it takes 3 arguments,</p><p>→ Number of data to extract</p><p>→ An Iterable (List/Tuple/Dictionary)</p><p>→ Condition to be satisfied, respectively</p><h3>Step: 5 Summarizing the string</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*CZPHk2FDrgTZUvgEzg5qcw.png" /><figcaption>Fig 10: Finding N largest</figcaption></figure><p>And the <em>nlargest</em> function returns a list containing the top 3 sentences which are stored as <em>summarized_sentences</em>.</p><pre>[Machine learning algorithms build a mathematical model of sample data, known as “training data”, in order to make predictions or decisions without being explicitly programmed to perform the task., Machine learning algorithms are used in the applications of email filtering, detection of network intruders, and computer vision, where it is infeasible to develop an algorithm of specific instructions for performing the task., Data mining is a field of study within machine learning, and focuses on exploratory data analysis through unsupervised learning.]</pre><p>Each sentence in this list is of <em>spacy.span</em> type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*H6ULsKQN8P8LsmPtM1PwoA.png" /><figcaption>Fig 11: Type of token</figcaption></figure><pre>spacy.tokens.span.Span</pre><p>This can be converted to a string by the following lines of code,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*O3Spc4W6YKrfdrPJnLlS4Q.png" /><figcaption>Fig 12: Final result</figcaption></figure><p>Resulting in a final summarized output as</p><pre>Machine learning algorithms build a mathematical model of sample data, known as “training data”, in order to make predictions or decisions without being explicitly programmed to perform the task. Machine learning algorithms are used in the applications of email filtering, detection of network intruders, and computer vision, where it is infeasible to develop an algorithm of specific instructions for performing the task. Data mining is a field of study within machine learning, and focuses on exploratory data analysis through unsupervised learning.</pre><h3>Summarization using Gensim</h3><p>Gensim package is known to have an inbuilt summarization function but it is not as efficient as spaCy. The code is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*hftqLaGKwuXT7XU0hX7eaA.png" /><figcaption>Fig 13: Summarization using Gensim</figcaption></figure><p>The respective output is,</p><pre>&#39;Machine learning algorithms build a mathematical model of sample data, known as “training data”, in order to make predictions or decisions without being explicitly programmed to perform the task.&#39;</pre><p>The full code is available in <a href="https://github.com/kamal2230/text-summarization">GitHub</a>.</p><h3>Conclusion</h3><p>I hope you have now understood how to perform text summarization using spaCy. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca4867c6b744" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/text-summarization-using-spacy-ca4867c6b744">Text summarization using spaCy</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spell Checker Using Pyspellchecker Package]]></title>
            <link>https://medium.com/swlh/spell-checker-using-pyspellchecker-package-82185fa8c417?source=rss-3b5d58dc183f------2</link>
            <guid isPermaLink="false">https://medium.com/p/82185fa8c417</guid>
            <category><![CDATA[spell-check]]></category>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[spacy]]></category>
            <dc:creator><![CDATA[Kamal khumar]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 13:31:48 GMT</pubDate>
            <atom:updated>2020-07-26T12:11:27.701Z</atom:updated>
            <content:encoded><![CDATA[<h4>This story explains, what is pyspellchecker, and how to use it.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBCWjn5uYRy6UbQlwyxANQ.jpeg" /></figure><h3>What is pyspellchecker?</h3><p>The <strong>pyspellchecker</strong> is an open-source package that allows you to correct spelling, as well as see candidate spellings for a misspelled word.</p><p>To install the package, you can use pip:</p><pre>pip install pyspellchecker</pre><p>First, we import the necessary packages,</p><p>Once installed, the <strong>pyspellchecker</strong> is straightforward to use. Note that even though we use “pyspellchecker” when installing via pip, we just type “spellchecker” in the package import statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*tBXTQJF5xYCNj6-vlBfl6w.png" /><figcaption>Fig 1: Import Statements</figcaption></figure><p>And to view all the available directories, <em>dir </em>method can be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*8WCAq8A3MEkE8m4q-xjhHA.png" /><figcaption>Fig 2: Invoking dir method</figcaption></figure><p>And the output is all available directories.</p><pre>[‘_SpellChecker__edit_distance_alt’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__slots__’, ‘__str__’, ‘__subclasshook__’, ‘_case_sensitive’, ‘_check_if_should_check’, ‘_distance’, ‘_tokenizer’, ‘_word_frequency’, ‘candidates’, ‘correction’, ‘distance’, ‘edit_distance_1’, ‘edit_distance_2’, ‘export’, ‘known’, ‘split_words’, ‘unknown’, ‘word_frequency’, ‘word_probability’]</pre><p>The next piece is to create a SpellChecker object, which we’ll term as “spell”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*q_exZEVT7iKSYeR4vh_4ag.png" /><figcaption>Fig 3: Creating an object</figcaption></figure><p>And the text we are about to handle is <em>immigrants in Toronto </em>and the string is stored in the variable<em> docx.</em></p><p>The string is,</p><pre>People have travelled through and inhabited the Toronto area, located on a broad sloping plateau interspersed with rivers, deep ravines, and urban forest, for more than 10,000 years. After the broadly disputed Torronto Purchase, when the Mississauga surrendered the area to the British Crown,the British established the town of York in 1793 and later designeted it as the capital of Upper Canada. During the War of 1812, the town was the site of the Battle of York and suffered heavy damage by American troops. York was renamed and incorporated in 1834 as the city of Toronto. It was designated as the capitel of the province of Ontario in 1867 during Canadian Confederation. The city proper has since expanded past its original borders through both annexation and amalgamation to its current area of 630.2 km2 (243.3 sq mi). The diverse population of Tornto reflects its current and historical role as an important destination for immigrants to Canada. More than 50 percent of residants belong to a visible minority population group, and over 200 distinct ethnic origins are represented among its inhabitats. While the majority of Torontonians speak English as their premary language, over 160 languages are spoken in the city. Toront is a prominent center for music, theatre, motion picture production, and tilevision production, and is home to the headquarters of Canada’s major notional broadcast networks and media outlets. Its varied caltural institutions, which include numerous museums and gelleries, festivals and public events, entertaiment districts, national historic sites, and sports actevities, attract over 43 million touriets each year. Torunto is known for its many skysvrapers and high-rise buildinds, in particalar the tallest free-standind structure in the Western Hemisphere, the CN Tower.</pre><p>And all the text tokens present in the <em>docx</em> is captured using re.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*TtmgV2FUoR7E0BJXWu-ssg.png" /><figcaption>Fig 4: Invoking re</figcaption></figure><p>The result is,</p><pre>[‘People’, ‘have’, ‘travelled’, ‘through’, ‘and’, ‘inhabited’, ‘the’, ‘Toronto’, ‘area’, ‘located’, ‘on’, ‘a’, ‘broad’, ‘sloping’, ‘plateau’, ‘interspersed’, ‘with’, ‘rivers’, ‘deep’, ‘ravines’, ‘and’, ‘urban’, ‘forest’, ‘for’, ‘more’, ‘than’, ‘years’, ‘After’, ‘the’, ‘broadly’, ‘disputed’, ‘Torronto’, ‘Purchase’, ‘when’, ‘the’, ‘Mississauga’, ‘surrendered’, ‘the’, ‘area’, ‘to’, ‘the’, ‘British’, ‘Crown’, ‘the’, ‘British’, ‘established’, ‘the’, ‘town’, ‘of’, ‘York’, ‘in’, ‘and’, ‘later’, ‘designeted’, ‘it’, ‘as’, ‘the’, ‘capital’, ‘of’, ‘Upper’, ‘Canada’, ‘During’, ‘the’, ‘War’, ‘of’, ‘the’, ‘town’, ‘was’, ‘the’, ‘site’, ‘of’, ‘the’, ‘Battle’, ‘of’, ‘York’, ‘and’, ‘suffered’, ‘heavy’, ‘damage’, ‘by’, ‘American’, ‘troops’, ‘York’, ‘was’, ‘renamed’, ‘and’, ‘incorporated’, ‘in’, ‘as’, ‘the’, ‘city’, ‘of’, ‘Toronto’, ‘It’, ‘was’, ‘designated’, ‘as’, ‘the’, ‘capitel’, ‘of’, ‘the’, ‘province’, ‘of’, ‘Ontario’, ‘in’, ‘during’, ‘Canadian’, ‘Confederation’, ‘The’, ‘city’, ‘proper’, ‘has’, ‘since’, ‘expanded’, ‘past’, ‘its’, ‘original’, ‘borders’, ‘through’, ‘both’, ‘annexation’, ‘and’, ‘amalgamation’, ‘to’, ‘its’, ‘current’, ‘area’, ‘of’, ‘km’, ‘sq’, ‘mi’, ‘The’, ‘diverse’, ‘population’, ‘of’, ‘Tornto’, ‘reflects’, ‘its’, ‘current’, ‘and’, ‘historical’, ‘role’, ‘as’, ‘an’, ‘important’, ‘destination’, ‘for’, ‘immigrants’, ‘to’, ‘Canada’, ‘More’, ‘than’, ‘percent’, ‘of’, ‘residants’, ‘belong’, ‘to’, ‘a’, ‘visible’, ‘minority’, ‘population’, ‘group’, ‘and’, ‘over’, ‘distinct’, ‘ethnic’, ‘origins’, ‘are’, ‘represented’, ‘among’, ‘its’, ‘inhabitats’, ‘While’, ‘the’, ‘majority’, ‘of’, ‘Torontonians’, ‘speak’, ‘English’, ‘as’, ‘their’, ‘premary’, ‘language’, ‘over’, ‘languages’, ‘are’, ‘spoken’, ‘in’, ‘the’, ‘city’, ‘Toront’, ‘is’, ‘a’, ‘prominent’, ‘center’, ‘for’, ‘music’, ‘theatre’, ‘motion’, ‘picture’, ‘production’, ‘and’, ‘tilevision’, ‘production’, ‘and’, ‘is’, ‘home’, ‘to’, ‘the’, ‘headquarters’, ‘of’, ‘Canada’, ‘s’, ‘major’, ‘notional’, ‘broadcast’, ‘networks’, ‘and’, ‘media’, ‘outlets’, ‘Its’, ‘varied’, ‘caltural’, ‘institutions’, ‘which’, ‘include’, ‘numerous’, ‘museums’, ‘and’, ‘gelleries’, ‘festivals’, ‘and’, ‘public’, ‘events’, ‘entertaiment’, ‘districts’, ‘national’, ‘historic’, ‘sites’, ‘and’, ‘sports’, ‘actevities’, ‘attract’, ‘over’, ‘million’, ‘touriets’, ‘each’, ‘year’, ‘Torunto’, ‘is’, ‘known’, ‘for’, ‘its’, ‘many’, ‘skysvrapers’, ‘and’, ‘high’, ‘rise’, ‘buildinds’, ‘in’, ‘particalar’, ‘the’, ‘tallest’, ‘free’, ‘standind’, ‘structure’, ‘in’, ‘the’, ‘Western’, ‘Hemisphere’, ‘the’, ‘CN’, ‘Tower’]</pre><p>The next step is to find all the misspelled words and it can be done by passing the string <em>docx</em> into the “<em>unknown”</em> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*1PigJZUrPY71jQtZncYByQ.png" /><figcaption>Fig 5: Invoking the unknown function</figcaption></figure><p>And this “<em>misspelled”</em> list contains all the misspelled words in the string.</p><p>Finally, the “<em>misspelled”</em> list is parsed and each token from the list is passed to the function “<em>correction” </em>to get the<em> </em>correct spelling of the token and “<em>candidates” </em>function is used to avail all possible suggestions of that token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*6froE9nGkkAT0aG4-ZzCNw.png" /><figcaption>Fig 6: parsing misspelt words</figcaption></figure><p>The output of this is,</p><pre>tilevision → television {‘television’}<br>gelleries → galleries {‘galleries’} <br>particalar → particular {‘particular’} <br>skysvrapers → skyscrapers {‘skyscrapers’} <br>torontonians → torontonians {‘torontonians’} <br>residants → residents {‘residents’} <br>caltural → cultural {‘cultural’}<br>mississauga → mississauga {‘mississauga’}<br>inhabitats → inhabitants {‘inhabitants’}<br>standind → standing {“standin’”, ‘standing’}<br>actevities → activities {‘activities’}<br>buildinds → buildings {‘buildings’}<br>capitel → capital {‘capital’, ‘capitol’}<br>designeted → designated {‘designated’}<br>entertaiment → entertainment {‘entertainment’}<br>toront → toronto {‘toronto’}<br>torronto → toronto {‘toronto’}<br>touriets → tourists {‘tourists’}<br>torunto → toronto {‘toronto’}<br>tornto → toronto {‘toronto’, ‘tonto’}<br>premary → primary {‘primary’}</pre><p>The above-quoted program is demonstrated subjective to the English language whereas the same can be implemented by following the above methodology for various languages like <em>Spanish</em>, <em>German</em>, <em>French</em>, and <em>Portuguese</em>.</p><p>Briefing on this statement, the following presents a demo to extract the output in <em>French.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*TKPS1yQD1n5gn6U9xnyWdg.png" /><figcaption>Fig 7: Demo code in French</figcaption></figure><p>The output is,</p><pre>resaissir → ressaisir {‘ressaisir’}<br>plonbier → plombier {‘plombier’}<br>matinnée → matinée {‘matinée’}<br>tecnicien → technicien {‘technicien’}</pre><p>The full code is available in <a href="https://github.com/kamal2230/Spell-Checker">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82185fa8c417" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/spell-checker-using-pyspellchecker-package-82185fa8c417">Spell Checker Using Pyspellchecker 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[Text Classification With BERT Model]]></title>
            <link>https://medium.com/swlh/text-classification-with-bert-model-5560622157bd?source=rss-3b5d58dc183f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5560622157bd</guid>
            <category><![CDATA[advantages-of-bert]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[ktrain]]></category>
            <dc:creator><![CDATA[Kamal khumar]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 09:41:43 GMT</pubDate>
            <atom:updated>2020-07-25T15:35:00.043Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog explains, what is BERT, advantages of BERT, how to classify the text using BERT model with Ktrain package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCOPv1aqIy8j5kO-tDvcmg.png" /></figure><h4>What is BERT?</h4><p>BERT, which stands for Bidirectional Encoder Representations from Transformers developed by researchers at Google in 2018, is based on Transformers, a deep learning model in which every output element is connected to every input element, and the weightings between them are dynamically calculated based upon their connection. (In NLP, this process is called <em>attention</em>.)</p><p>Historically, language models could only read text input sequentially — either left-to-right or right-to-left — but couldn’t do both at the same time. BERT is different because it is designed to read in both directions at once. This capability, enabled by the introduction of Transformers, is known as bi-directionality.</p><h3>Why BERT NLP Will Be Revolutionary?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqN0va_lSip23VPUN2mAxw.png" /></figure><p>What makes it’s unique from the rest of the model is that it’s is the first deeply bidirectional, unsupervised language representation, pre-trained using only a plain text corpus. Since it’s open-sourced, anyone with machine learning knowledge can easily build an NLP model without the need for sourcing massive datasets for training the model thus saving time, energy, knowledge and resources.</p><p>Finally, BERT is pre-trained on a large corpus of unlabelled text which includes the entire <strong>Wikipedia </strong>(that’s about 2,500 million words) and a book corpus (800 million words).</p><p>To accomplish this, we will be using <a href="https://github.com/amaiya/ktrain/tree/master/ktrain"><em>ktrain</em></a>, a <strong>fastai</strong>-like interface to <strong>Keras. </strong><em>ktrain </em>is open-source and available here.</p><p>To install <em>ktrain</em>, simply type the following:</p><pre>pip3 install ktrain</pre><p>To begin, let’s import the <em>ktrain</em> and <em>ktrain.text</em> modules:</p><pre>import ktrain<br>from ktrain import text</pre><h3>Step 1: Load the data</h3><p>Load the in-built 20newsgroups data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iY92Ssjf96oAUSGYoRv0Iw.png" /></figure><h3>Step 2: Load BERT and wrap it in a Learner object</h3><p>The first argument to get_learner uses the <em>ktrain</em>text_classifier function to load the pre-trained BERT model with a randomly initialized final Dense layer. The second and third arguments are the training and validation data, respectively. The last argument get_learner is the batch size. We use a small batch size of 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nT687JnzYdg_X4mfQhQNUQ.png" /></figure><h3>Step 3: Train the model</h3><p>To train the model, we use the fit_onecycle method of <em>ktrain</em> which employs a <a href="https://arxiv.org/pdf/1803.09820.pdf">1cycle learning rate policy</a> that linearly increases the learning rate for the first half of training and then decreases the learning rate for the latter half:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*9XfdDOFId42yKE4xApFfsw.png" /></figure><p>As can be seen from the <strong>Keras</strong> output, this achieves a <strong>99.65%</strong> accuracy in four epochs:</p><pre>begin training using onecycle policy with max lr of 2e-05...<br>Train on 2257 samples<br>Epoch 1/4<br>2257/2257 [==============================] - 498s 221ms/sample - loss: 0.6748 - accuracy: 0.7288<br>Epoch 2/4<br>2257/2257 [==============================] - 477s 211ms/sample - loss: 0.1240 - accuracy: 0.9575<br>Epoch 3/4<br>2257/2257 [==============================] - 476s 211ms/sample - loss: 0.0394 - accuracy: 0.9867<br>Epoch 4/4<br>2257/2257 [==============================] - 475s 211ms/sample - loss: 0.0101 - accuracy: 0.9965<br>&lt;tensorflow.python.keras.callbacks.History at 0x7fc74aab2588&gt;</pre><h3>Step 4: Plot the learning rate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*-JoLq-ba2lV1E8wMCJXhpg.png" /></figure><p>And the plot will be,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*KWom4kA63kMnoKDzkNRJDA.png" /></figure><h3>Step 5: Validating the test data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50C66BxRgH8Gsdb1Wek1jg.png" /></figure><p>The test data will be validated and the output is,</p><pre>                          precision    recall  f1-score   support<br><br>           alt.atheism       0.91      0.93      0.92       319<br>         comp.graphics       0.99      0.95      0.97       389<br>               sci.med       0.97      0.96      0.97       396<br>soc.religion.christian       0.96      0.97      0.97       398<br><br>              accuracy                           0.96      1502<br>             macro avg       0.96      0.96      0.96      1502<br>          weighted avg       0.96      0.96      0.96      1502</pre><pre>array([[298,   0,   9,  12],<br>       [ 15, 371,   2,   1],<br>       [  7,   4, 382,   3],<br>       [  9,   1,   1, 387]])</pre><h3>Step 6: Storing the model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*VKuL9nCpLJ4vSEBfJ9teqQ.png" /></figure><p>The full source code available on <a href="https://github.com/kamal2230/Bert-Basics">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5560622157bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/text-classification-with-bert-model-5560622157bd">Text Classification With BERT Model</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>
    </channel>
</rss>