<?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 Mike McCarty on Medium]]></title>
        <description><![CDATA[Stories by Mike McCarty on Medium]]></description>
        <link>https://medium.com/@mike.mccarty?source=rss-208afe45c999------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*V2IlEAqdqP8IQsUPRvI6dA.jpeg</url>
            <title>Stories by Mike McCarty on Medium</title>
            <link>https://medium.com/@mike.mccarty?source=rss-208afe45c999------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:27:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mike.mccarty/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[Custom Machine Learning Estimators at Scale on Dask & RAPIDS]]></title>
            <link>https://medium.com/capital-one-tech/custom-machine-learning-estimators-at-scale-on-dask-rapids-e2b9519a6d1f?source=rss-208afe45c999------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2b9519a6d1f</guid>
            <category><![CDATA[rapids-ai]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Mike McCarty]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 17:16:00 GMT</pubDate>
            <atom:updated>2021-03-04T17:16:00.535Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to build reusable components that integrate with Scikit-learn, Dask, and RAPIDS</h4><figure><img alt="man holding iphone and wearing black headphones with white music vector icons connecting the 2 devices" src="https://cdn-images-1.medium.com/max/936/0*jSYcd9sXfkao-Byq.jpg" /></figure><p>When building reusable data science and machine learning code, developers often need to add custom business logic around existing open source libraries, such as scikit-learn. These customization may perform data preprocessing, segment that data in a specific way or implement a proprietary algorithm. Custom logic results in more code to understand and maintain, which adds complexity and introduces risk. This blog post will discuss how to leverage the <a href="https://scikit-learn.org/stable/developers/develop.html">scikit-learn library’s API</a> to add such customizations in a way that can minimize code, reduce maintenance, facilitate reuse, and provide the ability to <a href="https://medium.com/capital-one-tech/dask-and-rapids-the-next-big-things-for-data-science-and-machine-learning-at-capital-one-d4bba136cc70">scale</a> with technologies such as <a href="https://dask.org/">Dask</a> and <a href="https://rapids.ai/">RAPIDS</a>.</p><h3>Why is it difficult to follow the scikit-learn API in modeling code?</h3><p>The end goal of any machine learning endeavor is usually to get the best model for a given dataset as quickly as possible. In machine learning, so much time is spent on data processing, model training, and validation that the design and maintainability of the code created in the process is sometimes overlooked. In a world of limited resources, perhaps this prioritization makes sense. Afterall, it is the model that will be put into production, not the code that produced it. In banks and other financial institutions, models must go through a validation process — where reproducibility is critical — before they are deployed into production. Once the model is deployed, the code that produced it will often sit in a git repository untouched for weeks, months, or even years. Until one day when a model developer, which may or may not be the original author, will come back to the code to update the model. They will greatly benefit — in time and reduced cost — from a well tested and documented repository that is easy to understand so they can get to work quickly.</p><p>In practice, following standards and applying them can be challenging because</p><ul><li>Standards must be understood before they can be applied.</li><li>Applying a standard to your problem takes effort.</li></ul><p>Overcoming these challenges takes careful thought and requires precious time that may not be abundant on a data science project. The PyData ecosystem is composed of many evolving standards and APIs making it difficult to keep up with the changes. All of this can slow down the model development process so the path of least resistance is to use a library wrapped in your own design that best suits your application. However, this often leads to problems such as <a href="https://scikit-learn.org/stable/common_pitfalls.html#data-leakage">data leaks</a> due to user error or repeated code because the design was not modular enough to allow extensions. In the latter case, the maintenance overhead is high due to an increasingly large and complex code base where fixing bugs or scaling, even with Dask and RAPIDS, becomes challenging.</p><h3>Scikit-learn example</h3><p>We will use the following example from the scikit-learn <a href="https://scikit-learn.org/stable/tutorial/statistical_inference/putting_together.html#pipelining">documentation </a>to illustrate the points in this post.</p><pre>from sklearn import datasets<br>from sklearn.decomposition import PCA<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.pipeline import Pipeline<br>from sklearn.model_selection import GridSearchCV, train_test_split<br>import numpy as np<br><br>X_digits, y_digits = datasets.load_digits(return_X_y=True)<br><br># Define a pipeline to search for the best combination of PCA truncation<br># and classifier regularization.<br>pca = PCA()<br># set the tolerance to a large value to make the example faster<br>logistic = LogisticRegression(max_iter=10000, tol=0.1)<br>pipe = Pipeline(steps=[(&#39;pca&#39;, pca), (&#39;logistic&#39;, logistic)])<br># Parameters of pipelines can be set using ‘__’ separated parameter names:<br>param_grid = {<br>    &#39;pca__n_components&#39;: [5, 15, 30, 45, 64],<br>    &#39;logistic__C&#39;: np.logspace(-4, 4, 4),<br>}<br><br>search = GridSearchCV(pipe, param_grid, n_jobs=-1)<br><br>X_train, X_test, y_train, y_test = train_test_split(X_digits, y_digits, random_state=123)<br><br>search.fit(X_train, y_train)<br><br>best = search.best_estimator_<br><br>print(f&quot;Training set score: {best.score(X_train, y_train)}&quot;)<br>print(f&quot;Test set score: {best.score(X_test, y_test)}&quot;)</pre><p>Output:</p><pre>Training set score: 1.0<br>Test set score: 0.9666666666666667</pre><h3>Customizing the Scikit-learn Example</h3><p>Suppose we want to modify this example to mutate data after the PCA step. Perhaps we have a set of features that we always want to include from another data source or need to tokenize the data. We could do this by removing the pipeline and adding a function to perform the mutation on X.</p><pre>def mutate(X):<br>    &quot;&quot;&quot;Mutates X&quot;&quot;&quot;<br>    # ... do something ...<br>    return X<br><br>pca = PCA(n_components=search.best_params_[&#39;pca__n_components&#39;])<br>logistic = LogisticRegression(<br>    max_iter=10000, tol=0.1, C=search.best_params_[&#39;logistic__C&#39;])<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X_digits, y_digits, random_state=123)<br><br>X_train = pca.fit_transform(X_train, y_train)<br>X_train = mutate(X_train)<br>logistic = logistic.fit(X_train, y_train)<br><br>X_test = pca.transform(X_test) # &lt;- Don&#39;t call fit again!<br>X_test = mutate(X_test) # &lt;-Don’t forget to call mutate on X_test!<br><br>print(f&quot;Training set score: {logistic.score(X_train, y_train)}&quot;)<br>print(f&quot;Test set score: {logistic.score(X_test, y_test)}&quot;)</pre><p>Output:</p><pre>Training set score: 1.0<br>Test set score: 0.9666666666666667</pre><p>This allows for customizations without requiring the user to learn about scikit-learn pipelines. However, if you are collaborating with or developing a library for other teams this pattern quickly becomes problematic. This code could be encapsulated into a class and then be copied many times. Some of those classes could even be slightly modified to add extended functionality or scale. Additionally, if you discover a bug in one of the classes, you will potentially have many places to fix it. <em>Happy hunting!</em></p><p>Consider an alternative that extends the scikit-learn API by adding a custom estimator that contains the mutation logic.</p><pre>from sklearn.base import BaseEstimator, TransformerMixin<br>from abc import ABCMeta<br><br>class Mutate(TransformerMixin, BaseEstimator, metaclass=ABCMeta):<br>    def fit(self, X, y):<br>        return self<br>    <br>    def transform(self, X):<br>        &quot;&quot;&quot;Mutates X&quot;&quot;&quot;<br>        # ... do something ...<br>        return X<br><br>pca = PCA(n_components=search.best_params_[&#39;pca__n_components&#39;])<br>logistic = LogisticRegression(max_iter=10000, tol=0.1, C=search.best_params_[&#39;logistic__C&#39;])<br><br>pipe = Pipeline(steps=[(&#39;pca&#39;, pca), (&#39;mutate&#39;, Mutate()), (&#39;logistic&#39;, logistic)])<br><br>X_train, X_test, y_train, y_test = train_test_split(X_digits, y_digits, random_state=123)<br><br>pipe.fit(X_train, y_train)<br>print(f&quot;Training set score: {pipe.score(X_train, y_train)}&quot;)<br>print(f&quot;Test set score: {pipe.score(X_test, y_test)}&quot;)</pre><p>Output:</p><pre>Training set score: 1.0<br>Test set score: 0.9666666666666667</pre><p>By adding a custom estimator, we have encapsulated the mutation in a way that allows us to insert it into the exact step of the pipeline. An additional benefit to this approach is that we only have to maintain one class that can grow over time to contain more functionality and scale.</p><pre>def transform(self, X):<br>    &quot;&quot;&quot;Mutates X&quot;&quot;&quot;<br>    # ... do something ...<br>    if is_dask_collection(X):<br>        # Do Dask things<br>    elif is_rapids_collection(X):<br>        # Do RAPIDS things<br>    return X</pre><p>The primary disadvantage of this approach, and probably why it is not followed, is that the developer needs enough understanding of `scikit-learn` to fit the problem into the API.</p><h3>Existing scalable custom estimators in Dask &amp; RAPIDS</h3><p>Actually this is not a new pattern. In fact, we already have plenty of examples of custom scalable estimators in the PyData community. <a href="https://ml.dask.org/">dask-ml</a> is a library of scikit-learn extensions that scale data and perform parallel computations using Dask. It provides many drop-in replacements for scikit-learn estimators.</p><p>Here is what the toy example pipeline looks like with dask-ml.</p><pre>from dask.distributed import Client, progress<br>client = Client(processes=False, threads_per_worker=4,<br>                n_workers=1, memory_limit=&#39;3GB&#39;)</pre><pre>from dask_ml.datasets import make_classification<br>from dask_ml.decomposition import PCA<br>from dask_ml.linear_model import LogisticRegression<br>from dask_ml.model_selection import GridSearchCV, train_test_split<br>from sklearn.pipeline import Pipeline  # &lt;-- using the sklearn pipeline<br>import numpy as np<br><br>X, y = make_classification(n_samples=1000, n_features=20,<br>                           chunks=100, n_informative=4,<br>                           random_state=0)<br><br># Define a pipeline to search for the best combination of PCA truncation<br># and classifier regularization.<br>pca = PCA()<br># set the tolerance to a large value to make the example faster<br>logistic = LogisticRegression(fit_intercept=False, max_iter=10000, tol=0.1)<br>pipe = Pipeline(steps=[(&#39;pca&#39;, pca), (&#39;logistic&#39;, logistic)])<br># Parameters of pipelines can be set using ‘__’ separated parameter names:<br>param_grid = {<br>    &#39;pca__n_components&#39;: [5, 15, 30, 45, 64],<br>    &#39;logistic__C&#39;: np.logspace(-4, 4, 4),<br>}<br><br>search = GridSearchCV(pipe, param_grid, n_jobs=-1)<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=123)<br><br>search.fit(X_train, y_train)<br><br>best = search.best_estimator_<br><br>print(f&quot;Training set score: {best.score(X_train, y_train)}&quot;)<br>print(f&quot;Test set score: {best.score(X_test, y_test)}&quot;)</pre><p>Alternatively, one can use <a href="https://docs.rapids.ai/api/cuml/stable/">cuML</a> ‘s drop-in replacements to scale on NVIDIA GPU’s with RAPIDS.</p><pre>from dask.distributed import Client<br>from dask_cuda import LocalCUDACluster<br>from cuml.dask.datasets.classification import make_classification<br><br>cluster = LocalCUDACluster()<br>client = Client(cluster)<br><br>X, y = make_classification(n_samples=1000, n_features=20,<br>                           chunks=100, n_informative=4,<br>                           random_state=0)</pre><pre>from cuml.dask.decomposition import PCA<br>from cuml.linear_model import LogisticRegression<br><br>pca = PCA()<br># set the tolerance to a large value to make the example faster<br>logistic = LogisticRegression(max_iter=10000, tol=0.1)<br>pipe = Pipeline(steps=[(&#39;pca&#39;, pca), (&#39;logistic&#39;, logistic)])</pre><h3>Designing your own scikit-learn estimators that scale with Dask &amp; RAPIDS</h3><p>At this point, we have shown how the same pipeline can be scaled in two ways and you may see a pattern emerging. The data structures and modeling algorithms depend on the same underlying corresponding libraries, but are loosely coupled from one another. In other words, we have separated the data loading logic from the computation, which relies on either the <em>array-like </em>or <em>dataframe</em> API. Under the hood, we see that the Dask estimators know how to deal with Dask collections and the cuML estimators know how to deal with RAPIDS collections. It all works if we read the data using the library that matches the estimator. Can we build our own estimators following this pattern to encapsulate custom business logic in a way that scales on both Dask and RAPIDS?</p><p>First let’s look at the ways to read data for in-memory, distributed, and accelerated frameworks.</p><pre>import pandas as pd<br>df = pd.read_csv(...)<br><br>import dask.dataframe as dd<br>df = dd.read_csv(...)<br><br>import cudf as cdf<br>df = cdf.read_csv(...)</pre><p>Notice, all three of these libraries provide drop-in replacements that can be used as an abstraction layer that generalizes reading data into memory and data operations. Once we have a <em>dataframe-like</em> structure, we can define an estimator that makes careful assumptions about the data API.</p><pre>from mylib import CustomEstimator<br>est = CustomEstimator(**params)<br>est.fit(df)</pre><p>Alternatively, if we want to standardize on the array interface, our estimator’s fit method can accept X’s and y’s. We have found that the <em>array-like</em> API is more consistent for scikit-learn tasks across the three frameworks making our custom estimator code more generalizable for scaling. Below we show a slightly modified version of our CustomEstimator usage for the <em>array-like</em> interface.</p><pre>from mylib import CustomEstimator<br>est = CustomEstimator(**params)<br>X, y = df[features].values, df[target].values<br>est.fit(X, y)</pre><h3>Custom scikit-learn estimator</h3><p>With an understanding of a basic design for separating data reading and manipulations from the business logic, let’s walk through an example of what this might look like in practice. Below, we define our own custom cross validation class CustomSearchCV that implements an in-memory version of the model training logic following the scikit-learn API.</p><pre>from sklearn.base import BaseEstimator, clone<br>from sklearn.model_selection import train_test_split<br>import copy<br>import pandas as pd<br>import numpy as np<br><br>class CustomSearchCV(BaseEstimator):<br>    <br>    def __init__(self, estimator, cv, logger):<br>        self.estimator = estimator<br>        self.cv = cv<br>        self.logger = logger<br>    <br>    def fit(self, X, y=None, **fit_kws):<br>        if isinstance(X, pd.DataFrame):<br>            X = X.values<br>        # Insert more guards here!<br>            <br>        X_base, X_holdout, y_base, y_holdout = train_test_split(<br>            X, y, random_state=123)<br>        <br>        self.split_scores_ = []<br>        self.holdout_scores_ = []<br>        self.estimators_ = []            <br>        <br>        for train_idx, test_idx in self.cv.split(X_base, y_base):<br>            X_test, y_test = X_base[test_idx], y_base[test_idx]<br>            X_train, y_train = X_base[train_idx], y_base[train_idx]<br><br>            estimator_ = clone(self.estimator)<br>            estimator_.fit(X_train, y_train, **fit_kws)<br><br>            self.logger.info(&quot;... log things ...&quot;)<br>            self.estimators_.append(estimator_)<br>            self.split_scores_.append(estimator_.score(X_test, y_test))            <br>            self.holdout_scores_.append(<br>                estimator_.score(X_holdout, y_holdout))<br>    <br>        self.best_estimator_ = \<br>                self.estimators_[np.argmax(self.holdout_scores_)]<br>        return self</pre><p>CustomSearchCV works well with existing estimators, such as sklearn.model_selection.RepeatedKFold and xgboost.XGBRegressor. Users can even define their own folding class and inject it into our estimator. An example of usage is shown below.</p><pre>from sklearn.model_selection import RepeatedKFold<br>import xgboost as xgb<br><br>from mylib import make_classifier_data, logger<br><br>X, y = make_classifier_data(<br>    n_samples=100_000,<br>    n_features=100,<br>    response_rate=0.25,<br>    predictability=0.25,<br>    random_state=123,<br>)<br><br>cv = RepeatedKFold(n_splits=2, n_repeats=2, random_state=2652124)<br>clf = CustomSearchCV(xgb.XGBClassifier(n_jobs=-1), cv, logger)<br><br>clf.fit(X, y)<br>clf.best_estimator_</pre><h3>Scale with Dask</h3><p>CustomSearchCV can work with Dask collections with a few minor modifications to the fit method. First, create a Dask client to connect to your cluster.</p><pre>from dask.distributed import Client, progress<br><br>client = Client()<br>client</pre><p>Then add the following logic to check the input data to determine whether or not it is a Dask collection.</p><pre>from dask.base import is_dask_collection<br>import dask.dataframe as dd<br>...<br>    def fit(self, X, y=None, **fit_kws):<br>        if isinstance(X, dd.DataFrame):<br>            X = X.to_dask_array(lengths=True)<br>        elif isinstance(X, pd.DataFrame):<br>            X = X.values<br>        if is_dask_collection(X):<br>            from dask_ml.model_selection import train_test_split<br>        else:<br>            from sklearn.model_selection import train_test_split<br>        ...</pre><p>Now, we can read (or generate) data using Dask and inject a Dask-enable estimator into our CustomSearchCV object. In this case, we inject the xgb.dask.DaskXGBClassifier.</p><pre>from sklearn.model_selection import RepeatedKFold<br>import xgboost as xgb<br><br>from mylib import logger, make_classifier_data<br><br>X, y = make_classifier_data(<br>    n_samples=100_000,<br>    n_features=1000,<br>    response_rate=0.25,<br>    predictability=0.25,<br>    random_state=123,<br>    dask_ml=True,<br>    chunks=1000<br>)<br><br>cv = RepeatedKFold(n_splits=2, n_repeats=2, random_state=2652124)<br>clf = CustomSearchCV(xgb.dask.DaskXGBClassifier(), cv, logger)<br><br>clf.fit(X, y)<br>clf.best_estimator_</pre><h3>Scale with GPUs</h3><h4>Single GPU</h4><p>After making similar modifications to CustomSearchCV we can perform training on a single GPU by initializing xgb.XGBClassifier with tree_method=&quot;gpu_hist&quot;. In this case, we don&#39;t need to modify the data reading (or generation) since XGBoost knows how to move data onto the GPU.</p><pre>from sklearn.model_selection import RepeatedKFold<br>from mylib import make_classifier_data, logger<br>import xgboost as xgb<br><br>X, y = make_classifier_data(<br>    n_samples=100_000,<br>    n_features=1000,<br>    response_rate=0.25,<br>    predictability=0.25,<br>    random_state=123<br>)<br>cv = RepeatedKFold(n_splits=2, n_repeats=2, random_state=2652124)<br>xgb_clf = xgb.XGBClassifier(n_jobs=-1, tree_method=&quot;gpu_hist&quot;)<br>clf = CustomSearchCV(xgb_clf, cv, logger)<br>clf.fit(X, y)<br>clf.best_estimator_</pre><h4>Single node, multiple GPU</h4><p>Many systems have multiple GPUs that can be combined to form a single host cluster using Dask and RAPIDS. Below, we initialize xgb.dask.DaskXGBClassifier with tree_method=&quot;gpu_hist&quot; and connect it to a dask_cuda.LocalCUDACluster. By default, the LocalCUDACluster will add a cuda-worker (GPU worker) for each GPU on the host. If we run this code on a system with eight GPUs, we will have an eight worker cluster. <a href="https://www.nvidia.com/en-us/design-visualization/nvlink-bridges/">NVLink</a> and <a href="https://arrow.apache.org/">Apache Arrow</a> allow for extremely efficient distributed data access among the GPUs.</p><p>Additionally, as GPU memory fills, the data will spill to system memory, which is typically much larger than what is available on the GPUs. This makes single node, multiple GPU computing well suited for many data science and machine learning problems. The example below shows the usage with no modifications to the CustomSearchCV class.</p><pre>from sklearn.model_selection import RepeatedKFold<br>from mylib import make_classifier_data, logger<br><br>import xgboost as xgb<br><br>cv = RepeatedKFold(n_splits=2, n_repeats=2, random_state=2652124)<br>dclf = xgb.dask.DaskXGBClassifier(tree_method=&quot;gpu_hist&quot;)<br>clf = CustomSearchCV(dclf, cv, logger)</pre><pre>from dask.distributed import Client<br>from dask_cuda import LocalCUDACluster<br><br>cluster = LocalCUDACluster()<br>client = Client(cluster)</pre><pre>X, y = make_classifier_data(<br>    n_samples=100_000,<br>    n_features=1000,<br>    response_rate=0.25,<br>    predictability=0.25,<br>    random_state=123,<br>    dask_ml=True,<br>    chunks=1000<br>)<br>X = X.persist()<br><br>dclf.client = client<br>clf.fit(X, y)<br>clf.best_estimator_</pre><p>Inspect the Dask dashboard and GPU utilization while running this code. Notice the Dask cluster is busy doing work and then pauses while the GPU utilization spikes. Here we are splitting data in Dask on the system memory and CPU, then training the <a href="https://xgboost.readthedocs.io/en/latest/tutorials/model.html">XGBoost</a> model on GPUs. A future improvement is to perform the training splits on the GPU.</p><p>The CustomSearchCV estimator can contain custom logic for scalable hyperparameter tuning or perform some of the pruning, regularization, and early stopping techniques discussed in a previous post on <a href="https://www.capitalone.com/tech/machine-learning/how-to-control-your-xgboost-model/">controlling XGBoost models</a>.</p><h3>Notes</h3><p>Here are a few additional notes to consider:</p><ul><li>Standardizing on the array-like interface for internal data structures early in the fit procedure allows for reduced complexity related to scaling with Dask and RAPIDS.</li><li>Make sure X values pulled from dataframes contain only features for training and seperate labels as 1d arrays or pd.Series.</li><li>Make sure X values do not contain columns used for segmentation, such as dates.</li><li>Minimize dataframe to array conversions to avoid performance bottlenecks.</li><li>Methods should return collections that match the input type.</li><li>Developers should use the check_estimator helper function in sklearn.utils.estimator_checks to verify that their custom estimators adhere to the API.</li></ul><h3>Conclusion</h3><p>In this post, we have discussed patterns for adding custom functionally to scikit-learn modeling code. We have found that by following the scikit-learn API we can minimize customizations and encapsulate scaling logic in a single place. This reduces the cost of maintenance over time and provides developers with examples of how to integrate their code into the ecosystem. Following a standard API allows us to share estimators and combine them to serve many use cases.</p><p><em>Originally published at </em><a href="https://www.capitalone.com/tech/machine-learning/custom-machine-learning-estimators-on-dask-and-rapids/"><em>https://www.capitalone.com</em></a><em>.</em></p><p><em>DISCLOSURE STATEMENT: © 2021 Capital One. Opinions are those of the individual author. Unless noted otherwise in this post, Capital One is not affiliated with, nor endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are property of their respective owners.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2b9519a6d1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capital-one-tech/custom-machine-learning-estimators-at-scale-on-dask-rapids-e2b9519a6d1f">Custom Machine Learning Estimators at Scale on Dask &amp; RAPIDS</a> was originally published in <a href="https://medium.com/capital-one-tech">Capital One Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dask and RAPIDS: The Next Big Things for Data Science and Machine Learning at Capital One]]></title>
            <link>https://medium.com/capital-one-tech/dask-and-rapids-the-next-big-things-for-data-science-and-machine-learning-at-capital-one-d4bba136cc70?source=rss-208afe45c999------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4bba136cc70</guid>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rapids-ai]]></category>
            <dc:creator><![CDATA[Mike McCarty]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 15:01:01 GMT</pubDate>
            <atom:updated>2019-11-25T15:01:01.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXtMfGFLYzdcPZuY9z7UcQ.gif" /></figure><h4><strong>By </strong>Ryan McEntee, Senior Director of Software Engineering and Mike McCarty, Director of Software Engineering</h4><h3><strong>Setting the Stage</strong></h3><p>Over the past 3+ years, I’ve had the opportunity to lead Capital One’s engineering effort to modernize our enterprise Data Science, Quantitative Analyst and Data Analyst platforms. Our core objective was to migrate our enterprise users of data from an on-premises, predominantly SAS-based platform to a custom built, cloud native platform that supported a wide variety of open source technologies. As you can imagine, my team and I have learned a tremendous amount from this experience, but what might be surprising is that not all of the lessons have been technical.</p><p>Our early strategy entailed looking to top Data Science and Machine Learning Engineering talent (both internal and external to the company), and our industry trend research to understand the leading open source technologies and platforms in the space. We also spent a tremendous amount of time engaging with end users from across the enterprise, covering a wide spectrum of technical acumen, to identify current pain points that we had to address. Addressing these pain points was very important as our ultimate goal was to not only enable the latest and greatest technology, but to also improve the efficiency and efficacy of our end user population.</p><p>After delivering the first iteration of our new cloud-based platform, we saw rapid, widespread adoption along with great feedback. Mission accomplished, right? Unfortunately, that was not the case. Almost immediately, we noticed a significant number of the largest AWS instances being spun up within the platform with users only utilizing 1 of the 128 available cores on each instance. Additionally, the jobs running on these instances would run for many hours as they were storing up to 3TB of data in memory using single threaded Python or R. With one of our goals being to increase compute utilization, missing the mark would be an understatement with these workloads.</p><p>Despite all of the emphasis we put on understanding the pain points of our end users, we failed to consider the inevitable skill transformation our end user population would endure.</p><h3><strong>Understanding People Transformation is Key to Success</strong></h3><p>In all of our user research, we didn’t realize just how much training and support the SAS users would need to be able to parallelize jobs using open source technologies. It was very easy for them to do this in SAS, but it was very difficult and time consuming to parallelize their workloads without it.</p><p>For example, a legacy SAS user would first need to become proficient in the most popular Python computational libraries, many of which do not utilize multiple CPU cores let alone multiple servers. Once parallelization is required to scale for larger data sets, they would also need to become proficient in Spark to re-code their solution. The re-code would likely be significant as many Python computational libraries (i.e. NumPy &amp; Pandas) are not performant in Spark and the dataframe APIs are different. Additionally, when a job crashes in Spark, to effectively debug the error, the end users would need to know Java. Considering that our business can’t stop operating while end users learn these new technologies, the outlook to complete this transformation had a very long tail.</p><p>Well, what about the engineers; couldn’t they help lift the burden of re-coding from Python to Spark? The short answer is “no.” End users of data at Capital One greatly outnumber our engineering workforce, so developing their skills to enable them to self-serve was key to our success.</p><p>This is where Dask and RAPIDS enter the picture.</p><h3><strong>Why Dask and RAPIDS?</strong></h3><p>Dask offers a promising solution for scaling Python workloads where end users can leverage a familiar API, and avoid the need for learning Spark and adjusting their code for incompatibilities. Yes, there is still learning required to leverage Dask, but the barrier to entry is much lower than with Spark. RAPIDS, the GPU-accelerated data science libraries incubated by NVIDIA, offers the same API compatibility and enables NVIDIA GPU computing from Python. What has been just as compelling as the lower barrier to entry is that Dask and RAPIDS have also shown impressive performance gains when applied to some existing use cases.</p><p>At Capital One, early implementations of Dask have reduced model training times by 91% within a few months of development effort. The figure below shows improvements we have made with a local Dask cluster during one step in a model training pipeline; the performance is even better in production on a distributed Dask cluster. Dask speeds up the iteration cycle during development, which allows developers to test their code faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*W_zv1_ih2xAxOG5UQnZI5A.png" /></figure><p>Dask and RAPIDS can be used in tandem to scale computations horizontally and vertically on GPUs. The figure below shows a weak scaling study on an XGBoost training execution using a dataset that does not fit into memory on a single system. Here Dask is used to distribute computations across multiple GPUs on a single EC2 instance on AWS. Each GPU gets a special Dask worker that knows how to run computations on it using RAPIDS. The original training time on a multi-core CPU system is also included for reference. Please note the y-axis is logarithmically scaled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cfbnRfBfDhP8QbfE4qxW3g.png" /></figure><p>With these improvements, we have seen roughly 100x improvement model training times and costs have gone down 97%, assuming you are only paying for computation during training.</p><p>Now that the potential computational performance gains using Dask and RAPIDS have been demonstrated, the next steps are to understand model accuracy, improve deployment infrastructure, and train users. As issues are found, the team will contribute to the open source projects as much as possible.</p><p>Dask and RAPIDS scale Python natively, which allows Capital One Data Scientists and ML Engineers to maintain ownership of their code and focus on what they do best.</p><h3><strong>Want to Know More?</strong></h3><p>This is the introductory first post in a series of blogs where our resident Dask and RAPIDS expert, Mike McCarty, will dive into the deep technical details of both Dask and RAPIDS. We will also keep you all posted on developments as we work to implement these technologies at scale within Capital One.</p><h3><strong>Dask and RAPIDS Resources</strong></h3><ul><li><a href="https://dask.org/">https://dask.org/</a></li><li><a href="https://rapids.ai/">https://rapids.ai</a></li></ul><p><em>DISCLOSURE STATEMENT: © 2019 Capital One. Opinions are those of the individual author. Unless noted otherwise in this post, Capital One is not affiliated with, nor endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are property of their respective owners.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4bba136cc70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capital-one-tech/dask-and-rapids-the-next-big-things-for-data-science-and-machine-learning-at-capital-one-d4bba136cc70">Dask and RAPIDS: The Next Big Things for Data Science and Machine Learning at Capital One</a> was originally published in <a href="https://medium.com/capital-one-tech">Capital One Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>