<?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[TheLeanProgrammer - Medium]]></title>
        <description><![CDATA[The biggest power in the world is to be able to give life to something, and guess what? Code gives you this ability! Here in this publication, we build stuff, we share knowledge in tech, and share our stories, feel free to join — https://theleanprogrammer.com/writer-request/ - Medium]]></description>
        <link>https://medium.com/theleanprogrammer?source=rss----a0ec77e9cd3---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>TheLeanProgrammer - Medium</title>
            <link>https://medium.com/theleanprogrammer?source=rss----a0ec77e9cd3---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 11 Nov 2026 05:46:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/theleanprogrammer" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JavaScript replaceAll()]]></title>
            <link>https://medium.com/theleanprogrammer/javascript-replaceall-814a2b550d70?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/814a2b550d70</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[es2021]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Harsha]]></dc:creator>
            <pubDate>Wed, 17 May 2023 14:47:21 GMT</pubDate>
            <atom:updated>2023-05-17T14:47:21.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*BZsRSXdZC5FGXlvZ3gt1AA.jpeg" /><figcaption>image source : soliloquywp.com</figcaption></figure><p>ES2021 has introduced the replaceAll() method for string manipulation in javascript.</p><p><strong>const newString = oldString.replaceAll(pattern,replacement)</strong></p><p>As you may have guessed by its name it replaces all the occurrences of the pattern with the replacement passed to it.</p><p>Many of you will say we already have the <strong>replace() </strong>method then what’s the need?🤔</p><p>Let me tell you the replace method only replaces the first occurrence of the pattern😕</p><p>Let’s understand this with an example</p><pre>let str = &quot;I love Java.Java is very easy to learn.&quot;<br>let str1 = str.replace(“Java”,”JavaScript”)</pre><pre>console.log(str);   //&quot;I love Java.Java is very easy to learn.&quot;<br>console.log(str1);  //&quot;I love JavaScript.Java is very easy to learn.&quot;</pre><p>So if you want to replace all the occurrences with the replace() method you need to be familiar with the regular expressions as replace method uses regular expressions with the g flag to replace every match pattern in the string😨</p><pre>let str = &quot;I love Java.Java is very easy to learn.&quot;<br>let str1 = str.replace(/Java/g,&quot;JavaScript&quot;)</pre><pre>console.log(str);  //&quot;I love Java.Java is very easy to learn.&quot;<br>console.log(str1); //&quot;I love JavaScript.JavaScript is very easy to learn.&quot;</pre><p>replaceAll is the easy method instead of learning the regular expression🤭</p><pre>let str = &quot;I love Java.Java is very easy to learn.&quot;<br>let str1 = str.replaceAll(&quot;Java&quot;,&quot;JavaScript&quot;)</pre><pre>console.log(str);  //&quot;I love Java.Java is very easy to learn.&quot;<br>console.log(str1); //&quot;I love JavaScript.JavaScript is very easy to learn.&quot;</pre><p>Note that this method does not mutate the string value it’s called on. It returns a new string.</p><p>Thanks for reading! For more such javascript-related information follow me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=814a2b550d70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theleanprogrammer/javascript-replaceall-814a2b550d70">JavaScript replaceAll()</a> was originally published in <a href="https://medium.com/theleanprogrammer">TheLeanProgrammer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hackers Targeting Critical Infrastructure]]></title>
            <link>https://medium.com/theleanprogrammer/hackers-targeting-critical-infrastructure-73a8e477411f?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/73a8e477411f</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[hacker]]></category>
            <category><![CDATA[hackerspaces]]></category>
            <dc:creator><![CDATA[Devraj Ganguly]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 13:48:29 GMT</pubDate>
            <atom:updated>2022-02-05T13:48:29.481Z</atom:updated>
            <content:encoded><![CDATA[<h4>FBI, NSA and CISA Warns About Russian Hackers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFCa6ya3eFgHHoIO3sSK4A.png" /></figure><p>Amid renewed tensions between the U.S. and Russia over <a href="https://apnews.com/article/joe-biden-europe-russia-ukraine-geneva-090d1bd24f7ced8ab84907a9ed031878">Ukraine</a> and <a href="https://thehill.com/policy/international/588860-tensions-between-us-russia-rise-over-military-involvement-in-kazakhstan">Kazakhstan</a>, American cybersecurity and intelligence agencies on Tuesday released a joint advisory on how to detect, respond to, and mitigate cyberattacks orchestrated by Russian state-sponsored actors.</p><p>To that end, the Cybersecurity and Infrastructure Security Agency (CISA), Federal Bureau of Investigation (FBI), and National Security Agency (NSA) have laid bare the tactics, techniques, and procedures (TTPs) adopted by the adversaries, including spear-phishing, brute-force, and <a href="https://www.cisa.gov/known-exploited-vulnerabilities-catalog">exploiting known vulnerabilities</a> to gain initial access to target networks.</p><p>The list of flaws exploited by Russian hacking groups to gain an initial foothold, which the agencies said are “common but effective,” are below —</p><ul><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2018-13379">CVE-2018–13379</a> (FortiGate VPNs)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-1653">CVE-2019–1653</a> (Cisco router)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-2725">CVE-2019–2725</a> (Oracle WebLogic Server)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-7609">CVE-2019–7609</a> (Kibana)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-9670">CVE-2019–9670</a> (Zimbra software)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-10149">CVE-2019–10149</a> (Exim Simple Mail Transfer Protocol)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-11510">CVE-2019–11510</a> (Pulse Secure)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-19781">CVE-2019–19781</a> (Citrix)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2020-0688">CVE-2020–0688</a> (Microsoft Exchange)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2020-4006">CVE-2020–4006</a> (VMWare)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2020-5902">CVE-2020–5902</a> (F5 Big-IP)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2020-14882">CVE-2020–14882</a> (Oracle WebLogic)</li><li><a href="https://nvd.nist.gov/vuln/detail/CVE-2021-26855">CVE-2021–26855</a> (Microsoft Exchange, exploited frequently alongside <a href="https://nvd.nist.gov/vuln/detail/CVE-2021-26857">CVE-2021–26857</a>, <a href="https://nvd.nist.gov/vuln/detail/CVE-2021-26858">CVE-2021–26858</a>, and <a href="https://nvd.nist.gov/vuln/detail/CVE-2021-27065">CVE-2021–27065</a>)</li></ul><p>“Russian state-sponsored APT actors have also demonstrated sophisticated tradecraft and cyber capabilities by compromising third-party infrastructure, compromising third-party software, or developing and deploying custom malware,” the agencies <a href="https://www.cisa.gov/uscert/ncas/current-activity/2022/01/11/cisa-fbi-and-nsa-release-cybersecurity-advisory-russian-cyber">said</a>.</p><p>“The actors have also demonstrated the ability to maintain persistent, undetected, long-term access in compromised environments — including cloud environments — by using legitimate credentials.”</p><p>Russian APT groups have been historically observed setting their sights on operational technology (OT) and industrial control systems (ICS) with the goal of deploying destructive malware, chief among them being the intrusion campaigns against Ukraine and the U.S. energy sector as well as attacks exploiting trojanized <a href="https://thehackernews.com/2021/12/solarwinds-hackers-targeting-government.html">SolarWinds Orion updates</a> to breach the networks of U.S. government agencies.</p><p>To increase cyber resilience against this threat, the agencies recommend mandating multi-factor authentication for all users, looking out for signs of abnormal activity implying lateral movement, enforcing network segmentation, and keeping operating systems, applications, and firmware up to date.</p><p>“Consider using a centralized patch management system,” the advisory reads. “For OT networks, use a risk-based assessment strategy to determine the OT network assets and zones that should participate in the patch management program.”</p><p>Other recommended best practices are as follows —</p><ul><li>Implement robust log collection and retention</li><li>Require accounts to have strong passwords</li><li>Enable strong spam filters to prevent phishing emails from reaching end-users</li><li>Implement rigorous configuration management programs</li><li>Disable all unnecessary ports and protocols</li><li>Ensure OT hardware is in read-only mode</li></ul><p>Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter <a href="http://tinyletter.com/TheLeanProgrammer">tinyletter.com/TheLeanProgrammer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73a8e477411f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theleanprogrammer/hackers-targeting-critical-infrastructure-73a8e477411f">Hackers Targeting Critical Infrastructure</a> was originally published in <a href="https://medium.com/theleanprogrammer">TheLeanProgrammer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 types of Multi*-Classification]]></title>
            <link>https://medium.com/theleanprogrammer/7-types-of-multi-classification-using-python-71f4ca6034d5?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/71f4ca6034d5</guid>
            <category><![CDATA[machine-learning-python]]></category>
            <category><![CDATA[data-science-pick]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[bobrupakroy]]></category>
            <category><![CDATA[multi-classifications]]></category>
            <dc:creator><![CDATA[Rupak (Bob) Roy - II]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 13:43:27 GMT</pubDate>
            <atom:updated>2023-03-20T05:55:38.032Z</atom:updated>
            <content:encoded><![CDATA[<h4>Inside AI</h4><p>Full guide to knn, logistic, support vector machine, kernel svm, naive bayes, decision tree classification, random forest, Deep Learning and even with Grid Search Multi-Classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r--Xppw_DkpVUeniSTl9mw.jpeg" /></figure><p>As usual,</p><p>Hi! How are you doing? I hope it&#39;s great……</p><p>Today let&#39;s understand and perform all types of classification for Multi-Class/ Multi-Label target variable.</p><p>Let’s get started, we will use a dataset that has 7 types/categories of glass. The dataset is available at UCI <a href="https://archive.ics.uci.edu/ml/datasets/Glass+Identification">https://archive.ics.uci.edu/ml/datasets/Glass+Identification</a></p><p>Number of Attributes: 10 (including an Id#) plus the class attribute</p><p>— all attributes are continuously valued</p><pre>Attribute Information:<br>1. Id number: 1 to 214<br>2. RI: refractive index<br>3. Na: Sodium (unit measurement: weight percent in corresponding oxide, as are attributes 4-10)<br>4. Mg: Magnesium<br>5. Al: Aluminum<br>6. Si: Silicon<br>7. K: Potassium<br>8. Ca: Calcium<br>9. Ba: Barium<br>10. Fe: Iron<br>11. Type of glass: (class attribute)<br>-- 1 building_windows_float_processed<br>-- 2 building_windows_non_float_processed<br>-- 3 vehicle_windows_float_processed<br>-- 4 vehicle_windows_non_float_processed (none in this database)<br>-- 5 containers<br>-- 6 tableware<br>-- 7 headlamps</pre><p><strong>Let’s get started with our commonly used Classification method:</strong></p><p><strong>1.) Logistic Regression then we will use</strong></p><p><strong>2.) Knn</strong></p><p><strong>3.) Support Vector Machine</strong></p><p><strong>4.) Kernel SVM</strong></p><p><strong>5.) Naive Bayes</strong></p><p><strong>6.) Decision Tree Classification</strong></p><p><strong>7.) Random Forest Classification</strong></p><p>Any else Classification? Let me know in the comment below.</p><pre># Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><p>Till here it’s the same as before, load the data then split the data into X and Y where Y is the dependent/target variable 9th column (glass categories) and rest from 0 to 9 are independent variables X</p><blockquote>Note: in python index position of the columns start from 0 and not from 1.</blockquote><p>Then before we will split the data into train &amp; test datasets, we need to check for any categorical imbalance. If one of the categories is way too less than the rest, it&#39;s better to remove the imbalanced category as it means it doesn’t have enough data to learn the cause-effect relationship. In general, I make sure it should least have 5–10% of the total categories.</p><p>After this step, we will transform all the columns(dependent variables) into one standard value/range that will reduce the spread, magnitude of the data points without losing the original meaning of the data.</p><p>It helps the algorithm to compute the data faster and efficiently.</p><pre>#Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#Feature Scaling<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><p>Now it&#39;s time to fit the data with logistic regression and predict with test results.</p><pre>#Fitting Logistic Regression to the Training set<br>from sklearn.linear_model import LogisticRegression<br>classifier = LogisticRegression(random_state = 0)<br>classifier.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred = classifier.predict(X_test)</pre><blockquote>DONE… !!! super easy isn’t it ?</blockquote><p>Let’s compare the predicted results with our original dataset.</p><pre>#We can also compare the actual versus predicted<br>df = pd.DataFrame({&#39;Actual&#39;: y_test.flatten(), &#39;Predicted&#39;: y_pred.flatten()})</pre><pre>df</pre><p>Fatten it helps to represent data in a 1-dimensional array like a list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*W_qMTHUruD6W5HZCl_4Cvw.jpeg" /><figcaption>Actual Vs Predicted</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*HVzrIMGt2hl_xdoBZcDGiA.jpeg" /><figcaption>Multi-Class Confusion Matrix</figcaption></figure><p>What we can understand from this confusion matrix, that 11 data points of class 0 are actually class 0 and detected class 0, 3 data points which is actually class 0 but detected class 1. The same goes for the 2nd row 10 data points are actually class 1 but detected class 0 and 12 data points are actually class 1 and detected correctly class 1 and the list goes on.</p><p>Alright, we have another metric to evaluate the model performance is by <strong>using metrics.accuracy_score</strong></p><pre>#evaluation Metrics<br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))<br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><pre>Accuracy Score: 0.5925925925925926<br>Balanced Accuracy Score: 0.5476190476190476</pre><p>Well, our classifier didn’t work well, no worries! We will try another powerful classifier and see if it improves, but before that let me put all the pieces together in case if you wish to use it as a template.</p><pre>#Logistic Regression</pre><pre>#Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>#Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre>#Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#Feature Scaling<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#Fitting Logistic Regression to the Training set<br>from sklearn.linear_model import LogisticRegression<br>classifier = LogisticRegression(random_state = 0)<br>classifier.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred = classifier.predict(X_test)</pre><pre>#We can also compare the actual versus predicted<br>df = pd.DataFrame({&#39;Actual&#39;: y_test.flatten(), &#39;Predicted&#39;: y_pred.flatten()})<br>df</pre><pre>#Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><pre>#Predict on unseen data<br>classifier.predict([[22,33,44,11,55,11,44,55]])</pre><p>Next is KNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWasHiVtn11iRVTXZRDVYw.jpeg" /></figure><p>What is KNN?</p><p>K-Nearest Neighbors (<strong>KNN</strong>) is one of the simplest algorithms used in <strong>Machine Learning</strong> for regression and classification. <strong>KNN</strong> algorithms classify new data points based on similarity measures (e.g. Euclidean distance function).</p><p>Classification is done by a majority vote to its neighbors (K).</p><figure><img alt="K Nearest Neighbors Plot" src="https://cdn-images-1.medium.com/max/888/1*Y0QWfqolVESaHRXvtqaq5g.jpeg" /><figcaption>K Nearest Neighbors</figcaption></figure><p>Let’s get started on how to apply KNN for Multi-Classification problems.</p><pre>#K-Nearest Neighbors (K-NN)</pre><pre>#Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>#Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br>#Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre>#Check for class imbalance<br>dataset.groupby(y).size()<br>#------------------------------------------------------------<br>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><p>Till here it’s the same as before, load the data, define X and Y, split the data, and then scale the independent variables</p><p>NOW we will fit the KNN to our training data set where K nearest neighbors K =9 , metric = minkowski which helps to measure three-dimensional Euclidean space and p = 2 is the Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2</p><pre># Fitting K-NN to the Training set<br>from sklearn.neighbors import KNeighborsClassifier<br>knn_model = KNeighborsClassifier(n_neighbors = 9, metric = &#39;minkowski&#39;, p = 2)<br>knn_model.fit(X_train, y_train)</pre><p>That’s it!</p><p>Let’s check the model accuracy</p><pre># Predicting the Test set results<br>y_pred = knn_model.predict(X_test)</pre><pre>#Model Evaluation------------------------------------------------------------<br>#We can also compare the actual versus predicted<br>df = pd.DataFrame({&#39;Actual&#39;: y_test.flatten(), &#39;Predicted&#39;: y_pred.flatten()})<br>df</pre><pre># Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><pre>Accuracy Score: 0.5925925925925926<br>Balanced Accuracy Score: 0.3948412698412698</pre><p>Not much!!! Well, we definitely learn how to apply knn for the Multi-Classification problem.</p><p>Here are all the pieces of KNN together</p><pre># K-Nearest Neighbors (K-NN)</pre><pre>#Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>#Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre>#Check for class imbalance<br>dataset.groupby(y).size()<br>#-------------------------------------------------------------------<br>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#Fitting K-NN to the Training set<br>from sklearn.neighbors import KNeighborsClassifier<br>knn_model = KNeighborsClassifier(n_neighbors = 9, metric = &#39;minkowski&#39;, p = 2)<br>knn_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred = knn_model.predict(X_test)</pre><pre>#Model Evaluation--------------------------------------------<br>#We can also compare the actual versus predicted<br>df = pd.DataFrame({&#39;Actual&#39;: y_test.flatten(), &#39;Predicted&#39;: y_pred.flatten()})<br>df</pre><pre>#Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred)) <br>#--------------------------------------</pre><pre>#Predict on unseen data<br>knn_model.predict([[22,33,44,11,55,11,44,55]])</pre><blockquote>Next is SVM an another powerful classifier</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdOHz6vRaVwi4CDqBjt_4g.jpeg" /></figure><p>SUPPORT VECTOR MACHINE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*LiTpHWC00p62TqXdckEXJw.png" /></figure><h3>What is SVM?</h3><p>SVM is a supervised machine learning algorithm that can be used for classification or regression problems</p><p>In <strong><em>brief, the principle working</em></strong> of SVM is to find the nearest data point(either class) with the help of a hyper-plane. This distance is called as <strong>Margin</strong></p><p>SVM is highly preferred by many as it produces significant accuracy with less computation power.</p><blockquote>Lets get understand this with the help of an example.</blockquote><pre>#Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>#Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()</pre><pre>#Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre>#Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#----------------------------------------------------------</pre><pre>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><p>Well till here it’s the same as others. First, we import the data that defined X &amp; Y, Split the data into train and test sets, scale the independent variables to reduce the magnitude of the spread of data points without losing their original meaning.</p><p>It&#39;s time to fit the SVM into the training set.</p><pre>#Fitting SVM to the Training set</pre><pre>from sklearn.svm import SVC<br>svm_model = SVC(kernel = &#39;linear&#39;, random_state = 0)<br>svm_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred = svm_model.predict(X_test)</pre><pre>#We can also compare the actual versus predicted<br>df = pd.DataFrame({&#39;Actual&#39;: y_test.flatten(), &#39;Predicted&#39;: y_pred.flatten()})</pre><pre>df</pre><pre>#Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics<br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))<br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><pre>Output<br>Accuracy Score: 0.6111111111111112<br>Balanced Accuracy Score: 0.5496031746031745</pre><p>Okay, we did improve a bit. I believe the data is way too non-linearly separately. Let’s try another advanced version of SVM called Kernel SVM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHtvYeLkw_2LQikCCrytMg.jpeg" /></figure><p>What is Kernel SVM</p><p>The complexity of Linear svm grows with the size of the dataset. In simple words Kernel SVM ‘rbf’ transforms complex non-linear data to higher dimensional 3D space to separate the data classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*Wdy35SYGzhRGDvmo3Ve4zg.jpeg" /><figcaption>kernel svm helps to transform non-linear data in high dimensional space.</figcaption></figure><figure><img alt="Converting to 3D space. makes it possible to separate the data points" src="https://cdn-images-1.medium.com/max/728/1*MxDls8xP_mqx_fTI3v_oNg.png" /><figcaption>Converting to 3D space. makes it possible to separate the data points</figcaption></figure><p>Usually linear and polynomial kernels are less time-consuming and provide less accuracy than the rbf or Gaussian kernels.</p><blockquote>So, the rule of thumb is: use linear SVMs (or logistic regression) for linear problems, and nonlinear kernels such as the Radial Basis Function kernel for non-linear problems.</blockquote><p>Lets. Compare Linear svm with kernel Radial based svm</p><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre># Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#-----------------------------------------------------------------<br># Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#fearure scale<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><p>Well till here it’s the same things everywhere. Load the data then define X and Y, split the data, and transform to the standard range to reduce the magnitude of data without losing its original meaning.</p><p>Now we will fit the data in both <strong><em>Linear</em></strong> as well as<strong><em> Kernel ‘rbf’ </em></strong>SVM to compare both of them.</p><pre>#Fitting SVM to the Training set<br>from sklearn.svm import SVC<br>svm_model = SVC(kernel = &#39;linear&#39;, random_state = 0)<br>svm_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred = svm_model.predict(X_test)</pre><pre>#Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred)) <br>#------------------------------------------------------------------<br>#Fitting Kernal SVM to the Training set<br>from sklearn.svm import SVC<br>Ksvm_model = SVC(kernel = &#39;rbf&#39;, random_state = 0)<br>Ksvm_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred = Ksvm_model.predict(X_test)</pre><pre>#Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm1 = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*pENHefeLRmdZvA0IehZjPw.jpeg" /><figcaption>Confusion Matrix: Top| cm | Linear SVM, Second cm1| Kernel ‘rbf’ SVM</figcaption></figure><p><strong><em>The confusion matrix</em></strong> of Kernel SVM is performing better in identifying <strong>True Positive</strong> and <strong>True Negative</strong> than Linear SVM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*_OGfneby_Exa_wXjQqAzJg.jpeg" /><figcaption>Evaluation Metrics | First | Linear SVM, Second | Kernel ‘rbf’ SVM</figcaption></figure><p>The accuracy score of our Kernel svm model is better than linear svm</p><blockquote>Hence Kernel SVM performs better than Linear SVM.</blockquote><p>Well, that’s not enough, we have a more powerful classifier.</p><p>Let me put all the codes together for Kernel SVM</p><pre>#Kernal SVM<br># Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre># Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#-----------------------------------------------------<br># Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#feature scale<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#-----------------------------------------------------------------<br># Fitting SVM to the Training set<br>from sklearn.svm import SVC<br>svm_model = SVC(kernel = &#39;linear&#39;, random_state = 0)<br>svm_model.fit(X_train, y_train)</pre><pre># Predicting the Test set results<br>y_pred = svm_model.predict(X_test)</pre><pre># Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><pre>#-----------------------------------------------------------------<br># Fitting Kernal SVM to the Training set<br>from sklearn.svm import SVC<br>Ksvm_model = SVC(kernel = &#39;rbf&#39;, random_state = 0)<br>Ksvm_model.fit(X_train, y_train)</pre><pre># Predicting the Test set results<br>y_pred = Ksvm_model.predict(X_test)</pre><pre># Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm1 = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><p>Next similar to SVM we have Naïve Bayes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRVGgUx8wHyqMe5f1lOf0Q.jpeg" /></figure><p><strong>What is Naive Bayes in short?</strong></p><p>Naïve Bayes classifiers are a family of simple “probabilistic classifiers” based on applying Bayes’ theorem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*mYbKnfxldig8pP7mX7KrCA.png" /><figcaption>Naive Bayes</figcaption></figure><p><em>P</em>(<em>c|x</em>) is the posterior probability of <em>class</em> (<em>target</em>) given <em>predictor</em> (<em>attribute</em>).</p><ul><li><em>P</em>(<em>c</em>) is the prior probability of <em>class</em>.</li><li><em>P</em>(<em>x|c</em>) is the likelihood which is the probability of <em>predictor</em> given <em>class</em>.</li><li><em>P</em>(<em>x</em>) is the prior probability of <em>predictor</em>.</li></ul><p><strong>Likelihood:</strong> How probable is the evidence given that our hypothesis is true.</p><p><strong>Prior:</strong> How probable was our hypothesis before observing the evidence?</p><p><strong>Posterior:</strong> How probable is our hypothesis given the observed evidence?</p><p><strong>Marginal:</strong> How probable is the new evidence under all possible hypotheses?</p><p>It&#39;s a long chapter about how Naive Bayes works. if are you interested to go in-depth further you can visit my other site. However</p><blockquote>In short Naive Bayes uses class of probability method to classify the problem solution.</blockquote><p>Let’s see how can we apply Naïve Bayes in Multi-Classification</p><pre>#Naive Bayes</pre><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre># Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#---------------------------------------------<br># Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#fearure scaling/Normalization<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre># Fitting Naive Bayes to the Training set<br>from sklearn.naive_bayes import GaussianNB<br>NB_model = GaussianNB()<br>NB_model.fit(X_train, y_train)</pre><pre># Predicting the Test set results<br>y_pred2 = NB_model.predict(X_test)</pre><pre># Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm2 = confusion_matrix(y_test, y_pred2)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred2))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*fji5PjBgNeAnwUJqcqFZpw.jpeg" /></figure><p>Naïve Bayes didn’t perform well for this data. And also it makes sense Naïve Bayes is usually good for textual data.</p><p>Well, we have 2 more powerful algorithms to go.</p><p>Let me put all the Naive Bayes codes together</p><pre>#Naive Bayes</pre><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre>#Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#-----------------------------------------------------<br>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#fearure scaling/Normalization<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#Fitting Naive Bayes to the Training set<br>from sklearn.naive_bayes import GaussianNB<br>NB_model = GaussianNB()<br>NB_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred2 = NB_model.predict(X_test)</pre><pre>#Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm2 = confusion_matrix(y_test, y_pred2)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred2))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred2))</pre><p>Next is Decision Trees / Rule-based Classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VteN7Hxp5XL3NJSRnnEbxQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BvFrYY-pG7YTfOtT6x01A.jpeg" /></figure><p><strong>What are Decision Trees?</strong></p><blockquote><strong>Decision Trees are a non-parametric supervised learning method used for both classification and regression tasks. The goal is to create a model that predicts the value of a target variable by learning simple decision rules derived from the data features.</strong></blockquote><p>The decision rules are generally in form of if-then-else statements. The deeper the tree, the more complex the rules and fitter the model.</p><p>A decision tree gives output in a tree-like graph with nodes. Take this graph as an example, beautifully explained.</p><figure><img alt="Decision Trees | Graph Credit ~ TDS" src="https://cdn-images-1.medium.com/max/1000/1*81SBo5YUZDVTODdtmV9d0Q.jpeg" /><figcaption>Decision Trees | Graph Credit ~ TDS</figcaption></figure><p>Let’s get hands-on experience on how to perform Decision trees.</p><pre>#Decision Tree Classification<br>#Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>#Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()</pre><pre>#Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre>#Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#----------------------------------------------------</pre><pre>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#fearure scaling/Normalization<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#Fitting Decision Tree Classification to the Training set<br>from sklearn.tree import DecisionTreeClassifier<br>dt_model = DecisionTreeClassifier(criterion = &#39;entropy&#39;, random_state = 0)<br>dt_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred = dt_model.predict(X_test)</pre><pre>#Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics<br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))<br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><p>So what we got</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*23iBKjuWk0RG3cn7tZVbnQ.jpeg" /><figcaption>Confusion Matrix: Decision Tree</figcaption></figure><p><strong><em>Confusion matrix</em></strong>|Decision Tree is performing better in identifying <strong>True Positives</strong> than Naïve Bayes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*kqnZhZ7nutS44d3hCrb0jw.jpeg" /></figure><p><strong>The accuracy score of our Decision Tree model is better than Naïve Bayes</strong></p><p>Hence Decision Tree is performing better for this non-linearly separable data.</p><p>Wait since decision trees are rule-based classifiers and we can generate rules, <strong>let’s visualize</strong> and see what we go.</p><pre>from sklearn.tree import export_graphviz<br>#export the decision tree to a tree.dot file<br>#for visualizing the plot easily anywhere<br>export_graphviz(dt_model, out_file =&#39;e:/multi-class_tree.dot&#39;,<br>feature_names =[&#39;RI&#39;,&#39;Na&#39;,&#39;Mg&#39;,&#39;Ai&#39;,&#39;Si&#39;,&#39;K&#39;,&#39;Ca&#39;,&#39;Ba&#39;,&#39;Fe&#39;])</pre><p>The tree is finally exported and we can visualize using <a href="http://www.webgraphviz.com/">http://www.webgraphviz.com/</a> by copying the data from the ‘multi-class_tree.dot’ file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgeADz3t2BiBSMv_M-DYmQ.jpeg" /><figcaption>Decision Tree Classification with <a href="http://www.webgraphviz.com/">http://www.webgraphviz.com/</a></figcaption></figure><p>Well, it’s a long list of trees, very difficult to put everything out here. So our classification did perform very well from the previous classifier.</p><p>Next, we have another classifier call Random Forest an upgrade version of Decision Tree Classifier</p><p>Let me put all of the Decision Tree Classifier codes together.</p><pre>#Decision Tree Classification <br># Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre># Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#------------------------------------------------------<br># Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#feature scaling/Normalization<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre># Fitting Decision Tree Classification to the Training set<br>from sklearn.tree import DecisionTreeClassifier<br>dt_model = DecisionTreeClassifier(criterion = &#39;entropy&#39;, random_state = 0)<br>dt_model.fit(X_train, y_train)</pre><pre># Predicting the Test set results<br>y_pred = dt_model.predict(X_test)</pre><pre># Making the Confusion Matrix <br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><pre>#if we wish to enter manually<br>dt_model.predict([[22,33,44,11,55,11,44,55]])</pre><pre>#----------------------------------------------<br>from sklearn.tree import export_graphviz  <br>  # export the decision tree to a tree.dot file <br># for visualizing the plot easily anywhere <br>export_graphviz(dt_model, out_file =&#39;e:/multi-class_tree.dot&#39;, <br>               feature_names =[&#39;RI&#39;,&#39;Na&#39;,&#39;Mg&#39;,&#39;Ai&#39;,&#39;Si&#39;,&#39;K&#39;,&#39;Ca&#39;,&#39;Ba&#39;,&#39;Fe&#39;])</pre><pre>&quot;&quot;&quot;<br>The tree is finally exported and we can visualized using  <br><a href="http://www.webgraphviz.com/">http://www.webgraphviz.com/</a> by copying the data from the ‘tree.dot’ file.&quot;&quot;&quot;</pre><p><strong>Next RANDOM FOREST</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLd3jZ3rVFVlUKwpAsKKfw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFKTirgY925tA5JHqJgaFQ.jpeg" /></figure><p>What is a random forest?</p><p>Random Forest is the upgrade version of decision trees. The name itself refers it consists of a large number of individual decision trees that operate as an ensemble. Thus we are combining the predictive power of several decision trees to give more accuracy.</p><figure><img alt="Random Forest Graphical Representation" src="https://cdn-images-1.medium.com/max/931/1*FppcDTwT3bwQwK0FIuecDw.jpeg" /><figcaption>Random Forest Graphical Representation</figcaption></figure><p>Let’s get started with the help of an example</p><pre>#Random Forest Classification</pre><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre># Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#---------------------------------------------------------<br># Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#feature scaling/Normalization<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><p>Till here it’s the same basic data pre-processing step from loading the data, defining X &amp; Y, splitting the data into train, and test to data normalization/scaling to reduce the magnitude of the spread of data points.</p><p>Now we will fit the random forest into the dataset. Also, we will do for decision tree so that later we can compare the performance.</p><pre>#Fitting Decision Tree Classification to the Training set<br>from sklearn.tree import DecisionTreeClassifier<br>dt_model = DecisionTreeClassifier(criterion = &#39;entropy&#39;, random_state = 0)<br>dt_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred = dt_model.predict(X_test)</pre><pre>#Making the Confusion Matrix <br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)<br> <br>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred)) <br>#------------------------------------</pre><pre>#Fitting Random Forest Classification to the Training set<br>from sklearn.ensemble import RandomForestClassifier<br>rf_model = RandomForestClassifier(n_estimators = 800, criterion = &#39;entropy&#39;, random_state = 0)<br>rf_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred2 = rf_model.predict(X_test)</pre><pre># Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm2 = confusion_matrix(y_test, y_pred2)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred2))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*d2bUrxadM0ea5HBswtfUKg.jpeg" /></figure><p>Well, we did increase the Balanced Accuracy by 4% with the default random forest settings.</p><p>Now to know the best settings it is not possible to try each and every setting one by one, it’s a tedious and time-consuming process and not very productive. For that, we have an automated process to find the best optimal settings for each classifier is called GRID SEARCH. But before we move ahead with Grid Search let me put all the pieces of Random Forest together so that later you can use it as a template.</p><pre>#Random Forest Classification</pre><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre># Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#-----------------------------------------------------------------------------------------------<br># Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#feature scaling/Normalization<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#-------------------------------------------------------------------------------------------------</pre><pre># Fitting Decision Tree Classification to the Training set<br>from sklearn.tree import DecisionTreeClassifier<br>dt_model = DecisionTreeClassifier(criterion = &#39;entropy&#39;, random_state = 0)<br>dt_model.fit(X_train, y_train)</pre><pre># Predicting the Test set results<br>y_pred = dt_model.predict(X_test)</pre><pre># Making the Confusion Matrix <br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)<br> <br>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred))</pre><pre>#---------------------------------------------------------</pre><pre># Fitting Random Forest Classification to the Training set<br>from sklearn.ensemble import RandomForestClassifier<br>rf_model = RandomForestClassifier(n_estimators = 700, criterion = &#39;entropy&#39;, random_state = 0)<br>rf_model.fit(X_train, y_train)</pre><pre># Predicting the Test set results<br>y_pred2 = rf_model.predict(X_test)</pre><pre># Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm2 = confusion_matrix(y_test, y_pred2)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred2))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred2))</pre><blockquote>Next Grid Search</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SQE4A3EVsC9uhHQa3BqhA.jpeg" /></figure><h3>Grid Search</h3><p>Finding the best parameters by manual tuning is a tedious process and time-consuming as it contains so many parameters to be tested over and over again. Well, it’s time-consuming and not productive. So to overcome this issue we will look into a method <strong>‘GRID SEARCH’</strong> to automate the task of finding the best model parameters for us.</p><p>We will divide this into 2 sections: <strong>a) Grid Search for finding the best hyperparameters for our machine learning model b.) Grid Search for Deep Learning models.</strong></p><p>Let’s start with <strong><em>a) Grid Search for machine learning models</em></strong></p><pre>#Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>#Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()</pre><pre>#Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><p>Then we will split the data into train and test, scale our data before we fit our model. For this example, we will use Random Forest Classifier (RF) which now has the highest accuracy score with default parameters.</p><p>To automate the search of the best parameters of our Random Forest Model.</p><pre># Fitting Random Forest Classification to the Training set</pre><pre>from sklearn.ensemble import RandomForestClassifier<br>rf_model = RandomForestClassifier(n_estimators = 500, criterion = &#39;entropy&#39;, random_state = 1)<br>rf_model.fit(X_train, y_train)</pre><pre>#Applying Grid Search to find the best model and the best parameters<br>from sklearn.model_selection import GridSearchCV<br>parameters = [{ &#39;n_estimators&#39;: [500,1000,1500,2000]}]</pre><pre>grid_search = GridSearchCV(estimator = rf_model,<br>param_grid = parameters,scoring = &#39;accuracy&#39;,cv = 7)<br>grid_search = grid_search.fit(X_train, y_train)</pre><pre>best_accuracy = grid_search.best_score_<br>best_parameters = grid_search.best_params_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*az398Sh6b4x-ooRl4kWgMQ.jpeg" /></figure><p>And what we have…….. Best Parameters for n_estimators: 1500</p><p>Okay, let’s try out with n_estimators and see if it improves our model.</p><pre>#Lets retry our model with the new paramters<br># Fitting Random Forest Classification to the Training set<br>from sklearn.ensemble import RandomForestClassifier<br>rf_model = RandomForestClassifier(n_estimators = 1700, criterion = &#39;entropy&#39;, random_state = 1)<br>rf_model.fit(X_train, y_train)</pre><pre># Predicting the Test set results<br>y_pred2 = rf_model.predict(X_test)</pre><pre># Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm2 = confusion_matrix(y_test, y_pred2)</pre><pre>#evaluation Metrics <br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred2))  <br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*HZjo5XIP7FNAByeH3QS2yQ.jpeg" /></figure><p>Nice! It did improve from <strong><em>0.70 to 0.72</em></strong>. You can use these codes as a template with a few modifications like the list of parameters for different types of classifiers and to know the parameters you can simply select the classifier name <strong>‘svm’ + press ‘ctrl’ + ‘i’</strong></p><p>Let’s me put all of the pieces together.</p><pre>#Importing the libraries<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>#Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()</pre><pre>#Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre>#Check for class imbalance<br>dataset.groupby(y).size()</pre><pre>#-----------------------------------------------------------</pre><pre>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)</pre><pre>#feature scale<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#Applying Grid Search to find the best model and the best parameters</pre><pre>from sklearn.model_selection import GridSearchCV<br>parameters = [{ &#39;n_estimators&#39;: [500,1000,1500,2000]}]</pre><pre>grid_search = GridSearchCV(estimator = rf_model,</pre><pre>param_grid = parameters,scoring = &#39;accuracy&#39;,cv = 7)</pre><pre>grid_search = grid_search.fit(X_train, y_train)</pre><pre>best_accuracy = grid_search.best_score_<br>best_parameters = grid_search.best_params_</pre><pre>###########################################################</pre><pre>#Lets retry our model with the new parameters<br>#Fitting Random Forest Classification to the Training set<br>from sklearn.ensemble import RandomForestClassifier<br>rf_model = RandomForestClassifier(n_estimators = 1700, criterion = &#39;entropy&#39;, random_state = 1)<br>rf_model.fit(X_train, y_train)</pre><pre>#Predicting the Test set results<br>y_pred2 = rf_model.predict(X_test)</pre><pre>#Making the Confusion Matrix<br>from sklearn.metrics import confusion_matrix<br>cm2 = confusion_matrix(y_test, y_pred2)</pre><pre>#evaluation Metrics<br>from sklearn import metrics<br>print(&#39;Accuracy Score:&#39;, metrics.accuracy_score(y_test, y_pred2))<br>print(&#39;Balanced Accuracy Score:&#39;, metrics.balanced_accuracy_score(y_test, y_pred2))</pre><p>Still not that satisfied with the accuracy level, isn’t it? have you tried the next-generation machine learning technique? Deep Learning.</p><p>So what are we waiting for, let’s try it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWasHiVtn11iRVTXZRDVYw.jpeg" /></figure><p>I believe you are already aware of how Neural Networks work if not…don’t worry,, there are plenty of resources available on the web to get started with. However, I will too walk you through in brief what is neuron networks and how it learns?</p><figure><img alt="Parts Of Neuron" src="https://cdn-images-1.medium.com/max/800/1*J7IkqMHhOjaga0WWbC9DIA.jpeg" /><figcaption>Parts Of Neuron</figcaption></figure><p>In this diagram/photo, Dendrites are the receivers of the neuron while Axom is the transmitter of neuron signal.</p><h3>What is a neuron?</h3><p><strong>In Artificial Intelligence Neuron</strong> is a mathematical function that models the functioning of a biological <strong>neuron</strong>. Typically, a <strong>neuron</strong> computes the weighted average of its input, and this sum is passed through a nonlinear function, also called as activation function, such as the sigmoid, Relu</p><p>Now if we put this in a flow diagram it will look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*bvGxacDBssy78fq0WNKt5w.png" /><figcaption>Simple Neuron Network Diagram</figcaption></figure><p>In real off-course we gonna have larger and more complex neuronal networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3AZj6pqDkBtU5xhVwm4yg.jpeg" /><figcaption>Multi-layer Neuron Network</figcaption></figure><p><strong>How does it learn?</strong></p><p>When they go process data back and forth (also known as backpropagation). They create weights to save the optimized parameter settings over n over again that gives less error/loss inaccuracy. Once it reaches the point where further calculation doesn’t give any improvement over preceding accuracy, the parameter settings are saved as weights. Now there are different types of methods to minimize the loss inaccuracy. One of them is the Gradient Descent.</p><blockquote><em>Gradient Descent is an optimized algorithm often used for finding weights.</em></blockquote><h3>Types of Gradient Descent</h3><p>1. <strong>Batch Gradient Descent:</strong> it calculates the error for each example in the training dataset <strong><em>but only updates the model after all training examples have been evaluated.</em></strong> In other words, it takes the whole data and adjusts weights with iterations &amp; iterations.</p><p><strong>Pros:</strong></p><p>a) Fewer updates to the model means this variant of gradient descent is<strong><em> more computationally efficient</em></strong> than stochastic gradient descent.</p><p>b) And with the decreased update frequency results in a more stable error gradient and that may result in more <strong><em>stable convergence</em></strong>.</p><p><strong>Cons:</strong></p><p>a.) However <strong><em>stable error may result in premature convergence</em></strong> of the model to a less optimal set of parameters.</p><p>b.) It is implemented in such a way that it <strong><em>requires the entire training set in memory</em></strong> and is available to the algorithm. Thus with respect to training speed, may become slow for a large dataset.</p><p>2. <strong>Stochastic Gradient Descent </strong>calculates the error and updates the model for each example in the training dataset.</p><p>In other words: <strong><em>one row at a time,</em></strong> adjust the weights with iterations. Helps to avoid the local minimum rather than the global minimum and it&#39;s faster.</p><p><strong>Pros:</strong></p><p>a.) This variant is simpler to understand and implement for beginners</p><p>b.) The <strong><em>frequent updates immediately give an insight into the performance</em></strong> of the model and the rate of improvement.</p><p>c.) The increased model update frequency one row at a time can result in <strong><em>faster learning </em></strong>on some problems.</p><p><strong>Cons:</strong></p><p>a.) However updating the model so frequently is <strong><em>computationally expensive </em></strong>than others variants of gradient descent, especially train models on a large dataset.</p><p>b.) But the frequent updates can result in a noisy gradient signal which may cause the model parameters and in turn the model error to jump around.</p><p>3. <strong>Mini-Batch Gradient Descent:</strong> is a variation of the gradient descent algorithm that splits the training set into small batches that are used to calculate model error and update model co-efficient.</p><p>Mini-batch gradient descent seeks to find a <strong><em>balance between the robustness of stochastic gradient descent and the efficiency of batch gradient descent.</em></strong></p><p><strong>Pros:</strong></p><p>a.) The model update frequency is higher than batch gradient descent which allows for a more robust convergence and avoiding local minima.</p><p>b.) The batch updates <strong><em>provide a computationally more efficient process </em></strong>than stochastic gradient descent.</p><p>c.) The batching allows both the efficiency of <strong><em>not having all the training data in memory</em></strong> and algorithm implementation.</p><p><strong>Cons:</strong></p><p>a.) Mini-batch requires the configuration of an additional<strong><em> ‘mini-batch’ size hyperparameter for the learning algorithm.</em></strong></p><p>b.) Error information must be accumulated across mini-batches of training examples like batch gradient descent Thus requiring high computational power.</p><blockquote>THE MOST COMMONLY USED OPTIMIZER IN DEEP LEARNING is ADAM, an another optimized algorithm.</blockquote><p>NOW Since we have an idea of how Neural networks work. Let’s get started with a real-life example.</p><p>First, we will import the data and the libraries as go.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>#Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()</pre><pre>#Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre>#Check for class imbalance<br>dataset.groupby(y).size()</pre><p>Then as usual define what is X and what is Y. I have also added groupby(y).size() to check any imbalance classes.</p><p>Now the interesting and the most important part to performing multi-classification in deep learning is to encode the target variable (y) that converts each category into a dummy variable to classify each category ……done that’s it!</p><pre>#encode class values as integers<br>from sklearn.preprocessing import LabelEncoder<br>encoder = LabelEncoder()<br>encoder.fit(y)<br>encoded_Y = encoder.transform(y)</pre><pre>from keras.utils import np_utils<br>#convert integers to dummy variables (i.e. one hot encoded)<br>dummy_y = np_utils.to_categorical(y)</pre><p>We will split the data into train and test set as usual and one more simple and super fast step we have to do is split the dataset into training and test dataset for the ANN to learn and test then we have to do Feature scaling to bring the magnitude into a small range that will help to reduce the workload in ANN without compromising the original meaning of the data.</p><blockquote>Thus scaling doesn’t add any noise neither loses the original meaning of the data.</blockquote><pre>#fix random seed for reproducibility<br>seed = 7</pre><pre>#Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, Y_train, Y_test = train_test_split(X, dummy_y, test_size=0.33, random_state=seed)</pre><pre>#fearure scaling/Normalization<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><p># AND WE ARE DONE WITH THE DATA PREPARATION !!!!!!!!!</p><h3>#LET’s START THE FUN PART- CREATING A NEURAL NETWORK!!!</h3><pre>#Create ANN<br>from keras.models import Sequential<br>from keras.layers import Dense<br>from keras.wrappers.scikit_learn import KerasClassifier</pre><pre>from sklearn.model_selection import cross_val_score<br>from sklearn.model_selection import KFold<br>from sklearn.pipeline import Pipeline</pre><p>#a small note on Keras and TensorFlow BUZZ word that we hear all the time.</p><p><strong><em>TensorFlow</em></strong> is an end-to-end open-source platform. It’s a comprehensive and flexible ecosystem of tools, libraries, and other resources that provide workflows with high-level APIs.</p><p><strong>Keras</strong>, on the other hand, is a high-level neural networks library that is running on top of TensorFlow, CNTK, and Theano. Using Keras in deep learning allows developers to easily build neural networks without worrying much about the mathematical aspects of tensor algebra, numerical techniques, and optimization methods. Keras was developed with the objective of allowing people to write their own scripts without having to learn the backend in detail.</p><h3>Let’s Get Back To The Track!</h3><pre>#define baseline model<br>def baseline_model():</pre><pre>#create model<br>model = Sequential()<br>model.add(Dense(30, input_dim=8, activation=&#39;relu&#39;))<br>model.add(Dense(8, activation=&#39;softmax&#39;))</pre><pre>#Compile model<br>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><pre>return model</pre><pre>estimator.fit(X_train,Y_train)<br>estimator.predict(X_test)<br>predictions = estimator.predict(X_test)<br>print(predictions)</pre><p># we will add and connect layers using .add and DENSE with units = 30 hmmm..! what does that 30 means?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*AfM3Zx4HOTqTyuDhpssbUg.jpeg" /></figure><p>30 refers to a number of nodes/neurons in the layer, usually, we choose half of the number of columns(variables) we have in our dataset.</p><p>Next, we have <strong><em>kernel _initializer = ‘uniform’ </em></strong>where uniform is a function to initialize the weights for Stochastic gradient descent or any other optimizer like ‘ADAM’ What is an optimizer? we will get to the part in a few seconds.</p><p><strong><em>Activation = ‘relu’</em></strong> stands for the rectified linear unit is the rectifier to create and measure the non-linearity.</p><p>Relu is linear for all positive values and zeroes for all negative values. The downside for being zero for all negative values is a problem called “dying RELU” . a Relu neuron is “dead” if it’s stuck on the negative side and always outputs 0. The dying problem is likely to occur when the learning rate is too high or there is a large negative bias. ‘Leaky ReLU’ and ‘ELU’ are also good alternatives to try. Other variants include ReLU-6, Concatenated ReLU(CReLU), Exponential Linear(ELU,SELU), Parametric ReLU.</p><p>Last one is <strong><em>‘input_dim’</em></strong> simply refers to the number of columns(input dimensions)</p><p>Further, we will add a second layer the same way we did above, the only difference is we don’t need to add “input_dim” becoz it will learn itself from the first layer the input dimensions value is 30</p><p><strong><em>Activation ‘relu’</em> </strong>is used for regression output and</p><p><strong><em>Activation ‘softmax’</em> </strong>function used when we need multi-class classification output with a Dense value 8 means it has 8 classes.</p><pre>#compile model<br>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><p>This function is actually used to compile all the layers in other words calculate weights(settings) in the neural network.</p><p><strong><em>Optimizer = ‘adam” </em></strong>just like Stochastic Gradient Descent (SGD) optimizes the algorithm to find the optimal set of weights in neural networks using pre-defined kernel_initializer =”uniform” that we set a while ago.</p><p><strong><em>Loss = ‘binary_crossentropy’</em></strong> is the function used to calculate the loss in accuracy for the <strong><em>Classification </em></strong>problem, for <em>Regression </em>its <em>RMSE (Root Mean Square Error) for Multi-class we use loss = ‘categorical _cros entropy’</em></p><p><strong><em>Metric== [‘accuracy’]</em></strong> is again another function to display the accuracy of the model.</p><pre>estimator = KerasClassifier(build_fn=baseline_model, epochs=350, batch_size=1, verbose=1)</pre><p>Finally, we will use our model function with wrapper function ‘KerasClassifier where<strong> ‘build_fn’</strong> refers to the model function,<strong> epochs = 350</strong> refers a number of iteration that will be used to train the model, <strong>batch_size = 1</strong> refers to the data batch size to be used at a time to train our model, <strong>verbose = 1</strong> it just displays the process during the training of our model.</p><p>It&#39;s time to fit out the model with X_train and y_train..done!</p><pre>estimator.fit(X_train,Y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*HIzpRZcophPvY4WEZl6RdQ.jpeg" /></figure><p>Wow now we have an accuracy of 99% The highest of all, that’s why deep learning is very famous for non-linearly separable data. However, tuning deep learning models can be a bit difficult as it has lots of parameters to tune but we can also use GRID Search to automate and find the best optimal parameters for us for each case scenario. Search for Grid Search from my profile if wish to see in detail ‘how to use Grid Search for Deep Learning.</p><p>Our model is ready to predict new data.</p><pre>estimator.predict(X_test)<br>predictions = estimator.predict(X_test)<br>print(predictions)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*l6p3e3dixAJ3ks4PdJi0dQ.jpeg" /></figure><p>The values from 1 to 7 are the predictions of classes</p><p>Done.. we can also use Kfold to cross-validate our model</p><pre>kfold = KFold(n_splits=20, shuffle=True)<br>results = cross_val_score(estimator, X_train, Y_train, cv=kfold)<br>print(&quot;Baseline: %.2f%% (%.2f%%)&quot; % (results.mean()*100, results.std()*100))</pre><p>The whole code will look something like this.</p><pre>#ANN</pre><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;glass.data&#39;, header = None,index_col = 0)</pre><pre>#drop the missing values<br>dataset = dataset.dropna()<br># Statistical summary of the variables<br>dataset.describe()</pre><pre>X = dataset.iloc[:,0:9].values<br>y = dataset.iloc[:, 9].values</pre><pre># Check for class imbalance<br>dataset.groupby(y).size()</pre><pre># encode class values as integers<br>from sklearn.preprocessing import LabelEncoder<br>encoder = LabelEncoder()<br>encoder.fit(y)<br>encoded_Y = encoder.transform(y)</pre><pre>from keras.utils import np_utils<br># convert integers to dummy variables (i.e. one hot encoded)<br>dummy_y = np_utils.to_categorical(y)</pre><pre># fix random seed for reproducibility<br>seed = 7</pre><pre># Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, Y_train, Y_test = train_test_split(X, dummy_y, test_size=0.33, random_state=seed)</pre><pre>#fearure scaling/Normalization<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#Create ANN<br>from keras.models import Sequential<br>from keras.layers import Dense<br>from keras.wrappers.scikit_learn import KerasClassifier</pre><pre>from sklearn.model_selection import cross_val_score<br>from sklearn.model_selection import KFold<br>from sklearn.pipeline import Pipeline</pre><pre>#define baseline model<br>def baseline_model():<br> # create model<br> model = Sequential()<br> model.add(Dense(30, input_dim=8, activation=&#39;relu&#39;))<br> model.add(Dense(8, activation=&#39;softmax&#39;))<br> # Compile model<br> model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br> return model<br> <br>estimator = KerasClassifier(build_fn=baseline_model, epochs=350, batch_size=1, verbose=1)</pre><pre>estimator.fit(X_train,Y_train)</pre><pre>estimator.predict(X_test)<br>predictions = estimator.predict(X_test)<br>print(predictions)</pre><pre>#-----------------------------------------------------<br>kfold = KFold(n_splits=20, shuffle=True)<br>results = cross_val_score(estimator, X_train, Y_train, cv=kfold)<br>print(&quot;Baseline: %.2f%% (%.2f%%)&quot; % (results.mean()*100, results.std()*100))</pre><p>Congratulations! we have completed all. It&#39;s a long blog, I tried to keep it as short as possible keeping the important concepts intact.</p><p>I hope you have enjoyed</p><p>Feel Free to ask because <strong>“Curiosity Leads To Perfection”</strong></p><p><strong>Some of my alternative internet presences are</strong> <a href="https://www.facebook.com/rupakroybob">Facebook</a>, <a href="https://www.instagram.com/bobrupak/">Instagram</a>, <a href="https://www.udemy.com/course/ai-master-class">Udemy</a>, Blogger, Issuu, and more.</p><p>Also available on Quora @ <a href="https://www.quora.com/profile/Rupak-Bob-Roy">https://www.quora.com/profile/Rupak-Bob-Roy</a></p><p>Stay tuned for more updates.! have a good day….</p><figure><img alt="https://www.quora.com/profile/Rupak-Bob-Roy" src="https://cdn-images-1.medium.com/max/1024/1*gfPIy2ojh9kAO9_6-I_EBA.jpeg" /><figcaption><a href="https://www.quora.com/profile/Rupak-Bob-Roy">https://www.quora.com/profile/Rupak-Bob-Roy</a></figcaption></figure><h3>~ Be Happy and Enjoy!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJteR7R65t_02wfJ_rCyog.jpeg" /><figcaption>pexel</figcaption></figure><p>Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter <a href="http://tinyletter.com/TheLeanProgrammer">tinyletter.com/TheLeanProgrammer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71f4ca6034d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theleanprogrammer/7-types-of-multi-classification-using-python-71f4ca6034d5">7 types of Multi*-Classification</a> was originally published in <a href="https://medium.com/theleanprogrammer">TheLeanProgrammer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[App Storage Options]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/theleanprogrammer/all-types-of-storage-you-can-use-in-your-android-kotlin-app-dd2163eded30?source=rss----a0ec77e9cd3---4"><img src="https://cdn-images-1.medium.com/max/1400/1*HBYbSW6AtRwrcCPKI5_ifA.png" width="1400"></a></p><p class="medium-feed-snippet">Best Memory Option For Android/KOTLIN</p><p class="medium-feed-link"><a href="https://medium.com/theleanprogrammer/all-types-of-storage-you-can-use-in-your-android-kotlin-app-dd2163eded30?source=rss----a0ec77e9cd3---4">Continue reading on TheLeanProgrammer »</a></p></div>]]></description>
            <link>https://medium.com/theleanprogrammer/all-types-of-storage-you-can-use-in-your-android-kotlin-app-dd2163eded30?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/dd2163eded30</guid>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <dc:creator><![CDATA[Sumeet Bhalla]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 13:39:31 GMT</pubDate>
            <atom:updated>2022-02-05T13:39:30.942Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Get rid of falsy values from Array]]></title>
            <link>https://medium.com/theleanprogrammer/get-rid-of-falsy-values-from-array-26e3dea24fe4?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/26e3dea24fe4</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Harsha]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 13:29:35 GMT</pubDate>
            <atom:updated>2023-05-19T06:23:18.458Z</atom:updated>
            <content:encoded><![CDATA[<h4>Falsy Values In Javascript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-foxOEKTSjD_WzeHjiBqgQ.png" /></figure><p>Thinking what are falsy values?</p><p>Well, A <strong>falsy</strong> <strong>value</strong> is a <strong>value</strong> that is considered false when encountered in a Boolean context.</p><p>In javascript falsy values are</p><blockquote>1. null</blockquote><blockquote>2. undefined</blockquote><blockquote>3. NaN</blockquote><blockquote>4. 0</blockquote><blockquote>5. -0</blockquote><blockquote>6. 0n (BigInt zero)</blockquote><blockquote>7. false</blockquote><blockquote>8. “” (empty string)</blockquote><p>Easiest way to remove these falsy values from Array is to use filter method with Boolean function.</p><p>Suppose Array is</p><p>myArray =[1, true, NaN, null, ‘hello’, 0, 78, {}, undefined,’’,false, ‘truthy’];</p><p>let <strong>newArray = myArray.filter(Boolean)</strong></p><p>newArray will be [1, true, ’hello’, 78, {}, ‘truthy’];</p><p>Isn’t that easy?</p><p>Happy learning!!!</p><p>Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter <a href="http://tinyletter.com/TheLeanProgrammer">tinyletter.com/TheLeanProgrammer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26e3dea24fe4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theleanprogrammer/get-rid-of-falsy-values-from-array-26e3dea24fe4">Get rid of falsy values from Array</a> was originally published in <a href="https://medium.com/theleanprogrammer">TheLeanProgrammer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Chrome Extension ?]]></title>
            <link>https://medium.com/theleanprogrammer/how-to-build-a-chrome-extension-b13582281c61?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/b13582281c61</guid>
            <category><![CDATA[google-chrome]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[google-chrome-extensions]]></category>
            <dc:creator><![CDATA[Vaidhyanathan S M]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 07:04:35 GMT</pubDate>
            <atom:updated>2022-01-03T07:04:35.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building A Chrome Extension</h3><h4>Step By Step Guide With Prerequisites</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iHt7q6edhWcJpYw_AsSPg.png" /></figure><p>In this article, we are going to look at How to Build a Google Chrome Extension. It is very simple to create one and the only prerequisites are that you need to know basic HTML, CSS, and JavaScript.</p><p>We are going to create a Social Profile Launcher Extension. With this, we can quickly launch our social profile links in just one click. First of all, Let’s create a new project folder and name it “social_profile_launcher”. So, the folder structure is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*JJNPuDjXDmy2bTxbKMjMtg.png" /><figcaption>Project Folder Structure</figcaption></figure><p>We have an images folder that contains an image in its original size. In the project’s root folder, we have the same images reduced to 128 x 128 pixels and 19 x 19 pixels. Next, we have a manifest.json file. Every extension has this JSON formatted manifest file that provides important information about the extension. And then, we have an HTML and JS file.</p><p>Now, let’s start with the manifest.json file. This is the JSON formatted file that’s going to contain all the necessary information regarding the extension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/284c637bcc917b0ffb3d394a8053a7cd/href">https://medium.com/media/284c637bcc917b0ffb3d394a8053a7cd/href</a></iframe><p>The activeTab permission gives temporary access to the currently active tab when the user invokes the extension. Access to the tab lasts while the user is on that page, and is revoked when the user navigates away or closes the tab.</p><p>Now that we are done with the manifest.json file, let’s move on to popup.html file, which is going to be the landing page when the user clicks on the launcher icon.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f49d33b65a4432c47cffaf0015688f19/href">https://medium.com/media/f49d33b65a4432c47cffaf0015688f19/href</a></iframe><p>As you can see above, we have the popup.js file here. We won’t be using it in our project, but if you were to add some functionality, you can very well do so.</p><p>Now, head over to “Manage Extensions”. Make sure “Developer Mode” is enabled. Then click on “Load Unpacked” on the top left and select the project folder. Now, the icon of our extension will be visible on the top right once you pin it. So, that’s it. We have created the chrome extension successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*oCDc5shO8H3NwLmq2zloZA.png" /><figcaption>Social Profile Launcher</figcaption></figure><p>We come to the end of this tutorial. Thanks for reading! Happy Coding!</p><p>If you have any queries please post in the <strong>comment</strong> section below. Connect with me on <a href="https://www.linkedin.com/in/vaidhyanathansm/">LinkedIn</a>. Also, if you want to look at my amazing collection of apps developed, don’t forget to check <a href="https://play.google.com/store/apps/developer?id=Programmers+Gateway">Google Play Store</a>.</p><p>Know more about me <a href="http://vaidhyanathansm.netlify.app/">here</a>.</p><p>Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter <a href="http://tinyletter.com/TheLeanProgrammer">tinyletter.com/TheLeanProgrammer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b13582281c61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theleanprogrammer/how-to-build-a-chrome-extension-b13582281c61">How to Build a Chrome Extension ?</a> was originally published in <a href="https://medium.com/theleanprogrammer">TheLeanProgrammer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Libraries For Data Scientists]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/theleanprogrammer/python-libraries-for-data-scientists-4ae71ea35554?source=rss----a0ec77e9cd3---4"><img src="https://cdn-images-1.medium.com/max/1400/1*gvbbDXYeaFMPOh0yuReU9Q.png" width="1400"></a></p><p class="medium-feed-snippet">14 Python Libraries which Data Scientists use less to None</p><p class="medium-feed-link"><a href="https://medium.com/theleanprogrammer/python-libraries-for-data-scientists-4ae71ea35554?source=rss----a0ec77e9cd3---4">Continue reading on TheLeanProgrammer »</a></p></div>]]></description>
            <link>https://medium.com/theleanprogrammer/python-libraries-for-data-scientists-4ae71ea35554?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/4ae71ea35554</guid>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[14-python-libraries]]></category>
            <category><![CDATA[data-scientist]]></category>
            <dc:creator><![CDATA[Mohsin Raza]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 06:52:15 GMT</pubDate>
            <atom:updated>2022-01-03T06:52:14.992Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[JS |Minimum swaps to get together 1’s]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/theleanprogrammer/js-ds-minimum-swaps-to-get-together-1s-amazon-interview-question-c24c4806e4d7?source=rss----a0ec77e9cd3---4"><img src="https://cdn-images-1.medium.com/max/1400/1*SeCRNHnC7cZB0I9jnsWzzg.png" width="1400"></a></p><p class="medium-feed-snippet">Amazon Interview Question</p><p class="medium-feed-link"><a href="https://medium.com/theleanprogrammer/js-ds-minimum-swaps-to-get-together-1s-amazon-interview-question-c24c4806e4d7?source=rss----a0ec77e9cd3---4">Continue reading on TheLeanProgrammer »</a></p></div>]]></description>
            <link>https://medium.com/theleanprogrammer/js-ds-minimum-swaps-to-get-together-1s-amazon-interview-question-c24c4806e4d7?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/c24c4806e4d7</guid>
            <dc:creator><![CDATA[Sonika | @Walmart | Frontend Developer | 11 Years]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 06:51:28 GMT</pubDate>
            <atom:updated>2022-01-03T06:51:28.241Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Longest Substring with K Distinct Characters]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/theleanprogrammer/js-longest-substring-with-k-distinct-characters-sliding-window-technique-7585a0d34ee4?source=rss----a0ec77e9cd3---4"><img src="https://cdn-images-1.medium.com/max/1400/1*Nx_R0Ui3f8Je1Jc0XPtQ0g.png" width="1400"></a></p><p class="medium-feed-snippet">JS|Sliding Window Technique</p><p class="medium-feed-link"><a href="https://medium.com/theleanprogrammer/js-longest-substring-with-k-distinct-characters-sliding-window-technique-7585a0d34ee4?source=rss----a0ec77e9cd3---4">Continue reading on TheLeanProgrammer »</a></p></div>]]></description>
            <link>https://medium.com/theleanprogrammer/js-longest-substring-with-k-distinct-characters-sliding-window-technique-7585a0d34ee4?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/7585a0d34ee4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Sonika | @Walmart | Frontend Developer | 11 Years]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 06:48:31 GMT</pubDate>
            <atom:updated>2024-08-25T06:41:25.568Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[PSA:The Risks of Remote JDWP Debugging]]></title>
            <link>https://medium.com/theleanprogrammer/psa-the-risks-of-remote-jdwp-debugging-732ebbff4ad7?source=rss----a0ec77e9cd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/732ebbff4ad7</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Shai Almog]]></dc:creator>
            <pubDate>Sat, 06 Nov 2021 09:14:00 GMT</pubDate>
            <atom:updated>2021-11-06T09:14:25.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>PSA</h3><h4>The Risks of Remote JDWP Debugging</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZtLPG45Zwd9GOVMBpL5mg.png" /></figure><p>When I teach or lecture and mention security I always love the analogy of security as an Onion. This is a common cliché yet it’s still a powerful analogy for people who are new to the concepts. The equivalent analogy I would pick for remote debugging is like leaving your front door open with all your valuables piled in easy-to-spot and well-labeled boxes. Calling JDWP insecure doesn’t make any sense. It wasn’t designed to be secure so it isn’t…</p><p>Java Debug Wire Protocol (AKA JDWP) was designed for testing internally. Over the past few years, I’ve run into quite a few individuals that made the mistake of leaving it on even in production!</p><p>That’s INSANE!</p><p>Even internally it’s a HUGE risk with <a href="https://www.idwatchdog.com/insider-threats-and-data-breaches/">60% of breaches originating from inside the organization</a>. Well…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*7O2UNmMckcuv1wjx.jpeg" /></figure><p>This isn’t just a security risk, that could essentially give every hacker the “keys” to your server and full access to your server code… It’s also a serious stability hazard that could easily crash your production servers.</p><p>Even for staging, this is a problematic case. Staging servers are sometimes exposed to the internet but might serve as a stepping stone to the internal servers (e.g. same host so they slide under the firewall rule). Hackers can easily “hop” into the “real” servers once they are able to hack (or enter an open door really) the remote debug protocol.</p><p>Before I proceed I’d like to clarify my bias: I work for <a href="https://lightrun.com/">Lightrun</a>. We implement a tool that in many respects is a replacement for a debugger designed to work securely in staging and production. Still, you should read this even if you have no intention of using Lightrun since the facts I list below are still applicable to anyone using remote debugging.</p><p>Another thing I’d like to point out is that I’m not a security expert. I did read a few excellent articles on the subject from security experts such as <a href="https://blog.aquasec.com/jdwp-misconfiguration-container-images">Assaf Morag</a> . I think they are great if you’re a security researcher or a DevOps. This article focuses on the perspective of developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PFZnpcA4uZYHK3FGu7npA.jpeg" /></figure><p>Notice you don’t need to be a security expert to understand these concepts and inherent flaws. In that sense, this post is much simpler than the one from Assaf. This post is also heavily biased towards Java since that’s my main field of expertise, but the situation isn’t much better in other languages/platforms.</p><h3>Insecure By Design</h3><p>Most remote debugging protocols such as JDWP are a product of a different era. An era that gave us telnet and HTTP. Most aren’t even encrypted by default. Just leaving JDWP enabled <a href="https://nvd.nist.gov/vuln/detail/CVE-2018-5486">warrants a CVE</a> .</p><p>JDWP effectively allows remote code execution. Lets you access all the bytecode of the server which is effectively almost the same as giving access to your full server source code. It lets attackers do almost anything since it wasn’t designed with security in mind.</p><p>I won’t even get into the complexities of man-in-the-middle attacks etc. That’s just insane.</p><p>I think the best mitigation is to tunnel the connection over SSH. It doesn’t solve all the problems but it’s at least not a huge hole like we normally have. Instead of enabling remote debugging as you normally would in the past, just enable it to your servers localhost as such:</p><pre>java -agentlib:jdwp=transport=dt_socket,server=y,address=9000 ApplicationName</pre><p>To connect to this remotely you will need SSH access to the machine and execute the following command:</p><pre>ssh remoteUser@remoteHost -L 9000:127.0.0.1:9000 -N</pre><p>If you need credentials for the command also add them there. This will open a tunnel between your local machine’s port 9000 and the remote one. You will be able to debug on localhost but it would work as a standard remote debugger. The only difference is that it wouldn’t be as bad in terms of security.</p><h3>Crash and Burn</h3><p>Unfortunately, such workarounds don’t impact everything else that is broken in the debug protocols. Some operations in the debugger require more than one step in terms of the protocol. As a result, you could send a request to the debuggee, lose your connection and the debuggee could be stuck in a problematic state.</p><p>This is an inherent limitation of the JDWP protocol and can’t be worked around in a standard debugger.</p><p>The problem is that even unintentional actions can demolish a server. A simple conditional breakpoint that invokes a method as part of the condition can demolish server performance and crash it.</p><h3>Information Sifting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*Nf0wgT_c4Bsf8Am-.jpeg" /></figure><p>In the cult classic office space, the heroes sift pennies from transactions. Big organizations block a lot of this access and rightly so.</p><p>Imagine if all your colleagues had debugged access to your server… All you need is one conditional breakpoint on the user login code and you have the password of a person you can hack. If you’re smart you’ll try that password on a different site without anyone knowing so it can’t even be traced to you.</p><p>Seriously don’t do that!</p><p>This is a very real risk of placing JDWP on servers and something you need to keep in mind.</p><h3>How we Solved these Issues at Lightrun</h3><p>Pretty much all of those problems don’t exist in Lightrun. Before I go into that, Lightrun doesn’t just let you start debugging… You need to authenticate. There’s an access system with corporate compliance, user roles that provide specific permissions, etc.</p><h3>Insecure By Design</h3><p>Lightrun doesn’t use JDWP and instead uses a custom agent. This means that there is no need to open an additional port to your service.</p><p>The agent connects to a management server so information is always pulled, never pushed. Furthermore, connections use certificate pinning to block man in the middle attacks.</p><h3>Crash and Burn</h3><p>Operations on Lightrun are executed using a fail-safe mechanism and a Sandbox.</p><p>Operations sent to the agent are atomic so a connection failure won’t impact the agent.</p><p>Furthermore, conditions and expressions are sandboxed and checked. If too much CPU is used or a write operation is detected the operation is discarded or rate limited. You will get a printout that rate-limiting occurred and your server will remain stable and performant.</p><h3>Information Sifting</h3><p>Lightrun has PII reduction and blocklists. This means that Lightrun can detect problematic patterns in logs such as credit card numbers. It can then block those numbers from entering the logs.</p><p>This is fully configurable per install so you can configure this for social security numbers etc.</p><p>Blocklists let you define classes, files, etc. that are blocked to debugging. Just exclude the authentication and authorization packages once you finish debugging the initial setup and a malicious developer won’t be able to place a snapshot there.</p><p>Finally, everything in Lightrun is audited. That means that even if you forgot to limit the access this would all be logged. Any snapshot (breakpoint) or log added by the user is added to the audit log. So a malicious developer would leave a digital trail we can follow.</p><h3>TL;DR</h3><p>Don’t use remote debugging unless you REALLY have to and then make sure no one can access your system… Even under those circumstances be vigilant and tunnel your connections via SSH.</p><p>Be careful with conditional breakpoints and other similarly elaborate debugger features. They are a recipe for disaster in such situations.</p><p>Be aware that you’re effectively giving every user who has access to the server the keys to the kingdom. Not just the source and the DB, access to all the encrypted data too such as passwords!</p><p>I hope you found this useful and keep safe out there with your deployments. Follow me on <a href="https://twitter.com/debugagent">twitter.com/debugagent</a> for updates and more.</p><p>Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter <a href="http://tinyletter.com/TheLeanProgrammer">tinyletter.com/TheLeanProgrammer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=732ebbff4ad7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theleanprogrammer/psa-the-risks-of-remote-jdwp-debugging-732ebbff4ad7">PSA:The Risks of Remote JDWP Debugging</a> was originally published in <a href="https://medium.com/theleanprogrammer">TheLeanProgrammer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>