<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ayush Mittal on Medium]]></title>
        <description><![CDATA[Stories by Ayush Mittal on Medium]]></description>
        <link>https://medium.com/@ayushmittal_26071996?source=rss-cbb32a13187f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BMfly2cCrsxqiJX8.jpg</url>
            <title>Stories by Ayush Mittal on Medium</title>
            <link>https://medium.com/@ayushmittal_26071996?source=rss-cbb32a13187f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:18:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayushmittal_26071996/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing Google Smart Compose]]></title>
            <link>https://medium.com/@ayushmittal_26071996/implementing-google-smart-compose-ad64dc1c0682?source=rss-cbb32a13187f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad64dc1c0682</guid>
            <category><![CDATA[smart-compose]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[encoder-decoder]]></category>
            <dc:creator><![CDATA[Ayush Mittal]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 09:55:05 GMT</pubDate>
            <atom:updated>2022-04-16T04:21:04.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this project we will implement a paper from google researches titled Gmail Smart Compose: Real Time Assisted writing. In this paper the authors present a system for generating interactive and real time suggestions in Gmail that will help its users in writing mails by reducing repetitive typing. The authors in this paper make use of the cutting edge machine learning techniques for language model training which enabled high-quality suggestion prediction, and constructed novel serving infrastructure for high-throughput and real-time inference. Due to the insufficiency of the data we did not implement the exact architecture that the paper suggests but made some modifications to the architecture that better suit our data.</p><h3>Business Problem</h3><p>Email writing can be a tedious task in today’s competitive world. The problem is we do not have a tool that make this email writing fast and better for the users. Hence the business problem we solve in this project is designing a solution that can make email writing fast and better.</p><h3>ML formulation of the business problem:</h3><p>Here we generate or predict suggestions of next few words to the users in real-time when they are writing an email.</p><h3>Business Constraints:</h3><p>The latency of the system should be very low as the suggestions are generated in real-time.</p><h3>Use of Deep Learning in solving the problem</h3><p>We use deep learning model to understand the context of the text, so that appropriate predictions of what user wants to write are made.</p><h3>Source of Data</h3><p>The dataset used was Enron Email Dataset which was downloaded from <a href="https://www.cs.cmu.edu/~enron/">https://www.cs.cmu.edu/~enron/</a>. It contains data from about 150 users, mostly senior management of Enron, organized into folders. The corpus contains a total of about 0.5M messages.</p><h3>Preprocessing of data</h3><p>Since we have a corpus of emails, we need to preprocess the data so that we can perform Exploratory Data Analysis and Modelling on the data.</p><p><strong>Steps:</strong></p><ol><li>Parse each email and get the a) Body b) Subject and c) Previous Mail.</li><li>We will remove all the special character except [.], [?], [!], [,]and [‘] from all the fields.</li><li>We will replace all the names and the organizations using nltk with [name] and [org] respectively.</li><li>We will also remove all the digits from the columns to make the dataset a little cleaner and easier to handle.</li><li>We will also remove all the website links and email address from the data.</li></ol><h3>Exploratory Data Analysis</h3><p>In this section we will do a high level analysis on the three columns that we created from the email dataset.</p><ol><li><strong><em>Analysis on the Body Column</em></strong></li></ol><p>We check the number of words in each records. For which we first get the number of words in each record , sort them and then calculate the percentile values. The percentile values are as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*ci-uzJfXYPLkxSUsk8BqIQ.png" /></figure><p>We can clearly see that the number words shoot up suddenly after the 90 percentile. So, we will deep dive and check the number percentiles values from 90 -100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*eztTJkryPFSLIcE-E14iDA.png" /></figure><p>Looking at the above values we can make a conclusion that we may only take 99% of the data for modelling and we can drop rest 1% of the data as they seem to be outliers.</p><p><strong><em>2. Analysis on subject columns</em></strong></p><p>We do a similar analysis on subject column. So, first we will see the percentile values for the number of words in each subject field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*CkYAero4G2j8adsATwjtlw.png" /></figure><p>Here too we see the same trend, but also when inspecting the values of the subject column we found that most of the values in the subject column do not have any information as they only have 5–6 words. So we will not use this column.</p><p><strong><em>3. Previous Email</em></strong></p><p>Here too we will perform the same EDA as done for email and subject fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*I5YiY8y2mxmTGw2CiTaORg.png" /></figure><p>Here we see that around 80 percent of the data do not have any previous mail, so will not use this column as well because the information provided by this field is minimum.</p><h3><strong>Results From EDA</strong></h3><p>After the EDA, we thought of using only the body column for the prediction of words.</p><h3>First Cut Approach</h3><ol><li><strong>Preprocessing:</strong></li></ol><p>We will preprocess the data as shown above.</p><p><strong>2</strong>. <strong>EDA:</strong></p><p>We will perform high level EDA as shown above to see if we can use the data for modelling or not.</p><p><strong>3. Dataset Creation:</strong></p><ol><li>We will divide the body of each email into three parts:</li></ol><p>a. Input to the Encoder</p><p>b. Input to the Decoder</p><p>c. Output of the decoder.</p><p>Example:</p><p>Since we are predicting the words, so if we have a sentence: “Please be on time next time.” , we will split it as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NpfYarS75XhQW7TXUAu7Q.png" /></figure><p><strong>4. Embedding Used:</strong></p><p>We will use Bpemb Embeddings for our model. BPEmb is a collection of pre-trained subword embeddings in 275 languages, based on Byte-Pair Encoding (BPE) and trained on Wikipedia. Its intended use is as input for neural models in natural language processing.</p><p>We use these embedding because of the following reasons:</p><ul><li>Subwords allow guessing the meaning of unknown / out-of-vocabulary words. E.g., the suffix -shire in Melfordshire indicates a location.</li><li>Byte-Pair Encoding gives a subword segmentation that is often good enough, without requiring tokenization or morphological analysis. In this case the BPE segmentation might be something like melf ord shire.</li><li>Pre-trained byte-pair embeddings work surprisingly well, while requiring no tokenization and being much smaller than alternatives: an 11 MB BPEmb English model matches the results of the 6 GB FastText model in our evaluation.</li></ul><p><strong>5. Modelling:</strong></p><p>We will use a Bi-directional Encoder-Decoder model with GRU units.</p><p><strong>Bi-directional Network:</strong> When we are dealing with long sequences of data and the model is required to learn relationship between future and past word as well. we need to send data in that manner. To solve this problem bidirectional network was introduced. In bidirectional LSTM we give the input from both the directions from right to left and from left to right</p><p><strong>GRU</strong> : The workflow of the Gated Recurrent Unit, in short GRU, is the same as the RNN but the difference is in the operation and gates associated with each GRU unit. To solve the problem faced by standard RNN, GRU incorporates the two gate operating mechanisms called Update gate and Reset gate.</p><p><strong>Difference between GRU and LSTM:</strong><br>GRU does not possess any internal memory, they don’t have an output gate that is present in LSTM.<br>In LSTM the input gate and target gate are coupled by an update gate and in GRU reset gate is applied directly to the previous hidden state. In LSTM the responsibility of reset gate is taken by the two gates i.e., input and target.</p><p><strong>6. Performance Metric:</strong></p><p>The performance metric used in the paper is Log-Perplexity.</p><p><em>Log Perplexity(x) = − Õ x p(x) logp(x)</em></p><p>here x is the Ground Truth and p(x) is the predicted value. The perplexity metric measures how well a model fits the data. A model with lower perplexity assigns higher probabilities to the true target tokens, thus is expected to be more superior for prediction.</p><h3>Models Used</h3><p>We will use a Bi-directional Encoder-Decoder model with GRU units.</p><h3>Code</h3><ol><li>Divide the data in train and test.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbf85855a711aef6662985469107bfad/href">https://medium.com/media/cbf85855a711aef6662985469107bfad/href</a></iframe><p>2. Getting the Bpemb Embeddings and creating tokenizing the train and test dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83c529d4acc2c8fa106954a502cd7ece/href">https://medium.com/media/83c529d4acc2c8fa106954a502cd7ece/href</a></iframe><p>3. Getting the max. length and applying padding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6452425cbbf8688960de952ea267282/href">https://medium.com/media/f6452425cbbf8688960de952ea267282/href</a></iframe><p>4. Creating the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/552c9f527c765b1b92bf7cc314a7812c/href">https://medium.com/media/552c9f527c765b1b92bf7cc314a7812c/href</a></iframe><p>5. Defining the loss function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff7dae097dff45cc2a480274a74ed9f/href">https://medium.com/media/6ff7dae097dff45cc2a480274a74ed9f/href</a></iframe><p>6. Training the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d678ed65351aba620ab1d42cde0e7b/href">https://medium.com/media/c8d678ed65351aba620ab1d42cde0e7b/href</a></iframe><p>Sample of training:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eee56062de8b401e210b83f6882eb5e8/href">https://medium.com/media/eee56062de8b401e210b83f6882eb5e8/href</a></iframe><p>7. Results</p><p>The loss graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*p3Aa5fp31ISJEUI9H4Ayrw.png" /><figcaption>The orange line is training loss whereas the blue line is the validation loss</figcaption></figure><p>The perplexity graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*p3Aa5fp31ISJEUI9H4Ayrw.png" /><figcaption>The orange line is training perplexity whereas the blue line is the validation perplexity</figcaption></figure><p>8. Inference Code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d49c3493ba81592ae225bcbf13eb8a92/href">https://medium.com/media/d49c3493ba81592ae225bcbf13eb8a92/href</a></iframe><p>9. Sample inputs and outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*yQrRWRNl-qqy_jGV9F8yOA.png" /></figure><p>10. Perplexity on test data set</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Dm-usNdSeICF0TfZu1dWg.png" /></figure><h3>Observations:</h3><p>We see that when the word just before the prediction is incorrect, then the predictions are affected whereas if the mistakes in the words or repetition of words are there before the last word then the model still works well.</p><p>Also since the previous mail context is not there so all the predictions are based on the pattern of the main body of the dataset, so the predictions can be improved with the previous mail context.</p><h3>Experiments Done:</h3><ol><li>Used the simple keras tokenizer, it gave a higher perplexity then by using Bpemb embeddings.</li><li>Used different optimizers, learning rates and dropout. After many experiments found the above configuration as the best one.</li><li>Also tried with unidirectional encoder-decoder architecture but since many sentences are long so bidirectional gave better results as expected.</li></ol><h3>Future Work</h3><p>We will use try to get more data so that the context from subject and previous can also help make predictions and will also experiment with advanced transformer models.</p><h3>References</h3><p>Gmail Smart Compose: Real-Time Assisted Writing;arXiv:1906.00080v1.</p><p>Applied AI (<a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com/</a>)</p><h3>GitHub Repo :</h3><p><a href="https://github.com/ayush2696/GmailSmartCompose">https://github.com/ayush2696/GmailSmartCompose</a></p><h3>LinkedIn:</h3><p><a href="http://www.linkedin.com/in/ayush-mittal26">www.linkedin.com/in/ayush-mittal26</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad64dc1c0682" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predict if SQL Injection Query can get access to Database.]]></title>
            <link>https://medium.com/@ayushmittal_26071996/predict-if-sql-injection-query-can-get-access-to-database-831b534fa032?source=rss-cbb32a13187f------2</link>
            <guid isPermaLink="false">https://medium.com/p/831b534fa032</guid>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[sql-injection]]></category>
            <dc:creator><![CDATA[Ayush Mittal]]></dc:creator>
            <pubDate>Sat, 19 Feb 2022 12:41:48 GMT</pubDate>
            <atom:updated>2022-02-22T14:59:30.135Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The first question that comes to mind when we read the topic : “Predict if the SQL injection query can get the access to the database”, is what is a SQL-injection? So, SQL injection, also known as SQLI, is a common attack that uses malicious SQL code for backend database manipulation to access information that was not intended to be displayed. This information may include any number of items, including sensitive company data, user lists or private customer details. Hence, in this case study we will be predicting whether a query that is entered by a user is a sql-injection or not that can connect to the database.</p><h3>Business Problem</h3><p>This is the age of web applications, where most of the applications we interact with are web based and SQL plays a very big part in this revolution. Sql is the most used language that is used by these applications to interact with the database systems and this also results in it being exploited by hackers to get unauthorized access to the database behind it. Hence if we have a system that checks all queries before executing them in the database we can filter out which queries are malicious and which are not. This provides significant security to our system and businesses profit from it by keeping their systems secure at all times.</p><p><strong><em>Problem Statement:</em></strong></p><ol><li>Identify which Sql query is a sql-injection and which is a valid query.</li></ol><p>2. This could help organizations to protect their data and applications from malicious users.</p><h3>Use of Machine Learning in solving the problem</h3><p>We use machine learning models to learn patterns in the query, so that the model can identify what parts of query can make it a sql injection.</p><h3><strong>Source of Data</strong></h3><p>The dataset was downloaded from <a href="https://www.kaggle.com/sajid576/sql-injection-dataset">https://www.kaggle.com/sajid576/sql-injection-dataset</a>. The dataset has two columns: <strong>1</strong>. <strong>Query</strong> and <strong>2</strong>. <strong>Label</strong>.</p><p>The Query column is string type and has SQL queries whereas the Label column consists of 1 and 0, where 1 symbolizes the query <strong>being</strong> a SQL injection and 0 symbolizes a query <strong>not being</strong> a SQL injection.</p><h3><strong>Existing Approaches</strong></h3><p>There are many existing approaches to the problem, a few are listed below:</p><ol><li><strong>SQL injection attack Detection using SVM</strong></li></ol><p>url: <a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.259.2515&amp;re%20p=rep1&amp;type=pdf">https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.259.2515&amp;re p=rep1&amp;type=pdf</a></p><p>Summary: In this paper we predict whether a query is a sql-injection or not by applying svm algorithm to the given dataset. The proposed sol. is,first Tokenize the dataset, train an SVM model and then make predictions.</p><p>2. <strong>Ensemble Machine Learning Approaches for Detection of SQL Injection Attack.</strong></p><p><em>url</em>: <a href="https://hrcak.srce.hr/file/367636">https://hrcak.srce.hr/file/367636</a></p><p><em>Summary</em>: In this paper we predict whether a query is a SQL-Injection or not by applying Gradient, Boosting Machine (GBM), Adaptive Boosting (AdaBoost),Extended Gradient Boosting Machine (XGBM), and Light Gradient Boosting Machine (LGBM) on preprocessed dataset. The preprocessed data set is created as follows:</p><p>i) We consider features as shown in the table below.</p><p>ii) We then tokenize each query point and then create a vector as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*cnAyZO9FzEa4e2H29M4ojw.png" /><figcaption>Features that were created in the paper.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*AmCQYsnmfFMdvQbHOcTdhw.png" /><figcaption>Example of tokenization</figcaption></figure><p>3. <strong>SQL Injection Detection Using Machine Learning</strong></p><p><em>url</em>: <a href="https://www.revistageintec.net/index.php/revista/article/view/1939/1%20264">https://www.revistageintec.net/index.php/revista/article/view/1939/1 264</a></p><p><em>Summary</em>: In this paper we predict whether a query is a sql-injection or not by applying various algorithms like Naive Bayes Classifier, SVM, CNN, Logistic Regression and Passive aggressive Classifier. The author in this paper first suggest to tokenize a query points to create a dataset(For example: Parsing “or 1=1–1” into “or”, “1=1”, “ — ”, “1”) and then apply above algorithms to classify whether a query is sql-injection or not.</p><h3><strong>Improvements</strong></h3><p>For my case study I try use features that are described in paper 2 above and then then also generate features like in paper 3 and then apply various machine learning models on them.</p><p>I do this because all sorts of symbols have importance in queries and they are accounted for when we create features like shown in paper 2 above. Also there are many keywords or combination of words that are found in SQL Injections and hence we also tokenize the the queries using Bag of Words to get the tokenization mentioned in Paper 3.</p><h3><strong>Exploratory Data Analysis</strong></h3><p>This is one of the most important parts of the case study because we will see how each character/symbol can contribute in identifying a query as Sql Injection or not.</p><p><strong>Features:</strong></p><ol><li>Single Quotes (‘’)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*W6LBbPTr2TLMRs8ohkGwyQ.png" /><figcaption>We see the that when the single quote appears 1 or 3 times in a query its generally that the query is an SQL injection and if the single quote comes 6 or 13 times its mostly not a SQL injection.</figcaption></figure><p>2. Double Quotes(“”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*ctpCLFc9J3xFAhYDjoBnqQ.png" /><figcaption>We see the that when the double quote appears 1 or 3 times in a a query its generally that the query is an SQL injection</figcaption></figure><p>3. Hash(#)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*H2QJSUBvCwkURT4X9h9mxg.png" /><figcaption>We see the that when the hash appears 1 time in a query its generally that the query is an SQL injection.</figcaption></figure><p>4. Dollar($)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*XGMg4hLIL4w2lgFPgXKO1w.png" /><figcaption>We see that dollar only appears once in each of the query types and it very difficult to make any assumption.</figcaption></figure><p>5. Parenthesis( () )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*P_wpgxy278aUxP7F9_KZFw.png" /><figcaption>We see that if either of the parenthesis occur 3 times or 5 or more times then it is generally an SQL injection.</figcaption></figure><p>6. Square Brackets( [] )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*62b-UfR7ZwyygimWIw2q2g.png" /><figcaption>From the above graph we notice that square brackets are hardly seen in the queries and if we see some then it is mostly not a SQL injection.</figcaption></figure><p>7. At the rate ( @ )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*PSlFgfNz8p4KLjDu3YdTMA.png" /><figcaption>We rarely see the appearance of @ symbol in our queries, and even if they appear we cannot say anything conclusively.</figcaption></figure><p>8. Colon (:)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*4Ljrfza8zHoiVOmweuv_ZQ.png" /><figcaption>We see from the above graph that there is an overlap for : symbol and hence we cannot make any conclusions from it.</figcaption></figure><p>9. Semicolon(;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*NBTvMZrwjrSf_pN379dlAQ.png" /><figcaption>We see from the above graph that semicolon hardly occurs in any query and if we see a semicolon it is usually not a SQL injection.</figcaption></figure><p>10. equals(=)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*1jfw9bgz-bPHM6m8-G8dUQ.png" /><figcaption>We see from the above graph that there is an overlap for equals symbol and hence we cannot make any conclusions from it</figcaption></figure><p>11. Angular Brackets( &lt;&gt; )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*04_lzKa21sVngfKdobTb6A.png" /><figcaption>We see that angular brackets hardly occur in any query but a handful of queries which have angular brackets are SQL injection but since the quantity is so small we cannot say anything conclusively.</figcaption></figure><p>12. Question Mark(?)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*5I61L5qfQZ5hLzpJdxI6ug.png" /><figcaption>We see that question mark hardly occur in any query but a handful of queries which have question mark are not SQL injection but since the quantity is so small we cannot say anything conclusively.</figcaption></figure><p>13. Caret(^)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*GworTGgHzXL9d-2WNyl8Jg.png" /><figcaption>We see that angular brackets hardly occur in any query and can be ignored.</figcaption></figure><p>14. UnderScore(_)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*wt72LOP8b_vB1aOUV-K_fA.png" /><figcaption>We see that when underscore occurs more than once it is generally a sql injection.</figcaption></figure><p>15. Curly Brackets( {} )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*j26o_qNLXSwMvW8ZJChRIA.png" /><figcaption>We see that Curly Brackets hardly occur in any query and can be ignored.</figcaption></figure><p>16. Arithmetic Operators( +,-,*,/)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*52Pw8Bc28McfcWHndxsdmw.png" /><figcaption>We see overlap of the arithmetic feature for two classes and we cannot say anything conclusively.</figcaption></figure><p>17. Comma(,)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*zl9IzgWVKCVyEbE5fy9P0g.png" /><figcaption>We see that if comma appers 5 or more times in a sql query then it is probably a sql injection.</figcaption></figure><p>18. Dot(.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*pFsp03bOawWB4ztH4xxUbg.png" /><figcaption>We see overlap of the dot feature for two classes and we cannot say anything conclusively</figcaption></figure><p>19. Single-Line Comment( — )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*ZIJirEowLpXZdpn7kST0-w.png" /><figcaption>We see that if there is a single line comment present in the query then is it a SQL injection</figcaption></figure><p>20. Multi-Line Comment(/*)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*zXp8MBH7knxLl0crLgkN5Q.png" /><figcaption>We see multiline comments hardly occur in any query and hence we may not use this feature.</figcaption></figure><p>21. Whitespace ( )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*rC7voZvPijmGOhwFvLBmSA.png" /><figcaption>We see that higher frequencies of white spaces are generally found in SQL injection.</figcaption></figure><p>22. Percentage(%)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ixW6gbsUmrgMYg8ieFolRg.png" /><figcaption>As we overlap for the frequencies of percentage sign hence we cannot say anything conclusively.</figcaption></figure><p>23. Logical operators( AND ,OR, NOT, XOR, &amp;&amp;, ||, !)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*ZZ--Y6Gm8ZS3WX5X6MP5hg.png" /><figcaption>We see that if the logical operators occur 3 times or more the queries are generally SQL injection.</figcaption></figure><p>24. Punctuations(!\”#$%&amp;\’()*+,-.\/:;&lt;=&gt;?@[\\]^_`{|}~)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*uy95dR-hIFXs04Uc0wqmeg.png" /><figcaption>We see that as the number of punctuations increases, the chances of it being a SQL-injection also increases.</figcaption></figure><p>To make the visualization clear, we will also plot the Box-Plot for the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*Luj5RRwQXsg0mzBgI-Q6qw.png" /><figcaption>After reading the above graph we can see that the boxes for the two classes do not overlap completely and hance we can say that as the number of punctuations increases it chances of being a SQL injection also increases.</figcaption></figure><p>25. Hexadecimal Numbers(regex used = 0[xX][0–9a-fA-F]+\s )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*q7DHh9bOS9fmrC29UExOsQ.png" /><figcaption>We see that when hexadecimal numbers occur in a query its generally a SQL injection.</figcaption></figure><p>26. Null</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*gx1NqBWi2hcsCLe_U1dukg.png" /><figcaption>We notice that null values seldom occur in a query but if we have more than 1 null value its observed to be a SQL-Injection.</figcaption></figure><p>27. Digits</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*NCEZzIt4dGNodOViQl2Iaw.png" /><figcaption>We see that as the number of digits increase in a query the query tends to be a SQL injection.</figcaption></figure><p>Since we cannot see the graph clearly, to confirm our observation we will also plot a box-plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*zz_acFuU2Y7QQGy8T_2XUQ.png" /><figcaption>The box plot confirms our hypothesis as we do not see much overlap between the two classes, hence as the number of digits increase the query is shown to be a SQL-Injection.</figcaption></figure><p>28. Alphabets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*knBBcsS-c8JVJZ7hP5MqrA.png" /><figcaption>From box plot we do not see much overlap between the two classes, hence as the number of alphabets increase the query is shown to be a SQL-Injection.</figcaption></figure><p>29. We will plot word cloud of queries for each label to see if we can observe specific words being present in each type of query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*8et1iXomuej-Y_rh73TbRQ.png" /><figcaption>This is the word cloud for queries which are labelled as SQL Injection and we clearly see that we find hexadecimal number, special functions, etc. in these queries.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*xATNHjUXzJ75s6XjCvc9PQ.png" /><figcaption>This is the word cloud for queries which are <strong>not</strong> labelled as SQL Injection and we clearly see that we find select, order by, top, etc. which are all general keywords used in SQL.</figcaption></figure><h3>First Cut Approach</h3><ol><li><strong>Preprocessing:</strong></li></ol><p>First I will convert all the text to lowercase and then will see if there are any duplicates, if yes then delete those duplicate values.</p><p><strong>2</strong>. <strong>EDA:</strong></p><p>a. In EDA, we will check the class imbalance.</p><p>b. I will also create and analyze the features as shown above.</p><p><strong>3. Modelling:</strong></p><p><em>i. Featurization:</em></p><p>1. Tokenize each query to create features (Bag of words on queries).</p><p>2. Create features based on the research paper 2 mentioned above.</p><p><em>ii. Apply machine learning algorithms like logistic regression, naïve bayes ,SVM and XGBOOST on Featurization(1).</em></p><p><em>iii. Apply the same machine learning algorithms to the features that we create in Featurization(2).</em></p><p><em>iv. Compare the metrics and choose the best model and featurization technique.</em></p><h3>Models Used</h3><p>We will use 4 machine learning models namely Logistic Regression, SVM, Naïve Bayes and XGBoost.</p><p>We select these 4 models because these models are highly efficient in classification problems. Most of the problems in machine learning can be solved by one of these 4 models.</p><h3><strong>Code</strong></h3><ol><li>Creating features for the models.</li></ol><p>a. Custom features which we analyzed on EDA section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*i5il2h4uTvIfePB9celX0Q.png" /></figure><p>b. Using BoW(Bag of words) on queries to create unigram and bigram features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*wOg6l9t-jpFgRajEG03xLQ.png" /></figure><p>c. Combining all the features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*XAiGY6EHA63UVQqXiW7_MQ.png" /></figure><p>d. Since all the features are numeric its better if we scale the features, models work better with scaled features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*IDy_LJlDfiIEDY0QU67X3g.png" /></figure><p>e. Using <strong>Logistic Regression</strong> with Grid Search CV to find the best parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*YWb7oRKzf_fsCmroBH7oEQ.png" /></figure><p>Results from the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*J-nEH5ztH8-GSauaJzHNKA.png" /><figcaption>X-axis has the hyperparameter C in log values. Y-axis has the auc score for each of these values.</figcaption></figure><p>Confusion matrix after training Logistic Regression with the best found parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*yur62B1IKjbn7s8s_U43hQ.png" /><figcaption>X-axis has the actual values. Y-axis has the predicted values.</figcaption></figure><p><strong>F1- Score</strong> : 0.905</p><p>f. Using <strong>SVM</strong> with Grid Search CV to find the best parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*Sy2dKt5a2rzbX0RQrzNbmQ.png" /></figure><p>Results from the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*WcXU0v58rgq7NHlxX1zP_Q.png" /><figcaption>X-axis has the hyperparameter C, kernel. Y-axis has the auc score for each of these values.</figcaption></figure><p>Confusion matrix after training SVM with the best found parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*D-4Us-qBMJY3pn7tMmfRcQ.png" /><figcaption>X-axis has the actual values. Y-axis has the predicted values.</figcaption></figure><p><strong>F1-Score </strong>: 0.911</p><p>g. Using <strong>Naïve Bayes</strong> to find the best parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*KxgBEk3u0sB1a8c220wZng.png" /></figure><p>Results from the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*dM2mvTCZRYUGYMbW-v8ELQ.png" /><figcaption>X-axis has the hyperparameter alpha . Y-axis has the auc score for each of these values.</figcaption></figure><p>Confusion matrix after training Naive Bayes with the best found parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*KHZ2yMtwfWPW_MI5GuxjqA.png" /><figcaption>X-axis has the actual values. Y-axis has the predicted values.</figcaption></figure><p><strong>F1-Score</strong> : 0.97</p><p>h. Using<strong> XGBoost</strong> with Grid Search CV to find the best parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*7u_Y9S-B56t2eRb7T84SrQ.png" /></figure><p>Results from the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*VGkwQuGt3jx2ZKtOdrbS3A.png" /><figcaption>X-axis has the hyperparameter n_estimators, learning rate. Y-axis has the auc score for each of these values.</figcaption></figure><p>Confusion matrix after training XGBoost with the best found parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*kBlonq28VOQ4ZU_Mvo1CcA.png" /><figcaption>X-axis has the actual values. Y-axis has the predicted values.</figcaption></figure><p><strong>F1- Score</strong> : 0.995</p><h3>Comparison of Models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0vNvjIIVF_YYoicQOlLuQ.png" /><figcaption>X-axis is the metrics that we observe and Y-axis is the models.</figcaption></figure><p>We see that XGBoost is the best performing model with the F1-Score of 0.995. We also get a very high True Positive Rate, which signifies that the chances of a SQL Injection being blocked is high.</p><h3>Future Work</h3><p>We will also apply Deep Learning algorithms to get a even better F1-score.</p><h3>References</h3><p>SQL injection attack Detection using SVM; Romil Rawat and Shailendra Kumar Shrivastav; International Journal of Computer Applications (0975–8887).</p><p>Ensemble Machine Learning Approaches for Detection of SQL Injection Attack; Umar Farooq; ISSN 1846–6168 (Print), ISSN 1848–5588 (Online)</p><p>SQL Injection Detection Using Machine Learning; S.S. Anandha Krishnan, Adhil N Sabu, Priya P Sajan and A.L. Sreedeep4;ISSN: 2237–0722,Vol. 11 №3 (2021)</p><p>Applied AI (<a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com/</a>)</p><h3>GitHub Repo :</h3><p><a href="https://github.com/ayush2696/Machine-Learning/tree/main/Case%20Study/Sql-Injection%20Detection">Machine-Learning/Case Study/Sql-Injection Detection at main · ayush2696/Machine-Learning</a></p><h3>LinkedIn:</h3><p><a href="http://www.linkedin.com/in/ayush-mittal26">www.linkedin.com/in/ayush-mittal26</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831b534fa032" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>