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
import sklearn
from sklearn.preprocessing import StandardScaler, Imputer
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
# 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", delimiter=";")
# Load in the feature summary file.
feat_info = pd.read_csv("AZDIAS_Feature_Summary.csv", delimiter=";")
cat Data_Dictionary.md
display(feat_info)
# 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(azdias.shape)
display(azdias.head())
display(azdias.tail())
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.
def is_int(x):
try:
int(x)
return True
except ValueError:
return False
def parse_missing_value_codes(s):
'''
@param string of missing value codes
e.g. "[-1, 0]"
'''
s = s[1:-1].split(",") if s != "" else []
s = [ int(x) if is_int(x) else x for x in s ]
return s
missing_value_codes = feat_info["missing_or_unknown"].map(lambda x: parse_missing_value_codes(x))
def replace_missing_value_codes(df):
df_output = df.copy()
for i in range(len(df.columns)):
if i % 5 == 0:
print("Replacing missing value codes with np.nan for column {}/{}...".format(i, len(df_output.columns)-1))
col_name = df_output.columns[i]
df_output[col_name] = df_output[col_name].map(lambda x: np.nan if x in missing_value_codes[i] else x)
return df_output
azdias_cleaned = replace_missing_value_codes(azdias)
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.
num_na_by_column = azdias_cleaned.isnull().sum(axis=0)
# Histogram
histogram = plt.hist(num_na_by_column)
# Summary statistics
num_na_by_column.describe()
# Compute the outlier threshold by 0.75 quantile + 1.5 * IQR
iqr = num_na_by_column.quantile(0.75) - num_na_by_column.quantile(0.25)
OUTLIER_THRESHOLD = num_na_by_column.quantile(0.75) + 1.5 * iqr
# Plot bar chart
fig = plt.figure(figsize=(14, 5))
plt.bar(x=num_na_by_column.index, height=num_na_by_column)
ticks = plt.xticks(rotation=90)
hlines = plt.axhline(OUTLIER_THRESHOLD, linestyle="--", color="black")
# Outliers:
outlier_columns = num_na_by_column.index[num_na_by_column > OUTLIER_THRESHOLD]
outlier_columns
# Investigate patterns in the amount of missing data in each column.
for val in num_na_by_column[num_na_by_column > 0].unique():
na_count_grp = num_na_by_column[num_na_by_column==val].index.tolist()
if len(na_count_grp) > 1:
print("Variables with {} missing values: \n{}".format(val, na_count_grp))
print("")
Variables with 4854 missing values:
Variables with 111196 missing values:
Variables with 77792 missing values:
Variables with 73499 missing values:
Variables with 93148 missing values:
Variables with 99352 missing values:
Variables with 133324 missing values:
Variables with 93740 missing values:
Variables with 158064 missing values:
Variables with 116515 missing values:
Variables with 97375 missing values:
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
azdias_dropped_outliers = azdias_cleaned.drop(outlier_columns, axis=1)
def remove_outlier_columns(df):
df_output = df.copy()
# Determine outlier threshold
num_na_by_column = df_output.isnull().sum(axis=0)
iqr = num_na_by_column.quantile(0.75) - num_na_by_column.quantile(0.25)
OUTLIER_THRESHOLD = num_na_by_column.quantile(0.75) + 1.5 * iqr
# Find names of outlier columns and print
outlier_columns = num_na_by_column.index[num_na_by_column > OUTLIER_THRESHOLD]
print("Removing features with high number of missing values: {}".format(outlier_columns))
# Drop outlier columns
df_output.drop(outlier_columns, axis=1, inplace=True)
return df_output
# Save data as checkpoint
azdias_cleaned.to_csv("azdias_cleaned.csv", index=False)
azdias_dropped_outliers.to_csv("azdias_dropped_outliers.csv", index=False)
# Read data back in
azdias_cleaned = pd.read_csv("azdias_cleaned.csv")
azdias_dropped_outliers = pd.read_csv("azdias_dropped_outliers.csv")
(Double click this cell and replace this text with your own text, reporting your observations regarding the amount of missing data in each column. Are there any patterns in missing values? Which columns were removed from the dataset?)
AGER_TYP
, GEBURTSJAHR
, TITEL_KZ
, ALTER_HH
, KK_KUNDENTYP
, and KBA05_BAUMAX
.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?
row_null_totals = azdias_dropped_outliers.isnull().sum(axis=1)
# Write code to divide the data into two subsets based on the number of missing
# values in each row.
# Define outlier threshold
iqr = row_null_totals.quantile(0.75) - row_null_totals.quantile(0.25)
MISSING_VAL_THRESHOLD = row_null_totals.quantile(0.75) + 1.5 * iqr
# Split dataset
above_threshold = azdias_dropped_outliers.isnull().sum(axis=1) > MISSING_VAL_THRESHOLD
azdias_above_threshold = azdias_dropped_outliers[above_threshold]
azdias_below_threshold = azdias_dropped_outliers[~above_threshold]
def remove_outlier_rows(df):
row_null_totals = df.isnull().sum(axis=1)
# Define outlier threshold
iqr = row_null_totals.quantile(0.75) - row_null_totals.quantile(0.25)
MISSING_VAL_THRESHOLD = row_null_totals.quantile(0.75) + 1.5 * iqr
# Split dataset
above_threshold = row_null_totals > MISSING_VAL_THRESHOLD
return df[~above_threshold]
def get_outlier_rows(df):
row_null_totals = df.isnull().sum(axis=1)
# Define outlier threshold
iqr = row_null_totals.quantile(0.75) - row_null_totals.quantile(0.25)
MISSING_VAL_THRESHOLD = row_null_totals.quantile(0.75) + 1.5 * iqr
# Split dataset
above_threshold = row_null_totals > MISSING_VAL_THRESHOLD
return df[above_threshold]
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
def compare_subsets(col_name):
f, ax = plt.subplots(1, 2)
sns.countplot(azdias_below_threshold.loc[:, col_name], ax=ax[0]).set_title("Below threshold")
sns.countplot(azdias_above_threshold.loc[:, col_name], ax=ax[1]).set_title("Above threshold")
f.tight_layout()
compare_subsets(azdias_above_threshold.columns[6])
compare_subsets(azdias_above_threshold.columns[7])
compare_subsets(azdias_above_threshold.columns[8])
compare_subsets(azdias_above_threshold.columns[9])
compare_subsets(azdias_above_threshold.columns[10])
(Double-click this cell and replace this text with your own text, reporting your observations regarding missing data in rows. Are the data with lots of missing values are qualitatively different from data with few or no missing values?)
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?
feat_info["type"].value_counts()
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?
cat_vars = feat_info.loc[feat_info["type"]=="categorical", "attribute"]
cat_vars = cat_vars[~cat_vars.isin(outlier_columns)].reset_index(drop=True)
azdias_below_threshold[cat_vars].head()
binary_vars = []
multilevel_vars = []
for variable in cat_vars:
counts = azdias_below_threshold[variable].value_counts()
if len(counts) == 2:
var_type = "binary"
binary_vars.append(variable)
elif len(counts) >=3:
var_type = "multi-level categorical"
multilevel_vars.append(variable)
else:
var_type = "single value"
print("{} : {}".format(variable, var_type))
azdias_recoded = azdias_below_threshold.copy()
# Using a combination of the dataframe preview and the type printout, recode the multi-level categoricals -
# Re-encode categorical variable(s) to be kept in the analysis.
for var in multilevel_vars:
print("Variable: {} recoded with one hot encoding".format(var))
encoded_var = pd.get_dummies(azdias_recoded[var], prefix=var)
azdias_recoded = pd.concat([azdias_recoded, encoded_var], axis=1)
azdias_recoded.drop(var, axis=1, inplace=True)
# Recode the non-numeric binary variable
for var in binary_vars:
if azdias_recoded[var].dtype=="object":
unique_vals = azdias_recoded[var].unique()
for i in range(len(unique_vals)):
print("Variable: {}\t Value {} recoded to {}".format(var, unique_vals[i], i))
azdias_recoded.loc[azdias_recoded[var] == unique_vals[i], var] = i
azdias_recoded[var] = azdias_recoded[var].astype("float64")
def recode_categorical(df):
cat_vars = feat_info.loc[feat_info["type"]=="categorical", "attribute"]
cat_vars = cat_vars[~cat_vars.isin(outlier_columns)].reset_index(drop=True)
binary_vars = []
multilevel_vars = []
for variable in cat_vars:
counts = df[variable].value_counts()
if len(counts) == 2:
binary_vars.append(variable)
elif len(counts) >=3:
multilevel_vars.append(variable)
for var in multilevel_vars:
print("Variable: {} recoded with one hot encoding".format(var))
encoded_var = pd.get_dummies(df[var], prefix=var)
df = pd.concat([df, encoded_var], axis=1)
df.drop(var, axis=1, inplace=True)
for var in binary_vars:
if df[var].dtype=="object":
unique_vals = df.loc[~df[var].isnull(), var].unique()
for i in range(len(unique_vals)):
print("Variable: {}\t Value {} recoded to {}".format(var, unique_vals[i], i))
df.loc[df[var] == unique_vals[i], var] = i
df[var] = df[var].astype("float64")
return df
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding categorical features. Which ones did you keep, which did you drop, and what engineering steps did you perform?)
feat_info
. Next, I identified the sublist of binary variables and the sublist of multi-level categorical variables. I replaced each multi-level categorical variable with one hot encoding using pd.get_dummies()
. Finally, I replaced each non-numeric binary variable with 0s and 1s. This was done by iterating over the list of binary variables, checking the dtype of each variable, and replacing only when the dtype was non-numeric.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.
mixed_vars = feat_info.loc[feat_info["type"]=="mixed", "attribute"]
mixed_vars = mixed_vars[~mixed_vars.isin(outlier_columns)].reset_index(drop=True)
print(mixed_vars)
azdias_recoded.drop(["LP_LEBENSPHASE_FEIN", "LP_LEBENSPHASE_GROB", "PLZ8_BAUMAX"], axis=1, inplace=True)
def helper1(x):
'''
Helper 1 to recode "PRAEGENDE_JUGENDJAHRE" decade part
'''
if x in [1, 2]:
return 0
elif x in [3, 4]:
return 1
elif x in [5, 6, 7]:
return 2
elif x in [8, 9]:
return 3
elif x in [10, 11, 12, 13]:
return 4
elif x in [14, 15]:
return 5
else:
return None
def helper2(x):
'''
Helper 2 to recode "PRAEGENDE_JUGENDJAHRE" mvmt part
'''
if x in [1, 3, 5, 8, 10, 12, 14]:
return 0
elif x in [2, 4, 6, 7, 9, 11, 13, 15]:
return 1
else:
return None
def helper3(x):
'''
Helper 3 to create rural flag from "WOHNLAGE"
'''
if x in [1, 2, 3, 4, 5]:
return 0
elif x in [7, 8]:
return 1
else:
return None
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
values = azdias_recoded["PRAEGENDE_JUGENDJAHRE"]
azdias_recoded["PRAEGENDE_JUGENDJAHRE_DECADE"] = values.map(lambda x: helper1(x))
azdias_recoded["PRAEGENDE_JUGENDJAHRE_MVMT"] = values.map(lambda x: helper2(x))
# Drop old variable
azdias_recoded.drop("PRAEGENDE_JUGENDJAHRE", axis=1, inplace=True)
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
values = azdias_recoded["CAMEO_INTL_2015"]
# Use x > 0 as a way to detect NaN values
azdias_recoded["CAMEO_INTL_2015_WEALTH"] = values.map(lambda x: int(list(str(int(x)))[0]) if not np.isnan(float(x)) else x)
azdias_recoded["CAMEO_INTL_2015_LIFESTG"] = values.map(lambda x: int(list(str(int(x)))[1]) if not np.isnan(float(x)) else x)
# Drop old variable
azdias_recoded.drop("CAMEO_INTL_2015", axis=1, inplace=True)
# Create rural flag
values = azdias_recoded["WOHNLAGE"]
azdias_recoded["IS_RURAL"] = values.map(lambda x: helper3(x))
azdias_recoded.drop("WOHNLAGE", axis=1, inplace=True)
def handle_mixed_vars(df):
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
values = df["PRAEGENDE_JUGENDJAHRE"]
df["PRAEGENDE_JUGENDJAHRE_DECADE"] = values.map(lambda x: helper1(x))
df["PRAEGENDE_JUGENDJAHRE_MVMT"] = values.map(lambda x: helper2(x))
# Drop old variable
df.drop("PRAEGENDE_JUGENDJAHRE", axis=1, inplace=True)
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
values = df["CAMEO_INTL_2015"]
# Use x > 0 as a way to detect NaN values
df["CAMEO_INTL_2015_WEALTH"] = values.map(lambda x: int(list(str(int(x)))[0]) if not np.isnan(float(x)) else x)
df["CAMEO_INTL_2015_LIFESTG"] = values.map(lambda x: int(list(str(int(x)))[1]) if not np.isnan(float(x)) else x)
# Drop old variable
df.drop("CAMEO_INTL_2015", axis=1, inplace=True)
# Create rural flag
values = df["WOHNLAGE"]
df["IS_RURAL"] = values.map(lambda x: helper3(x))
df.drop("WOHNLAGE", axis=1, inplace=True)
df.drop(["LP_LEBENSPHASE_FEIN", "LP_LEBENSPHASE_GROB", "PLZ8_BAUMAX"], axis=1, inplace=True)
return df
# Save as checkpoint
azdias_recoded.to_csv("azdias_recoded.csv", index=False)
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding mixed-value features. Which ones did you keep, which did you drop, and what engineering steps did you perform?)
As noted above, aside from the two specified features, the rest of the mixed-value features were handled in the following way:
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.)
# Do whatever you need to in order to ensure that the dataframe only contains
# the columns that should be passed to the algorithm functions.
# Check original variables if handled properly
def check_df(df):
for index, row in feat_info[["attribute", "type"]].iterrows():
if row["attribute"] in outlier_columns:
if row["attribute"] in df.columns:
print("{}: (*) {} is an outlier column and should be removed from the dataset.".format(index, row["attribute"]))
else:
print("{}: {} removed from dataset for being an outlier.".format(index, row["attribute"]))
elif row["type"] in ["numeric", "interval", "ordinal"]:
if row["attribute"] not in df.columns:
print("{}: (*) Warning: {} is missing from the dataset.".format(index, row["attribute"]))
else:
print("{}: {} retained for being numeric, interval, or ordinal.".format(index, row["attribute"]))
elif row["type"]=="categorical":
if row["attribute"] in binary_vars:
if row["attribute"] not in df.columns:
print("{}: (*) Warning: {} is missing from the dataset.".format(index, row["attribute"]))
elif df[row["attribute"]].dtype=="object":
print("{}: (*) Warning: {} is not numerically encoded.".format(index, row["attribute"]))
else:
print("{}: {} is a properly encoded binary feature.".format(index, row["attribute"]))
else:
if row["attribute"] not in df.columns:
print("{}: {} multi-level categorical variable handled properly.".format(index, row["attribute"]))
else:
print("{}: (*) Warning: Check if {} multi-level categorical variable handled properly.".format(index, row["attribute"]))
elif row["type"]=="mixed":
if row["attribute"] not in df.columns:
print("{}: {} mixed-feature handled properly, either removed or recoded.".format(index, row["attribute"]))
else:
print("{}: (*) Warning: mixed feature {} still in dataset, check if handled properly.".format(index, row["attribute"]))
for col in df.columns[~df.columns.isin(feat_info["attribute"])]:
if not any(a in col for a in multilevel_vars):
print("Check if derived from mixed variable:", col)
return
check_df(azdias_recoded)
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, ...
df_cleaned = replace_missing_value_codes(df)
# remove selected columns and rows, ...
# Originally here I tried to use a generic drop outlier function, but we want to drop the same columns
df_dropped_outliers = df_cleaned.drop(outlier_columns, axis=1)
df_below_threshold = remove_outlier_rows(df_dropped_outliers)
# select, re-encode, and engineer column values.
df = recode_categorical(df_below_threshold)
df = handle_mixed_vars(df)
# check dataframe
check_df(df)
# Return the cleaned dataframe.
return df
customer_df = pd.read_csv("Udacity_CUSTOMERS_Subset.csv", delimiter=";")
cleaned_customer_df = clean_data(customer_df)
# Check that columns present in each dataframe are the same
compare_cols = pd.concat([pd.DataFrame(azdias_recoded.columns, columns=["azdias_cols"]),
pd.DataFrame(cleaned_customer_df.columns, columns=["customer_cols"])], axis=1)
compare_cols[compare_cols["azdias_cols"] != compare_cols["customer_cols"]].head()
# Add GEBAEUDETYP_5.0 column (with all zeroes) to cleaned_customer_df
cleaned_customer_df_2 = pd.concat([cleaned_customer_df.iloc[:, 0:132],
pd.DataFrame(np.zeros([len(cleaned_customer_df.index), 1]).astype(np.uint8),
columns=["GEBAEUDETYP_5.0"]),
cleaned_customer_df.iloc[:, 132:len(cleaned_customer_df.columns)]], axis=1)
compare_cols = pd.concat([pd.DataFrame(azdias_recoded.columns, columns=["azdias_cols"]),
pd.DataFrame(cleaned_customer_df_2.columns, columns=["customer_cols"])], axis=1)
compare_cols[compare_cols["azdias_cols"] != compare_cols["customer_cols"]]
# Ensure column names are the same
cleaned_customer_df_2.columns = azdias_recoded.columns
# Check that dtypes of all columns are the same
azdias_recoded.dtypes[azdias_recoded.dtypes != cleaned_customer_df_2.dtypes]
# Save final cleaned versions for now
azdias_recoded.to_csv("azdias_FINAL_CLEAN.csv", index=False)
cleaned_customer_df_2.to_csv("cust_FINAL_CLEAN.csv", index=False)
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.# Read in clean azdias data
azdias_df = pd.read_csv("azdias_FINAL_CLEAN.csv")
# Maximum % of missing values in any column
np.mean(azdias_df.isnull(), axis=0).max()
# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
imp = Imputer()
azdias_imputed = imp.fit_transform(azdias_df)
# Apply feature scaling to the general population demographics data.
ss = StandardScaler()
azdias_scaled = ss.fit_transform(azdias_imputed)
# Check that the scaling worked correctly (within a certain dist from )
eps = 1e-10
print(all(abs(azdias_scaled.mean(axis=0)) < eps))
print(all(abs(azdias_scaled.std(axis=0)-1) < eps))
(Double-click this cell and replace this text with your own text, reporting your decisions regarding feature scaling.)
For feature scaling, we have two options: one is to impute the missing values first (with means using Imputer) and scale after or to scale first and impute means after.
With the first option, the concern is whether or not the imputation will affect the way the features are scaled. With simple imputation, we know imputation will only increase the frequency of the mean value in that column, since the mean will be imputed for missing values. Depending on the number of values to be imputed, if the feature itself is not concentrated around the mean, this may change the distribution of the feature significantly and in turn affect scaling in the second step.
With the second option, we would work with the data on a feature-by-feature basis. For features that have no missing values, compute the mean and std and scale as normal. For features that have missing values, first compute the scaling parameters and then impute values. With option 2, there is less concern of our imputation affecting the known distribution of the true data. However, this option is (slightly) more work to implement.
Another important concern with imputation in general is imputation for binary variables, which may not make sense. In this case, we would want to impute the most common value (of the two) instead of using the mean.
If we recall, we removed most of the features with high numbers of missing values (computed above, we see that any feature has at most 6% values missing), so I don't think there is a major worry of imputation affecting the feature distributions dramatically, so I will go with option 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.# Apply PCA to the data.
pca = PCA()
pca.fit(azdias_scaled)
# Investigate the variance accounted for by each principal component.
explained_variance = pca.explained_variance_
pct_explained_variance = explained_variance / np.sum(explained_variance)
cumul_pct_exp_variance = np.cumsum(pct_explained_variance)
fig, axarr = plt.subplots(2, 1, figsize=(18, 12))
axarr[0].bar(list(range(1, len(pct_explained_variance)+1)), pct_explained_variance)
axarr[0].set_title("Explained variance for each component")
axarr[1].plot(cumul_pct_exp_variance)
axarr[1].set_title("Cumulative explained variance")
cumul_pct_exp_variance[100]
cumul_pct_exp_variance[10]
# Re-apply PCA to the data while selecting for number of components to retain.
pca = PCA(n_components=10)
azdias_pca = pca.fit_transform(azdias_scaled)
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding dimensionality reduction. How many principal components / transformed features are you retaining for the next step of the analysis?)
After performing PCA, I'll choose to keep 10 components. The "elbow" in the scree plot is rather low, around 10 by visual examination and it would only capture around 30% of the variance in the data. Ideally, I'd like to capture more variance in the data, but choosing too many components would make k-means clustering more computationally intensive and also possibly make it harder to find distinct clusters due to the curse of dimensionality. The point of PCA is to perform dimension reduction so that we have a manageable feature set to use, so I'll choose 10 and see what the results look like. If they aren't satisfactory, I can come back and increase the number of 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.
def get_top_three_features(i):
top_three = sorted([x for x in zip(pca.components_[i-1], azdias_df.columns)], key=lambda x: -abs(x[0]))[0:3]
print("Top three weighted features for principal component {}".format(i))
for num, pair in enumerate(top_three):
print("{}: {:30s}\tWeight: {}".format(num+1, pair[1], pair[0]))
return top_three
# 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.
get_top_three_features(1)
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
get_top_three_features(2)
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.
get_top_three_features(3)
(Double-click this cell and replace this text with your own text, reporting your observations from detailed investigation of the first few principal components generated. Can we interpret positive and negative values from them in a meaningful way?)
MOBI_REGIO
is a variable representing movement in the region, with low numbers representing higher movement, LP_STATUS_GROB_1.0
is a dummy indicator for whether or not a customer is a low-income earner, KBA05_ANTG1
represents number of 1-2 family homes in the microcell. Taken together, higher values for PC1 indicate an individual that is more likely to be a low-income earner that lives in a region that is characterized by higher movement, and has a low number of 1-2 family homes in the microcell.PRAEGENDE_JUGENDJAHRE_DECADE
is a derived variable that indicates the decade of the dominating movement of person's youth with 0 representing the 40s and 15 representing the 90s. ALTERSKATEGORIE_GROB
is estimated age based on given name analysis. FINANZ_SPARER
indicates how much of a money-saver the individual is with, lower values being more conservative. Taken together, higher values for PC2 indicate an individual that is likely to be older, with a higher level of financial conservativeness.ANREDE_KZ
is gender, with 1 male and 2 female. SEMIO_VERT
and SEMIO_KAEM
are personality typologies, with VERT representing dreamful and KAEM representing combative. Lower numbers indicate greater affinity. Taken together, higher values for PC3 indicate an individual that is more likely be be male, more combative, and less dreamful.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.MIN_CLUST = 2
MAX_CLUST = 20
all_avg_dists = []
# all_cluster_scores = []
# Over a number of different cluster counts...
for k in range(MIN_CLUST, MAX_CLUST):
print(k)
# run k-means clustering on the data and...
kmeans = KMeans(n_clusters=k, random_state=1234, n_jobs=-1)
kmeans.fit(azdias_pca)
# compute the average within-cluster distances.
total_dist = 0
for i in range(azdias_pca.shape[0]):
label = kmeans.labels_[i]
dist = np.linalg.norm(azdias_pca[i] - kmeans.cluster_centers_[label])
total_dist += dist
avg_dist = total_dist / azdias_pca.shape[0]
# Save avg dist
all_avg_dists.append(avg_dist)
# all_cluster_scores.append(kmeans.score(azdias_pca))
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
plt.plot(range(MIN_CLUST, MAX_CLUST), all_avg_dists)
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
SELECTED_K = 10
kmeans = KMeans(n_clusters=SELECTED_K, random_state=1234, n_jobs=-1)
kmeans.fit(azdias_pca)
azdias_label_preds = kmeans.labels_
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding clustering. Into how many clusters have you decided to segment the population?)
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 CLEAN customer demographics data.
# (Data was cleaned in an earlier cell in this notebook when clean_df was defined)
customers = pd.read_csv("cust_FINAL_CLEAN.csv")
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
customers = imp.transform(customers)
customers = ss.transform(customers)
customers = pca.transform(customers)
customers_label_preds = kmeans.predict(customers)
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.
unique, azdias_counts = np.unique(azdias_label_preds, return_counts=True)
unique, customer_counts = np.unique(customers_label_preds, return_counts=True)
# Get "above threshold" datasets from step 1.1.3
azdias_dropped_outliers = pd.read_csv("azdias_dropped_outliers.csv")
azdias_above_threshold = get_outlier_rows(azdias_dropped_outliers)
customer_df = pd.read_csv("Udacity_CUSTOMERS_Subset.csv", delimiter=";")
customer_cleaned = replace_missing_value_codes(customer_df)
customer_dropped_outliers = customer_cleaned.drop(outlier_columns, axis=1)
customer_above_threshold = get_outlier_rows(customer_dropped_outliers)
azdias_counts = np.append(azdias_counts, azdias_above_threshold.shape[0])
customer_counts = np.append(customer_counts, customer_above_threshold.shape[0])
azdias_props = azdias_counts / sum(azdias_counts) * 100
customer_props = customer_counts / sum(customer_counts) * 100
# Plot proportion of data and ratio
fig, axarr = plt.subplots(1, 3, figsize=(16, 4))
sns.barplot(np.arange(0, 11), azdias_props, ax=axarr[0])
sns.barplot(np.arange(0, 11), customer_props, ax=axarr[1])
sns.barplot(np.arange(0, 11), customer_props / azdias_props, ax=axarr[2])
axarr[0].set_title("General population cluster proportions")
axarr[0].set_ylabel("Percentage (%)")
axarr[0].set_xlabel("Cluster label")
axarr[1].set_title("Customer dataset cluster proportions")
axarr[1].set_ylabel("Percentage (%)")
axarr[1].set_xlabel("Cluster label")
axarr[2].set_title("Customer dataset / general population cluster ratio")
axarr[2].axhline(1, color="black", linestyle="--")
axarr[2].set_xlabel("Cluster label")
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?
# Clusters 6 and 8 are overrepresented in the customer population
print(kmeans.cluster_centers_[6])
print(kmeans.cluster_centers_[8])
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
# Clusters 4, 0, and 9 and 10 underrepresented in the customer population
print(kmeans.cluster_centers_[0])
print(kmeans.cluster_centers_[4])
print(kmeans.cluster_centers_[9])
(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?)
Looking at all this data together, it seems that overall the customer segments that are popular with the company are young, middle-class females and high-income, middle-aged conservative males.
In contrast, the customer segments that are not popular with the company are low-income individuals and young, moderately conservative high-income males.
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.