<?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 Kevin Arvai on Medium]]></title>
        <description><![CDATA[Stories by Kevin Arvai on Medium]]></description>
        <link>https://medium.com/@arvkevi?source=rss-b3a3607891a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HozI2-vj9oNFSbNgRiMneA.jpeg</url>
            <title>Stories by Kevin Arvai on Medium</title>
            <link>https://medium.com/@arvkevi?source=rss-b3a3607891a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:28:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arvkevi/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[Tune In: Decision Threshold Optimization with scikit-learn’s TunedThresholdClassifierCV]]></title>
            <link>https://medium.com/data-science/tune-in-decision-threshold-optimization-with-scikit-learns-tunedthresholdclassifiercv-7de558a2cf58?source=rss-b3a3607891a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de558a2cf58</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Kevin Arvai]]></dc:creator>
            <pubDate>Mon, 27 May 2024 19:54:45 GMT</pubDate>
            <atom:updated>2024-05-27T19:54:45.025Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use cases and code to explore the new class that helps tune decision thresholds in scikit-learn</h4><p>The 1.5 release of scikit-learn includes a new class, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TunedThresholdClassifierCV.html">TunedThresholdClassifierCV</a>, making optimizing decision thresholds from scikit-learn classifiers easier. A decision threshold is a cut-off point that converts predicted probabilities output by a machine learning model into discrete classes. The default decision threshold of the .predict() method from scikit-learn classifiers in a binary classification setting is 0.5. Although this is a sensible default, it is rarely the best choice for classification tasks.</p><p>This post introduces the TunedThresholdClassifierCV class and demonstrates how it can optimize decision thresholds for various binary classification tasks. This new class will help bridge the gap between data scientists who build models and business stakeholders who make decisions based on the model’s output. By fine-tuning the decision thresholds, data scientists can enhance model performance and better align with business objectives.</p><p>This post will cover the following situations where tuning decision thresholds is beneficial:</p><ol><li><strong>Maximizing a metric</strong>: Use this when choosing a threshold that maximizes a scoring metric, like the F1 score.</li><li><strong>Cost-sensitive learning</strong>: Adjust the threshold when the cost of misclassifying a false positive is not equal to the cost of misclassifying a false negative, and you have an estimate of the costs.</li><li><strong>Tuning under constraints</strong>: Optimize the operating point on the ROC or precision-recall curve to meet specific performance constraints.</li></ol><p>The code used in this post and links to datasets are available on <a href="https://github.com/arvkevi/tunein-blog">GitHub</a>.</p><p>Let’s get started! First, import the necessary libraries, read the data, and split training and test data.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd<br>from sklearn.compose import ColumnTransformer<br>from sklearn.compose import make_column_selector as selector<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import (<br>    RocCurveDisplay,<br>    f1_score,<br>    make_scorer,<br>    recall_score,<br>    roc_curve,<br>    confusion_matrix,<br>)<br>from sklearn.model_selection import TunedThresholdClassifierCV, train_test_split<br>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import OneHotEncoder, StandardScaler<br><br>RANDOM_STATE = 26120</pre><h4>Maximizing a metric</h4><p>Before starting the model-building process in any machine learning project, it is crucial to work with stakeholders to determine which metric(s) to optimize. Making this decision early ensures that the project aligns with its intended goals.</p><p>Using an accuracy metric in fraud detection use cases to evaluate model performance is not ideal because the data is often imbalanced, with most transactions being non-fraudulent. The F1 score is the harmonic mean of precision and recall and is a better metric for imbalanced datasets like fraud detection. Let’s use the TunedThresholdClassifierCV class to optimize the decision threshold of a logistic regression model to maximize the F1 score.</p><p>We’ll use the <a href="https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud">Kaggle Credit Card Fraud Detection dataset</a> to introduce the first situation where we need to tune a decision threshold. First, split the data into train and test sets, then create a scikit-learn pipeline to scale the data and train a logistic regression model. Fit the pipeline on the training data so we can compare the original model performance with the tuned model performance.</p><pre>creditcard = pd.read_csv(&quot;data/creditcard.csv&quot;)<br>y = creditcard[&quot;Class&quot;]<br>X = creditcard.drop(columns=[&quot;Class&quot;])<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=RANDOM_STATE, stratify=y<br>)<br><br># Only Time and Amount need to be scaled<br>original_fraud_model = make_pipeline(<br>    ColumnTransformer(<br>        [(&quot;scaler&quot;, StandardScaler(), [&quot;Time&quot;, &quot;Amount&quot;])],<br>        remainder=&quot;passthrough&quot;,<br>        force_int_remainder_cols=False,<br>    ),<br>    LogisticRegression(),<br>)<br>original_fraud_model.fit(X_train, y_train)</pre><p>No tuning has happened yet, but it’s coming in the next code block. The arguments for TunedThresholdClassifierCV are similar to other CV classes in scikit-learn, such as <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">GridSearchCV</a>. At a minimum, the user only needs to pass the original estimator and TunedThresholdClassifierCV will store the decision threshold that maximizes balanced accuracy (default) using 5-fold stratified K-fold cross-validation (default). It also uses this threshold when calling .predict(). However, any scikit-learn metric (or callable) can be used as the scoring metric. Additionally, the user can pass the familiar cv argument to customize the cross-validation strategy.</p><p>Create the TunedThresholdClassifierCV instance and fit the model on the training data. Pass the original model and set the scoring to be &quot;f1&quot;. We&#39;ll also want to set store_cv_results=True to access the thresholds evaluated during cross-validation for visualization.</p><pre>tuned_fraud_model = TunedThresholdClassifierCV(<br>    original_fraud_model,<br>    scoring=&quot;f1&quot;,<br>    store_cv_results=True,<br>)<br><br>tuned_fraud_model.fit(X_train, y_train)<br><br># average F1 across folds<br>avg_f1_train = tuned_fraud_model.best_score_<br># Compare F1 in the test set for the tuned model and the original model<br>f1_test = f1_score(y_test, tuned_fraud_model.predict(X_test))<br>f1_test_original = f1_score(y_test, original_fraud_model.predict(X_test))<br><br>print(f&quot;Average F1 on the training set: {avg_f1_train:.3f}&quot;)<br>print(f&quot;F1 on the test set: {f1_test:.3f}&quot;)<br>print(f&quot;F1 on the test set (original model): {f1_test_original:.3f}&quot;)<br>print(f&quot;Threshold: {tuned_fraud_model.best_threshold_: .3f}&quot;)<br></pre><pre>Average F1 on the training set: 0.784<br>F1 on the test set: 0.796<br>F1 on the test set (original model): 0.733<br>Threshold:  0.071</pre><p>Now that we’ve found the threshold that maximizes the F1 score check tuned_fraud_model.best_score_ to find out what the best average F1 score was across folds in cross-validation. We can also see which threshold generated those results using tuned_fraud_model.best_threshold_. You can visualize the metric scores across the decision thresholds during cross-validation using the objective_scores_ and decision_thresholds_ attributes:</p><pre>fig, ax = plt.subplots(figsize=(5, 5))<br>ax.plot(<br>    tuned_fraud_model.cv_results_[&quot;thresholds&quot;],<br>    tuned_fraud_model.cv_results_[&quot;scores&quot;],<br>    marker=&quot;o&quot;,<br>    linewidth=1e-3,<br>    markersize=4,<br>    color=&quot;#c0c0c0&quot;,<br>)<br>ax.plot(<br>    tuned_fraud_model.best_threshold_,<br>    tuned_fraud_model.best_score_,<br>    &quot;^&quot;,<br>    markersize=10,<br>    color=&quot;#ff6700&quot;,<br>    label=f&quot;Optimal cut-off point = {tuned_fraud_model.best_threshold_:.2f}&quot;,<br>)<br>ax.plot(<br>    0.5,<br>    f1_test_original,<br>    label=&quot;Default threshold: 0.5&quot;,<br>    color=&quot;#004e98&quot;,<br>    linestyle=&quot;--&quot;,<br>    marker=&quot;X&quot;,<br>    markersize=10,<br>)<br>ax.legend(fontsize=8, loc=&quot;lower center&quot;)<br>ax.set_xlabel(&quot;Decision threshold&quot;, fontsize=10)<br>ax.set_ylabel(&quot;F1 score&quot;, fontsize=10)<br>ax.set_title(&quot;F1 score vs. Decision threshold -- Cross-validation&quot;, fontsize=12)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*yRJvWcVrifcjUGq-YQ1YOg.png" /><figcaption>Image created by the author.</figcaption></figure><pre># Check that the coefficients from the original model and the tuned model are the same<br>assert (tuned_fraud_model.estimator_[-1].coef_ ==<br>        original_fraud_model[-1].coef_).all()</pre><p>We’ve used the same underlying logistic regression model to evaluate two different decision thresholds. The underlying models are the same, evidenced by the coefficient equality in the assert statement above. Optimization in TunedThresholdClassifierCV is achieved using post-processing techniques, which are applied directly to the predicted probabilities output by the model. However, it&#39;s important to note that TunedThresholdClassifierCV uses cross-validation by default to find the decision threshold to avoid overfitting to the training data.</p><h4>Cost-sensitive learning</h4><p>Cost-sensitive learning is a type of machine learning that assigns a cost to each type of misclassification. This translates model performance into units that stakeholders understand, like dollars saved.</p><p>We will use the <a href="https://accelerator.ca.analytics.ibm.com/bi/?perspective=authoring&amp;pathRef=.public_folders%2FIBM%2BAccelerator%2BCatalog%2FContent%2FDAT00148&amp;id=i9710CF25EF75468D95FFFC7D57D45204&amp;objRef=i9710CF25EF75468D95FFFC7D57D45204&amp;action=run&amp;format=HTML&amp;cmPropStr=%7B%22id%22%3A%22i9710CF25EF75468D95FFFC7D57D45204%22%2C%22type%22%3A%22reportView%22%2C%22defaultName%22%3A%22DAT00148%22%2C%22permissions%22%3A%5B%22execute%22%2C%22read%22%2C%22traverse%22%5D%7D">TELCO customer churn dataset</a>, a binary classification dataset, to demonstrate the value of cost-sensitive learning. The goal is to predict whether a customer will churn or not, given features about the customer’s demographics, contract details, and other technical information about the customer’s account. The motivation to use this dataset (and some of the code) is from <a href="https://www.wandb.courses/courses/decision-optimization">Dan Becker’s course on decision threshold optimization</a>.</p><pre>data = pd.read_excel(&quot;data/Telco_customer_churn.xlsx&quot;)<br>drop_cols = [<br>    &quot;Count&quot;, &quot;Country&quot;, &quot;State&quot;, &quot;Lat Long&quot;, &quot;Latitude&quot;, &quot;Longitude&quot;,<br>    &quot;Zip Code&quot;, &quot;Churn Value&quot;, &quot;Churn Score&quot;, &quot;CLTV&quot;, &quot;Churn Reason&quot;<br>]<br>data.drop(columns=drop_cols, inplace=True)<br><br># Preprocess the data<br>data[&quot;Churn Label&quot;] = data[&quot;Churn Label&quot;].map({&quot;Yes&quot;: 1, &quot;No&quot;: 0})<br>data.drop(columns=[&quot;Total Charges&quot;], inplace=True)<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    data.drop(columns=[&quot;Churn Label&quot;]),<br>    data[&quot;Churn Label&quot;],<br>    test_size=0.2,<br>    random_state=RANDOM_STATE,<br>    stratify=data[&quot;Churn Label&quot;],<br>)</pre><p>Set up a basic pipeline for processing the data and generating predicted probabilities with a random forest model. This will serve as a baseline to compare to the TunedThresholdClassifierCV.</p><pre>preprocessor = ColumnTransformer(<br>    transformers=[(&quot;one_hot&quot;, OneHotEncoder(),<br>                   selector(dtype_include=&quot;object&quot;))],<br>    remainder=&quot;passthrough&quot;,<br>)<br><br>original_churn_model = make_pipeline(<br>    preprocessor, RandomForestClassifier(random_state=RANDOM_STATE)<br>)<br>original_churn_model.fit(X_train.drop(columns=[&quot;customerID&quot;]), y_train);</pre><p>The choice of preprocessing and model type is not important for this tutorial. The company wants to offer discounts to customers who are predicted to churn. During collaboration with stakeholders, you learn that giving a discount to a customer who will not churn (a false positive) would cost $80. You also learn that it’s worth $200 to offer a discount to a customer who would have churned. You can represent this relationship in a cost matrix:</p><pre>def cost_function(y, y_pred, neg_label, pos_label):<br>    cm = confusion_matrix(y, y_pred, labels=[neg_label, pos_label])<br>    cost_matrix = np.array([[0, -80], [0, 200]])<br>    return np.sum(cm * cost_matrix)<br><br>cost_scorer = make_scorer(cost_function, neg_label=0, pos_label=1)</pre><p>We also wrapped the cost function in a scikit-learn custom scorer. This scorer will be used as the scoring argument in the TunedThresholdClassifierCV and to evaluate profit on the test set.</p><pre>tuned_churn_model = TunedThresholdClassifierCV(<br>    original_churn_model,<br>    scoring=cost_scorer,<br>    store_cv_results=True,<br>)<br><br>tuned_churn_model.fit(X_train.drop(columns=[&quot;CustomerID&quot;]), y_train)<br><br># Calculate the profit on the test set<br>original_model_profit = cost_scorer(<br>    original_churn_model, X_test.drop(columns=[&quot;CustomerID&quot;]), y_test<br>)<br>tuned_model_profit = cost_scorer(<br>    tuned_churn_model, X_test.drop(columns=[&quot;CustomerID&quot;]), y_test<br>)<br><br>print(f&quot;Original model profit: {original_model_profit}&quot;)<br>print(f&quot;Tuned model profit: {tuned_model_profit}&quot;)</pre><pre>Original model profit: 29640<br>Tuned model profit: 35600</pre><p>The profit is higher in the tuned model compared to the original. Again, we can plot the objective metric against the decision thresholds to visualize the decision threshold selection on training data during cross-validation:</p><pre>fig, ax = plt.subplots(figsize=(5, 5))<br>ax.plot(<br>    tuned_churn_model.cv_results_[&quot;thresholds&quot;],<br>    tuned_churn_model.cv_results_[&quot;scores&quot;],<br>    marker=&quot;o&quot;,<br>    markersize=3,<br>    linewidth=1e-3,<br>    color=&quot;#c0c0c0&quot;,<br>    label=&quot;Objective score (using cost-matrix)&quot;,<br>)<br>ax.plot(<br>    tuned_churn_model.best_threshold_,<br>    tuned_churn_model.best_score_,<br>    &quot;^&quot;,<br>    markersize=10,<br>    color=&quot;#ff6700&quot;,<br>    label=&quot;Optimal cut-off point for the business metric&quot;,<br>)<br>ax.legend()<br>ax.set_xlabel(&quot;Decision threshold (probability)&quot;)<br>ax.set_ylabel(&quot;Objective score (using cost-matrix)&quot;)<br>ax.set_title(&quot;Objective score as a function of the decision threshold&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GaMD_kIj-v5cAGVIPQFww.png" /><figcaption>Image created by the author.</figcaption></figure><p>In reality, assigning a static cost to all instances that are misclassified in the same way is not realistic from a business perspective. There are more advanced methods to tune the threshold by assigning a weight to each instance in the dataset. This is covered in <a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_cost_sensitive_learning.html#sphx-glr-auto-examples-model-selection-plot-cost-sensitive-learning-py">scikit-learn’s cost-sensitive learning example</a>.</p><h4>Tuning under constraints</h4><p>This method is not covered in the scikit-learn documentation currently, but is a common business case for binary classification use cases. The tuning under constraint method finds a decision threshold by identifying a point on either the ROC or precision-recall curves. The point on the curve is the maximum value of one axis while constraining the other axis. For this walkthrough, we’ll be using the Pima Indians diabetes dataset. This is a binary classification task to predict if an individual has diabetes.</p><p>Imagine that your model will be used as a screening test for an average-risk population applied to millions of people. There are an estimated 38 million people with diabetes in the US. This is roughly 11.6% of the population, so the model’s specificity should be high so it doesn’t misdiagnose millions of people with diabetes and refer them to unnecessary confirmatory testing. Suppose your imaginary CEO has communicated that they will not tolerate more than a 2% false positive rate. Let’s build a model that achieves this using TunedThresholdClassifierCV.</p><p>For this part of the tutorial, we’ll define a constraint function that will be used to find the maximum true positive rate at a 2% false positive rate.</p><pre>def max_tpr_at_tnr_constraint_score(y_true, y_pred, max_tnr=0.5):<br>    fpr, tpr, thresholds = roc_curve(y_true, y_pred, drop_intermediate=False)<br>    tnr = 1 - fpr<br>    tpr_at_tnr_constraint = tpr[tnr &gt;= max_tnr].max()<br>    return tpr_at_tnr_constraint<br><br>max_tpr_at_tnr_scorer = make_scorer(<br>    max_tpr_at_tnr_constraint_score, max_tnr=0.98)<br>data = pd.read_csv(&quot;data/diabetes.csv&quot;)<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    data.drop(columns=[&quot;Outcome&quot;]),<br>    data[&quot;Outcome&quot;],<br>    stratify=data[&quot;Outcome&quot;],<br>    test_size=0.2,<br>    random_state=RANDOM_STATE,<br>)</pre><p>Build two models, one logistic regression to serve as a baseline model and the other, TunedThresholdClassifierCV which will wrap the baseline logistic regression model to achieve the goal outlined by the CEO. In the tuned model, set scoring=max_tpr_at_tnr_scorer. Again, the choice of model and preprocessing is not important for this tutorial.</p><pre># A baseline model<br>original_model = make_pipeline(<br>    StandardScaler(), LogisticRegression(random_state=RANDOM_STATE)<br>)<br>original_model.fit(X_train, y_train)<br><br># A tuned model<br>tuned_model = TunedThresholdClassifierCV(<br>    original_model,<br>    thresholds=np.linspace(0, 1, 150),<br>    scoring=max_tpr_at_tnr_scorer,<br>    store_cv_results=True,<br>    cv=8,<br>    random_state=RANDOM_STATE,<br>)<br>tuned_model.fit(X_train, y_train)</pre><p>Compare the difference between the default decision threshold from scikit-learn estimators, 0.5, and one found using the tuning under constraint approach on the ROC curve.</p><pre># Get the fpr and tpr of the original model<br>original_model_proba = original_model.predict_proba(X_test)[:, 1]<br>fpr, tpr, thresholds = roc_curve(y_test, original_model_proba)<br>closest_threshold_to_05 = (np.abs(thresholds - 0.5)).argmin()<br>fpr_orig = fpr[closest_threshold_to_05]<br>tpr_orig = tpr[closest_threshold_to_05]<br><br># Get the tnr and tpr of the tuned model<br>max_tpr = tuned_model.best_score_<br>constrained_tnr = 0.98<br><br># Plot the ROC curve and compare the default threshold to the tuned threshold<br>fig, ax = plt.subplots(figsize=(5, 5))<br># Note that this will be the same for both models<br>disp = RocCurveDisplay.from_estimator(<br>    original_model,<br>    X_test,<br>    y_test,<br>    name=&quot;Logistic Regression&quot;,<br>    color=&quot;#c0c0c0&quot;,<br>    linewidth=2,<br>    ax=ax,<br>)<br>disp.ax_.plot(<br>    1 - constrained_tnr,<br>    max_tpr,<br>    label=f&quot;Tuned threshold: {tuned_model.best_threshold_:.2f}&quot;,<br>    color=&quot;#ff6700&quot;,<br>    linestyle=&quot;--&quot;,<br>    marker=&quot;o&quot;,<br>    markersize=11,<br>)<br>disp.ax_.plot(<br>    fpr_orig,<br>    tpr_orig,<br>    label=&quot;Default threshold: 0.5&quot;,<br>    color=&quot;#004e98&quot;,<br>    linestyle=&quot;--&quot;,<br>    marker=&quot;X&quot;,<br>    markersize=11,<br>)<br>disp.ax_.set_ylabel(&quot;True Positive Rate&quot;, fontsize=8)<br>disp.ax_.set_xlabel(&quot;False Positive Rate&quot;, fontsize=8)<br>disp.ax_.tick_params(labelsize=8)<br>disp.ax_.legend(fontsize=7)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*20y-E-5q0cQB9VkRJ5oxWA.png" /><figcaption>Image created by the author.</figcaption></figure><p>The tuned under constraint method found a threshold of 0.80, which resulted in an average sensitivity of 19.2% during cross-validation of the training data. Compare the sensitivity and specificity to see how the threshold holds up in the test set. Did the model meet the CEO’s specificity requirement in the test set?</p><pre># Average sensitivity and specificity on the training set<br>avg_sensitivity_train = tuned_model.best_score_<br><br># Call predict from tuned_model to calculate sensitivity and specificity on the test set<br>specificity_test = recall_score(<br>    y_test, tuned_model.predict(X_test), pos_label=0)<br>sensitivity_test = recall_score(y_test, tuned_model.predict(X_test))<br><br>print(f&quot;Average sensitivity on the training set: {avg_sensitivity_train:.3f}&quot;)<br>print(f&quot;Sensitivity on the test set: {sensitivity_test:.3f}&quot;)<br>print(f&quot;Specificity on the test set: {specificity_test:.3f}&quot;)</pre><pre>Average sensitivity on the training set: 0.192<br>Sensitivity on the test set: 0.148<br>Specificity on the test set: 0.990</pre><h4>Conclusion</h4><p>The new TunedThresholdClassifierCV class is a powerful tool that can help you become a better data scientist by sharing with business leaders how you arrived at a decision threshold. You learned how to use the new scikit-learn TunedThresholdClassifierCV class to maximize a metric, perform cost-sensitive learning, and tune a metric under constraint. This tutorial was not intended to be comprehensive or advanced. I wanted to introduce the new feature and highlight its power and flexibility in solving binary classification problems. Please check out the scikit-learn documentation, user guide, and examples for thorough usage examples.</p><p>A huge shoutout to <a href="https://github.com/glemaitre">Guillaume Lemaitre</a> for his work on this feature.</p><p>Thanks for reading. Happy tuning.</p><p>Data Licenses:<br>Credit card fraud: DbCL<br>Pima Indians diabetes: CC0<br>TELCO churn: <a href="https://developer.ibm.com/terms/download-of-content-agreement/">commercial use OK</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de558a2cf58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tune-in-decision-threshold-optimization-with-scikit-learns-tunedthresholdclassifiercv-7de558a2cf58">Tune In: Decision Threshold Optimization with scikit-learn’s TunedThresholdClassifierCV</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Tips for Contributing to Open Source Software]]></title>
            <link>https://medium.com/data-science/five-tips-for-contributing-to-open-source-software-8fd3d6f5606f?source=rss-b3a3607891a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd3d6f5606f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Kevin Arvai]]></dc:creator>
            <pubDate>Mon, 14 Oct 2019 04:08:22 GMT</pubDate>
            <atom:updated>2019-10-14T04:08:22.213Z</atom:updated>
            <content:encoded><![CDATA[<h4>A data scientist’s perspective</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VcFdOHBwJ9-jl3cl" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Contributing to Open-Source Software (OSS) can be a rewarding endeavor, especially for new data scientists. It helps improve skills, provides invaluable experience when collaborating on projects, and gives you a chance to showcase your code. However, many data scientists do not consider themselves to be formally trained software developers. This can make contributing to OSS a scary proposition.</p><p>One source of fear is that it seems like every step in the software development process, from design to continuous integration, has a set of best practices that are often overlooked in data science training. This leaves data scientists feeling under-equipped to participate in an arena tailored for software developers. It’s been <a href="https://www.freecodecamp.org/news/how-to-get-over-your-fear-of-contributing-to-open-source-6160e4cdf0d3/">documented</a> that even some skilled software developers have anxiety when deciding to contribute to OSS, well, multiply that anxiety for a data scientist.</p><p>Almost all the popular data science libraries we use every day are successful OSS projects sometimes maintained and often improved by the community. Scikit-learn, PyTorch, and TensorFlow come to mind. See, data scientists can write high-quality code! Ultimately, data scientists are writing code with the intent to ship a model to production or deploy a robust data pipeline. Since we’re writing software, we should be held to the same standards as other software projects.</p><p>In this post, I’d like to share a few things that I’ve learned over the past couple of years of developing software in data science. My intent is to share the pieces of information that I wish someone shared with me when I was beginning my data science journey. The hope is that inexperienced data scientists who are hesitant to get started will use these tips to feel empowered to start writing better data science code and contribute to OSS sooner rather than later.</p><ol><li><strong>Find an experienced software developer…</strong></li></ol><p>…and pay attention! This item had the single greatest impact on my personal development. All my current software development habits are a direct result of incorporating experienced software developers in my life in some form or another. It’s worth noting that you don’t have to be best friends with these people. The experienced developer could take the form of a tech lead on your team at work, a classmate, or someone from a local meetup. Additionally, there are some really great developers who <a href="https://twitter.com/b0rk">regularly tweet</a>, <a href="https://dev.to/">post in forums</a>, <a href="https://hackernoon.com/">write technical blogs</a>, and create podcasts (<a href="https://talkpython.fm/">Talk Python</a> is my favorite). Try your best to identify people who are not data scientists, as they can provide you with opinions that would be more difficult to find in the data science field.</p><p>The key to this tip is to <strong>listen to</strong><em> </em>and<em> </em><strong>engage with</strong> these people. First, ask yourself, “Why are they are implementing such a method”? If you don’t understand, look it up. If you still don’t understand (or if you do) send them an email or reply with a comment asking them to expand on their point. Chances are, these people have good reasons behind their decisions. Seeing or hearing these reasons in the context of your question will give you a better understanding of the topic from a software development perspective. I’m not recommending you continually hound experienced developers, it’s important to respect their time and space.</p><p>2. <strong>The open-source community is NOT out to get you</strong></p><p>An unfortunate misconception that prevents people from contributing to OSS is that if they make their code public it will be laughed at or ridiculed. The majority of the time, this is just not true. It’s no different than any other type of community, a few bad apples can ruin the party for everyone. I have contributed to small OSS projects, popular OSS projects, and <a href="https://github.com/arvkevi">even maintain a few of my own</a>. In each of these scenarios, every interaction has been at the very least respectful, and in most cases, people are appreciative. After more than two years of contributions to OSS, if someone were disrespectful toward me, they would clearly be an outlier at this point.</p><p>3. <strong>Practice git, etc.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*83h1XPayUrxFlyAJt5h--A.png" /><figcaption>It’s never been easier to practice git, all the major hosting platforms allow users to create unlimited private repositories.</figcaption></figure><p>Some people state “unfamiliarity with git” or even just “unfamiliarity with GitHub” as their reason for not contributing to OSS. This is why the title for number three contains “etc”. GitHub, Bitbucket, and GitLab have a substantial amount of functionality that supports a git workflow, but is not considered part of “git” <em>per se. </em>So even for an experienced git user who has never used GitHub, there is still a slight learning curve on the road to proficiency.</p><p>Instead of coding all of your projects locally, reserve some extra time to push to one of the platforms mentioned above. Make it private, you can still securely share the repo with a friend if you like. Practice making pull requests or visually inspect the git commit history after rebasing a feature branch. Becoming more familiar with the tabs, buttons, tools, and the git workflow in a private repository will give you confidence when working on your public contributions.</p><p>You will be hard-pressed to find a successful data science project not using some form of version control for their software development, git just happens to be the most popular. For this reason, try to practice using a git workflow for your everyday projects. Then, when collaborating with people on an OSS project, you won’t be hung up on git workflow mishaps and you spend your time focusing on the code.</p><p>4. <strong>Use</strong> <strong>software best practices</strong></p><p>Rachel Tatman, a data scientist from Kaggle, recently <a href="https://www.youtube.com/watch?v=Trar7GZOPl8&amp;feature=youtu.be">posted a video</a> and a <a href="https://www.kaggle.com/rtatman/six-steps-to-more-professional-data-science-code">kernel</a> outlining how to write more professional-looking data science code, so I’ll recommend to follow her advice and keep the sections short where we overlap. Each of these will make your life easier when interacting with collaborators, again allowing you to focus on adding features rather than going back to clean up bad habits.</p><p>4a. <strong>Make variable names human-readable</strong></p><p>Other data scientists may know that i and j are elements of the array A but mathematical notations don’t translate to informative variable names in source code. I like to use variable names that would have meaning when re-reading the source code or for someone else reading for the first time. But I’ll leave it to Will Koehrsen to <a href="https://towardsdatascience.com/data-scientists-your-variable-names-are-awful-heres-how-to-fix-them-89053d2855be">suggest naming conventions for data scientists</a>.</p><p>4b. <strong>Comment generously</strong></p><p>Whether they are aware of it or not, data scientists often implement a coding style called <a href="https://tomaugspurger.github.io/method-chaining.html">method chaining</a>. When there is a DataFrame object in memory, we often know the exact next steps to transform a column into the format we want. One downside to method chaining is that the chains can be difficult to debug, especially when there are no comments. Think of others when writing comments and remember, a short comment can go a long way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb80e6a68bd358f2c67af7a7c9f911c/href">https://medium.com/media/bcb80e6a68bd358f2c67af7a7c9f911c/href</a></iframe><p>4c.<strong> Write Unit Tests</strong></p><p>You will thank yourself later, or whoever is reviewing your pull request will thank you. Sometimes unit tests just don’t make sense for small one-off data science projects. But unit tests become more important as you think about scaling up your code or collaborating with others.</p><p>Code is easier to test when it is modular, which translates to writing functions with the intent that they will perform one or two operations. Below is an example of a function that normalizes a pandas DataFrame in Python. The unit test for this function asserts that the mean and standard deviation are 0.0 and 1.0, respectively. If this test ever fails, the developer knows that something has gone wrong in the `normalize_dataframe` method and will know where to start debugging.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afe6bf1313383648334309290bcba452/href">https://medium.com/media/afe6bf1313383648334309290bcba452/href</a></iframe><p>4d.<strong> Use Continuous Integration (CI)</strong></p><p>Congrats, you wrote unit tests and pushed your code to GitHub, but a few days later, someone reports an issue stating they can’t get your code to run on their machine. CI would help identify these problems before they become issues on GitHub. <a href="https://travis-ci.org/">Travis</a> is an example of a CI service that integrates directly with GitHub free of charge for public repos. CI services allow you to build and test your code in containerized environments. I recommend setting up <a href="https://github.com/marketplace/category/continuous-integration">one of the CI services</a> for projects that you intend on collaborating with others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ju-zaKh1ry3FyxSK6GDBTQ.png" /><figcaption>Travis interface showing a passing build with multiple versions of Python on a Linux kernel.</figcaption></figure><p>5.<strong> Use a debugger</strong></p><p>Using a code editor with a debugger, sometimes referred to as an integrated development environment (IDE), can seem like overkill for data science projects. But once you learn how to use your editor’s debugger, it becomes a powerful tool for software development. A debugger allows users to execute code up until a <em>breakpoint</em> then explore the variable namespace, which makes it much easier to “debug” why a program may be crashing. You should give yourself at least 30 days of trying out a debugger for development before giving up hope and switching back to notebooks. Take the time to read the tutorial and ask a more experienced software developer (perhaps from Tip #1) if they can walk you through debugging your next bug.</p><p>Jupyter notebooks are a popular choice for many users when first starting a data science project. Notebooks are great for exploratory data analysis and visualizations, but they have their shortcomings, <a href="https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit">reviewed here by Joel Grus</a>. Namely, the cells cannot be run out of order, they are difficult for beginners to understand, and they encourage bad habits. The two popular IDEs <a href="https://www.jetbrains.com/help/pycharm/jupyter-notebook-support.html">PyCharm</a> and <a href="https://code.visualstudio.com/docs/python/jupyter-support-py">VS Code</a> have recognized the popularity of notebooks and recently integrated support for them directly in the IDE. Hopefully, data scientists will come to IDEs for the notebook support but stay for the debugger.</p><p>Bonus:<strong> Be receptive to constructive criticism</strong></p><p>Keep in mind that OSS is maintained and improved by both formal and informal code reviews. People will look at your code, critique it, and might ask you to change a few lines. If you’ve made it this far, isn’t this what you were looking for? Someone has taken the time to review your code and spent enough energy to try and improve it.</p><p>As your software development skills improve, you will encounter other users asking to you modify your code, but you might want to leave it as-is. Defend your decision with the same respect that you were expecting to receive, it’s really no different than being a sensible human.</p><p>I hope you find these tips useful. The tips were directed toward open-source but can be applied to commercial data scientists and developers also. As you gain proficiency with some of them, you should notice that the time it takes for you to identify and fix a bug or implement feature in an OSS environment is reduced. By putting in the time now to becoming a better programmer, you’ll have more time in the long run to solve the worlds’ data science problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd3d6f5606f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/five-tips-for-contributing-to-open-source-software-8fd3d6f5606f">Five Tips for Contributing to Open Source Software</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine tuning a classifier in scikit-learn]]></title>
            <link>https://medium.com/data-science/fine-tuning-a-classifier-in-scikit-learn-66e048c21e65?source=rss-b3a3607891a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/66e048c21e65</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kevin Arvai]]></dc:creator>
            <pubDate>Wed, 24 Jan 2018 16:59:40 GMT</pubDate>
            <atom:updated>2019-07-21T10:18:57.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*za9Jt26YZC9CVmqjoGeBjA.jpeg" /></figure><p>It’s easy to understand that many machine learning problems benefit from either precision or recall as their optimal performance metric but implementing the concept requires knowledge of a detailed process. My first few attempts to fine-tune models for recall (sensitivity) were difficult, so I decided to share my experience.</p><p>This post is from <a href="https://www.kaggle.com/kevinarvai/fine-tuning-a-classifier-in-scikit-learn">my first Kaggle kernel</a>, where my aim was not to build a robust classifier, rather I wanted to show the practicality of optimizing a classifier for sensitivity. In figure A below, the goal is to move the decision threshold to the left. This minimizes false negatives, which are especially troublesome in the dataset chosen for this post. It contains features from images of 357 benign and 212 malignant breast biopsies. A false negative sample equates to missing a diagnosis of a malignant tumor. The data file can be downloaded <a href="https://www.kaggle.com/uciml/breast-cancer-wisconsin-data">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*J8kWRRekByVSJi8XDTSsgw.jpeg" /><figcaption>The goal of this post is to outline how to move the decision threshold to the left in Figure A, reducing false negatives and maximizing sensitivity.</figcaption></figure><p>With scikit-learn, tuning a classifier for recall can be achieved in (at least) two main steps.</p><ol><li>Using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">GridSearchCV</a> to tune your model by searching for the best hyperparameters and keeping the classifier with the highest recall score.</li><li>Adjust the decision threshold using the precision-recall curve and the roc curve, which is a more involved method that I will walk through.</li></ol><p>Start by loading the necessary libraries and the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61d033783821cebcc0af4b9b57b18ded/href">https://medium.com/media/61d033783821cebcc0af4b9b57b18ded/href</a></iframe><p>The class distribution can be found by counting the diagnosis column. B for benign and M for malignant.</p><pre>B    357<br>M    212<br>Name: diagnosis, dtype: int64</pre><p>Convert the class labels and split the data into training and test sets. train_test_split with stratify=True results in consistent class distribution between training and test sets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccbe20176e2beff90cfa07bfecaee31d/href">https://medium.com/media/ccbe20176e2beff90cfa07bfecaee31d/href</a></iframe><pre># show the distribution<br>print(&#39;y_train class distribution&#39;)<br>print(y_train.value_counts(normalize=True))</pre><pre>print(&#39;y_test class distribution&#39;)<br>print(y_test.value_counts(normalize=True))</pre><pre>y_train class distribution<br>0    0.626761<br>1    0.373239<br>Name: diagnosis, dtype: float64<br>y_test class distribution<br>0    0.629371<br>1    0.370629<br>Name: diagnosis, dtype: float64</pre><p>Now that the data has been prepared, the classifier can be built.</p><h3>First strategy: Optimize for sensitivity using GridSearchCV with the scoring argument.</h3><p>First build a generic classifier and setup a parameter grid; random forests have many tunable parameters, which make it suitable for GridSearchCV. The scorers dictionary can be used as the scoring argument in GridSearchCV. When multiple scores are passed, GridSearchCV.cv_results_ will return scoring metrics for each of the score types provided.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f6d02bde8417204ef62881bd0208c74/href">https://medium.com/media/8f6d02bde8417204ef62881bd0208c74/href</a></iframe><p>The function below uses <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">GridSearchCV</a> to fit several classifiers according to the combinations of parameters in the param_grid. The scores from scorers are recorded and the best model (as scored by the refit argument) will be selected and &quot;refit&quot; to the full training data for downstream use. This also makes predictions on the held out X_test and prints the confusion matrix to show performance.</p><p>The point of the wrapper function is to quickly reuse the code to fit the best classifier according to the type of scoring metric chosen. First, try precision_score, which should limit the number of false positives. This isn&#39;t well-suited for the goal of maxium sensitivity, but allows us to quickly show the difference between a classifier optimized for precision_score and one optimized for recall_score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04afed440a35e6896223e489758a380d/href">https://medium.com/media/04afed440a35e6896223e489758a380d/href</a></iframe><pre>grid_search_clf = grid_search_wrapper(refit_score=&#39;precision_score&#39;)</pre><pre>Best params for precision_score<br>{&#39;max_depth&#39;: 15, &#39;max_features&#39;: 20, &#39;min_samples_split&#39;: 3, &#39;n_estimators&#39;: 300}<br><br>Confusion matrix of Random Forest optimized for precision_score on the test data:<br>     pred_neg  pred_pos<br>neg        85         5<br>pos         3        50</pre><p>The precision, recall, and accuracy scores for every combination of the parameters in param_grid are stored in cv_results_. Here, a pandas DataFrame helps visualize the scores and parameters for each classifier iteration. This is included to show that although accuracy may be relatively consistent across classifiers, it’s obvious that precision and recall have a trade-off. Sorting by precision, the best scoring model should be the first record. This can be checked by looking at the parameters of the first record and comparing them to grid_search.best_params_ above.</p><pre>results = pd.DataFrame(grid_search_clf.cv_results_)<br>results = results.sort_values(by=&#39;mean_test_precision_score&#39;, ascending=False)</pre><pre>results[[&#39;mean_test_precision_score&#39;, &#39;mean_test_recall_score&#39;, &#39;mean_test_accuracy_score&#39;, &#39;param_max_depth&#39;, &#39;param_max_features&#39;, &#39;param_min_samples_split&#39;, &#39;param_n_estimators&#39;]].round(3).head()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Earvkevi%2F203%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Earvkevi%2F203.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a83c9793bb45d6f42bc7b47ddd6f5cef/href">https://medium.com/media/a83c9793bb45d6f42bc7b47ddd6f5cef/href</a></iframe><p>That classifier was optimized for precision. For comparison, to show how GridSearchCV selects the best classifier, the function call below returns a classifier optimized for recall. The grid might be similar to the grid above, the only difference is that the classifer with the highest recall will be refit. This will be the most desirable metric in the cancer diagnosis classification problem, there should be less false negatives on the test set confusion matrix.</p><pre>grid_search_clf = grid_search_wrapper(refit_score=&#39;recall_score&#39;)</pre><pre>Best params for recall_score<br>{&#39;max_depth&#39;: 5, &#39;max_features&#39;: 3, &#39;min_samples_split&#39;: 5, &#39;n_estimators&#39;: 100}<br><br>Confusion matrix of Random Forest optimized for recall_score on the test data:<br>     pred_neg  pred_pos<br>neg        84         6<br>pos         3        50</pre><p>Copy the same code for the generating the results table again, only this time it the best scores will be recall.</p><pre>results = pd.DataFrame(grid_search_clf.cv_results_)<br>results = results.sort_values(by=&#39;mean_test_precision_score&#39;, ascending=False)</pre><pre>results[[&#39;mean_test_precision_score&#39;, &#39;mean_test_recall_score&#39;, &#39;mean_test_accuracy_score&#39;, &#39;param_max_depth&#39;, &#39;param_max_features&#39;, &#39;param_min_samples_split&#39;, &#39;param_n_estimators&#39;]].round(3).head()</pre><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Earvkevi%2F201%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Earvkevi%2F201.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecff6f2902786c832e075713756a42b0/href">https://medium.com/media/ecff6f2902786c832e075713756a42b0/href</a></iframe><p>The first strategy doesn’t yield impressive results for recall_score, it doesn’t significantly reduce (if at all) the number of false negatives compared to the classifier optimized for precision_score. Ideally, when designing a cancer diagnosis test, the classifier should strive as few false negatives as possible.</p><h3>Strategy 2: Adjust the decision threshold to identify the operating point</h3><p>The precision_recall_curve and roc_curve are useful tools to visualize the sensitivity-specificty tradeoff in the classifier. They help inform a data scientist where to set the decision threshold of the model to maximize either sensitivity or specificity. This is called the “operating point” of the model.</p><blockquote>The key to understanding how to fine tune classifiers in scikit-learn is to understand the methods.predict_proba() and .decision_function(). These return the raw probability that a sample is predicted to be in a class. This is an important distinction from the absolute class predictions returned by calling the .predict() method.</blockquote><p>To make this method generalizable to all classifiers in scikit-learn, know that some classifiers (like RandomForest) use .predict_proba() while others (like SVC) use .decision_function(). The default threshold for RandomForestClassifier is 0.5, so use that as a starting point. Create an array of the class probabilites called y_scores.</p><pre>y_scores = grid_search_clf.predict_proba(X_test)[:, 1]</pre><pre># for classifiers with decision_function, this achieves similar results<br># y_scores = classifier.decision_function(X_test)</pre><p>Generate the precision-recall curve for the classifier:</p><pre>p, r, thresholds = precision_recall_curve(y_test, y_scores)</pre><p>Here adjusted_classes is a simple function to return a modified version of y_scores that was calculated above, only now class labels will be assigned according to the probability threshold t. The other function below plots the precision and recall with respect to the given threshold value, t.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eb2220c5e020a6ab9e46fa9d0f7044b/href">https://medium.com/media/3eb2220c5e020a6ab9e46fa9d0f7044b/href</a></iframe><p>Re-execute this function for several iterations, changing t each time, to tune the threshold until there are 0 False Negatives. On this particular run, I had to go all the way down to 0.29 before reducing the false negatives to 0.</p><pre>precision_recall_threshold(p, r, thresholds, 0.30)</pre><pre>pred_neg  pred_pos<br>neg        79        11<br>pos         1        52</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*cGoL45jYxDu9O0Ajx_yGgw.png" /></figure><p>Another way to view the trade off between precision and recall is to plot them together as a function of the decision threshold.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f982facf55ad22fdd410662ed1742a9c/href">https://medium.com/media/f982facf55ad22fdd410662ed1742a9c/href</a></iframe><pre># use the same p, r, thresholds that were previously calculated<br>plot_precision_recall_vs_threshold(p, r, thresholds)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*kCn4y9dCYJ9yx9xZ13YzdA.png" /></figure><p>Finally, the ROC curve shows that to achieve a 1.0 recall, the user of the model must select an operating point that allows for some false positive rate &gt; 0.0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3440b7f4bd9549e522766d7cad78bc9/href">https://medium.com/media/f3440b7f4bd9549e522766d7cad78bc9/href</a></iframe><pre>fpr, tpr, auc_thresholds = roc_curve(y_test, y_scores)<br>print(auc(fpr, tpr)) # AUC of ROC<br>plot_roc_curve(fpr, tpr, &#39;recall_optimized&#39;)</pre><pre>0.9914046121593292</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*tXhR8eh6OprNx3rS-PQXnw.png" /></figure><p>Thanks for following along. The concept of tuning a model for specificity and sensitivity should be more clear and you should be comfortable implementing the methods in your scikit-learn model. I’m interested to hear suggestions to improve the code and/or the classifiers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66e048c21e65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/fine-tuning-a-classifier-in-scikit-learn-66e048c21e65">Fine tuning a classifier in scikit-learn</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Out of Core Genomics]]></title>
            <link>https://medium.com/data-science/out-of-core-genomics-8aa5ef487d1e?source=rss-b3a3607891a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aa5ef487d1e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[genomics]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Kevin Arvai]]></dc:creator>
            <pubDate>Tue, 26 Dec 2017 14:31:03 GMT</pubDate>
            <atom:updated>2017-12-31T00:37:13.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOcLTHqePMga4YNKPTll6Q.jpeg" /></figure><h3>Out of Core Genomics in Python</h3><p>It’s often the case where data scientists want to explore a data set that doesn’t fit into memory. As data continues to grow in size, so too, do our tools to work with these data need to expand. Motivation for this post originates from my interest in working with <a href="https://opensnp.org/">openSNP</a> data. openSNP is an open-source platform where users upload their genotype data from direct-to-consumer genetics companies like <a href="https://www.23andme.com/">23andMe</a>. Raw result files are often hundreds of thousands of records long, each record representing a location in the human genome. There are over 4,000 raw result files in the openSNP data however, my laptop runs a VirtualBox with only 5GB RAM, which meant I needed to find some clever solutions beyond the standard pandas library in order to work with this much data. This post describes one of several applications that can benefit from out-of-core computing.</p><h3>Download the openSNP data</h3><p>openSNP has over 40 GB of genotype &amp; phenotype data stored as text files!<br> For the purposes of this demo, the analysis will be limited to only the 23andMe files. Below are a few shell commands to download the raw data, create a directory, and move the 23andMe files to their own directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c92e685d256464fb50b42a158d003aa/href">https://medium.com/media/4c92e685d256464fb50b42a158d003aa/href</a></iframe><p>Here’s a look at an example 23andMe result file, the header is commented out with # then there are 600,000+ rows of genotype data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*fnqa7CuiK8vYH03TOyvclw.jpeg" /></figure><h3>Extract a reasonably-sized test set</h3><p>For this exercise, use a manageable subset of the full openSNP data so the demonstration will execute in a reasonable amount of time. Create a new directory and copy genotype files that begin with the name: user21 .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c03b643b13655f8746935aef048edcb/href">https://medium.com/media/5c03b643b13655f8746935aef048edcb/href</a></iframe><h3>Pure pandas</h3><p>First, start with a pure <a href="http://pandas.pydata.org/">pandas</a> read_csv solution, something that should be familiar to Python data scientists. Try to create a large DataFrame in memory. The join method can accomplish this task. Even though it&#39;s an expensive operation, the test data set we just extracted is small enough that it will successfully execute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e0c5f99e8fead8a07ea6799f642982a/href">https://medium.com/media/0e0c5f99e8fead8a07ea6799f642982a/href</a></iframe><pre>CPU times: user 7min 48s, sys: 9.83 s, total: 7min 58s <br>Wall time: 8min 15s</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d78X7nVdCLeSey2RNwsrcw.png" /></figure><p>On the test set of 43 files, the entire DataFrame fits into memory. However, using this pure pandas method on the entire openSNP data set of 1,915 files would eventually crash the laptop because it would run out of pyhsical memory.</p><h3>Dask — parallel out-of-core DataFrame</h3><p>Enter <a href="http://dask.pydata.org/en/latest/index.html">dask</a>, a Python library that implements out-of-core DataFrames. It’s API is similar to pandas, with a few additional methods and arguments. Dask creates a computation graph that will read the same files in parallel and create a “lazy” DataFrame that isn&#39;t executed until comptue() is explicitly called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/0*VtPcoXneqzWWzmdQ.png" /><figcaption>example computation graph from <a href="http://dask.pydata.org/en/latest/_images/pipeline.png">http://dask.pydata.org/en/latest/_images/pipeline.png</a></figcaption></figure><p>Lazily read the genotype files into a dask DataFrame, this operation doesn’t actually read the files into memory, evidenced by the cpu times, instead it builds a graph similar to the one above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09db3efa2b4450c453fcb818fc9f3c56/href">https://medium.com/media/09db3efa2b4450c453fcb818fc9f3c56/href</a></iframe><pre>CPU times: user 112 ms, sys: 52 ms, total: 164 ms <br>Wall time: 298 ms</pre><p>Performing an operation on the dask DataFrame, such as set_index() triggers computation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fdc28161c1b5224ebe9d2dd118db87e/href">https://medium.com/media/5fdc28161c1b5224ebe9d2dd118db87e/href</a></iframe><pre>CPU times: user 4min 44s, sys: 23 s, total: 5min 7s <br>Wall time: 4min 45s</pre><p>The dask compute() method provides familiar results. Since the join method wasn’t performed on the dask DataFrame, in contrast to the pure pandas method, just investigate one record (or one SNP).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76d45dff6602b70218749ed882f515d9/href">https://medium.com/media/76d45dff6602b70218749ed882f515d9/href</a></iframe><pre>CPU times: user 3min 31s, sys: 36.1 s, total: 4min 7s <br>Wall time: 3min 46s </pre><pre>CC 37 <br>CT 5<br>TT 1 <br>Name: genotype, dtype: int64</pre><p>Again, in contrast to ddf (dask), gtdf is in memory so this operation is blazing fast.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8526f2a4359024409fb2f33358f7c64e/href">https://medium.com/media/8526f2a4359024409fb2f33358f7c64e/href</a></iframe><pre>CPU times: user 4.3 s, sys: 8.1 s, total: 12.4 s <br>Wall time: 1min 1s</pre><pre>CC 37 <br>CT 5<br>TT 1 <br>Name: rs1333525, dtype: int64</pre><p>At first blush, the computation times are deceiving. The dask method took longer because of the lazy computation, it still had to read all the files and then perform the operation. However, when you consider the <strong>8 minutes 15 seconds</strong> required to join gtdf DataFrame in addtion to the <strong>1 minute 1 second</strong> for gtdf.loc[rs13333525&#39;].value_counts(), that&#39;s <strong>9 minutes 16 seconds</strong>. In contrast, the dask method required 3 steps. First setting the computation graph was &lt; 1 second. So the real comparison comes from the <strong>4 minutes 45 seconds</strong> to set the index and <strong>3 minutes 46 seconds</strong> to perform ddf.loc[&#39;rs1333525&#39;][&#39;genotype&#39;].value_counts().compute() for a grand total of <strong>8 minutes 31 seconds</strong>. Seems like a marginal speedup on our test data of only 43 files. The real power of dask comes into play when the DataFrame simply won’t fit into memory.</p><h3>Increase query peformance — Convert .txt/.csv to Parquet!</h3><p>It would be nice to speed up the dask queries so we can work with the DataFrame for downstream analysis in a reasonable amount of time. The solution is to store the raw text data on disk in an efficient binary format. A popular choice for this is traditionally <a href="https://support.hdfgroup.org/HDF5/doc/H5.intro.html">HDF5</a>, but I chose to use <a href="https://parquet.apache.org/">parquet</a> becuase HDF5 can be tricky to work with. Dask uses the <a href="http://fastparquet.readthedocs.io/en/latest/index.html">fastparquet</a> implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93dbf5dffa53667bcd6e85f1d8fda61/href">https://medium.com/media/e93dbf5dffa53667bcd6e85f1d8fda61/href</a></iframe><pre>CPU times: user 12min 35s, sys: 1min 41s, total: 14min 17s<br>Wall time: 19min 30s</pre><p>Essentially, what this has done is converted .txt files to parquet files. How much performance is really gained from this? Revisiting the dask DataFrame, ddf, remember that took 3 minutes and 46 seconds to compute value_counts() . Compare after converting to parquet format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/719b8654e6902a4f647be67123319a23/href">https://medium.com/media/719b8654e6902a4f647be67123319a23/href</a></iframe><pre>CPU times: user 8.18 s, sys: 608 ms, total: 8.79 s <br>Wall time: 11.7 s </pre><pre>CC 37 <br>CT 5 <br>TT 1 <br>Name: genotype, dtype: int64</pre><p>Parquet offers a noticeable performance increase for querying data, even with this small validation set of 43 files. Scaling this up to 1,915 files, the parallel .txt version, ddf, took 5+ hours to execute value_counts() for one SNP. to_parquet on the 1,915 file DataFrame took a couple hours. Once you see the query performance improvements, it&#39;s well worth the up-front cost of converting from .txt or .csv to parquet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0AuKtKnFQJrjB8QTsh5Gew.jpeg" /></figure><h3>Performance on the entire openSNP data set</h3><p>I pre-computed the parquet files for the entire gt23 directory using the same commands above and stored the parquet files in gt23_pq. <em>Some malformed files needed to be cleaned and/or removed.</em></p><pre>$ find gt23_pq/ -type f | wc -l</pre><pre>1898</pre><p>Now, issue the same value_counts() command that was used on the test data set from the previous code block, but this will consider the all of the 23andMe genotype files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14a020fafd4d5b84c68c821d76bca9d7/href">https://medium.com/media/14a020fafd4d5b84c68c821d76bca9d7/href</a></iframe><pre>CPU times: user 6.67 s, sys: 112 ms, total: 6.78 s<br>Wall time: 7.2 s</pre><pre>CC    1625<br>CT     277<br>TT      13<br>Name: genotype, dtype: int64</pre><p>These results highlight the far superior performance of parquet over .csv or .txt. Additionally, dask proved it&#39;s value as an easy-to-use tool when physical memory is a constraint. By now you&#39;ve probably noticed I wasn&#39;t able to assign the user identifier to each column. dd.read_csv() assumes the column names in each file are identical.</p><h3>Implemenation on the entire openSNP dataset</h3><p>The dask and parquet portion of the tutorial have concluded. I wanted to show how easy dask and parquet make it to work with large data sets. The example below compares variant frequencies in the openSNP data to <a href="http://exac.broadinstitute.org/">exAC</a> data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c07d9af7266955c8448cdfc2ae01ef14/href">https://medium.com/media/c07d9af7266955c8448cdfc2ae01ef14/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Vxwd1k0HJ30tt6bVvp4rlw.png" /></figure><p>I hope you find this post useful and think about using dask and parquet when working with structured text files. I really encourage you to check out the dask and parquet documentation and follow along on some of their tutorials. Thanks for reading, comments and code improvements welcome!</p><p>updated from my github pages site <a href="https://arvkevi.github.io/Out_of_Core_Genomics.html">https://arvkevi.github.io/Out_of_Core_Genomics.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aa5ef487d1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/out-of-core-genomics-8aa5ef487d1e">Out of Core Genomics</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>