<?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 PINAKI SEN on Medium]]></title>
        <description><![CDATA[Stories by PINAKI SEN on Medium]]></description>
        <link>https://medium.com/@senpinaki222?source=rss-db3c69755975------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E9hzXOMxiILL5hwjBSoZfw.jpeg</url>
            <title>Stories by PINAKI SEN on Medium</title>
            <link>https://medium.com/@senpinaki222?source=rss-db3c69755975------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:03:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@senpinaki222/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[Optimizing a Variational Quantum Circuit, studying the character of the optimized cost as a…]]></title>
            <link>https://senpinaki222.medium.com/optimizing-a-variational-quantum-circuit-studying-the-character-of-the-optimized-cost-as-a-a8bac2e9ba46?source=rss-db3c69755975------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8bac2e9ba46</guid>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[quantum-machine-learning]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[qml]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[PINAKI SEN]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 11:11:59 GMT</pubDate>
            <atom:updated>2020-10-30T14:26:31.519Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing a Variational Quantum Circuit, studying the character of the optimized cost as a function of layers in the circuit</h3><p>An approach to optimizing a variational quantum circuit using a gradient-free optimizer and study the change in cost function with increasing the number of layers in the circuit.</p><p>Variational Quantum Circuits (also known as VQC) are basically quantum algorithms consisting of one or more parameterized gates where the gate parameters are trainable. VQC is commonly used in Quantum Machine Learning and many other optimization problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brijfavbFNl8qSCJKTO8aQ.png" /></figure><p>As shown in the picture, a VQC starts with initial state preparation (in QML problems, various feature mapping techniques are used for that, whereas it can be left as zero state also as per the requirement of problems we are solving). After the initial state preparation comes to the variational circuit consisting of one or more trainable parameterized gates (maybe some non-parameterized gates also), which we have to optimize. Finally, the measurement is done and the measured value is used again as feedback for optimizing the trainable parameters of the variational circuit. <strong>Importantly, the optimization is not a part of the Quantum circuit, it is done by a classical optimizer.</strong></p><h3>A little back story</h3><p>The problem statement, I will be discussing here is one of the four selection tasks of the second cohort of QOSF mentorship program. You can learn more about the <a href="https://qosf.org/">Quantum Open Source Foundation</a> and the mentorship program <a href="https://qosf.org/qc_mentorship/">here</a>.</p><p><strong><em>Disclaimer:</em></strong> <em>Unfortunately</em>😔<em>, I didn’t get through the selection task as there was a very less number of mentors compared to the huge quantity of submissions. Also, I will be discussing some of the points where I could have done better along with the approach.</em></p><h3>Problem Statement</h3><p>The problem statement was basically studying how the optimized cost of a Variational circuit changes with the increasing number of layers (also known as repetitions). Each layer, that was specified in the problem statement has two blocks, namely U1 and U2.</p><p>U1, also denoted as ‘Odd blocks’ has four RX gates with trainable parameters one applied on each of the four qubits. Similarly, U2 (Even blocks) consists of RZ gates in the same manner, followed by a specific combination of CZ gates on the four qubits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*qqVwaRNf1_3rqZM-mjJuoA.png" /><figcaption>Design of Each layer mentioned in the problem statement</figcaption></figure><p>The circuit shown in the above picture is the design of each layer, where the left side of the barrier is U1 (odd block) and the right side is U2 (even block). In each layer, there will be a total of eight parameters to be optimized, four for the RX gates, four for the RZ. CZ gates require no parameter.</p><p>Now we need to study the optimized cost of statevector of the quantum circuit with respect to a random statevector |phi&gt;, which should be constant for all the circuits.</p><h3>My approach using Gradient-free optimizer</h3><p>Here we will be going through the implementation using pennylane, everything starting from the necessary imports up to plotting the optimized cost as a function of the number of layers in the circuit. Also, we will look into how the cost decreased in each circuit in the course of the optimization process.</p><h4>Necessary Imports</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f327f233f309e069224236e8aa65a24/href">https://medium.com/media/3f327f233f309e069224236e8aa65a24/href</a></iframe><p><em>Although I have imported NumPy directly, it is recommended to import the wrapped version of Numpy provided by Pennylane</em>.</p><h4>Function to initialize theta values</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1e4bbbb08f831dc198317be841943c4/href">https://medium.com/media/f1e4bbbb08f831dc198317be841943c4/href</a></iframe><p>The <em>initialize_theta</em> function takes only the no. of layers as argument. It initializes a random NumPy array having dimensions (layers*2, 4). For each layer, there will be two rows, one for a set of RX gate parameters another for RY. As the no. of qubits has been fixed, the column no. is also fixed at 4.</p><h4>Initializing random statevector |Phi&gt;</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56e4a569550892ad1295b429287aa266/href">https://medium.com/media/56e4a569550892ad1295b429287aa266/href</a></iframe><p>As mentioned in the problem statement, the cost function should be calculated with respect to a random statevector. As the circuit consists of 4 qubits, there will be 2⁴, i.e. 16 elements in the statevector, which we randomly initialized using random.randn function of Numpy.</p><p><strong><em>Better approach: </em></strong><em>Using the above approach to generate random |phi&gt; is not actually feasible. Firstly, while randomly initializing we are not taking care of the statevector to be normalized, so the sum of the square of all the elements is not equal to one here. This led to a huge difference between |phi&gt; and the output statevector even after being optimized.</em></p><p><em>So what we should do is either taking care of the normalization while initializing using a random function or creating a four qubit circuit with random gates and considering its output statevector as |phi&gt;. The second approach is much more feasible.</em></p><h4>Creating the Circuit</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8e4dbf7caa90d79ecd9474ef2f3f286/href">https://medium.com/media/e8e4dbf7caa90d79ecd9474ef2f3f286/href</a></iframe><p>The <em>simulate_circuit() </em>takes the NumPy array of parameters and calculates the no. of qubits from the dimension of the Numpy array itself. So we don’t have to explicitly pass the no. of qubits in the function.</p><p>Although we could have directly called the <em>circuit() </em>function, there are some restrictions in the return type of circuit function of pennylane. It can return either a single or tuple of measured observable values. So we encapsulated the <em>circuit()</em> function within another function named <em>simulate_circuit()</em>, which returns the statevector of the device instance using <em>dev.state</em></p><p><strong><em>Better approach: </em></strong><em>We can call the states of the qubits as an observable using qml.probs(). You can learn more about that </em><a href="https://pennylane.readthedocs.io/en/stable/introduction/measurements.html#probability"><em>here</em></a><em>.</em></p><h4>Calculating the Cost</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/218839d4ac855a7f4d12931fbe5c6ba3/href">https://medium.com/media/218839d4ac855a7f4d12931fbe5c6ba3/href</a></iframe><p>The cost of the circuit is here denoted by ‘<em>distance’. W</em>e take the difference between the elements of the output statevector of simulated Quantum circuit, denoted by |Psi&gt; and random vector |phi&gt; then return the sum of square of mod of all the elements.</p><h4>Optimizing the circuit parameters</h4><p>There is plenty of both Gradient-based and Gradient-free optimizers in Pennylane. In this problem, we will be using Rotosolve, a gradient-free optimizer provided in Pennylane. You can learn more about the built-in optimizers <a href="https://pennylane.readthedocs.io/en/stable/introduction/optimizers.html">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9342c68ce24b528e06b1f7425f71e1c0/href">https://medium.com/media/9342c68ce24b528e06b1f7425f71e1c0/href</a></iframe><p>The <em>optimize() </em>function takes the Numpy array of gate parameters and no. of iterations as arguments (and also the learning rate if you are using a gadient-based optimizer). There are two more optional arguments: print_distance and plot_distance. When set to <em>True, it prints and plots the costs of each iteration steps.</em></p><p><strong><em>callback:</em></strong> As the circuit becomes more computationally expensive with an increasing number of layers, I have tried to terminate unnecessary extra iterations. Although the maximum iterations is specified as 50 while calling the <em>optimize() function, the optimization process will be terminated midway, if the cost of the circuit remains the same up to 2 decimal places for three consecutive optimization steps.</em></p><h4>Main Function</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3579226d66cc73c4b63524c35636efc5/href">https://medium.com/media/3579226d66cc73c4b63524c35636efc5/href</a></iframe><p>Gradient free optimizers being computationally expensive, I was able to simulate only up to 15 layer circuit.</p><h4>Plotting the optimized cost as a function of no. of layers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/278e860be598cf983a95b6f44e4c8caa/href">https://medium.com/media/278e860be598cf983a95b6f44e4c8caa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*l0uRMtvdV1o8WTx53jMc2w.png" /></figure><p>As can be observed from the plot, from a single-layer circuit up to 6 layers, the optimized cost dropped extensively. From layer 6 to layer 10 the drop became quite small. Finally from a circuit with 10 layers to 15 layers, the optimized cost was the same approximately. More importantly from a specific circuit to the next one, the optimized cost either decreased or remained the same here.</p><h4>No. of iterations as a function layers in the circuit</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df7d730d7819956c4b6a7859cee5100f/href">https://medium.com/media/df7d730d7819956c4b6a7859cee5100f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*9dDTYTayr9uwsc4Tpl-Alw.png" /></figure><p>Although the maximum iteration is set to 50, due to the terminating condition in the <em>optimize() </em>function, none of all 15 circuits took above 40 iterations. You can visualize the no.of iteration taken by each circuit to reach the minimum cost in this plot.</p><h4>Optimization steps of a single circuit</h4><p>For each circuit irrespective of the no. layers, the trend of cost function in the course of the optimization process looks quite similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*6PjhuLJmpZcjtc_JOzagZQ.jpeg" /></figure><p>A plot of cost functions at each step of optimization for circuits with a single layer and 12 layers has been shown in the above picture. You can have a look into the plot of costs in each optimization step for the rest of the circuits in this <a href="https://github.com/senpinaki222/qosf_selection_task/blob/master/task_1_upto_layer_12_plotted_each_layer.ipynb">notebook</a>.</p><p>Here is the<strong> </strong><a href="https://github.com/senpinaki222/qosf_selection_task"><strong>GitHub repo</strong></a>, where you can get some more insights along with all the information discussed above 😎.</p><p><strong>Qiskit is another famous framework for Quantum Computing. In case you are more familiar with that, I will recommend this </strong><a href="https://markcunningham.tech/2020/10/29/a-task-using-optimization-in-qiskit/"><strong>blog</strong></a><strong>, by </strong><a href="https://markcunningham.tech/"><strong>Mark Cunningham</strong></a><strong>, where he has described his approach to this same problem using Qiskit.</strong></p><p>Thanks a lot for reading. Please let me know if any corrections/suggestions. Please do 👏 if you like the post. Thanks in advance 😄…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8bac2e9ba46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PRAW — a python package to scrape Reddit Post data]]></title>
            <link>https://medium.com/analytics-vidhya/praw-a-python-package-to-scrape-reddit-post-data-b759a339ed9a?source=rss-db3c69755975------2</link>
            <guid isPermaLink="false">https://medium.com/p/b759a339ed9a</guid>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[praw]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[PINAKI SEN]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 12:55:06 GMT</pubDate>
            <atom:updated>2020-07-02T14:41:35.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>PRAW — a python package to scrape Reddit Post data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwMTgdfGPkyt4ry72Glewg.png" /></figure><h3><strong>Introduction</strong></h3><p>RRAW which stands for “Python Reddit API Wrapper” is a python package that allows simple access to Reddit’s API. It has a well documented <a href="https://praw.readthedocs.io/en/latest/">official website</a> which can be referred to for code snippets. Here I will discuss steps to install, configure and write some python script to scrape Reddit posts.</p><h3>Installation &amp; Upgrade</h3><pre>pip install praw</pre><pre>pip install --upgrade praw</pre><h3><strong>Requirements</strong></h3><p>Pandas should be installed previously, which will help to manage and store scraped data in CSV file more easily. If not installed, use the below command to install it.</p><pre>conda install pandas</pre><h3><strong>Sign Up and Registration</strong></h3><p>If you already have a Reddit profile, go and log in. If not, go <a href="https://www.reddit.com/">here</a> and click on the “SIGN UP” button as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPPI_iF--7ucL52co3d78g.png" /></figure><p>After signing up you will be redirected to the Reddit homepage. Click on the dropdown button beside the profile picture (shown by red arrow below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHqRUUR60I4ktvaPGtN3Qw.png" /></figure><p>Click on “Visit Old Reddit”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXIgV6Bwo75A7c0XTJ17gw.png" /></figure><p>Now go to preferences on the top right corner of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXWJsYm-3gfppHY0WNvxgQ.png" /></figure><p>Navigate to <strong>apps</strong> section on Nav Bar and click on the button <strong>“are you a developer? Create an app…” </strong>[shown in the below image using red arrow]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeOaxKzc2Rb2WMAz3WlTew.png" /></figure><p>Fill all the details and don’t forget to select the <strong>script </strong>[by default <strong>web app </strong>is selected]. Finally, click on the <strong>‘Create app’</strong> button. All the fields here are mandatory, ignoring anyone will not allow you to proceed further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwsPHGkUET9rmy-jUKuxiA.png" /></figure><p>You will be redirected to a page where <strong>personal use script </strong>and <strong>security token </strong>will be given[as marked in the picture]. Copy those in your clipboard, which will definitely be required while writing Python script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSl1RS-FD2MGWTP-C9JHaA.png" /></figure><h3><strong>Writing Python Script</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLYPIz22lTzv42BKVo9WSw.png" /></figure><p>Here I will be using Jupyter Notebook to demonstrate the whole process. You can use any Notebook or code editor of your choice.</p><p>We will create a dataset consisting of features of Reddit posts from various subreddits. PRAW provides almost 20 attributes to scrape various features of Reddit post such as Id, Author, Flair, Title, Upvote etc. Here we will store 7 features of each Reddit post to create the dataset.</p><h4><strong>Importing Libraries</strong></h4><pre>import praw<br>import pandas as pd</pre><h4><strong>Accessing API using secret token</strong></h4><pre>reddit = praw.Reddit(client_id = &quot;CLIENT_ID&quot;, #peronal use script<br>                    client_secret = &quot;CLIENT_SECRET&quot;, #secret token<br>                    usernme = &quot;USERNAME&quot;, #profile username<br>                    password = &quot;PASSWORD&quot;, #profile password<br>                    user_agent = &quot;USERAGENT&quot;)</pre><h4><strong>Initialize empty lists for each feature</strong></h4><pre>author_list = []<br>id_list = []<br>link_flair_text_list = []<br>num_comments_list = []<br>score_list = []<br>title_list = []<br>upvote_ratio_list = []</pre><h4><strong>Mention all subreddits that will be scraped</strong></h4><p>We will scrape hot posts from ten popular Subreddits. So all these subreddit names will be stored in a list and we will iterate over each element of the list.</p><pre>subreddit_list=  [&#39;india&#39;,<br>                  &#39;worldnews&#39;,<br>                  &#39;announcements&#39;,<br>                  &#39;funny&#39;,<br>                  &#39;AskReddit&#39;,<br>                  &#39;gaming&#39;,<br>                  &#39;pics&#39;,<br>                  &#39;science&#39;,<br>                  &#39;movies&#39;,<br>                  &#39;todayilearned&#39;<br>                 ]</pre><h4><strong>Subreddit and various attributes</strong></h4><p>The <em>subreddit( )</em> function takes a single parameter, i.e. the subreddit name. Each subreddit has a division named as <strong>hot</strong>. We access the hot Reddit posts using the function <em>hot( ), </em>which takes an attributes ‘limit’, using which we can specify the no. of posts that we want to access from that subreddit.</p><pre>subreddit = reddit.subreddit(subred)<br>hot_post = subreddit.hot(limit = 10000)</pre><p>Now we can iterate over the hot_post and for each instance we can call the attributes such as author, id, score, title etc. Each attribute then can be appended to the previously initialized columns accordingly. For example, the script for scraping a single attribute (here, author name) for 1000 hot posts from a subreddit ( here, India) has been shown below.</p><pre>subreddit = reddit.subreddit(&#39;india&#39;)<br>hot_post = subreddit.hot(limit = 1000)</pre><pre>for sub in hot_post:<br>  author_list.append(sub.author)</pre><p>You can learn about more attributes from the official website of PRAW <a href="https://praw.readthedocs.io/en/latest/">here</a>.</p><h4>Final Script</h4><p>The script to iterate through the list of 10 subreddit names, scraping &amp; storing specific attributes of each post is given below.</p><pre>for subred in subreddit_list:<br>    <br>  subreddit = reddit.subreddit(subred)<br>  hot_post = subreddit.hot(limit = 10000)</pre><pre>  for sub in hot_post:</pre><pre>    author_list.append(sub.author)<br>    id_list.append(sub.id)<br>    link_flair_text_list.append(sub.link_flair_text)<br>    num_comments_list.append(sub.num_comments)<br>    score_list.append(sub.score)<br>    title_list.append(sub.title)<br>    upvote_ratio_list.append(sub.upvote_ratio)</pre><pre>  print(subred, &#39;completed; &#39;, end=&#39;&#39;)<br>  print(&#39;total&#39;, len(author_list), &#39;posts has been scraped&#39;)</pre><p>The last two print statements will help us to visualize the termination of each subreddit and total no. of data scrapped till then.</p><h4>Storing Dataset in a CSV file</h4><p>For storing all the scraped data we will use the pandas library and convert the list of data into a pandas dataframe first, then to a CSV file. Each list will be treated as a column in the dataset and each row of the dataset will describe a unique Reddit post.</p><pre>df = pd.DataFrame({&#39;ID&#39;:id_list, <br>                   &#39;Author&#39;:author_list, <br>                   &#39;Title&#39;:title_list,<br>                   &#39;Count_of_Comments&#39;:num_comments_list,<br>                   &#39;Upvote_Count&#39;:score_list,<br>                   &#39;Upvote_Ratio&#39;:upvote_ratio_list,<br>                   &#39;Flair&#39;:link_flair_text_list<br>                  })<br>df.to_csv(&#39;reddit_dataset.csv&#39;, index = False)</pre><h3>Conclusion</h3><p>Here is the complete Python script. You can also clone the script and CSV file from this <a href="https://github.com/senpinaki222/PRAW-blog">Github repo</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d3496606a3560f2c52cdd4141415351/href">https://medium.com/media/7d3496606a3560f2c52cdd4141415351/href</a></iframe><p>Here is a <a href="https://www.kaggle.com/senpinaki222/reddit-post-dataset">Reddit Dataset</a> uploaded on Kaggle, that you can use for your Machine Learning project. Give it an upvote, if you find it helpful.</p><p>Thanks a lot for reading. Please let me know if any corrections/suggestions. Please do 👏 if you like the post. Thanks in advance…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b759a339ed9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/praw-a-python-package-to-scrape-reddit-post-data-b759a339ed9a">PRAW — a python package to scrape Reddit Post data</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Only train and test set is not enough for generalizing ML model, Significance of Validation set]]></title>
            <link>https://medium.com/analytics-vidhya/only-train-and-test-set-is-not-enough-for-generalizing-ml-model-significance-of-validation-set-cf68bb26881a?source=rss-db3c69755975------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf68bb26881a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[science-and-technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[analytics-vidhya]]></category>
            <dc:creator><![CDATA[PINAKI SEN]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 15:13:44 GMT</pubDate>
            <atom:updated>2020-06-28T12:52:10.647Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why only the train and test set is not enough for generalizing a ML model? Significance of Validation set.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xKrtd7AUkH3d7Jp4XtIig.png" /></figure><p>Using the same data for both training and testing of a Machine Learning model refrains us from detecting if a model is overfitted or not, as it will certainly behave accurate because of being tested on something it has already seen while training. So we split the data in training and testing set mostly in the 70–30 percent ratio and their names are self-explanatory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*QSXxOderidihfo1itIE7cw.png" /></figure><p><strong>Here is the catch. </strong>Splitting the data only in the train and test set is not always enough, mainly when we are juggling between various hypotheses of a certain ML algorithm. For this blog, I will be considering LinearRegression, one of the basic Machine learning algorithms.</p><p>Nowadays #<strong>from sklearn.linear_model import LinearRegression</strong># being so famous among the beginners in applied Machine Learning, most of us don’t come across the fact that behind the predefined function, there is a hypothesis (basically a polynomial function) that has to be chosen properly for achieving the maximum accuracy possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*iycu7qKS045TwN3YGhGMng.png" /></figure><p>For ease of assumption let’s say, we have only one feature. Then the initial approach is to use the first-degree polynomial but for obvious reasons, a first-degree polynomial will underfit on any real-life dataset. So we will try more higher degree polynomials as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SmhLjt_cF6stxxAbZ7xmA.jpeg" /></figure><p>Now to choose the best one from all these ten hypotheses, each will be trained on the training set and the cost function is calculated on the test set using the trained weights for each hypothesis. Finally, the hypothesis giving the least cost value on the test will be taken into consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzI3Ip2iuTSK_rmRiHiFBA.jpeg" /></figure><p>Say, here the cost function <strong>‘J’ </strong>for the fifth-degree polynomial seems to be the least one. So it’s considered as the final hypothesis and theta values associated with it as the final weights. Now the <strong><em>‘generalized’</em></strong> error of the final model has to be calculated on the test set again.</p><p><strong>But how can the final error be generalized???</strong> Model has already seen the test data before, while choosing between multiple hypotheses. This looks the same as when we used training data for both training and testing the model.</p><p><strong>Here comes the significance of the Validation set. </strong>We will be splitting the whole dataset into three segments rather than two, named as <strong>Training set</strong>, V<strong>alidation set</strong> and <strong>Test set</strong>. Generally, the split ratio is followed to be <strong>60–20–20</strong> respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gy5qpngejs1ur8dQnX5H6w.png" /></figure><p>Now the little change that will be applied in the previously explained process is to<strong> use the Validation set while choosing among multiple hypotheses, rather than using the test set</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kj2-0UiVLkkHTzh70MuvhA.jpeg" /></figure><p>Then choose the hypothesis having least cost value on the Validation set. <strong>Finally, calculate the Generalized error of the chosen hypothesis using the Test set.</strong></p><p>This time, the initial cost for each optional hypothesis has been calculated on the validation set and after choosing the final one, the generalized error is observed on the test set. So as the model has never been evaluated on any previously used data, now it is expected to predict properly on unseen data too.</p><p>There are more advanced concepts of k-fold cross validation over hold-out validation. In the previously discussed validation process ( i.e. hold-out validation) we hold the validation set forever, which reduces the training data by almost 20–30%. So in <a href="https://towardsdatascience.com/why-and-how-to-cross-validate-a-model-d6424b45261f"><strong>K-fold cross-validation</strong></a> process, the remaining dataset after excluding test data is not strongly divided and hold out in the train &amp; validation split. Rather average of validation on each fold is being calculated which leads to a less biased model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*dYvLlQIXZ6sP9Dz9pPLTvg.png" /></figure><p>Thanks a lot for reading. Please let me know if any corrections/suggestions. Please do 👏 if you like the post. Thanks in advance…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf68bb26881a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/only-train-and-test-set-is-not-enough-for-generalizing-ml-model-significance-of-validation-set-cf68bb26881a">Only train and test set is not enough for generalizing ML model, Significance of Validation set</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>