<?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 Jason Carpenter on Medium]]></title>
        <description><![CDATA[Stories by Jason Carpenter on Medium]]></description>
        <link>https://medium.com/@jmcarpenter2?source=rss-5cccfad33640------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bIy22K1ob6-kR__R.</url>
            <title>Stories by Jason Carpenter on Medium</title>
            <link>https://medium.com/@jmcarpenter2?source=rss-5cccfad33640------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:44:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jmcarpenter2/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[Swifter 1.0.0: Automatically efficient Pandas and Modin DataFrame applies]]></title>
            <link>https://medium.com/@jmcarpenter2/swifter-1-0-0-automatically-efficient-pandas-and-modin-dataframe-applies-cfbd9555e7c8?source=rss-5cccfad33640------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfbd9555e7c8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[modin]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <dc:creator><![CDATA[Jason Carpenter]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 17:40:13 GMT</pubDate>
            <atom:updated>2020-10-12T17:40:13.054Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swifter 1.0.0: automatically efficient pandas and modin dataframe apply operations</h3><p>Since <a href="https://medium.com/@jmcarpenter2/swiftapply-automatically-efficient-pandas-apply-operations-50e1058909f9">it’s conception</a> over two years ago, the <a href="http://github.com/jmcarpenter2/swifter">swifter</a> algorithm has enabled performant pandas applies of user-defined functions (UDFs) for thousands of python programmers.</p><p>The algorithm leverages a combination of attempting to execute the quick solution (vectorization), estimation and extrapolation, and validation of output to ensure that dataframe applies are swift and accurate.</p><p>The impact made by the swifter algorithm is best captured by the following <a href="https://github.com/jmcarpenter2/swifter/blob/master/examples/swifter_speed_comparison.ipynb">performance benchmark</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*Xc2lFnMS9F4rsSpfa2NPBQ.png" /><figcaption>Swifter apply performance benchmark log-log plot. Small dataframe applies make use of linear complexity applies with minimal overhead and perform at near-pandas speed. Large dataframe applies leverage Dask multiprocessing and converge to Dask performance seamlessly without any effort from the user.</figcaption></figure><p>Due to swifter’s algorithmic approach, dataframe applies automatically converge to either serial or multiprocessing dependent on the size of the data and complexity of the function applied.</p><p>However, this isn’t even the entire story. Prior to deciding whether to leverage Dask for multiprocessing or revert to a simple pandas apply, swifter first attempts simply vectorizing the operation. This attempt can massively enhance performance of dataframe applies, but requires that the user structures the function in a way that can be vectorized. I will walk through how to structure your apply function to enable vectorization and parallelization in the Best Practices section below.</p><p>Swifter is not only a performant means of applying UDFs to dataframes, but it is easy to use and comes with a progress bar. Incorporating the swifter algorithm is as simple as follows:</p><pre>import pandas as pd<br>import swifter</pre><pre>df = pd.DataFrame(...)</pre><pre>df.<strong>swifter</strong>.apply(...)</pre><p>All we have to do is add .swifter to the command chain and now the dataframe has access to swifter’s efficient apply methods.</p><h3>Version 1.0.0</h3><p>Swifter recently released version 1.0.0, which <a href="https://github.com/jmcarpenter2/swifter/blob/master/docs/changelog.md">now includes</a> the following <a href="https://github.com/jmcarpenter2/swifter/blob/master/docs/documentation.md">efficient apply functionalities</a> for pandas dataframes:</p><ul><li>df.swifter.apply(...)</li><li>df.swifter.applymap(...)</li><li>df.swifter.rolling(...).apply(...)</li><li>df.swifter.resample(...).apply(...)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*lesZyv9LGdUoEO_1StvHIw.png" /><figcaption>Swifter 1.0.0 introduces compatibility with Modin dataframes.</figcaption></figure><p>And not only that, I am pleased to announce that version 1.0.0 also includes compatibility with Modin dataframes. If you’re not familiar with Modin dataframes, <a href="https://github.com/modin-project/modin">check them out here</a>. Modin dataframe’s homepage concisely explains their value proposition: “Scale your pandas workflow by changing one line of code.” It’s as simple as changing your import statement.</p><pre>import <strong>modin</strong>.pandas as pd<br>import swifter</pre><pre>df = pd.DataFrame(...)</pre><pre>df.<strong>swifter</strong>.apply(...)</pre><p>This new compatibility between swifter and Modin now allows users of Modin to continue scaling pandas workflows by only changing the import statement, even when the code leverages swifter for performance enhancements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*io4CTRMrFgGXoXva4aTcGw.png" /><figcaption>Swifter apply performance benchmark log-log plot for Modin dataframes. Modin dataframe apply is already performant, but swifter can further improve performance of Modin dataframes by leveraging vectorization.</figcaption></figure><p>It is worth noting that because Modin dataframes are already distributed and performant, swifter’s primary value-add to Modin dataframes is the vectorization apply attempt before reverting to Modin applies. Though this is the current state, tighter swifter~modin integration and performance enhancing capabilities are in the works. Stay tuned for more on this soon.</p><h4>Latest improvements</h4><p>As swifter continues to build out API compatibility with various pandas and modin apply methods, in parallel we have managed to solve longstanding issues with the library.</p><p>The most critical shortcoming that users of swifter have historically had to deal with is related to string processing. <a href="https://github.com/jmcarpenter2/swifter/issues/14">Swifter was largely unable to improve performance for dataframe columns that included strings.</a> Until now, that is.</p><p>In recent versions of Dask DataFrame, this string processing shortcoming was resolved. Over several string processing functions, we see approximately 2x speed-up over pandas applies.</p><p>By leveraging Modin dataframes for swifter dataframe applies which target string dtype columns, swifter now significantly improves performance over pandas when applying to text data.</p><p>Previously, users of swifter could use the method df.swifter.<strong>allow_dask_on_strings(True)</strong>.apply(...) approach to force swifter to use Dask as an attempt at improving performance over pandas applies. Since Dask didn’t used to improve performance in all cases, this was not the default option.</p><p>Now, it is no longer necessary to allow_dask_on_strings because the default apply to string data is to use Modin, which consistently improves performance over pandas for string processing. Users of swifter are still able to use the allow_dask_on_strings method to force swifter to use Dask instead of Modin for string processing, if desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*YtLoG57_bSvyOdQpGu6wHg.png" /><figcaption>Swifter performance benchmark string processing plot (actual scale). Dask apply was formerly less performant than pandas for processing string dtype columns. Now, Dask apply improves performance by 2x. New default Modin apply reduces string processing time by an additional 25% over Dask apply.</figcaption></figure><h3>Best practices</h3><p>The <a href="https://github.com/jmcarpenter2/swifter/blob/master/examples/swifter_apply_examples.ipynb">swifter apply examples notebook</a> indicates how to leverage swifter most effectively, but I find that the key to unlocking swifter’s potential is sometimes closer than we realize. As I mentioned in the beginning, before determining whether to use the base dataframe apply or leverage parallelism to increase performance, swifter first attempts to vectorize the operation.</p><p>Though vectorization is only possible in a subset of apply functions, it is important to know when this is possible. More generally, it is critical to know how to structure function code such that we can fully unlock swifter’s performance enhancing algorithm. A simple example follows, with setup:</p><pre>import pandas as pd<br>import numpy as np<br>import swifter</pre><pre>df = pd.DataFrame({<br>    &quot;gaussian&quot;: np.random.normal(size=1_000_000),<br>    &quot;str_date&quot;: [&quot;2020-01-01&quot;] * 1_000_000,<br>})</pre><p>Functions are vectorizable, if simple and direct enough. For example, we can square every number in a column.</p><pre>df.gaussian.swifter.apply(lambda x: x**2)</pre><p>Or we can convert strings to datetimes.</p><pre>df.str_date.swifter.apply(pd.to_datetime)</pre><p>But notice how these functions have no conditionality in them. They are simple in the sense that they are applying a specific data manipulation to the entire column. These direct applies of the operation can be done in a vectorized fashion because there is no <a href="https://en.wikipedia.org/wiki/Control_flow">control-flow</a> involved.</p><p>As we add control-flow to our user-defined functions we can end up preventing the function from being vectorized, or even improve performance at all. The below function will not only fail to leverage vectorization, but due to the if-else statement it will not even utilize parallelization. Instead, it will revert to a pandas apply.</p><pre>def square_or_sqrt(x):<br>    return x**2 if x &gt; 0 else x**(1/2)</pre><pre>df.gaussian.swifter.apply(square_or_sqrt)<br><strong>Pandas</strong> Apply: 100%|██████████████████████████████| 1000000/1000000 [00:00&lt;00:00, 1051074.93it/s]</pre><p>So how can we solve this? Well, one way is to use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html">np.where</a> instead of if-else control-flow statements. With this reformulation of the function we can now at least leverage automatic parallelization with Dask via swifter.</p><pre>def square_or_sqrt(x):<br>    return np.where(x &gt; 0, x**2, x**(1/2))</pre><pre>df.gaussian.swifter.apply(square_or_sqrt)<br><strong>Dask</strong> Apply: 100%|█████████████████████████████████████████| 24/24 [00:00&lt;00:00, 47.32it/s]</pre><p>Understanding how the structure of the function you wish to apply to the dataframe can impact swifter’s ability to improve performance is essential to unlocking swifter’s full potential.</p><h4>References</h4><p>Swifter GitHub: <a href="https://github.com/jmcarpenter2/swifter">https://github.com/jmcarpenter2/swifter</a></p><p>Swifter Docs: <a href="https://github.com/jmcarpenter2/swifter/blob/master/docs/documentation.md">Documentation</a> + <a href="https://github.com/jmcarpenter2/swifter/blob/master/docs/changelog.md">Changelog</a></p><p>Swifter Examples: <a href="https://github.com/jmcarpenter2/swifter/blob/master/examples/swifter_apply_examples.ipynb">Apply examples</a> + <a href="https://github.com/jmcarpenter2/swifter/blob/master/examples/swifter_speed_comparison.ipynb">Performance Benchmark</a></p><p>Modin: <a href="https://github.com/modin-project/modin">GitHub</a> + <a href="https://modin.readthedocs.io/en/latest/?badge=latest">Documentation</a></p><p>Dask: <a href="https://github.com/dask/dask">GitHub</a> + <a href="https://dask.org/">Documentation</a></p><h4>Contributor Contact: Jason Carpenter</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jasonmcarpenter/">https://www.linkedin.com/in/jasonmcarpenter/</a></p><p>GitHub: <a href="https://github.com/jmcarpenter2">https://github.com/jmcarpenter2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfbd9555e7c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swiftapply — automatically efficient pandas apply operations]]></title>
            <link>https://medium.com/@jmcarpenter2/swiftapply-automatically-efficient-pandas-apply-operations-50e1058909f9?source=rss-5cccfad33640------2</link>
            <guid isPermaLink="false">https://medium.com/p/50e1058909f9</guid>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[python-pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[dataframes]]></category>
            <dc:creator><![CDATA[Jason Carpenter]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 16:58:41 GMT</pubDate>
            <atom:updated>2020-06-04T23:55:22.015Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swifter — automatically efficient pandas apply operations</h3><p>Easily apply any function to a pandas dataframe in the fastest available manner</p><p>Time is precious. There is absolutely no reason to be wasting it waiting for your function to be applied to your pandas series (1 column) or dataframe (&gt;1 columns). Don’t get me wrong, pandas is an amazing tool for python users, and a majority of the time pandas operations are very quick.</p><p>Here, I wish to take the pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html"><strong>apply</strong></a> function under close inspection. This function is incredibly useful, because it lets you easily apply any function that you’ve specified to your pandas series or dataframe. But there is a cost — the apply function essentially acts as a for loop, and <a href="https://ys-l.github.io/posts/2015/08/28/how-not-to-use-pandas-apply/">a slow one at that</a>. This means that the apply function is a linear operation, processing your function at O(n) complexity.</p><p>Experienced users of pandas and python may be well aware of the options available to increase the speed of their transformations: vectorize your function, compile it with <a href="http://cython.org/">cython</a> or <a href="https://numba.pydata.org/">numba</a>, or use a parallel processing library such as <a href="https://dask.pydata.org/en/latest/">dask</a> or <a href="https://docs.python.org/3.4/library/multiprocessing.html?highlight=process">multiprocessing</a>. But there is likely a broad category of python users who are either unaware of these options, don’t know how to use them, or don’t want to take the time to add the appropriate function calls to speed up their operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*A_ULZ1INKLpURq2nL4eAog.png" /><figcaption>What do you do?</figcaption></figure><h3><strong>swifter</strong></h3><p><em>It’s highly effective!</em></p><p>Swifter, available on pip from the <a href="https://github.com/jmcarpenter2/swifter">swifter<strong> </strong>package</a>, makes it <em>easy</em> to apply any function to your pandas series or dataframe in the <em>fastest </em>available manner.</p><p>What does this mean? First, swifter tries to run your operation in a vectorized fashion. Failing that, it automatically decides whether it is faster to perform dask parallel processing or use a simple pandas apply.</p><p>So, how do we use it? First, let’s install swifter at the command line.</p><pre>$ pip install -U pandas<br>$ pip install swifter</pre><p>Next, import the function into your python notebook or .py file.</p><pre>import pandas as pd<br>import swifter</pre><p>Now, you are ready to use swifter.</p><pre>myDF[&#39;outCol&#39;] = myDF[&#39;inCol&#39;].swifter.apply(anyfunction)</pre><h3>Examples</h3><p><a href="https://nbviewer.jupyter.org/github/jmcarpenter2/swifter/blob/master/examples/swiftapply_examples.ipynb">This notebook</a> gives a couple examples of swifter usage on a &gt;71 million rows SF Bay Area Bikeshare data set, but I will also provide examples inline here. All applied functions are in bold.</p><p>Example 1 (vectorized):</p><pre>def <strong>bikes_proportion</strong>(x, max_x):<br>    return x * 1.0 / max_x</pre><pre>data[&#39;bike_prop&#39;] = data[&#39;bikes_available&#39;].swifter.apply(<br>                    <strong>bikes_proportion</strong>,<br>                    max_x=np.max(data[&#39;bikes_available&#39;]))</pre><p>Example 2 (tries vectorized -&gt; fails -&gt; uses dask parallel processing instead):</p><pre>def <strong>convert_to_human</strong>(datetime):<br>    return datetime.weekday_name + &#39;, the &#39; + str(datetime.day) + &#39;th day of &#39; + datetime.strftime(&quot;%B&quot;) + &#39;, &#39; + str(datetime.year)</pre><pre>data[&#39;humanreadable_date&#39;] = data[&#39;date&#39;].swifter.apply(<br>                             <strong>convert_to_human</strong>)</pre><p>Example 3 (how to make non-vectorized code (13.8s) into vectorized code (231ms)):</p><pre># Parallel processing b/c if-else statement makes it non-vectorized<br>def <strong>gt_5_bikes</strong>(x):<br>    if x &gt; 5:<br>        return True<br>    else:<br>        return False</pre><pre><em># computes in 13.8s<br></em>data[&#39;gt_5_bikes&#39;] = data[&#39;bikes_available&#39;].swifter.apply(<strong>gt_5_bikes</strong>)</pre><pre><br># Vectorized version<br>def <strong>gt_5_bikes_vectorized</strong>(x):<br>    return np.where(x &gt; 5, True, False)</pre><pre><em># computes in 231ms<br></em>data[&#39;gt_5_bikes_vec&#39;] = data[&#39;bikes_available&#39;].swifter.apply(<br>                         <strong>gt_5_bikes_vectorized</strong>)</pre><h3>Benchmarks</h3><p><a href="https://nbviewer.jupyter.org/github/jmcarpenter2/swifter/blob/master/examples/swiftapply_speedcomparison.ipynb">This notebook</a> contains benchmarks using 4 different functions on the same &gt;71 million rows data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*jyI1mSzTBu4suXkUqAsikw.png" /><figcaption>Swifter vectorizes when possible for ≥100x speed increase</figcaption></figure><p>The first benchmark I will discuss is the pd.to_datetime function. Looking at the figures above (time in seconds v. number of rows), and below (log10 of both quantities), it becomes clear that using a pandas apply of pd.to_datetime is an incredibly slow operation (&gt; 1 hour) on a data set of this size. Instead, it would be better to use the vectorized form of the operation, since it is a vectorized function. Swifter automatically does this, when possible.</p><pre>df[&#39;date&#39;].<strong>apply</strong>(<strong>pd.to_datetime</strong>) # very slow</pre><pre><strong>pd.to_datetime</strong>(df[&#39;date&#39;]) # vectorized - very fast</pre><pre>df[&#39;date&#39;].swifter.apply(<strong>pd.to_datetime</strong>) # also vectorized - very fast</pre><p>Below, I’ve included the log10-log10 plot of time (seconds) v. rows so that we can interpret the measurable difference in performance. Remember, this means that every tickmark represents a 10x change in the value. That means that the difference between pandas and dask is 10x, and the difference between pandas and swifter/vectorized is 100x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*FUhv0f_JCrhKIi35yYLrGg.png" /><figcaption>X is 1, 10, 100, 1000, …</figcaption></figure><p>In the event that you wish to apply a function that is not vectorizable, like convert_to_human(datetime) function in example 2, then a choice must be made. Should we use parallel processing (which has some overhead), or a simple pandas apply (which only utilizes 1 CPU, but has no overhead)?</p><p>Looking at the below figure (log10 scale), we can see that in these situations, swifter uses pandas apply when it is faster (smaller data sets), and converges to dask parallel processing when that is faster (large data sets). In this manner, the user doesn’t have to think about which method to use, regardless of size of the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*w3ZoFCM7bmhvA4OcXuHwVQ.png" /><figcaption>Swifter converges to pandas apply on small datasets and dask parallel processing on large ones</figcaption></figure><p>Admittedly, the difference between swifter/dask and pandas doesn’t look very impressive in the above plot when the number of rows is high (log10 rows &gt; 5). However, when we convert it to normal scale below, we see the true performance gain. Even with this slow non-vectorizable function, swifter’s utilization of dask parallel processing increases speed by 3x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*Ept6ODYsW1QJrHnjMXhfIw.png" /></figure><p>This adaptive functionality makes swifter an efficient, easy to use apply function for all situations.</p><p>Please leave a comment if there’s any functionality you’d like to see added, or if you have any feedback.</p><p>If you wish to use or contribute to the package, here is the github repository: <a href="https://github.com/jmcarpenter2/swifter">https://github.com/jmcarpenter2/swifter</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/jasonmcarpenter/">https://www.linkedin.com/in/jasonmcarpenter/</a></p><p>Twitter: <a href="https://twitter.com/jcarpenter542">https://twitter.com/jcarpenter542</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50e1058909f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parfit — quick and powerful hyper-parameter optimization with visualizations]]></title>
            <link>https://blog.mlreview.com/parfit-hyper-parameter-optimization-77253e7e175e?source=rss-5cccfad33640------2</link>
            <guid isPermaLink="false">https://medium.com/p/77253e7e175e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[parameterization]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <dc:creator><![CDATA[Jason Carpenter]]></dc:creator>
            <pubDate>Sun, 26 Nov 2017 19:01:50 GMT</pubDate>
            <atom:updated>2017-11-29T20:55:49.817Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parfit — quick and powerful hyper-parameter optimization with visualizations</h3><p>Machine learning can be complex — there are several steps involved which can limit the speed of the iterative modeling process, even for experienced practitioners. As a student in <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a>’s Introductory Machine Learning course at the University of San Francisco, I have learned that the modeling process can be simplified and sped up. This is the goal of the <a href="https://github.com/fastai/fastai">fast.ai library</a>, which is constantly being improved upon. The aim of this post is to facilitate quick and effective hyper-parameter optimization of machine learning models, a key part of the iterative modeling process.</p><h4><strong>Introduction to hyper-parameters</strong></h4><p>First, let’s take a step back and ask “what are hyper-parameters, and why do I care?” If you are familiar with these concepts, then please skip ahead to the next section.</p><p><em>Hyper-parameters</em> in the context of machine learning are the parameters of the machine learning model which make an impact on how the model fits to the training data, and therefore the predictions on the test data. We care about these because, for example, incorrectly specified hyper-parameters can lead to the model overfitting on the training data and predicting poorly on the test data when the model is put into production. On the other hand, optimally specified hyper-parameters can greatly increase the performance of the model.</p><p>In general, the <a href="http://scikit-learn.org/stable/">sklearn package</a> in python has reasonably intuitive and somewhat effective default hyper-parameters for most models, but we can do better.</p><h4><strong>Scoring on validation sets</strong></h4><p>It is important to understand what it means to give a <em>score</em> to a model’s ability to make predictions on a validation set. A variety of <a href="http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics">metrics</a> can be applied, dependent on the type of problem (<a href="https://en.wikipedia.org/wiki/Statistical_classification">classification</a>/<a href="https://en.wikipedia.org/wiki/Regression_analysis">regression</a>). While selecting a metric is important, dependent on the use case of the model, the most crucial decision is how to create an effective validation set which has the properties of the test/production set.</p><p><strong>Rachel Thomas from fast.ai wrote an excellent blog post on </strong><a href="http://www.fast.ai/2017/11/13/validation-sets/"><strong>how (and why) to create a good validation set.</strong></a><strong> Before continuing, I highly recommend reading this post.</strong></p><p>Here are some key definitions extracted directly from her article.</p><ul><li>the <em>training set </em>is used to train a given model</li><li>the<strong> <em>validation set</em> </strong>is used to choose between models (for instance, does a random forest or a neural network better for your problem? Do you want a random forest with 40 trees or 50 trees?)</li><li>the<em> test set</em> tells you how you’ve done. If you’ve tried out a lot of different models, you may get one that does well on your validation set just by chance, and having a test set helps make sure that is not the case.</li></ul><p>The important take-home message from her post is:</p><blockquote>For certain data sets (e.g. time series), a random subset of the training data is not a good validation set. That is, it will not be representative of the test set for various reasons (e.g. a time component). We need to create an effective validation set for scoring our models.</blockquote><p>I am going to continue assuming that you have read Rachel’s article. That is, I will assume you know how to create an effective validation set, and have already done so.</p><h4><strong>How do we perform hyper-parameter optimization?</strong></h4><p>Let’s work with an example here: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">RandomForestClassifier</a> (implemented in sklearn). For reasons taught in Jeremy’s Introductory Machine Learning course (soon to be available as a MOOC), the two key parameters we are interested in are <em>max_features</em> and <em>min_samples_leaf</em>. That is, we want to know what combination of <em>max_features</em> and <em>min_samples_leaf</em> give us the best score on our validation set.</p><p>To do this, we typically perform an exhaustive grid search over all combinations of <em>max_features</em> and <em>min_samples_leaf</em>. The most commonly used package for this technique is <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV">GridSearchCV</a> (from sklearn). This package is highly effective if you are using a completely randomized training set that does not contain a time component as, by default, it internally scores using <a href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)">cross-validation</a>. This is an optimal method for estimating hyper-parameters because it takes the average score over all folds in the cross-validation routine and gives the best set of hyper-parameters based on this average.</p><p><strong>So… what’s the problem?</strong></p><p>Cross-validation using GridSearchCV optimizes on the training data! As mentioned in Rachel’s post, this is dangerous and not applicable to most real-world modeling problems (especially time series data). Instead, we want to optimize our hyper-parameters on the validation set.</p><p>Note that in GridSearchCV it is possible to specify a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.PredefinedSplit.html">PredefinedSplit</a> object for separating the training and validation sets within the GridSearchCV, but it is better practice to split the training and validation sets beforehand and enter the validation set as the scoring set to avoid confusion and bleeding over between your training and validation sets.</p><p>Now that we understand the problem, what’s our solution?</p><h3><strong>The solution is </strong><a href="https://github.com/jmcarpenter2/parfit"><strong>parfit</strong></a><strong>!</strong></h3><p>Introducing: <a href="https://github.com/jmcarpenter2/parfit">parfit</a>, a new package for hyper-parameter optimization, which (using parallel processing) allows the user to perform an exhaustive grid search on a model. This package has the following advantages:</p><ul><li><strong>Validate: </strong>Flexibly specify the validation set to score on</li><li><strong>Score: </strong>Flexibly choose the scoring metric</li><li><strong>Visualize: </strong>Optionally plot the scores over the grid of hyper-parameters entered</li><li><strong>Optimize:</strong> Automatically return the best model, associated hyper-parameters, and score of that model</li><li><strong>Easy to use: </strong>Do all of this with only one function call</li></ul><p><strong>Sounds great, how do i use it?</strong></p><p>To install the package, enter the following command in your terminal:</p><pre>pip install parfit</pre><p>Then, in your Jupyter notebook (or python program) run the following line to import the module:</p><pre>import parfit.parfit as pf</pre><p>Now, you are ready to rock and roll! In just a couple lines of code, you can find the best set of hyper-parameters for your validation set. Here is an example of how to perform an exhaustive search over a parameter grid for RandomForestClassifier. Notice below that I have only specified the RandomForestClassifier class, not instantiated the object with parentheses ().</p><pre>import numpy as np<br>from sklearn.model_selection import ParameterGrid<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import roc_auc_score</pre><pre>paramGrid = ParameterGrid({<br>    &#39;min_samples_leaf&#39;: [1,3,5,10,15,25,50,100,125,150,175,200],<br>    &#39;max_features&#39;: [&#39;sqrt&#39;, &#39;log2&#39;, 0.4, 0.5, 0.6, 0.7],<br>    &#39;n_estimators&#39;: [60],<br>    &#39;n_jobs&#39;: [-1],<br>    &#39;random_state&#39;: [42]<br><em>})</em></pre><pre>best_model, best_score, all_models, all_scores = pf.bestFit(RandomForestClassifier, paramGrid, <br>     X_train, y_train, X_val, y_val, <br>     metric=roc_auc_score, bestScore=&#39;max&#39;, scoreLabel=&#39;AUC&#39;)</pre><pre>print(best_model)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*HZfSg4ZezfgYCqsLE4ssqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*SBHceS0JcgKPCDT8tUZJPA.png" /></figure><p>From inspecting this grid, we can see that on these data, the highest scoring models used<em> max_features = 0.4 or 0.6 </em>and<em> min_samples_leaf = 100</em>. Not only that, we’ve automatically returned the model, with the single set of parameters which maximized the score on the validation set. Additionally, we’ve returned the score of that best model, so we know how we’re doing.</p><p>This package has support for varying any number of parameters, but only plotting support for a grid varying over 1–3 parameters (due to visualization limitations).</p><p>The <a href="https://github.com/jmcarpenter2/parfit">parfit github page</a> has documentation for each function in the package and notes on how to use the functions. There is also a parfit_ex.ipynb that gives examples of how to use for varying 1, 2, and 3 parameters on a generated data set.</p><p>My colleague and fellow Master’s in Analytics candidate at the University of San Francisco, Vinay Patlolla, wrote an excellent post in which he utilized parfit to show <a href="https://medium.com/@vinnsvinay/how-to-make-sgd-classifier-perform-as-well-as-logistic-regression-using-parfit-cc10bca2d3c4">how to make SGD Classifier perform as well as Logistic Regression</a>. In that post, there is also brief section on how to use parfit.</p><h4><strong>What is the full process?</strong></h4><ol><li>Create an effective <strong>validation set</strong></li><li>Choose your <strong>model(s)</strong></li><li>Create a <strong>parameter grid </strong>over which to evaluate your model on the validation set</li><li>Use <strong>parfit</strong> to visualize the scores over the grid and select the best model</li><li><strong>Re-train model</strong> on full training set, using<strong> best parameters</strong> from parfit</li><li><strong>Apply</strong> re-trained model<strong> to test set</strong></li></ol><p><strong>Current limitations of parfit:</strong></p><ul><li>The package is designed to be used with sklearn machine learning models</li><li>Need to pass a ParameterGrid object, as shown in above example</li></ul><p><strong>Have suggestions to improve the package?</strong></p><p>Let me know or <a href="https://github.com/jmcarpenter2/parfit">contribute to the package</a>!</p><p><strong>Linkedin</strong>: <a href="https://www.linkedin.com/in/jasonmcarpenter/">https://www.linkedin.com/in/jasonmcarpenter/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77253e7e175e" width="1" height="1" alt=""><hr><p><a href="https://blog.mlreview.com/parfit-hyper-parameter-optimization-77253e7e175e">Parfit — quick and powerful hyper-parameter optimization with visualizations</a> was originally published in <a href="https://blog.mlreview.com/">ML Review</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>