diff --git a/customer_segments/README.md b/customer_segments/README.md
new file mode 100644
index 0000000..4e2eae5
--- /dev/null
+++ b/customer_segments/README.md
@@ -0,0 +1,49 @@
+# Content: Unsupervised Learning
+## Project: Creating Customer Segments
+
+### Install
+
+This project requires **Python 2.7** and the following Python libraries installed:
+
+- [NumPy](http://www.numpy.org/)
+- [Pandas](http://pandas.pydata.org)
+- [matplotlib](http://matplotlib.org/)
+- [scikit-learn](http://scikit-learn.org/stable/)
+
+You will also need to have software installed to run and execute a [Jupyter Notebook](http://ipython.org/notebook.html)
+
+If you do not have Python installed yet, it is highly recommended that you install the [Anaconda](http://continuum.io/downloads) distribution of Python, which already has the above packages and more included. Make sure that you select the Python 2.7 installer and not the Python 3.x installer.
+
+### Code
+
+Template code is provided in the `customer_segments.ipynb` notebook file. You will also be required to use the included `visuals.py` Python file and the `customers.csv` dataset file to complete your work. While some code has already been implemented to get you started, you will need to implement additional functionality when requested to successfully complete the project. Note that the code included in `visuals.py` is meant to be used out-of-the-box and not intended for students to manipulate. If you are interested in how the visualizations are created in the notebook, please feel free to explore this Python file.
+
+### Run
+
+In a terminal or command window, navigate to the top-level project directory `customer_segments/` (that contains this README) and run one of the following commands:
+
+```bash
+ipython notebook customer_segments.ipynb
+```
+or
+```bash
+jupyter notebook customer_segments.ipynb
+```
+
+This will open the Jupyter Notebook software and project file in your browser.
+
+## Data
+
+The customer segments data is included as a selection of 440 data points collected on data found from clients of a wholesale distributor in Lisbon, Portugal. More information can be found on the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Wholesale+customers).
+
+Note (m.u.) is shorthand for *monetary units*.
+
+**Features**
+1) `Fresh`: annual spending (m.u.) on fresh products (Continuous);
+2) `Milk`: annual spending (m.u.) on milk products (Continuous);
+3) `Grocery`: annual spending (m.u.) on grocery products (Continuous);
+4) `Frozen`: annual spending (m.u.) on frozen products (Continuous);
+5) `Detergents_Paper`: annual spending (m.u.) on detergents and paper products (Continuous);
+6) `Delicatessen`: annual spending (m.u.) on and delicatessen products (Continuous);
+7) `Channel`: {Hotel/Restaurant/Cafe - 1, Retail - 2} (Nominal)
+8) `Region`: {Lisbon - 1, Oporto - 2, or Other - 3} (Nominal)
\ No newline at end of file
diff --git a/customer_segments/customer_segments.ipynb b/customer_segments/customer_segments.ipynb
new file mode 100644
index 0000000..6666c1a
--- /dev/null
+++ b/customer_segments/customer_segments.ipynb
@@ -0,0 +1,842 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Machine Learning Engineer Nanodegree\n",
+ "## Unsupervised Learning\n",
+ "## Project: Creating Customer Segments"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Welcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully!\n",
+ "\n",
+ "In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. \n",
+ "\n",
+ ">**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Getting Started\n",
+ "\n",
+ "In this project, you will analyze a dataset containing data on various customers' annual spending amounts (reported in *monetary units*) of diverse product categories for internal structure. One goal of this project is to best describe the variation in the different types of customers that a wholesale distributor interacts with. Doing so would equip the distributor with insight into how to best structure their delivery service to meet the needs of each customer.\n",
+ "\n",
+ "The dataset for this project can be found on the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Wholesale+customers). For the purposes of this project, the features `'Channel'` and `'Region'` will be excluded in the analysis — with focus instead on the six product categories recorded for customers.\n",
+ "\n",
+ "Run the code block below to load the wholesale customers dataset, along with a few of the necessary Python libraries required for this project. You will know the dataset loaded successfully if the size of the dataset is reported."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Import libraries necessary for this project\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "from IPython.display import display # Allows the use of display() for DataFrames\n",
+ "\n",
+ "# Import supplementary visualizations code visuals.py\n",
+ "import visuals as vs\n",
+ "\n",
+ "# Pretty display for notebooks\n",
+ "%matplotlib inline\n",
+ "\n",
+ "# Load the wholesale customers dataset\n",
+ "try:\n",
+ " data = pd.read_csv(\"customers.csv\")\n",
+ " data.drop(['Region', 'Channel'], axis = 1, inplace = True)\n",
+ " print(\"Wholesale customers dataset has {} samples with {} features each.\".format(*data.shape))\n",
+ "except:\n",
+ " print(\"Dataset could not be loaded. Is the dataset missing?\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Data Exploration\n",
+ "In this section, you will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which you will track through the course of this project.\n",
+ "\n",
+ "Run the code block below to observe a statistical description of the dataset. Note that the dataset is composed of six important product categories: **'Fresh'**, **'Milk'**, **'Grocery'**, **'Frozen'**, **'Detergents_Paper'**, and **'Delicatessen'**. Consider what each category represents in terms of products you could purchase."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Display a description of the dataset\n",
+ "display(data.describe())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Implementation: Selecting Samples\n",
+ "To get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, add **three** indices of your choice to the `indices` list which will represent the customers to track. It is suggested to try different sets of samples until you obtain customers that vary significantly from one another."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# TODO: Select three indices of your choice you wish to sample from the dataset\n",
+ "indices = []\n",
+ "\n",
+ "# Create a DataFrame of the chosen samples\n",
+ "samples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True)\n",
+ "print(\"Chosen samples of wholesale customers dataset:\")\n",
+ "display(samples)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 1\n",
+ "Consider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers. \n",
+ "\n",
+ "* What kind of establishment (customer) could each of the three samples you've chosen represent?\n",
+ "\n",
+ "**Hint:** Examples of establishments include places like markets, cafes, delis, wholesale retailers, among many others. Avoid using names for establishments, such as saying *\"McDonalds\"* when describing a sample customer as a restaurant. You can use the mean values for reference to compare your samples with. The mean values are as follows:\n",
+ "\n",
+ "* Fresh: 12000.2977\n",
+ "* Milk: 5796.2\n",
+ "* Grocery: 7951.3\n",
+ "* Detergents_paper: 2881.4\n",
+ "* Delicatessen: 1524.8\n",
+ "\n",
+ "Knowing this, how do your samples compare? Does that help in driving your insight into what kind of establishments they might be? \n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Implementation: Feature Relevance\n",
+ "One interesting thought to consider is if one (or more) of the six product categories is actually relevant for understanding customer purchasing. That is to say, is it possible to determine whether customers purchasing some amount of one category of products will necessarily purchase some proportional amount of another category of products? We can make this determination quite easily by training a supervised regression learner on a subset of the data with one feature removed, and then score how well that model can predict the removed feature.\n",
+ "\n",
+ "In the code block below, you will need to implement the following:\n",
+ " - Assign `new_data` a copy of the data by removing a feature of your choice using the `DataFrame.drop` function.\n",
+ " - Use `sklearn.cross_validation.train_test_split` to split the dataset into training and testing sets.\n",
+ " - Use the removed feature as your target label. Set a `test_size` of `0.25` and set a `random_state`.\n",
+ " - Import a decision tree regressor, set a `random_state`, and fit the learner to the training data.\n",
+ " - Report the prediction score of the testing set using the regressor's `score` function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature\n",
+ "new_data = None\n",
+ "\n",
+ "# TODO: Split the data into training and testing sets(0.25) using the given feature as the target\n",
+ "# Set a random state.\n",
+ "X_train, X_test, y_train, y_test = (None, None, None, None)\n",
+ "\n",
+ "# TODO: Create a decision tree regressor and fit it to the training set\n",
+ "regressor = None\n",
+ "\n",
+ "# TODO: Report the score of the prediction using the testing set\n",
+ "score = None"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 2\n",
+ "\n",
+ "* Which feature did you attempt to predict? \n",
+ "* What was the reported prediction score? \n",
+ "* Is this feature necessary for identifying customers' spending habits?\n",
+ "\n",
+ "**Hint:** The coefficient of determination, `R^2`, is scored between 0 and 1, with 1 being a perfect fit. A negative `R^2` implies the model fails to fit the data. If you get a low score for a particular feature, that lends us to beleive that that feature point is hard to predict using the other features, thereby making it an important feature to consider when considering relevance."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Visualize Feature Distributions\n",
+ "To get a better understanding of the dataset, we can construct a scatter matrix of each of the six product features present in the data. If you found that the feature you attempted to predict above is relevant for identifying a specific customer, then the scatter matrix below may not show any correlation between that feature and the others. Conversely, if you believe that feature is not relevant for identifying a specific customer, the scatter matrix might show a correlation between that feature and another feature in the data. Run the code block below to produce a scatter matrix."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Produce a scatter matrix for each pair of features in the data\n",
+ "pd.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 3\n",
+ "* Using the scatter matrix as a reference, discuss the distribution of the dataset, specifically talk about the normality, outliers, large number of data points near 0 among others. If you need to sepearate out some of the plots individually to further accentuate your point, you may do so as well.\n",
+ "* Are there any pairs of features which exhibit some degree of correlation? \n",
+ "* Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict? \n",
+ "* How is the data for those features distributed?\n",
+ "\n",
+ "**Hint:** Is the data normally distributed? Where do most of the data points lie? You can use [corr()](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.corr.html) to get the feature correlations and then visualize them using a [heatmap](http://seaborn.pydata.org/generated/seaborn.heatmap.html)(the data that would be fed into the heatmap would be the correlation values, for eg: `data.corr()`) to gain further insight."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Data Preprocessing\n",
+ "In this section, you will preprocess the data to create a better representation of customers by performing a scaling on the data and detecting (and optionally removing) outliers. Preprocessing data is often times a critical step in assuring that results you obtain from your analysis are significant and meaningful."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Implementation: Feature Scaling\n",
+ "If data is not normally distributed, especially if the mean and median vary significantly (indicating a large skew), it is most [often appropriate](http://econbrowser.com/archives/2014/02/use-of-logarithms-in-economics) to apply a non-linear scaling — particularly for financial data. One way to achieve this scaling is by using a [Box-Cox test](http://scipy.github.io/devdocs/generated/scipy.stats.boxcox.html), which calculates the best power transformation of the data that reduces skewness. A simpler approach which can work in most cases would be applying the natural logarithm.\n",
+ "\n",
+ "In the code block below, you will need to implement the following:\n",
+ " - Assign a copy of the data to `log_data` after applying logarithmic scaling. Use the `np.log` function for this.\n",
+ " - Assign a copy of the sample data to `log_samples` after applying logarithmic scaling. Again, use `np.log`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# TODO: Scale the data using the natural logarithm\n",
+ "log_data = None\n",
+ "\n",
+ "# TODO: Scale the sample data using the natural logarithm\n",
+ "log_samples = None\n",
+ "\n",
+ "# Produce a scatter matrix for each pair of newly-transformed features\n",
+ "pd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Observation\n",
+ "After applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features you may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before).\n",
+ "\n",
+ "Run the code below to see how the sample data has changed after having the natural logarithm applied to it."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Display the log-transformed sample data\n",
+ "display(log_samples)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Implementation: Outlier Detection\n",
+ "Detecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many \"rules of thumb\" for what constitutes an outlier in a dataset. Here, we will use [Tukey's Method for identfying outliers](http://datapigtechnologies.com/blog/index.php/highlighting-outliers-in-your-data-with-the-tukey-method/): An *outlier step* is calculated as 1.5 times the interquartile range (IQR). A data point with a feature that is beyond an outlier step outside of the IQR for that feature is considered abnormal.\n",
+ "\n",
+ "In the code block below, you will need to implement the following:\n",
+ " - Assign the value of the 25th percentile for the given feature to `Q1`. Use `np.percentile` for this.\n",
+ " - Assign the value of the 75th percentile for the given feature to `Q3`. Again, use `np.percentile`.\n",
+ " - Assign the calculation of an outlier step for the given feature to `step`.\n",
+ " - Optionally remove data points from the dataset by adding indices to the `outliers` list.\n",
+ "\n",
+ "**NOTE:** If you choose to remove any outliers, ensure that the sample data does not contain any of these points! \n",
+ "Once you have performed this implementation, the dataset will be stored in the variable `good_data`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# For each feature find the data points with extreme high or low values\n",
+ "for feature in log_data.keys():\n",
+ " \n",
+ " # TODO: Calculate Q1 (25th percentile of the data) for the given feature\n",
+ " Q1 = None\n",
+ " \n",
+ " # TODO: Calculate Q3 (75th percentile of the data) for the given feature\n",
+ " Q3 = None\n",
+ " \n",
+ " # TODO: Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)\n",
+ " step = None\n",
+ " \n",
+ " # Display the outliers\n",
+ " print(\"Data points considered outliers for the feature '{}':\".format(feature))\n",
+ " display(log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))])\n",
+ " \n",
+ "# OPTIONAL: Select the indices for data points you wish to remove\n",
+ "outliers = []\n",
+ "\n",
+ "# Remove the outliers, if any were specified\n",
+ "good_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 4\n",
+ "* Are there any data points considered outliers for more than one feature based on the definition above? \n",
+ "* Should these data points be removed from the dataset? \n",
+ "* If any data points were added to the `outliers` list to be removed, explain why.\n",
+ "\n",
+ "** Hint: ** If you have datapoints that are outliers in multiple categories think about why that may be and if they warrant removal. Also note how k-means is affected by outliers and whether or not this plays a factor in your analysis of whether or not to remove them."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Feature Transformation\n",
+ "In this section you will use principal component analysis (PCA) to draw conclusions about the underlying structure of the wholesale customer data. Since using PCA on a dataset calculates the dimensions which best maximize variance, we will find which compound combinations of features best describe customers."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Implementation: PCA\n",
+ "\n",
+ "Now that the data has been scaled to a more normal distribution and has had any necessary outliers removed, we can now apply PCA to the `good_data` to discover which dimensions about the data best maximize the variance of features involved. In addition to finding these dimensions, PCA will also report the *explained variance ratio* of each dimension — how much variance within the data is explained by that dimension alone. Note that a component (dimension) from PCA can be considered a new \"feature\" of the space, however it is a composition of the original features present in the data.\n",
+ "\n",
+ "In the code block below, you will need to implement the following:\n",
+ " - Import `sklearn.decomposition.PCA` and assign the results of fitting PCA in six dimensions with `good_data` to `pca`.\n",
+ " - Apply a PCA transformation of `log_samples` using `pca.transform`, and assign the results to `pca_samples`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# TODO: Apply PCA by fitting the good data with the same number of dimensions as features\n",
+ "pca = None\n",
+ "\n",
+ "# TODO: Transform log_samples using the PCA fit above\n",
+ "pca_samples = None\n",
+ "\n",
+ "# Generate PCA results plot\n",
+ "pca_results = vs.pca_results(good_data, pca)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 5\n",
+ "\n",
+ "* How much variance in the data is explained* **in total** *by the first and second principal component? \n",
+ "* How much variance in the data is explained by the first four principal components? \n",
+ "* Using the visualization provided above, talk about each dimension and the cumulative variance explained by each, stressing upon which features are well represented by each dimension(both in terms of positive and negative variance explained). Discuss what the first four dimensions best represent in terms of customer spending.\n",
+ "\n",
+ "**Hint:** A positive increase in a specific dimension corresponds with an *increase* of the *positive-weighted* features and a *decrease* of the *negative-weighted* features. The rate of increase or decrease is based on the individual feature weights."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Observation\n",
+ "Run the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it in six dimensions. Observe the numerical value for the first four dimensions of the sample points. Consider if this is consistent with your initial interpretation of the sample points."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Display sample log-data after having a PCA transformation applied\n",
+ "display(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Implementation: Dimensionality Reduction\n",
+ "When using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data is being explained. Because of this, the *cumulative explained variance ratio* is extremely important for knowing how many dimensions are necessary for the problem. Additionally, if a signifiant amount of variance is explained by only two or three dimensions, the reduced data can be visualized afterwards.\n",
+ "\n",
+ "In the code block below, you will need to implement the following:\n",
+ " - Assign the results of fitting PCA in two dimensions with `good_data` to `pca`.\n",
+ " - Apply a PCA transformation of `good_data` using `pca.transform`, and assign the results to `reduced_data`.\n",
+ " - Apply a PCA transformation of `log_samples` using `pca.transform`, and assign the results to `pca_samples`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# TODO: Apply PCA by fitting the good data with only two dimensions\n",
+ "pca = None\n",
+ "\n",
+ "# TODO: Transform the good data using the PCA fit above\n",
+ "reduced_data = None\n",
+ "\n",
+ "# TODO: Transform log_samples using the PCA fit above\n",
+ "pca_samples = None\n",
+ "\n",
+ "# Create a DataFrame for the reduced data\n",
+ "reduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2'])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Observation\n",
+ "Run the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Display sample log-data after applying PCA transformation in two dimensions\n",
+ "display(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2']))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualizing a Biplot\n",
+ "A biplot is a scatterplot where each data point is represented by its scores along the principal components. The axes are the principal components (in this case `Dimension 1` and `Dimension 2`). In addition, the biplot shows the projection of the original features along the components. A biplot can help us interpret the reduced dimensions of the data, and discover relationships between the principal components and original features.\n",
+ "\n",
+ "Run the code cell below to produce a biplot of the reduced-dimension data."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Create a biplot\n",
+ "vs.biplot(good_data, reduced_data, pca)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Observation\n",
+ "\n",
+ "Once we have the original feature projections (in red), it is easier to interpret the relative position of each data point in the scatterplot. For instance, a point the lower right corner of the figure will likely correspond to a customer that spends a lot on `'Milk'`, `'Grocery'` and `'Detergents_Paper'`, but not so much on the other product categories. \n",
+ "\n",
+ "From the biplot, which of the original features are most strongly correlated with the first component? What about those that are associated with the second component? Do these observations agree with the pca_results plot you obtained earlier?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Clustering\n",
+ "\n",
+ "In this section, you will choose to use either a K-Means clustering algorithm or a Gaussian Mixture Model clustering algorithm to identify the various customer segments hidden in the data. You will then recover specific data points from the clusters to understand their significance by transforming them back into their original dimension and scale. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 6\n",
+ "\n",
+ "* What are the advantages to using a K-Means clustering algorithm? \n",
+ "* What are the advantages to using a Gaussian Mixture Model clustering algorithm? \n",
+ "* Given your observations about the wholesale customer data so far, which of the two algorithms will you use and why?\n",
+ "\n",
+ "** Hint: ** Think about the differences between hard clustering and soft clustering and which would be appropriate for our dataset."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Implementation: Creating Clusters\n",
+ "Depending on the problem, the number of clusters that you expect to be in the data may already be known. When the number of clusters is not known *a priori*, there is no guarantee that a given number of clusters best segments the data, since it is unclear what structure exists in the data — if any. However, we can quantify the \"goodness\" of a clustering by calculating each data point's *silhouette coefficient*. The [silhouette coefficient](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette_score.html) for a data point measures how similar it is to its assigned cluster from -1 (dissimilar) to 1 (similar). Calculating the *mean* silhouette coefficient provides for a simple scoring method of a given clustering.\n",
+ "\n",
+ "In the code block below, you will need to implement the following:\n",
+ " - Fit a clustering algorithm to the `reduced_data` and assign it to `clusterer`.\n",
+ " - Predict the cluster for each data point in `reduced_data` using `clusterer.predict` and assign them to `preds`.\n",
+ " - Find the cluster centers using the algorithm's respective attribute and assign them to `centers`.\n",
+ " - Predict the cluster for each sample data point in `pca_samples` and assign them `sample_preds`.\n",
+ " - Import `sklearn.metrics.silhouette_score` and calculate the silhouette score of `reduced_data` against `preds`.\n",
+ " - Assign the silhouette score to `score` and print the result."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# TODO: Apply your clustering algorithm of choice to the reduced data \n",
+ "clusterer = None\n",
+ "\n",
+ "# TODO: Predict the cluster for each data point\n",
+ "preds = None\n",
+ "\n",
+ "# TODO: Find the cluster centers\n",
+ "centers = None\n",
+ "\n",
+ "# TODO: Predict the cluster for each transformed sample data point\n",
+ "sample_preds = None\n",
+ "\n",
+ "# TODO: Calculate the mean silhouette coefficient for the number of clusters chosen\n",
+ "score = None"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 7\n",
+ "\n",
+ "* Report the silhouette score for several cluster numbers you tried. \n",
+ "* Of these, which number of clusters has the best silhouette score?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Cluster Visualization\n",
+ "Once you've chosen the optimal number of clusters for your clustering algorithm using the scoring metric above, you can now visualize the results by executing the code block below. Note that, for experimentation purposes, you are welcome to adjust the number of clusters for your clustering algorithm to see various visualizations. The final visualization provided should, however, correspond with the optimal number of clusters. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Display the results of the clustering from implementation\n",
+ "vs.cluster_results(reduced_data, preds, centers, pca_samples)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Implementation: Data Recovery\n",
+ "Each cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the *averages* of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's center point corresponds to *the average customer of that segment*. Since the data is currently reduced in dimension and scaled by a logarithm, we can recover the representative customer spending from these data points by applying the inverse transformations.\n",
+ "\n",
+ "In the code block below, you will need to implement the following:\n",
+ " - Apply the inverse transform to `centers` using `pca.inverse_transform` and assign the new centers to `log_centers`.\n",
+ " - Apply the inverse function of `np.log` to `log_centers` using `np.exp` and assign the true centers to `true_centers`.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# TODO: Inverse transform the centers\n",
+ "log_centers = None\n",
+ "\n",
+ "# TODO: Exponentiate the centers\n",
+ "true_centers = None\n",
+ "\n",
+ "# Display the true centers\n",
+ "segments = ['Segment {}'.format(i) for i in range(0,len(centers))]\n",
+ "true_centers = pd.DataFrame(np.round(true_centers), columns = data.keys())\n",
+ "true_centers.index = segments\n",
+ "display(true_centers)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 8\n",
+ "\n",
+ "* Consider the total purchase cost of each product category for the representative data points above, and reference the statistical description of the dataset at the beginning of this project(specifically looking at the mean values for the various feature points). What set of establishments could each of the customer segments represent?\n",
+ "\n",
+ "**Hint:** A customer who is assigned to `'Cluster X'` should best identify with the establishments represented by the feature set of `'Segment X'`. Think about what each segment represents in terms their values for the feature points chosen. Reference these values with the mean values to get some perspective into what kind of establishment they represent."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 9\n",
+ "\n",
+ "* For each sample point, which customer segment from* **Question 8** *best represents it? \n",
+ "* Are the predictions for each sample point consistent with this?*\n",
+ "\n",
+ "Run the code block below to find which cluster each sample point is predicted to be."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "# Display the predictions\n",
+ "for i, pred in enumerate(sample_preds):\n",
+ " print(\"Sample point\", i, \"predicted to be in Cluster\", pred)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Conclusion"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this final section, you will investigate ways that you can make use of the clustered data. First, you will consider how the different groups of customers, the ***customer segments***, may be affected differently by a specific delivery scheme. Next, you will consider how giving a label to each customer (which *segment* that customer belongs to) can provide for additional features about the customer data. Finally, you will compare the ***customer segments*** to a hidden variable present in the data, to see whether the clustering identified certain relationships."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": true
+ },
+ "source": [
+ "### Question 10\n",
+ "Companies will often run [A/B tests](https://en.wikipedia.org/wiki/A/B_testing) when making small changes to their products or services to determine whether making that change will affect its customers positively or negatively. The wholesale distributor is considering changing its delivery service from currently 5 days a week to 3 days a week. However, the distributor will only make this change in delivery service for customers that react positively. \n",
+ "\n",
+ "* How can the wholesale distributor use the customer segments to determine which customers, if any, would react positively to the change in delivery service?*\n",
+ "\n",
+ "**Hint:** Can we assume the change affects all customers equally? How can we determine which group of customers it affects the most?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 11\n",
+ "Additional structure is derived from originally unlabeled data when using clustering techniques. Since each customer has a ***customer segment*** it best identifies with (depending on the clustering algorithm applied), we can consider *'customer segment'* as an **engineered feature** for the data. Assume the wholesale distributor recently acquired ten new customers and each provided estimates for anticipated annual spending of each product category. Knowing these estimates, the wholesale distributor wants to classify each new customer to a ***customer segment*** to determine the most appropriate delivery service. \n",
+ "* How can the wholesale distributor label the new customers using only their estimated product spending and the **customer segment** data?\n",
+ "\n",
+ "**Hint:** A supervised learner could be used to train on the original customers. What would be the target variable?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Visualizing Underlying Distributions\n",
+ "\n",
+ "At the beginning of this project, it was discussed that the `'Channel'` and `'Region'` features would be excluded from the dataset so that the customer product categories were emphasized in the analysis. By reintroducing the `'Channel'` feature to the dataset, an interesting structure emerges when considering the same PCA dimensionality reduction applied earlier to the original dataset.\n",
+ "\n",
+ "Run the code block below to see how each data point is labeled either `'HoReCa'` (Hotel/Restaurant/Cafe) or `'Retail'` the reduced space. In addition, you will find the sample points are circled in the plot, which will identify their labeling."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true,
+ "scrolled": false
+ },
+ "outputs": [],
+ "source": [
+ "# Display the clustering results based on 'Channel' data\n",
+ "vs.channel_results(reduced_data, outliers, pca_samples)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Question 12\n",
+ "\n",
+ "* How well does the clustering algorithm and number of clusters you've chosen compare to this underlying distribution of Hotel/Restaurant/Cafe customers to Retailer customers? \n",
+ "* Are there customer segments that would be classified as purely 'Retailers' or 'Hotels/Restaurants/Cafes' by this distribution? \n",
+ "* Would you consider these classifications as consistent with your previous definition of the customer segments?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Answer:**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n",
+ "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "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.0"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 1
+}
diff --git a/customer_segments/customers.csv b/customer_segments/customers.csv
new file mode 100644
index 0000000..5d29d9e
--- /dev/null
+++ b/customer_segments/customers.csv
@@ -0,0 +1,441 @@
+Channel,Region,Fresh,Milk,Grocery,Frozen,Detergents_Paper,Delicatessen
+2,3,12669,9656,7561,214,2674,1338
+2,3,7057,9810,9568,1762,3293,1776
+2,3,6353,8808,7684,2405,3516,7844
+1,3,13265,1196,4221,6404,507,1788
+2,3,22615,5410,7198,3915,1777,5185
+2,3,9413,8259,5126,666,1795,1451
+2,3,12126,3199,6975,480,3140,545
+2,3,7579,4956,9426,1669,3321,2566
+1,3,5963,3648,6192,425,1716,750
+2,3,6006,11093,18881,1159,7425,2098
+2,3,3366,5403,12974,4400,5977,1744
+2,3,13146,1124,4523,1420,549,497
+2,3,31714,12319,11757,287,3881,2931
+2,3,21217,6208,14982,3095,6707,602
+2,3,24653,9465,12091,294,5058,2168
+1,3,10253,1114,3821,397,964,412
+2,3,1020,8816,12121,134,4508,1080
+1,3,5876,6157,2933,839,370,4478
+2,3,18601,6327,10099,2205,2767,3181
+1,3,7780,2495,9464,669,2518,501
+2,3,17546,4519,4602,1066,2259,2124
+1,3,5567,871,2010,3383,375,569
+1,3,31276,1917,4469,9408,2381,4334
+2,3,26373,36423,22019,5154,4337,16523
+2,3,22647,9776,13792,2915,4482,5778
+2,3,16165,4230,7595,201,4003,57
+1,3,9898,961,2861,3151,242,833
+1,3,14276,803,3045,485,100,518
+2,3,4113,20484,25957,1158,8604,5206
+1,3,43088,2100,2609,1200,1107,823
+1,3,18815,3610,11107,1148,2134,2963
+1,3,2612,4339,3133,2088,820,985
+1,3,21632,1318,2886,266,918,405
+1,3,29729,4786,7326,6130,361,1083
+1,3,1502,1979,2262,425,483,395
+2,3,688,5491,11091,833,4239,436
+1,3,29955,4362,5428,1729,862,4626
+2,3,15168,10556,12477,1920,6506,714
+2,3,4591,15729,16709,33,6956,433
+1,3,56159,555,902,10002,212,2916
+1,3,24025,4332,4757,9510,1145,5864
+1,3,19176,3065,5956,2033,2575,2802
+2,3,10850,7555,14961,188,6899,46
+2,3,630,11095,23998,787,9529,72
+2,3,9670,7027,10471,541,4618,65
+2,3,5181,22044,21531,1740,7353,4985
+2,3,3103,14069,21955,1668,6792,1452
+2,3,44466,54259,55571,7782,24171,6465
+2,3,11519,6152,10868,584,5121,1476
+2,3,4967,21412,28921,1798,13583,1163
+1,3,6269,1095,1980,3860,609,2162
+1,3,3347,4051,6996,239,1538,301
+2,3,40721,3916,5876,532,2587,1278
+2,3,491,10473,11532,744,5611,224
+1,3,27329,1449,1947,2436,204,1333
+1,3,5264,3683,5005,1057,2024,1130
+2,3,4098,29892,26866,2616,17740,1340
+2,3,5417,9933,10487,38,7572,1282
+1,3,13779,1970,1648,596,227,436
+1,3,6137,5360,8040,129,3084,1603
+2,3,8590,3045,7854,96,4095,225
+2,3,35942,38369,59598,3254,26701,2017
+2,3,7823,6245,6544,4154,4074,964
+2,3,9396,11601,15775,2896,7677,1295
+1,3,4760,1227,3250,3724,1247,1145
+2,3,85,20959,45828,36,24231,1423
+1,3,9,1534,7417,175,3468,27
+2,3,19913,6759,13462,1256,5141,834
+1,3,2446,7260,3993,5870,788,3095
+1,3,8352,2820,1293,779,656,144
+1,3,16705,2037,3202,10643,116,1365
+1,3,18291,1266,21042,5373,4173,14472
+1,3,4420,5139,2661,8872,1321,181
+2,3,19899,5332,8713,8132,764,648
+2,3,8190,6343,9794,1285,1901,1780
+1,3,20398,1137,3,4407,3,975
+1,3,717,3587,6532,7530,529,894
+2,3,12205,12697,28540,869,12034,1009
+1,3,10766,1175,2067,2096,301,167
+1,3,1640,3259,3655,868,1202,1653
+1,3,7005,829,3009,430,610,529
+2,3,219,9540,14403,283,7818,156
+2,3,10362,9232,11009,737,3537,2342
+1,3,20874,1563,1783,2320,550,772
+2,3,11867,3327,4814,1178,3837,120
+2,3,16117,46197,92780,1026,40827,2944
+2,3,22925,73498,32114,987,20070,903
+1,3,43265,5025,8117,6312,1579,14351
+1,3,7864,542,4042,9735,165,46
+1,3,24904,3836,5330,3443,454,3178
+1,3,11405,596,1638,3347,69,360
+1,3,12754,2762,2530,8693,627,1117
+2,3,9198,27472,32034,3232,18906,5130
+1,3,11314,3090,2062,35009,71,2698
+2,3,5626,12220,11323,206,5038,244
+1,3,3,2920,6252,440,223,709
+2,3,23,2616,8118,145,3874,217
+1,3,403,254,610,774,54,63
+1,3,503,112,778,895,56,132
+1,3,9658,2182,1909,5639,215,323
+2,3,11594,7779,12144,3252,8035,3029
+2,3,1420,10810,16267,1593,6766,1838
+2,3,2932,6459,7677,2561,4573,1386
+1,3,56082,3504,8906,18028,1480,2498
+1,3,14100,2132,3445,1336,1491,548
+1,3,15587,1014,3970,910,139,1378
+2,3,1454,6337,10704,133,6830,1831
+2,3,8797,10646,14886,2471,8969,1438
+2,3,1531,8397,6981,247,2505,1236
+2,3,1406,16729,28986,673,836,3
+1,3,11818,1648,1694,2276,169,1647
+2,3,12579,11114,17569,805,6457,1519
+1,3,19046,2770,2469,8853,483,2708
+1,3,14438,2295,1733,3220,585,1561
+1,3,18044,1080,2000,2555,118,1266
+1,3,11134,793,2988,2715,276,610
+1,3,11173,2521,3355,1517,310,222
+1,3,6990,3880,5380,1647,319,1160
+1,3,20049,1891,2362,5343,411,933
+1,3,8258,2344,2147,3896,266,635
+1,3,17160,1200,3412,2417,174,1136
+1,3,4020,3234,1498,2395,264,255
+1,3,12212,201,245,1991,25,860
+2,3,11170,10769,8814,2194,1976,143
+1,3,36050,1642,2961,4787,500,1621
+1,3,76237,3473,7102,16538,778,918
+1,3,19219,1840,1658,8195,349,483
+2,3,21465,7243,10685,880,2386,2749
+1,3,140,8847,3823,142,1062,3
+1,3,42312,926,1510,1718,410,1819
+1,3,7149,2428,699,6316,395,911
+1,3,2101,589,314,346,70,310
+1,3,14903,2032,2479,576,955,328
+1,3,9434,1042,1235,436,256,396
+1,3,7388,1882,2174,720,47,537
+1,3,6300,1289,2591,1170,199,326
+1,3,4625,8579,7030,4575,2447,1542
+1,3,3087,8080,8282,661,721,36
+1,3,13537,4257,5034,155,249,3271
+1,3,5387,4979,3343,825,637,929
+1,3,17623,4280,7305,2279,960,2616
+1,3,30379,13252,5189,321,51,1450
+1,3,37036,7152,8253,2995,20,3
+1,3,10405,1596,1096,8425,399,318
+1,3,18827,3677,1988,118,516,201
+2,3,22039,8384,34792,42,12591,4430
+1,3,7769,1936,2177,926,73,520
+1,3,9203,3373,2707,1286,1082,526
+1,3,5924,584,542,4052,283,434
+1,3,31812,1433,1651,800,113,1440
+1,3,16225,1825,1765,853,170,1067
+1,3,1289,3328,2022,531,255,1774
+1,3,18840,1371,3135,3001,352,184
+1,3,3463,9250,2368,779,302,1627
+1,3,622,55,137,75,7,8
+2,3,1989,10690,19460,233,11577,2153
+2,3,3830,5291,14855,317,6694,3182
+1,3,17773,1366,2474,3378,811,418
+2,3,2861,6570,9618,930,4004,1682
+2,3,355,7704,14682,398,8077,303
+2,3,1725,3651,12822,824,4424,2157
+1,3,12434,540,283,1092,3,2233
+1,3,15177,2024,3810,2665,232,610
+2,3,5531,15726,26870,2367,13726,446
+2,3,5224,7603,8584,2540,3674,238
+2,3,15615,12653,19858,4425,7108,2379
+2,3,4822,6721,9170,993,4973,3637
+1,3,2926,3195,3268,405,1680,693
+1,3,5809,735,803,1393,79,429
+1,3,5414,717,2155,2399,69,750
+2,3,260,8675,13430,1116,7015,323
+2,3,200,25862,19816,651,8773,6250
+1,3,955,5479,6536,333,2840,707
+2,3,514,7677,19805,937,9836,716
+1,3,286,1208,5241,2515,153,1442
+2,3,2343,7845,11874,52,4196,1697
+1,3,45640,6958,6536,7368,1532,230
+1,3,12759,7330,4533,1752,20,2631
+1,3,11002,7075,4945,1152,120,395
+1,3,3157,4888,2500,4477,273,2165
+1,3,12356,6036,8887,402,1382,2794
+1,3,112151,29627,18148,16745,4948,8550
+1,3,694,8533,10518,443,6907,156
+1,3,36847,43950,20170,36534,239,47943
+1,3,327,918,4710,74,334,11
+1,3,8170,6448,1139,2181,58,247
+1,3,3009,521,854,3470,949,727
+1,3,2438,8002,9819,6269,3459,3
+2,3,8040,7639,11687,2758,6839,404
+2,3,834,11577,11522,275,4027,1856
+1,3,16936,6250,1981,7332,118,64
+1,3,13624,295,1381,890,43,84
+1,3,5509,1461,2251,547,187,409
+2,3,180,3485,20292,959,5618,666
+1,3,7107,1012,2974,806,355,1142
+1,3,17023,5139,5230,7888,330,1755
+1,1,30624,7209,4897,18711,763,2876
+2,1,2427,7097,10391,1127,4314,1468
+1,1,11686,2154,6824,3527,592,697
+1,1,9670,2280,2112,520,402,347
+2,1,3067,13240,23127,3941,9959,731
+2,1,4484,14399,24708,3549,14235,1681
+1,1,25203,11487,9490,5065,284,6854
+1,1,583,685,2216,469,954,18
+1,1,1956,891,5226,1383,5,1328
+2,1,1107,11711,23596,955,9265,710
+1,1,6373,780,950,878,288,285
+2,1,2541,4737,6089,2946,5316,120
+1,1,1537,3748,5838,1859,3381,806
+2,1,5550,12729,16767,864,12420,797
+1,1,18567,1895,1393,1801,244,2100
+2,1,12119,28326,39694,4736,19410,2870
+1,1,7291,1012,2062,1291,240,1775
+1,1,3317,6602,6861,1329,3961,1215
+2,1,2362,6551,11364,913,5957,791
+1,1,2806,10765,15538,1374,5828,2388
+2,1,2532,16599,36486,179,13308,674
+1,1,18044,1475,2046,2532,130,1158
+2,1,18,7504,15205,1285,4797,6372
+1,1,4155,367,1390,2306,86,130
+1,1,14755,899,1382,1765,56,749
+1,1,5396,7503,10646,91,4167,239
+1,1,5041,1115,2856,7496,256,375
+2,1,2790,2527,5265,5612,788,1360
+1,1,7274,659,1499,784,70,659
+1,1,12680,3243,4157,660,761,786
+2,1,20782,5921,9212,1759,2568,1553
+1,1,4042,2204,1563,2286,263,689
+1,1,1869,577,572,950,4762,203
+1,1,8656,2746,2501,6845,694,980
+2,1,11072,5989,5615,8321,955,2137
+1,1,2344,10678,3828,1439,1566,490
+1,1,25962,1780,3838,638,284,834
+1,1,964,4984,3316,937,409,7
+1,1,15603,2703,3833,4260,325,2563
+1,1,1838,6380,2824,1218,1216,295
+1,1,8635,820,3047,2312,415,225
+1,1,18692,3838,593,4634,28,1215
+1,1,7363,475,585,1112,72,216
+1,1,47493,2567,3779,5243,828,2253
+1,1,22096,3575,7041,11422,343,2564
+1,1,24929,1801,2475,2216,412,1047
+1,1,18226,659,2914,3752,586,578
+1,1,11210,3576,5119,561,1682,2398
+1,1,6202,7775,10817,1183,3143,1970
+2,1,3062,6154,13916,230,8933,2784
+1,1,8885,2428,1777,1777,430,610
+1,1,13569,346,489,2077,44,659
+1,1,15671,5279,2406,559,562,572
+1,1,8040,3795,2070,6340,918,291
+1,1,3191,1993,1799,1730,234,710
+2,1,6134,23133,33586,6746,18594,5121
+1,1,6623,1860,4740,7683,205,1693
+1,1,29526,7961,16966,432,363,1391
+1,1,10379,17972,4748,4686,1547,3265
+1,1,31614,489,1495,3242,111,615
+1,1,11092,5008,5249,453,392,373
+1,1,8475,1931,1883,5004,3593,987
+1,1,56083,4563,2124,6422,730,3321
+1,1,53205,4959,7336,3012,967,818
+1,1,9193,4885,2157,327,780,548
+1,1,7858,1110,1094,6818,49,287
+1,1,23257,1372,1677,982,429,655
+1,1,2153,1115,6684,4324,2894,411
+2,1,1073,9679,15445,61,5980,1265
+1,1,5909,23527,13699,10155,830,3636
+2,1,572,9763,22182,2221,4882,2563
+1,1,20893,1222,2576,3975,737,3628
+2,1,11908,8053,19847,1069,6374,698
+1,1,15218,258,1138,2516,333,204
+1,1,4720,1032,975,5500,197,56
+1,1,2083,5007,1563,1120,147,1550
+1,1,514,8323,6869,529,93,1040
+1,3,36817,3045,1493,4802,210,1824
+1,3,894,1703,1841,744,759,1153
+1,3,680,1610,223,862,96,379
+1,3,27901,3749,6964,4479,603,2503
+1,3,9061,829,683,16919,621,139
+1,3,11693,2317,2543,5845,274,1409
+2,3,17360,6200,9694,1293,3620,1721
+1,3,3366,2884,2431,977,167,1104
+2,3,12238,7108,6235,1093,2328,2079
+1,3,49063,3965,4252,5970,1041,1404
+1,3,25767,3613,2013,10303,314,1384
+1,3,68951,4411,12609,8692,751,2406
+1,3,40254,640,3600,1042,436,18
+1,3,7149,2247,1242,1619,1226,128
+1,3,15354,2102,2828,8366,386,1027
+1,3,16260,594,1296,848,445,258
+1,3,42786,286,471,1388,32,22
+1,3,2708,2160,2642,502,965,1522
+1,3,6022,3354,3261,2507,212,686
+1,3,2838,3086,4329,3838,825,1060
+2,2,3996,11103,12469,902,5952,741
+1,2,21273,2013,6550,909,811,1854
+2,2,7588,1897,5234,417,2208,254
+1,2,19087,1304,3643,3045,710,898
+2,2,8090,3199,6986,1455,3712,531
+2,2,6758,4560,9965,934,4538,1037
+1,2,444,879,2060,264,290,259
+2,2,16448,6243,6360,824,2662,2005
+2,2,5283,13316,20399,1809,8752,172
+2,2,2886,5302,9785,364,6236,555
+2,2,2599,3688,13829,492,10069,59
+2,2,161,7460,24773,617,11783,2410
+2,2,243,12939,8852,799,3909,211
+2,2,6468,12867,21570,1840,7558,1543
+1,2,17327,2374,2842,1149,351,925
+1,2,6987,1020,3007,416,257,656
+2,2,918,20655,13567,1465,6846,806
+1,2,7034,1492,2405,12569,299,1117
+1,2,29635,2335,8280,3046,371,117
+2,2,2137,3737,19172,1274,17120,142
+1,2,9784,925,2405,4447,183,297
+1,2,10617,1795,7647,1483,857,1233
+2,2,1479,14982,11924,662,3891,3508
+1,2,7127,1375,2201,2679,83,1059
+1,2,1182,3088,6114,978,821,1637
+1,2,11800,2713,3558,2121,706,51
+2,2,9759,25071,17645,1128,12408,1625
+1,2,1774,3696,2280,514,275,834
+1,2,9155,1897,5167,2714,228,1113
+1,2,15881,713,3315,3703,1470,229
+1,2,13360,944,11593,915,1679,573
+1,2,25977,3587,2464,2369,140,1092
+1,2,32717,16784,13626,60869,1272,5609
+1,2,4414,1610,1431,3498,387,834
+1,2,542,899,1664,414,88,522
+1,2,16933,2209,3389,7849,210,1534
+1,2,5113,1486,4583,5127,492,739
+1,2,9790,1786,5109,3570,182,1043
+2,2,11223,14881,26839,1234,9606,1102
+1,2,22321,3216,1447,2208,178,2602
+2,2,8565,4980,67298,131,38102,1215
+2,2,16823,928,2743,11559,332,3486
+2,2,27082,6817,10790,1365,4111,2139
+1,2,13970,1511,1330,650,146,778
+1,2,9351,1347,2611,8170,442,868
+1,2,3,333,7021,15601,15,550
+1,2,2617,1188,5332,9584,573,1942
+2,3,381,4025,9670,388,7271,1371
+2,3,2320,5763,11238,767,5162,2158
+1,3,255,5758,5923,349,4595,1328
+2,3,1689,6964,26316,1456,15469,37
+1,3,3043,1172,1763,2234,217,379
+1,3,1198,2602,8335,402,3843,303
+2,3,2771,6939,15541,2693,6600,1115
+2,3,27380,7184,12311,2809,4621,1022
+1,3,3428,2380,2028,1341,1184,665
+2,3,5981,14641,20521,2005,12218,445
+1,3,3521,1099,1997,1796,173,995
+2,3,1210,10044,22294,1741,12638,3137
+1,3,608,1106,1533,830,90,195
+2,3,117,6264,21203,228,8682,1111
+1,3,14039,7393,2548,6386,1333,2341
+1,3,190,727,2012,245,184,127
+1,3,22686,134,218,3157,9,548
+2,3,37,1275,22272,137,6747,110
+1,3,759,18664,1660,6114,536,4100
+1,3,796,5878,2109,340,232,776
+1,3,19746,2872,2006,2601,468,503
+1,3,4734,607,864,1206,159,405
+1,3,2121,1601,2453,560,179,712
+1,3,4627,997,4438,191,1335,314
+1,3,2615,873,1524,1103,514,468
+2,3,4692,6128,8025,1619,4515,3105
+1,3,9561,2217,1664,1173,222,447
+1,3,3477,894,534,1457,252,342
+1,3,22335,1196,2406,2046,101,558
+1,3,6211,337,683,1089,41,296
+2,3,39679,3944,4955,1364,523,2235
+1,3,20105,1887,1939,8164,716,790
+1,3,3884,3801,1641,876,397,4829
+2,3,15076,6257,7398,1504,1916,3113
+1,3,6338,2256,1668,1492,311,686
+1,3,5841,1450,1162,597,476,70
+2,3,3136,8630,13586,5641,4666,1426
+1,3,38793,3154,2648,1034,96,1242
+1,3,3225,3294,1902,282,68,1114
+2,3,4048,5164,10391,130,813,179
+1,3,28257,944,2146,3881,600,270
+1,3,17770,4591,1617,9927,246,532
+1,3,34454,7435,8469,2540,1711,2893
+1,3,1821,1364,3450,4006,397,361
+1,3,10683,21858,15400,3635,282,5120
+1,3,11635,922,1614,2583,192,1068
+1,3,1206,3620,2857,1945,353,967
+1,3,20918,1916,1573,1960,231,961
+1,3,9785,848,1172,1677,200,406
+1,3,9385,1530,1422,3019,227,684
+1,3,3352,1181,1328,5502,311,1000
+1,3,2647,2761,2313,907,95,1827
+1,3,518,4180,3600,659,122,654
+1,3,23632,6730,3842,8620,385,819
+1,3,12377,865,3204,1398,149,452
+1,3,9602,1316,1263,2921,841,290
+2,3,4515,11991,9345,2644,3378,2213
+1,3,11535,1666,1428,6838,64,743
+1,3,11442,1032,582,5390,74,247
+1,3,9612,577,935,1601,469,375
+1,3,4446,906,1238,3576,153,1014
+1,3,27167,2801,2128,13223,92,1902
+1,3,26539,4753,5091,220,10,340
+1,3,25606,11006,4604,127,632,288
+1,3,18073,4613,3444,4324,914,715
+1,3,6884,1046,1167,2069,593,378
+1,3,25066,5010,5026,9806,1092,960
+2,3,7362,12844,18683,2854,7883,553
+2,3,8257,3880,6407,1646,2730,344
+1,3,8708,3634,6100,2349,2123,5137
+1,3,6633,2096,4563,1389,1860,1892
+1,3,2126,3289,3281,1535,235,4365
+1,3,97,3605,12400,98,2970,62
+1,3,4983,4859,6633,17866,912,2435
+1,3,5969,1990,3417,5679,1135,290
+2,3,7842,6046,8552,1691,3540,1874
+2,3,4389,10940,10908,848,6728,993
+1,3,5065,5499,11055,364,3485,1063
+2,3,660,8494,18622,133,6740,776
+1,3,8861,3783,2223,633,1580,1521
+1,3,4456,5266,13227,25,6818,1393
+2,3,17063,4847,9053,1031,3415,1784
+1,3,26400,1377,4172,830,948,1218
+2,3,17565,3686,4657,1059,1803,668
+2,3,16980,2884,12232,874,3213,249
+1,3,11243,2408,2593,15348,108,1886
+1,3,13134,9347,14316,3141,5079,1894
+1,3,31012,16687,5429,15082,439,1163
+1,3,3047,5970,4910,2198,850,317
+1,3,8607,1750,3580,47,84,2501
+1,3,3097,4230,16483,575,241,2080
+1,3,8533,5506,5160,13486,1377,1498
+1,3,21117,1162,4754,269,1328,395
+1,3,1982,3218,1493,1541,356,1449
+1,3,16731,3922,7994,688,2371,838
+1,3,29703,12051,16027,13135,182,2204
+1,3,39228,1431,764,4510,93,2346
+2,3,14531,15488,30243,437,14841,1867
+1,3,10290,1981,2232,1038,168,2125
+1,3,2787,1698,2510,65,477,52
diff --git a/customer_segments/project_description.md b/customer_segments/project_description.md
new file mode 100644
index 0000000..704adad
--- /dev/null
+++ b/customer_segments/project_description.md
@@ -0,0 +1,65 @@
+# Machine Learning Engineer Nanodegree
+# Unsupervised Learning
+## Project: Creating Customer Segments
+
+## Project Overview
+In this project you will apply unsupervised learning techniques on product spending data collected for customers of a wholesale distributor in Lisbon, Portugal to identify customer segments hidden in the data. You will first explore the data by selecting a small subset to sample and determine if any product categories highly correlate with one another. Afterwards, you will preprocess the data by scaling each product category and then identifying (and removing) unwanted outliers. With the good, clean customer spending data, you will apply PCA transformations to the data and implement clustering algorithms to segment the transformed customer data. Finally, you will compare the segmentation found with an additional labeling and consider ways this information could assist the wholesale distributor with future service changes.
+
+## Project Highlights
+This project is designed to give you a hands-on experience with unsupervised learning and work towards developing conclusions for a potential client on a real-world dataset. Many companies today collect vast amounts of data on customers and clientele, and have a strong desire to understand the meaningful relationships hidden in their customer base. Being equipped with this information can assist a company engineer future products and services that best satisfy the demands or needs of their customers.
+
+Things you will learn by completing this project:
+
+- How to apply preprocessing techniques such as feature scaling and outlier detection.
+- How to interpret data points that have been scaled, transformed, or reduced from PCA.
+- How to analyze PCA dimensions and construct a new feature space.
+- How to optimally cluster a set of data to find hidden patterns in a dataset.
+- How to assess information given by cluster data and use it in a meaningful way.
+
+## Description
+A wholesale distributor recently tested a change to their delivery method for some customers, by moving from a morning delivery service five days a week to a cheaper evening delivery service three days a week. Initial testing did not discover any significant unsatisfactory results, so they implemented the cheaper option for all customers. Almost immediately, the distributor began getting complaints about the delivery service change and customers were canceling deliveries, losing the distributor more money than what was being saved. You've been hired by the wholesale distributor to find what types of customers they have to help them make better, more informed business decisions in the future. Your task is to use unsupervised learning techniques to see if any similarities exist between customers, and how to best segment customers into distinct categories.
+
+## Software and Libraries
+This project uses the following software and Python libraries:
+
+- [Python 2.7](https://www.python.org/download/releases/2.7/)
+- [NumPy](http://www.numpy.org/)
+- [pandas](http://pandas.pydata.org/)
+- [scikit-learn](http://scikit-learn.org/stable/)
+- [matplotlib](http://matplotlib.org/)
+
+You will also need to have software installed to run and execute a [Jupyter Notebook](http://ipython.org/notebook.html).
+
+If you do not have Python installed yet, it is highly recommended that you install the [Anaconda](http://continuum.io/downloads) distribution of Python, which already has the above packages and more included. Make sure that you select the Python 2.7 installer and not the Python 3.x installer.
+
+## Starting the Project
+
+For this assignment, you can find the `customer_segments` folder containing the necessary project files on the [Machine Learning projects GitHub](https://github.com/udacity/machine-learning), under the `projects` folder. You may download all of the files for projects we'll use in this Nanodegree program directly from this repo. Please make sure that you use the most recent version of project files when completing a project!
+
+This project contains three files:
+
+- `customer_segments.ipynb`: This is the main file where you will be performing your work on the project.
+- `customers.csv`: The project dataset. You'll load this data in the notebook.
+- `visuals.py`: This Python script provides supplementary visualizations for the project. Do not modify.
+
+In the Terminal or Command Prompt, navigate to the folder containing the project files, and then use the command `jupyter notebook customer_segments.ipynb` to open up a browser window or tab to work with your notebook. Alternatively, you can use the command `jupyter notebook` or `ipython notebook` and navigate to the notebook file in the browser window that opens. Follow the instructions in the notebook and answer each question presented to successfully complete the project. A **README** file has also been provided with the project files which may contain additional necessary information or instruction for the project.
+
+## Submitting the Project
+
+### Evaluation
+Your project will be reviewed by a Udacity reviewer against the **Creating Customer Segments project rubric**. Be sure to review this rubric thoroughly and self-evaluate your project before submission. All criteria found in the rubric must be *meeting specifications* for you to pass.
+
+### Submission Files
+When you are ready to submit your project, collect the following files and compress them into a single archive for upload. Alternatively, you may supply the following files on your GitHub Repo in a folder named `customer_segments` for ease of access:
+ - The `customer_segments.ipynb` notebook file with all questions answered and all code cells executed and displaying output.
+ - An **HTML** export of the project notebook with the name **report.html**. This file *must* be present for your project to be evaluated.
+
+Once you have collected these files and reviewed the project rubric, proceed to the project submission page.
+
+### I'm Ready!
+When you're ready to submit your project, click on the **Submit Project** button at the bottom of the page.
+
+If you are having any problems submitting your project or wish to check on the status of your submission, please email us at **machine-support@udacity.com** or visit us in the discussion forums.
+
+### What's Next?
+You will get an email as soon as your reviewer has feedback for you. In the meantime, review your next project and feel free to get started on it or the courses supporting it!
diff --git a/customer_segments/visuals.py b/customer_segments/visuals.py
new file mode 100644
index 0000000..466e8c4
--- /dev/null
+++ b/customer_segments/visuals.py
@@ -0,0 +1,163 @@
+###########################################
+# Suppress matplotlib user warnings
+# Necessary for newer version of matplotlib
+import warnings
+warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
+#
+# Display inline matplotlib plots with IPython
+from IPython import get_ipython
+get_ipython().run_line_magic('matplotlib', 'inline')
+###########################################
+
+import matplotlib.pyplot as plt
+import matplotlib.cm as cm
+import pandas as pd
+import numpy as np
+
+def pca_results(good_data, pca):
+ '''
+ Create a DataFrame of the PCA results
+ Includes dimension feature weights and explained variance
+ Visualizes the PCA results
+ '''
+
+ # Dimension indexing
+ dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
+
+ # PCA components
+ components = pd.DataFrame(np.round(pca.components_, 4), columns = list(good_data.keys()))
+ components.index = dimensions
+
+ # PCA explained variance
+ ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)
+ variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
+ variance_ratios.index = dimensions
+
+ # Create a bar plot visualization
+ fig, ax = plt.subplots(figsize = (14,8))
+
+ # Plot the feature weights as a function of the components
+ components.plot(ax = ax, kind = 'bar');
+ ax.set_ylabel("Feature Weights")
+ ax.set_xticklabels(dimensions, rotation=0)
+
+
+ # Display the explained variance ratios
+ for i, ev in enumerate(pca.explained_variance_ratio_):
+ ax.text(i-0.40, ax.get_ylim()[1] + 0.05, "Explained Variance\n %.4f"%(ev))
+
+ # Return a concatenated DataFrame
+ return pd.concat([variance_ratios, components], axis = 1)
+
+def cluster_results(reduced_data, preds, centers, pca_samples):
+ '''
+ Visualizes the PCA-reduced cluster data in two dimensions
+ Adds cues for cluster centers and student-selected sample data
+ '''
+
+ predictions = pd.DataFrame(preds, columns = ['Cluster'])
+ plot_data = pd.concat([predictions, reduced_data], axis = 1)
+
+ # Generate the cluster plot
+ fig, ax = plt.subplots(figsize = (14,8))
+
+ # Color map
+ cmap = cm.get_cmap('gist_rainbow')
+
+ # Color the points based on assigned cluster
+ for i, cluster in plot_data.groupby('Cluster'):
+ cluster.plot(ax = ax, kind = 'scatter', x = 'Dimension 1', y = 'Dimension 2', \
+ color = cmap((i)*1.0/(len(centers)-1)), label = 'Cluster %i'%(i), s=30);
+
+ # Plot centers with indicators
+ for i, c in enumerate(centers):
+ ax.scatter(x = c[0], y = c[1], color = 'white', edgecolors = 'black', \
+ alpha = 1, linewidth = 2, marker = 'o', s=200);
+ ax.scatter(x = c[0], y = c[1], marker='$%d$'%(i), alpha = 1, s=100);
+
+ # Plot transformed sample points
+ ax.scatter(x = pca_samples[:,0], y = pca_samples[:,1], \
+ s = 150, linewidth = 4, color = 'black', marker = 'x');
+
+ # Set plot title
+ ax.set_title("Cluster Learning on PCA-Reduced Data - Centroids Marked by Number\nTransformed Sample Data Marked by Black Cross");
+
+
+def biplot(good_data, reduced_data, pca):
+ '''
+ Produce a biplot that shows a scatterplot of the reduced
+ data and the projections of the original features.
+
+ good_data: original data, before transformation.
+ Needs to be a pandas dataframe with valid column names
+ reduced_data: the reduced data (the first two dimensions are plotted)
+ pca: pca object that contains the components_ attribute
+
+ return: a matplotlib AxesSubplot object (for any additional customization)
+
+ This procedure is inspired by the script:
+ https://github.com/teddyroland/python-biplot
+ '''
+
+ fig, ax = plt.subplots(figsize = (14,8))
+ # scatterplot of the reduced data
+ ax.scatter(x=reduced_data.loc[:, 'Dimension 1'], y=reduced_data.loc[:, 'Dimension 2'],
+ facecolors='b', edgecolors='b', s=70, alpha=0.5)
+
+ feature_vectors = pca.components_.T
+
+ # we use scaling factors to make the arrows easier to see
+ arrow_size, text_pos = 7.0, 8.0,
+
+ # projections of the original features
+ for i, v in enumerate(feature_vectors):
+ ax.arrow(0, 0, arrow_size*v[0], arrow_size*v[1],
+ head_width=0.2, head_length=0.2, linewidth=2, color='red')
+ ax.text(v[0]*text_pos, v[1]*text_pos, good_data.columns[i], color='black',
+ ha='center', va='center', fontsize=18)
+
+ ax.set_xlabel("Dimension 1", fontsize=14)
+ ax.set_ylabel("Dimension 2", fontsize=14)
+ ax.set_title("PC plane with original feature projections.", fontsize=16);
+ return ax
+
+
+def channel_results(reduced_data, outliers, pca_samples):
+ '''
+ Visualizes the PCA-reduced cluster data in two dimensions using the full dataset
+ Data is labeled by "Channel" and cues added for student-selected sample data
+ '''
+
+ # Check that the dataset is loadable
+ try:
+ full_data = pd.read_csv("customers.csv")
+ except:
+ print("Dataset could not be loaded. Is the file missing?")
+ return False
+
+ # Create the Channel DataFrame
+ channel = pd.DataFrame(full_data['Channel'], columns = ['Channel'])
+ channel = channel.drop(channel.index[outliers]).reset_index(drop = True)
+ labeled = pd.concat([reduced_data, channel], axis = 1)
+
+ # Generate the cluster plot
+ fig, ax = plt.subplots(figsize = (14,8))
+
+ # Color map
+ cmap = cm.get_cmap('gist_rainbow')
+
+ # Color the points based on assigned Channel
+ labels = ['Hotel/Restaurant/Cafe', 'Retailer']
+ grouped = labeled.groupby('Channel')
+ for i, channel in grouped:
+ channel.plot(ax = ax, kind = 'scatter', x = 'Dimension 1', y = 'Dimension 2', \
+ color = cmap((i-1)*1.0/2), label = labels[i-1], s=30);
+
+ # Plot transformed sample points
+ for i, sample in enumerate(pca_samples):
+ ax.scatter(x = sample[0], y = sample[1], \
+ s = 200, linewidth = 3, color = 'black', marker = 'o', facecolors = 'none');
+ ax.scatter(x = sample[0]+0.25, y = sample[1]+0.3, marker='$%d$'%(i), alpha = 1, s=125);
+
+ # Set plot title
+ ax.set_title("PCA-Reduced Data Labeled by 'Channel'\nTransformed Sample Data Circled");
\ No newline at end of file