In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.
This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.
It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.
At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# magic word for producing visualizations in notebook
%matplotlib inline
There are four files associated with this project (not including this one):
Udacity_AZDIAS_Subset.csv
: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).Udacity_CUSTOMERS_Subset.csv
: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).Data_Dictionary.md
: Detailed information file about the features in the provided datasets.AZDIAS_Feature_Summary.csv
: Summary of feature attributes for demographics data; 85 features (rows) x 4 columnsEach row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.
To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv
data files in this project: they're semicolon (;
) delimited, so you'll need an additional argument in your read_csv()
call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.
Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.
# Load in the general demographics data.
azdias = pd.read_csv("./Udacity_AZDIAS_Subset.csv", sep=';')
# Load in the feature summary file.
feat_info = pd.read_csv("AZDIAS_Feature_Summary.csv", sep=';')
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
print("The shape of azdias is {}".format(azdias.shape))
print("The shape of feat_info is {}".format(feat_info.shape))
azdias.head(n=5)
feat_info.head(n=5)
Check how what types and levels of data we have
feat_info.type.unique().tolist()
print(feat_info.information_level.unique().tolist())
Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut
esc --> a
(press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, andesc --> b
adds a new cell after the active cell. If you need to convert an active cell to a markdown cell, useesc --> m
and to convert to a code cell, useesc --> y
.
The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!
The fourth column of the feature attributes summary (loaded in above as feat_info
) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]
), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.
As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.
# Identify missing or unknown data values and convert them to NaNs.
# Change feat_info index
feat_info.set_index("attribute", inplace=True)
To see what are encode as NA
print(feat_info.missing_or_unknown.unique().tolist())
Change strings into list
na_dict ={'[-1,0]':[-1, 0], '[-1,0,9]':[-1,0,9], "[0]":[0], "[-1]":[-1], '[]':[], '[-1,9]':[-1,9],
'[-1,X]':[-1, "X"], '[XX]':["XX"], '[-1,XX]':[-1, 'XX']}
Use an anonymous function to change values into NA
cols = feat_info.index.tolist()
for col in cols:
na = na_dict[feat_info.loc[col].missing_or_unknown]
azdias[col] = azdias[col].map(lambda x: np.nan if x in na else x)
How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist()
function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)
For the remaining features, are there any patterns in which columns have, or share, missing data?
# Perform an assessment of how much missing data there is in each column of the
# dataset.
# Calculate the number of missing value of each column
missing = azdias.isnull().sum()
# Change the number into percents
missing_per = missing / len(azdias) * 100
missing_per.describe()
# Investigate patterns in the amount of missing data in each column.
plt.hist(missing_per, bins=50, facecolor='b', alpha=0.75)
plt.xlabel('Percentage of missing value (%)')
plt.ylabel('Counts')
plt.title('Histogram of missing value counts')
plt.grid(True)
plt.show()
From the plot we can see that most of columns have missing value less than 20%
outlier = sum(missing_per >= 20)
print("There are {} columns which have more 20% missing values".format(outlier))
top_6 = missing_per.nlargest(n = 6)
print(top_6)
top_6.plot.bar(figsize=(8,5))
plt.xlabel('Column name with missing values')
plt.ylabel('Percentage of missing values')
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
azdias_new = azdias.drop(top_6.index, axis = 1)
The average missing percent is 11.05%. Most of columns have missing value less than 20%, but there are six columns having more than 20% missing values. Those columns are 'TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX', 'GEBURTSJAHR', ALTER_HH'. So I removed them from the dataset.
Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.
In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.
countplot()
function to create a bar chart of code frequencies and matplotlib's subplot()
function to put bar charts for the two subplots side by side.Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.
# How much data is missing in each row of the dataset?
missing_row = azdias_new.isnull().sum(axis = 1)
plt.hist(missing_row, bins=50, facecolor='b', alpha=0.75)
plt.xlabel('Number of missing value')
plt.ylabel('Counts')
plt.title('Histogram of missing value counts')
plt.grid(True)
plt.show()
# Write code to divide the data into two subsets based on the number of missing
# values in each row.
# If there are more than 10 NA, we put it into high subset. Otherwise, we put it into low subset.
few = azdias_new[missing_row <= 10].reset_index(drop=True)
high = azdias_new[missing_row > 10].reset_index(drop=True)
print("The shape of few dataset is {}".format(few.shape))
print("The shape of high dataset is {}".format(high.shape))
# choose five columns
small_6 = missing_per.nsmallest(n = 5).index
small_6
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
def compare(compare_col):
num = len(compare_col)
fig, ax = plt.subplots(num,2, figsize=(20, 20))
ax[0,0].set_title('Few')
ax[0,1].set_title('High')
for i, col in enumerate(compare_col):
sns.countplot(few[col], ax=ax[i,0])
sns.countplot(high[col], ax=ax[i,1])
compare(small_6)
From the histogram plot we can see that fewer rows have more than 10 missing values compared to other rows. Thus, we set 10 as our threshold and divide the dataset into two subsets.
To see if the distribution of data values on columns that are missing very little data are similar or different between the two groups, we choose some columns to make barplots to compare them. Then we find out that the distribution are different. This may cause problem and bias in the following analysis if we just delete the high subset, so we'll revisit these data later on. Now we continue our analysis for using just the few subset.
Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info
) for a summary of types of measurement.
In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.
Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!
# How many features are there of each data type?
types = feat_info.type.unique().tolist()
# Discard columns with a large number of missing values
new_feat = feat_info.drop(top_6.index, axis = 0)
for i in types:
num = sum(new_feat.type == i)
print("{} : {}".format(i, num))
For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:
# Assess categorical variables: which are binary, which are multi-level, and
# which one needs to be re-encoded?
cate = new_feat.index[new_feat.type == "categorical"].tolist()
few[cate].head(n = 6)
multi_list = []
binary_list = []
for col in cate:
if len(few[col].unique()) > 2:
multi_list += [col]
else:
binary_list += [col]
print(binary_list)
print()
print(multi_list)
Refer to Data_Dictionary.md and check the dataframe, we know that
# Re-encode categorical variable(s) to be kept in the analysis.
# Change non-numeric values
map_dict = {"O":0, "W":1}
few['OST_WEST_KZ'] = few['OST_WEST_KZ'].map(map_dict)
# As customers dataset have different multilevels, we drop this feature.
few = few.drop("GEBAEUDETYP", axis = 1)
multi_list.remove("GEBAEUDETYP")
# OneHotEncoder
few = pd.get_dummies(few, prefix = multi_list, columns = multi_list)
few.head(n=5)
There are 18 categorical features (after dropping some columns). We keep all the categorical features, but we do some transformation
There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:
Be sure to check Data_Dictionary.md
for the details needed to finish these tasks.
Dominating movement of person's youth (avantgarde vs. mainstream; east vs. west)
We recode this below: 40s: 1, 50s: 2, 60s: 3, 70s: 4, 80s: 5, 90s: 6 Mainstream: 0, Avantgarde: 1
decade_dict = {1:1, 2:1, 3:2, 4:2, 5:3, 6:3}
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
mix = new_feat.index[new_feat.type == "mixed"].tolist()
decade_dict = {1:1, 2:1, 3:2, 4:2, 5:3, 6:3, 7:3, 8:4, 9:4, 10:5, 11:5, 12:5, 13:5, 14:6, 15:6}
move_dict = {1:0, 2:1, 3:0, 4:1, 5:0, 6:1, 7:1, 8:0, 9:1, 10:0, 11:1, 12:0, 13:1, 14:0, 15:1}
few["decade"] = few["PRAEGENDE_JUGENDJAHRE"].map(decade_dict)
few["movement"] = few["PRAEGENDE_JUGENDJAHRE"].map(move_dict)
few.drop("PRAEGENDE_JUGENDJAHRE", axis = 1)
few[["decade", "movement"]].head(n = 6)
German CAMEO: Wealth / Life Stage Typology, mapped to international code
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
# Define a function to engineer two new variables
def wealth(x):
if x==x:
x = int(x)
if x // 10 ==1:
return 1
if x // 10 ==2:
return 2
if x // 10 ==3:
return 3
if x // 10 ==4:
return 4
if x // 10 ==5:
return 5
def life_stage(x):
if x==x:
x = int(x)
if x % 10 ==1:
return 1
if x % 10 ==2:
return 2
if x % 10 ==3:
return 3
if x % 10 ==4:
return 4
if x % 10 ==5:
return 5
few["wealth"] = few["CAMEO_INTL_2015"].apply(wealth)
few["life_stage"] = few["CAMEO_INTL_2015"].apply(life_stage)
few.drop("CAMEO_INTL_2015", axis = 1)
few[["wealth", "life_stage"]].head(n = 6)
few = few.drop(mix, axis =1)
We engineer two mixed-type features, CAMEO_INTL_2015 and PRAEGENDE_JUGENDJAHRE. Then we drop other mixed-type features.
In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:
Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.
# If there are other re-engineering tasks you need to perform, make sure you
# take care of them here. (Dealing with missing data will come in step 2.1.)
few.shape
# Do whatever you need to in order to ensure that the dataframe only contains
# the columns that should be passed to the algorithm functions.
few.info()
few.describe()
few.head(n = 5)
few.isnull().sum()
Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.
def clean_data(df):
"""
Perform feature trimming, re-encoding, and engineering for demographics
data
INPUT: Demographics DataFrame
OUTPUT: Trimmed and cleaned demographics DataFrame
"""
# Put in code here to execute all main cleaning steps:
# convert missing value codes into NaNs, ...
for col in cols:
na = na_dict[feat_info.loc[col].missing_or_unknown]
df[col] = df[col].map(lambda x: np.nan if x in na else x)
# remove selected columns and rows, ...
df = df.drop(top_6.index, axis = 1)
missing_row = df.isnull().sum(axis = 1)
df = df[missing_row <= 10].reset_index(drop=True)
# select, re-encode, and engineer column values.
df['OST_WEST_KZ'] = df['OST_WEST_KZ'].map(map_dict)
df = df.drop("GEBAEUDETYP", axis = 1)
df = pd.get_dummies(df, prefix = multi_list, columns = multi_list)
df["decade"] = df["PRAEGENDE_JUGENDJAHRE"].map(decade_dict)
df["movement"] = df["PRAEGENDE_JUGENDJAHRE"].map(move_dict)
df["wealth"] = df["CAMEO_INTL_2015"].apply(wealth)
df["life_stage"] = df["CAMEO_INTL_2015"].apply(life_stage)
df = df.drop(mix, axis =1)
# Return the cleaned dataframe.
return df
clean_data(azdias).shape
Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:
.fit_transform()
method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.from sklearn.preprocessing import Imputer, StandardScaler
# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
fill_na = Imputer(strategy = "most_frequent", missing_values = "NaN", axis = 0)
few_impute = fill_na.fit_transform(few)
# Apply feature scaling to the general population demographics data.
scaler = StandardScaler()
few_scale = scaler.fit_transform(few_impute)
few_scale = pd.DataFrame(few_scale, columns=list(few))
few_scale.head(n=5)
We fill all NaN with mode. Then we do feature scaling (scaling each feature to mean 0 and standard deviation 1)
On your scaled data, you are now ready to apply dimensionality reduction techniques.
plot()
function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.from sklearn.decomposition import PCA
# Apply PCA to the data.
pca = PCA()
pca.fit(few_scale)
# Investigate the variance accounted for by each principal component.
plt.bar(range(len(pca.explained_variance_ratio_)), pca.explained_variance_ratio_)
plt.title("Variance explained by each component")
plt.xlabel("Principal component")
plt.ylabel("Ratio of variance explained")
plt.show()
plt.plot(range(len(pca.explained_variance_ratio_)),np.cumsum(pca.explained_variance_ratio_), '-')
plt.title("Cumulative Variance Explained")
plt.xlabel("Number of Components")
plt.ylabel("Ratio of variance explained")
plt.show()
# Re-apply PCA to the data while selecting for number of components to retain.
pca_80 = PCA(n_components=80)
azdias_pca = pca_80.fit_transform(few_scale)
sum(pca_80.explained_variance_ratio_)
I choose 80 components, capturing more than 79% of the variance.
len(pca_80.components_)
Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.
As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.
# Map weights for the first principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
def pca_results(full_dataset, pca, num):
'''
Create a DataFrame of the PCA results
Includes dimension feature weights and explained variance
Visualizes the PCA results
'''
# Dimension indexing
dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
# PCA components
components = pd.DataFrame(np.round(pca.components_, 4), columns = full_dataset.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(2,1,figsize = (20,14))
plt.subplots_adjust(hspace=0.45)
fig.suptitle("{} Componet Explained Variance {:.4f}".format(num,pca.explained_variance_ratio_[num-1]),fontsize=20)
# Plot the feature weights as a function of the components
weight = components.iloc[num - 1]
pos = weight[weight > 0]
pos.sort_values(ascending=False).plot(kind = "bar", ax = ax[0])
neg = weight[weight < 0]
neg.sort_values().plot(kind = "bar", ax = ax[1])
ax[0].set_ylabel("Feature Weights")
ax[1].set_ylabel("Feature Weights")
print(pos.sort_values(ascending=False)[0:5])
print(neg.sort_values()[0:5])
pca_results(few_scale, pca_80, 1)
pca_results(few_scale, pca_80, 2)
pca_results(few_scale, pca_80, 3)
We can see that several features have high weight in first component. In the first component, wealth has positive weight(high wealth score means poor under this condition) and low financial interest (FINANZ_MINIMALIST) have negative weight. It also makes sense in the real world.
You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.
.score()
method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.# Over a number of different cluster counts...
# run k-means clustering on the data and...
# compute the average within-cluster distances.
from sklearn.cluster import KMeans
def K_score(data, n):
kmeans = KMeans(n_clusters = n)
model = kmeans.fit(data)
score = np.abs(model.score(data))
return score
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
scores = []
clusters = list(range(1,12))
for k in clusters:
print(k)
scores.append(K_score(azdias_pca, k))
plt.plot(clusters, scores, linestyle='-', marker='o')
plt.xlabel('K')
plt.ylabel('Score')
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
kmeans = KMeans(n_clusters = 5)
k_model = kmeans.fit(azdias_pca)
labels = k_model.predict(azdias_pca)
I decided to choose 5 because after 5 clusters, the average distance decrease is obiviously smaller than before.
Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.
;
) delimited.clean_data()
function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.).fit()
or .fit_transform()
method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.# Load in the customer demographics data.
customers = pd.read_csv("./Udacity_CUSTOMERS_Subset.csv", sep=';')
customers = clean_data(customers)
customers.shape
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
customers_new = fill_na.transform(customers)
customers_new = scaler.fit_transform(customers_new)
customers_new = pd.DataFrame(customers_new, columns=list(customers))
customers_new.head(n=5)
customers_pca = pca_80.transform(customers_new)
customers_labels = k_model.predict(customers_pca)
At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.
Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.
Take a look at the following points in this step:
countplot()
or barplot()
function could be handy..inverse_transform()
method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.# Compare the proportion of data in each cluster for the customer data to the
# proportion of data in each cluster for the general population.
general_prop = []
customers_prop = []
cluster = [i for i in range(5)]
for i in range(5):
general_prop.append((labels == i).sum()/len(labels))
customers_prop.append((customers_labels == i).sum()/len(customers_labels))
df_cluster = pd.DataFrame({'cluster' : cluster, 'prop_general' : general_prop, 'prop_customers':customers_prop})
df_cluster.plot(x='cluster', y = ['prop_general', 'prop_customers'], kind='bar', figsize=(9,6))
plt.ylabel('proportion of persons in each cluster')
plt.show()
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?
centroid_2 = scaler.inverse_transform(pca_80.inverse_transform(k_model.cluster_centers_[2]))
over = pd.Series(data = centroid_2, index=list(customers))
over.head(n=5)
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
centroid_1 = scaler.inverse_transform(pca_80.inverse_transform(k_model.cluster_centers_[1]))
under = pd.Series(data = centroid_1, index=list(customers))
under.head(n=5)
pd.concat([over, under], axis=1)
(Double-click this cell and replace this text with your own text, reporting findings and conclusions from the clustering analysis. Can we describe segments of the population that are relatively popular with the mail-order company, or relatively unpopular with the company?)
From the clustering analysis, we can see that:
Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.