{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Customer Churn Prediction with XGBoost\n", "_**Using Gradient Boosted Trees to Predict Mobile Customer Departure**_\n", "\n", "---\n", "\n", "---\n", "\n", "## Contents\n", "\n", "1. [ML workflow](#ML-workflow)\n", "1. [Business problem](#Business-problem)\n", "1. [ML problem framing](#ML-problem-framing)\n", "1. [Data collection](#Data-collection)\n", " 1. [Setup](#Setup)\n", "1. [Data preparation](#Data-preparation)\n", "1. [Data visualization](#Data-visualization)\n", "1. [Feature engineering](#Feature-Engineering)\n", "1. [Model training](#Model-training)\n", "1. [Model evaluation](#Model-evaluation)\n", " 1. [Host](#Host)\n", " 1. [Evaluate](#Evaluate)\n", " 1. [Relative cost of errors](#Relative-cost-of-errors)\n", "---\n", "\n", "## ML workflow\n", "![ML flow](https://user-images.githubusercontent.com/1559391/56876053-57658900-6a0a-11e9-92a2-1822eb4b12af.png)\n", "\n", "## Business problem\n", "\n", "_This notebook has been adapted from an [AWS blog post](https://aws.amazon.com/blogs/ai/predicting-customer-churn-with-amazon-machine-learning/)_\n", "\n", "Losing customers is costly for any business. Identifying unhappy customers early on gives you a chance to offer them incentives to stay. This notebook describes using machine learning (ML) for the automated identification of unhappy customers, also known as customer churn prediction. ML models rarely give perfect predictions though, so this notebook is also about how to incorporate the relative costs of prediction mistakes when determining the financial outcome of using ML.\n", "\n", "We use an example of churn that is familiar to all of us–leaving a mobile phone operator. Seems like I can always find fault with my provider du jour! And if my provider knows that I’m thinking of leaving, it can offer timely incentives–I can always use a phone upgrade or perhaps have a new feature activated–and I might just stick around. Incentives are often much more cost effective than losing and reacquiring a customer.\n", "\n", "---\n", "## ML problem framing\n", "\n", "Now that we understand the business problem let's try to frame this into a machine learning problem. A simple way to look at this would be to understand what we are trying to predict. Here we want to know if the customer will curn or not. This fits a simple binary classification problem. \n", "There are multiple Sagemaker built-in algorithms that support classification. We will choose the algorithm that is very popular - XGboost\n", "\n", "![sagemaker-supported-algos](https://user-images.githubusercontent.com/1559391/56876636-7239fc80-6a0e-11e9-840c-c59663a90536.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Data collection\n", "\n", "Mobile operators have historical records on which customers ultimately ended up churning and which continued using the service. We can use this historical information to construct an ML model of one mobile operator’s churn using a process called training. After training the model, we can pass the profile information of an arbitrary customer (the same profile information that we used to train the model) to the model, and have the model predict whether this customer is going to churn. Of course, we expect the model to make mistakes–after all, predicting the future is tricky business! But I’ll also show how to deal with prediction errors.\n", "\n", "The dataset we use is publicly available and was mentioned in the book [Discovering Knowledge in Data](https://www.amazon.com/dp/0470908742/) by Daniel T. Larose. It is attributed by the author to the University of California Irvine Repository of Machine Learning Datasets. Let's download and read that dataset in now:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### Setup\n", "\n", "_This notebook was created and tested on an ml.m4.xlarge notebook instance._\n", "\n", "Let's start by specifying:\n", "\n", "- The S3 bucket and prefix that you want to use for training and model data. This should be within the same region as the Notebook Instance, training, and hosting.\n", "- The IAM role arn used to give training and hosting access to your data. See the documentation for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the boto regexp with a the appropriate full IAM role arn string(s)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "isConfigCell": true }, "outputs": [], "source": [ "# Define IAM role\n", "import boto3\n", "import re\n", "import sagemaker\n", "\n", "role = sagemaker.get_execution_role()\n", "sess = sagemaker.Session()\n", "bucket = sess.default_bucket()\n", "prefix = 'DEMO-xgboost-churn'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we'll import the Python libraries we'll need for the remainder of the exercise." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import io\n", "import os\n", "import sys\n", "import time\n", "import json\n", "from IPython.display import display\n", "from time import strftime, gmtime\n", "import sagemaker\n", "from sagemaker.predictor import csv_serializer\n", "import seaborn as sns\n", "sns.set(font_scale=1.0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!wget http://dataminingconsultant.com/DKD2e_data_sets.zip\n", "!unzip -o DKD2e_data_sets.zip" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data preparation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "churn = pd.read_csv('./Data sets/churn.txt')\n", "pd.set_option('display.max_columns', 500)\n", "churn" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data visualization\n", "\n", "By modern standards, it’s a relatively small dataset, with only 3,333 records, where each record uses 21 attributes to describe the profile of a customer of an unknown US mobile operator. The attributes are:\n", "\n", "- `State`: the US state in which the customer resides, indicated by a two-letter abbreviation; for example, OH or NJ\n", "- `Account Length`: the number of days that this account has been active\n", "- `Area Code`: the three-digit area code of the corresponding customer’s phone number\n", "- `Phone`: the remaining seven-digit phone number\n", "- `Int’l Plan`: whether the customer has an international calling plan: yes/no\n", "- `VMail Plan`: whether the customer has a voice mail feature: yes/no\n", "- `VMail Message`: presumably the average number of voice mail messages per month\n", "- `Day Mins`: the total number of calling minutes used during the day\n", "- `Day Calls`: the total number of calls placed during the day\n", "- `Day Charge`: the billed cost of daytime calls\n", "- `Eve Mins, Eve Calls, Eve Charge`: the billed cost for calls placed during the evening\n", "- `Night Mins`, `Night Calls`, `Night Charge`: the billed cost for calls placed during nighttime\n", "- `Intl Mins`, `Intl Calls`, `Intl Charge`: the billed cost for international calls\n", "- `CustServ Calls`: the number of calls placed to Customer Service\n", "- `Churn?`: whether the customer left the service: true/false\n", "\n", "The last attribute, `Churn?`, is known as the target attribute–the attribute that we want the ML model to predict. Because the target attribute is binary, our model will be performing binary prediction, also known as binary classification.\n", "\n", "Let's begin exploring the data:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Frequency tables for each categorical feature\n", "for column in churn.select_dtypes(include=['object']).columns:\n", " display(pd.crosstab(index=churn[column], columns='% observations', normalize='columns'))\n", "\n", "# Histograms for each numeric features\n", "display(churn.describe())\n", "%matplotlib inline\n", "hist = churn.hist(bins=30, sharey=True, figsize=(10, 10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see immediately that:\n", "- `State` appears to be quite evenly distributed\n", "- `Phone` takes on too many unique values to be of any practical use. It's possible parsing out the prefix could have some value, but without more context on how these are allocated, we should avoid using it.\n", "- Only 14% of customers churned, so there is some class imabalance, but nothing extreme.\n", "- Most of the numeric features are surprisingly nicely distributed, with many showing bell-like gaussianity. `VMail Message` being a notable exception (and `Area Code` showing up as a feature we should convert to non-numeric)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "churn = churn.drop('Phone', axis=1)\n", "churn['Area Code'] = churn['Area Code'].astype(object)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next let's look at the relationship between each of the features and our target variable." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for column in churn.select_dtypes(include=['object']).columns:\n", " if column != 'Churn?':\n", " display(pd.crosstab(index=churn[column], columns=churn['Churn?'], normalize='columns'))\n", "\n", "for column in churn.select_dtypes(exclude=['object']).columns:\n", " print(column)\n", " hist = churn[[column, 'Churn?']].hist(by='Churn?', bins=30)\n", " plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Interestingly we see that churners appear:\n", "- Fairly evenly distributed geographically\n", "- More likely to have an international plan\n", "- Less likely to have a voicemail plan\n", "- To exhibit some bimodality in daily minutes (either higher or lower than the average for non-churners)\n", "- To have a larger number of customer service calls (which makes sense as we'd expect customers who experience lots of problems may be more likely to churn)\n", "\n", "In addition, we see that churners take on very similar distributions for features like `Day Mins` and `Day Charge`. That's not surprising as we'd expect minutes spent talking to correlate with charges. Let's dig deeper into the relationships between our features." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "display(churn.corr())\n", "pd.plotting.scatter_matrix(churn, figsize=(20, 20))\n", "plt.show()\n", "plt.figure(figsize=(10,5))\n", "sns.heatmap(churn.corr())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Feature engineering\n", "\n", "We see several features that essentially have 100% correlation with one another. Including these feature pairs in some machine learning algorithms can create catastrophic problems, while in others it will only introduce minor redundancy and bias. Let's remove one feature from each of the highly correlated pairs: Day Charge from the pair with Day Mins, Night Charge from the pair with Night Mins, Intl Charge from the pair with Intl Mins:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "churn = churn.drop(['Day Charge', 'Eve Charge', 'Night Charge', 'Intl Charge'], axis=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we've cleaned up our dataset, let's determine which algorithm to use. As mentioned above, there appear to be some variables where both high and low (but not intermediate) values are predictive of churn. In order to accommodate this in an algorithm like linear regression, we'd need to generate polynomial (or bucketed) terms. Instead, let's attempt to model this problem using gradient boosted trees. Amazon SageMaker provides an XGBoost container that we can use to train in a managed, distributed setting, and then host as a real-time prediction endpoint. XGBoost uses gradient boosted trees which naturally account for non-linear relationships between features and the target variable, as well as accommodating complex interactions between features.\n", "\n", "Amazon SageMaker XGBoost can train on data in either a CSV or LibSVM format. For this example, we'll stick with CSV. It should:\n", "- Have the predictor variable in the first column\n", "- Not have a header row\n", "\n", "But first, let's convert our categorical features into numeric features." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model_data = pd.get_dummies(churn)\n", "model_data = pd.concat([model_data['Churn?_True.'], model_data.drop(['Churn?_False.', 'Churn?_True.'], axis=1)], axis=1)\n", "model_data.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now let's split the data into training, validation, and test sets. This will help prevent us from overfitting the model, and allow us to test the models accuracy on data it hasn't already seen." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "train_data, validation_data, test_data = np.split(model_data.sample(frac=1, random_state=1729), [int(0.7 * len(model_data)), int(0.9 * len(model_data))])\n", "train_data.to_csv('train.csv', header=False, index=False)\n", "validation_data.to_csv('validation.csv', header=False, index=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we'll upload these files to S3." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "boto3.Session().resource('s3').Bucket(bucket).Object(os.path.join(prefix, 'train/train.csv')).upload_file('train.csv')\n", "boto3.Session().resource('s3').Bucket(bucket).Object(os.path.join(prefix, 'validation/validation.csv')).upload_file('validation.csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Model training\n", "\n", "Moving onto training, first we'll need to specify the locations of the XGBoost algorithm containers." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sagemaker.amazon.amazon_estimator import get_image_uri\n", "container = get_image_uri(boto3.Session().region_name, 'xgboost')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, because we're training with the CSV file format, we'll create `s3_input`s that our training function can use as a pointer to the files in S3." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s3_input_train = sagemaker.s3_input(s3_data='s3://{}/{}/train'.format(bucket, prefix), content_type='csv')\n", "s3_input_validation = sagemaker.s3_input(s3_data='s3://{}/{}/validation/'.format(bucket, prefix), content_type='csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we can specify a few parameters like what type of training instances we'd like to use and how many, as well as our XGBoost hyperparameters. A few key hyperparameters are:\n", "- `max_depth` controls how deep each tree within the algorithm can be built. Deeper trees can lead to better fit, but are more computationally expensive and can lead to overfitting. There is typically some trade-off in model performance that needs to be explored between a large number of shallow trees and a smaller number of deeper trees.\n", "- `subsample` controls sampling of the training data. This technique can help reduce overfitting, but setting it too low can also starve the model of data.\n", "- `num_round` controls the number of boosting rounds. This is essentially the subsequent models that are trained using the residuals of previous iterations. Again, more rounds should produce a better fit on the training data, but can be computationally expensive or lead to overfitting.\n", "- `eta` controls how aggressive each round of boosting is. Larger values lead to more conservative boosting.\n", "- `gamma` controls how aggressively trees are grown. Larger values lead to more conservative models.\n", "\n", "More detail on XGBoost's hyperparmeters can be found on here - https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost_hyperparameters.html" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sess = sagemaker.Session()\n", "\n", "xgb = sagemaker.estimator.Estimator(container,\n", " role, \n", " train_instance_count=1, \n", " train_instance_type='ml.m4.xlarge',\n", " output_path='s3://{}/{}/output'.format(bucket, prefix),\n", " sagemaker_session=sess)\n", "xgb.set_hyperparameters(max_depth=5,\n", " eta=0.2,\n", " gamma=4,\n", " min_child_weight=6,\n", " subsample=0.8,\n", " silent=0,\n", " objective='binary:logistic',\n", " num_round=100)\n", "\n", "xgb.fit({'train': s3_input_train, 'validation': s3_input_validation}) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Model evaluation\n", "### Host\n", "\n", "Now that we've trained the algorithm, let's create a model and deploy it to a hosted endpoint." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xgb_predictor = xgb.deploy(initial_instance_count=1,\n", " instance_type='ml.t2.xlarge')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Evaluate\n", "\n", "Now that we have a hosted endpoint running, we can make real-time predictions from our model very easily, simply by making an http POST request. But first, we'll need to setup serializers and deserializers for passing our `test_data` NumPy arrays to the model behind the endpoint." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xgb_predictor.content_type = 'text/csv'\n", "xgb_predictor.serializer = csv_serializer\n", "xgb_predictor.deserializer = None" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we'll use a simple function to:\n", "1. Loop over our test dataset\n", "1. Split it into mini-batches of rows \n", "1. Convert those mini-batchs to CSV string payloads\n", "1. Retrieve mini-batch predictions by invoking the XGBoost endpoint\n", "1. Collect predictions and convert from the CSV output our model provides into a NumPy array" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def predict(data, rows=500):\n", " split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))\n", " predictions = ''\n", " for array in split_array:\n", " predictions = ','.join([predictions, xgb_predictor.predict(array).decode('utf-8')])\n", "\n", " return np.fromstring(predictions[1:], sep=',')\n", "\n", "predictions = predict(test_data.as_matrix()[:, 1:])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many ways to compare the performance of a machine learning model, but let's start by simply by comparing actual to predicted values. In this case, we're simply predicting whether the customer churned (`1`) or not (`0`), which produces a simple confusion matrix." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "confusion_matrix = pd.crosstab(index=test_data.iloc[:, 0], columns=np.round(predictions), rownames=['actual'], colnames=['predictions'])\n", "sns.set(font_scale=1.5)\n", "sns.heatmap(confusion_matrix, annot=True, fmt='.4f', cmap=\"YlGnBu\").set_title('Confusion Matrix')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Note, due to randomized elements of the algorithm, you results may differ slightly._\n", "\n", "Of the 48 churners, we've correctly predicted 39 of them (true positives). And, we incorrectly predicted 4 customers would churn who then ended up not doing so (false positives). There are also 9 customers who ended up churning, that we predicted would not (false negatives).\n", "\n", "An important point here is that because of the `np.round()` function above we are using a simple threshold (or cutoff) of 0.5. Our predictions from `xgboost` come out as continuous values between 0 and 1 and we force them into the binary classes that we began with. However, because a customer that churns is expected to cost the company more than proactively trying to retain a customer who we think might churn, we should consider adjusting this cutoff. That will almost certainly increase the number of false positives, but it can also be expected to increase the number of true positives and reduce the number of false negatives.\n", "\n", "To get a rough intuition here, let's look at the continuous values of our predictions." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.hist(predictions)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The continuous valued predictions coming from our model tend to skew toward 0 or 1, but there is sufficient mass between 0.1 and 0.9 that adjusting the cutoff should indeed shift a number of customers' predictions. For example..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "confusion_matrix = pd.crosstab(index=test_data.iloc[:, 0], columns=np.where(predictions > 0.3, 1, 0), rownames=['actual'], colnames=['predictions'])\n", "sns.set(font_scale=1.5)\n", "sns.heatmap(confusion_matrix, annot=True, fmt='.4f', cmap=\"YlGnBu\").set_title('Confusion Matrix')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that changing the cutoff from 0.5 to 0.3 results in 1 more true positives, 3 more false positives, and 1 fewer false negatives. The numbers are small overall here, but that's 6-10% of customers overall that are shifting because of a change to the cutoff. Was this the right decision? We may end up retaining 3 extra customers, but we also unnecessarily incentivized 5 more customers who would have stayed. Determining optimal cutoffs is a key step in properly applying machine learning in a real-world setting. Let's discuss this more broadly and then apply a specific, hypothetical solution for our current problem.\n", "\n", "### Relative cost of errors\n", "\n", "Any practical binary classification problem is likely to produce a similarly sensitive cutoff. That by itself isn’t a problem. After all, if the scores for two classes are really easy to separate, the problem probably isn’t very hard to begin with and might even be solvable with simple rules instead of ML.\n", "\n", "More important, if I put an ML model into production, there are costs associated with the model erroneously assigning false positives and false negatives. I also need to look at similar costs associated with correct predictions of true positives and true negatives. Because the choice of the cutoff affects all four of these statistics, I need to consider the relative costs to the business for each of these four outcomes for each prediction.\n", "\n", "#### Assigning costs\n", "\n", "What are the costs for our problem of mobile operator churn? The costs, of course, depend on the specific actions that the business takes. Let's make some assumptions here.\n", "\n", "First, assign the true negatives the cost of \\$0. Our model essentially correctly identified a happy customer in this case, and we don’t need to do anything.\n", "\n", "False negatives are the most problematic, because they incorrectly predict that a churning customer will stay. We lose the customer and will have to pay all the costs of acquiring a replacement customer, including foregone revenue, advertising costs, administrative costs, point of sale costs, and likely a phone hardware subsidy. A quick search on the Internet reveals that such costs typically run in the hundreds of dollars so, for the purposes of this example, let's assume \\$500. This is the cost of false negatives.\n", "\n", "Finally, for customers that our model identifies as churning, let's assume a retention incentive in the amount of \\\\$100. If my provider offered me such a concession, I’d certainly think twice before leaving. This is the cost of both true positive and false positive outcomes. In the case of false positives (the customer is happy, but the model mistakenly predicted churn), we will “waste” the \\\\$100 concession. We probably could have spent that \\\\$100 more effectively, but it's possible we increased the loyalty of an already loyal customer, so that’s not so bad." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Finding the optimal cutoff\n", "\n", "It’s clear that false negatives are substantially more costly than false positives. Instead of optimizing for error based on the number of customers, we should be minimizing a cost function that looks like this:\n", "\n", "```txt\n", "$500 * FN(C) + $0 * TN(C) + $100 * FP(C) + $100 * TP(C)\n", "```\n", "\n", "FN(C) means that the false negative percentage is a function of the cutoff, C, and similar for TN, FP, and TP. We need to find the cutoff, C, where the result of the expression is smallest.\n", "\n", "A straightforward way to do this, is to simply run a simulation over a large number of possible cutoffs. We test 100 possible values in the for loop below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cutoffs = np.arange(0.01, 1, 0.01)\n", "costs = []\n", "for c in cutoffs:\n", " costs.append(np.sum(np.sum(np.array([[0, 100], [500, 100]]) * \n", " pd.crosstab(index=test_data.iloc[:, 0], \n", " columns=np.where(predictions > c, 1, 0)))))\n", "\n", "costs = np.array(costs)\n", "plt.plot(cutoffs, costs)\n", "plt.show()\n", "print('Cost is minimized near a cutoff of:', cutoffs[np.argmin(costs)], 'for a cost of:', np.min(costs))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above chart shows how picking a threshold too low results in costs skyrocketing as all customers are given a retention incentive. Meanwhile, setting the threshold too high results in too many lost customers, which ultimately grows to be nearly as costly. The overall cost can be minimized at \\\\$ 8400 by setting the cutoff to 0.46, which is substantially better than the\n", "\\\\$ 20k+ I would expect to lose by not taking any action." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "confusion_matrix = pd.crosstab(index=test_data.iloc[:, 0], columns=np.where(predictions > 0.46, 1, 0), rownames=['actual'], colnames=['predictions'])\n", "sns.set(font_scale=1.5)\n", "sns.heatmap(confusion_matrix, annot=True, fmt='.4f', cmap=\"YlGnBu\").set_title('Confusion Matrix')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### (Optional) Clean-up\n", "\n", "If you're ready to be done with this notebook, please run the cell below. This will remove the hosted endpoint you created and avoid any charges from a stray instance being left on." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Completed\")\n", "sagemaker.Session().delete_endpoint(xgb_predictor.endpoint)" ] } ], "metadata": { "kernelspec": { "display_name": "conda_python3", "language": "python", "name": "conda_python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" }, "notice": "Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." }, "nbformat": 4, "nbformat_minor": 2 }