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 time
import pprint
import operator
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.preprocessing import LabelEncoder
# 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=';')
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
num_rows, num_cols = azdias.shape
print('Number of columns: {}'.format(num_cols))
print('Number of rows: {}'.format(num_rows))
azdias.head(5)
azdias.describe()
azdias.info()
azdias.dtypes
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.
col_names = azdias.columns
col_names
# turn missing_or_unknown to list
feat_info['missing_or_unknown'] = feat_info['missing_or_unknown'].apply(lambda x: x[1:-1].split(','))
start_time = time.time()
# Identify missing or unknown data values and convert them to NaNs.
for attrib, missing_values in zip(feat_info['attribute'], feat_info['missing_or_unknown']):
if missing_values[0] != '':
for value in missing_values:
if value.isnumeric() or value.lstrip('-').isnumeric():
value = int(value)
azdias.loc[azdias[attrib] == value, attrib] = np.nan
print("--- Run time: %s mins ---" % np.round(((time.time() - start_time)/60),2))
azdias.head()
azdias.to_csv('azdias_parsed.csv', sep=';', index = False)
#load the post parsed data set and perform similar exploratory functions
azdiasPP = pd.read_csv('azdias_parsed.csv', delimiter=';')
#As you can see, all of our missing or unknown codes have been transformed to NaNs
azdiasPP.head()
azdiasPP.describe()
azdiasPP.info()
azdiasPP.isnull().sum()
azdiasPP.isnull().sum().sum()
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.
missing_data = azdiasPP.isnull().sum()
#get the percentage
missing_data = missing_data[missing_data > 0]/(azdiasPP.shape[0]) * 100
#sort the values
missing_data.sort_values(inplace=True)
#plot the data as specified/sorted above
plt.hist(missing_data, bins = 25)
plt.xlabel('Percentage of missing data(%)')
plt.ylabel('Counts')
plt.title('Histogram of number of missing data')
plt.grid(True)
plt.show()
# Investigate patterns in the amount of missing data in each column.
missing_data.plot.barh(figsize=(15,30))
plt.xlabel('Column name with missing values')
plt.ylabel('Percentage of missing values')
plt.show()
#just to see the numbers as portrayed above in the plot
missing_data.sort_values(ascending=False)
# find columns with more that 25% of data missing
missing_25P = [col for col in azdiasPP.columns
if (azdiasPP[col].isnull().sum()/azdiasPP.shape[0])
* 100 > 25]
print(missing_25P)
missing_data.sort_values(ascending=False)
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
for col in missing_25P:
azdiasPP.drop(col, axis=1, inplace=True)
#check to make sure that our code was successful
missing_data_check = azdiasPP.isnull().sum()
#get the percentage
missing_data_check = missing_data_check[missing_data_check > 0]/(azdiasPP.shape[0]) * 100
#sort the values
missing_data_check.sort_values(inplace=True)
missing_data_check.sort_values(ascending = False)
here we investigated the data and looked at the amount of missing data in each columns and chose to remove columns which had more than 25% of their data missing, those include:['AGER_TYP', 'GEBURTSJAHR', 'TITEL_KZ', 'ALTER_HH', 'KK_KUNDENTYP', '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?
missing_row_data = azdiasPP.isnull().sum(axis=1)
missing_row_data = missing_row_data[missing_row_data > 0]/(len(azdiasPP.columns)) * 100
missing_row_data.sort_values(inplace=True)
plt.hist(missing_row_data, bins=25)
plt.xlabel('Percentage of missing row data (%)')
plt.ylabel('Counts')
plt.title('Histogram of missing data counts in rows')
plt.grid(True)
plt.show()
missing_row_counts = azdiasPP.isnull().sum(axis=1)
missing_row_counts.sort_values(ascending=False)
missing_row_counts.sum()
# Write code to divide the data into two subsets based on the number of missing
# values in each row.
# We use the drop parameter to avoid the old index being added as a column
## link ^ https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html
few_missing = azdiasPP[azdiasPP.isnull().sum(axis=1) < 10].reset_index(drop=True)
many_missing = azdiasPP[azdiasPP.isnull().sum(axis=1) >= 10].reset_index(drop=True)
plt.figure(figsize=(25,25))
for i, col in enumerate(azdiasPP.columns[:10]):
plt.subplot(5, 2, i+1)
sns.distplot(few_missing[col][few_missing[col].notnull()], label='few_missing')
sns.distplot(many_missing[col][many_missing[col].notnull()], label='many_missing')
plt.title('Distribution for column: {}'.format(col))
plt.legend();
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
#check here for some more example of code: https://jakevdp.github.io/PythonDataScienceHandbook/04.08-multiple-subplots.html
col_names_few = few_missing.columns
def print_countplot(cols,num):
fig, axs = plt.subplots(num,2, figsize=(20, 25))
# adjust the spacing between these plots
fig.subplots_adjust(hspace =2 , wspace=.2)
#This function returns a flattened one-dimensional array.
#A copy is made only if needed. The returned array will have
#the same type as that of the input array.
#Read more here: https://www.tutorialspoint.com/numpy/numpy_ndarray_ravel.htm
axs = axs.ravel()
for i in range(num):
sns.countplot(few_missing[cols[i]], ax=axs[i*2])
axs[i*2].set_title('few_missing')
sns.countplot(many_missing[cols[i]], ax=axs[i*2+1])
axs[i*2+1].set_title('many_missing')
print_countplot(col_names_few,8)
#many_missing = missing_row_counts[missing_row_counts > 10]
print('rows with many missing values:', many_missing.shape[0], 'or', \
np.round(many_missing.shape[0]*100/missing_row_counts.shape[0],2),
'% of all data')
# Save data with many missing rows
azdiasPP_many_missing = azdiasPP.iloc[many_missing.index]
#filling missing values in the few missing with the mean of the value, before and after
for col in few_missing.columns:
few_missing[col] = few_missing[col].interpolate(limit_direction='both')
few_missing[col].interpolate().count()
few_missing[col].interpolate().plot()
few_missing.head()
#check for any null values
few_missing.isnull().sum()
few_missing.isnull().sum().sum()
few_missing.drop(['CAMEO_DEU_2015'], axis=1, inplace=True)
few_missing.isnull().sum().sum()
few_missing.isnull().sum()
There were many rows with missing data, I chose to create a cut off around 10 missing values per row, deleted any rows with more than that, which lost us about 13% of the data set. I also chose to interpolate the rest of the values and deleted the columns that presisted with a significant number of empty values. now the data is clean and is void of any null vlaues.
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!
#set the attribute as the index
feat_info.set_index('attribute', inplace=True)
feat_info.head(n=10)
feat_info['col_names'] = feat_info.index
feat_info.head()
# How many features are there of each data type?
dtype={}
for col in few_missing.columns:
data_type = feat_info.loc[col].type
if data_type not in dtype:
dtype[data_type] = 1
else:
dtype[data_type] += 1
dtype
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?
for col in few_missing.columns:
if feat_info.loc[col].type == 'categorical':
print(col, len(few_missing[col].unique()), few_missing[col].dtype)
#extract categorical columns with more than 2 categories
non_binary_type = []
for col in few_missing.columns:
if feat_info.loc[col].type == 'categorical' and len(few_missing[col].unique()) > 2:
non_binary_type.append(col)
non_binary_type
# Find the column names for mixed type columns
mixed_type = []
for col in few_missing.columns:
if feat_info.loc[col].type == 'mixed':
mixed_type.append(col)
mixed_type
few_missing['SHOPPER_TYP'].value_counts()
few_missing['SHOPPER_TYP'] = few_missing['SHOPPER_TYP'].round()
few_missing['SHOPPER_TYP']
few_missing['SHOPPER_TYP'].value_counts()
# Re-encode categorical variable(s) to be kept in the analysis.
# we did not encode the others given that they are already binary.
#Onehot encoding for the one binary variable that takes on non-numeric values
# This will create an extra unecessary column:
##few_missing = pd.get_dummies(data=few_missing, columns=['OST_WEST_KZ'])
few_missing.loc[:, 'OST_WEST_KZ'].replace({'W':0, 'O':1}, inplace=True);
# Reencode Shopper type
few_missing = pd.get_dummies(data=few_missing, columns=['SHOPPER_TYP'])
#check the columns for the newly re-encoded categorical values
few_missing.head()
#remove categorical columns with more than 2 categories
non_binary_cols = ['CJT_GESAMTTYP',
'FINANZTYP',
'GFK_URLAUBERTYP',
'LP_FAMILIE_FEIN',
'LP_FAMILIE_GROB',
'LP_STATUS_FEIN',
'LP_STATUS_GROB',
'NATIONALITAET_KZ',
'VERS_TYP',
'ZABEOTYP',
'GEBAEUDETYP',
'CAMEO_DEUG_2015']
for col in non_binary_cols:
few_missing.drop(col, axis=1, inplace=True)
I checked the values and I have a significant number of ordinal values, catgeorical and several mixed ones too. I rencoded the categorical variable for easier wrangling and less uncessary columns. I also reencoded the shopper type and dummied it out. I deleted the remaining non-binary columns, I chose to drop them for ease of analysis. Obviosuly if the client wanted them encoded, that could also be done. I looked at the mixed ones as well to prepare for their engineering below.
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.
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
few_missing['PRAEGENDE_JUGENDJAHRE'].head()
few_missing['CAMEO_INTL_2015'].head()
# this information is based on the dictionary document
#Map generation
gen_dict = {0: [1, 2],
1: [3, 4],
2: [5, 6, 7],
3: [8, 9],
4: [10, 11, 12, 13],
5:[14, 15]}
def map_gen(x):
try:
for key, array in gen_dict.items():
if x in array:
return key
except ValueError:
return np.nan
# Map movement
mainstream = [1, 3, 5, 8, 10, 12, 14]
def map_mov(x):
try:
if x in mainstream:
return 0
else:
return 1
except ValueError:
return np.nan
# Create generation column
few_missing['PRAEGENDE_JUGENDJAHRE_decade'] = few_missing['PRAEGENDE_JUGENDJAHRE'].apply(map_gen)
# Create movement column
few_missing['PRAEGENDE_JUGENDJAHRE_movement'] = few_missing['PRAEGENDE_JUGENDJAHRE'].apply(map_mov)
# drop the original column
few_missing.drop(['PRAEGENDE_JUGENDJAHRE'], axis = 1, inplace=True)
few_missing.head()
# Map wealth
def map_wealth(x):
# Check of nan first, or it will convert nan to string 'nan'
try:
if pd.isnull(x):
return np.nan
else:
return int(str(x)[0])
except ValueError:
return np.nan
# Map life stage
def map_lifestage(x):
try:
if pd.isnull(x):
return np.nan
else:
return int(str(x)[1])
except ValueError:
return np.nan
# Create wealth column
few_missing['CAMEO_INTL_2015_wealth'] = few_missing['CAMEO_INTL_2015'].apply(map_wealth)
# Create life stage column
few_missing['CAMEO_INTL_2015_lifestage'] = few_missing['CAMEO_INTL_2015'].apply(map_lifestage)
# drop the original column
few_missing.drop(['CAMEO_INTL_2015'], axis = 1, inplace=True)
#Map WOHNLAGE
# Map Rural
rural = [7,8]
def map_rur(x):
try:
if x in rural:
return 0
else:
return 1
except ValueError:
return np.nan
# Map Neigh
neigh = [1,2,3,4,5]
def map_neigh(x):
try:
if x in neigh:
return 0
else:
return 1
except ValueError:
return np.nan
# Create rural column
few_missing['WOHNLAGE_rural'] = few_missing['WOHNLAGE'].apply(map_rur)
# Create neighborhood column
few_missing['WOHNLAGE_neigh'] = few_missing['WOHNLAGE'].apply(map_neigh)
# drop the original column
few_missing.drop(['WOHNLAGE'], axis = 1, inplace=True)
few_missing.head()
# dropping the other mixed columns
mixed = ['LP_LEBENSPHASE_FEIN', 'LP_LEBENSPHASE_GROB','PLZ8_BAUMAX']
for col in mixed:
few_missing.drop(col, axis=1, inplace=True)
few_missing.head()
To reingineer those mixed type values, it was helpful that they were assigned a numeric value. I was interested in reeingineering the LP_LEBENSPHASE_FEIN column, but unfortunately, it was too fine and had more than 3-4 vlaues per person and no clear code. if I had more time, I would have looked at it more deeply, but for now, I chose to drop the other mixed variables, including: 'LP_LEBENSPHASE_FEIN', 'LP_LEBENSPHASE_GROB','WOHNLAGE','KBA05_BAUMAX','PLZ8_BAUMAX'.
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.)
#check again for missing values
few_missing.isnull().sum()
# interpolate one more time to clear the empty values from the newly created columns
for col in few_missing.columns:
few_missing[col] = few_missing[col].interpolate(limit_direction='both')
few_missing.isnull().sum().sum()
#this could also work to clear the data from NaNs
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values=float("NaN"),
strategy="mean/most frequent/median",
axis=1, copy = False)
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, ...
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', delimiter=';')
feat_info['missing_or_unknown'] = feat_info['missing_or_unknown'].apply(lambda x: x[1:-1].split(','))
# Identify missing or unknown data values and convert them to NaNs.
for attrib, missing_values in zip(feat_info['attribute'], feat_info['missing_or_unknown']):
if missing_values[0] != '':
for value in missing_values:
if value.isnumeric() or value.lstrip('-').isnumeric():
value = int(value)
azdias.loc[azdias[attrib] == value, attrib] = np.nan
# remove selected columns and rows, ...
#Columns
columns_removed = ['AGER_TYP', 'GEBURTSJAHR', 'TITEL_KZ',
'ALTER_HH', 'KK_KUNDENTYP', 'KBA05_BAUMAX',
'CAMEO_DEU_2015']
for col in columns_removed:
df.drop(col, axis=1, inplace=True)
#Rows
few_missing = df[df.isnull().sum(axis=1) < 10].reset_index(drop=True)
#interpolate and impute the NaNs
for col in few_missing.columns:
few_missing[col] = few_missing[col].interpolate(limit_direction='both')
# select, re-encode, and engineer column values.
#drop non categorical
non_binary_cols = ['CJT_GESAMTTYP','FINANZTYP','GFK_URLAUBERTYP','LP_FAMILIE_FEIN',
'LP_FAMILIE_GROB','LP_STATUS_FEIN','LP_STATUS_GROB','NATIONALITAET_KZ',
'VERS_TYP','ZABEOTYP','GEBAEUDETYP','CAMEO_DEUG_2015']
for col in non_binary_cols:
few_missing.drop(col, axis=1, inplace=True)
#Reencode the categorical and get dummies for the shopper type
few_missing.loc[:, 'OST_WEST_KZ'].replace({'W':0, 'O':1}, inplace=True);
few_missing['SHOPPER_TYP'] = few_missing['SHOPPER_TYP'].round()
few_missing = pd.get_dummies(data=few_missing, columns=['SHOPPER_TYP'])
# Complete the mapping process of mixed features
few_missing['PRAEGENDE_JUGENDJAHRE_decade'] = few_missing['PRAEGENDE_JUGENDJAHRE'].apply(map_gen)
few_missing['PRAEGENDE_JUGENDJAHRE_movement'] = few_missing['PRAEGENDE_JUGENDJAHRE'].apply(map_mov)
few_missing.drop('PRAEGENDE_JUGENDJAHRE', axis=1, inplace=True)
few_missing['CAMEO_INTL_2015_wealth'] = few_missing['CAMEO_INTL_2015'].apply(map_wealth)
few_missing['CAMEO_INTL_2015_lifestage'] = few_missing['CAMEO_INTL_2015'].apply(map_lifestage)
few_missing.drop('CAMEO_INTL_2015', axis=1, inplace=True)
few_missing['WOHNLAGE_rural'] = few_missing['WOHNLAGE'].apply(map_rur)
few_missing['WOHNLAGE_neigh'] = few_missing['WOHNLAGE'].apply(map_neigh)
few_missing.drop('WOHNLAGE', axis=1, inplace=True)
#drop mixed
mixed = ['LP_LEBENSPHASE_FEIN','LP_LEBENSPHASE_GROB','PLZ8_BAUMAX']
for col in mixed:
few_missing.drop(col, axis=1, inplace=True)
# interpolate again to clean the data set
for col in few_missing.columns:
few_missing[col] = few_missing[col].interpolate(limit_direction='both')
# Return the cleaned dataframe.
return few_missing
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.# Apply feature scaling to the general population demographics data.
# use .as_matrix to convert a pandas data frame to a numpy matrix for scikit-learn
start_time = time.time()
scaler = StandardScaler()
few_missing[few_missing.columns] = scaler.fit_transform(few_missing[few_missing.columns].as_matrix())
print("--- Run time: %s mins ---" % np.round(((time.time() - start_time)/60),2))
#check the stats, mean, etc
few_missing.describe()
few_missing.head()
few_missing.columns
I used the standard scaler to normalize the values to analyze our data properly and provide a good solution that is not affected or skewed by varying scales within the data.
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.
start_time = time.time()
pca = PCA()
few_missing_pca = pca.fit_transform(few_missing)
print("--- Run time: %s mins ---" % np.round(((time.time() - start_time)/60),2))
def pca_plot1(pca):
'''
Creates a scree plot associated with the principal components
INPUT: pca - the result of instantian of PCA in scikit learn
OUTPUT:
None
'''
num_components = len(pca.explained_variance_ratio_)
ind = np.arange(num_components)
vals = pca.explained_variance_ratio_
plt.figure(figsize=(10, 6))
ax = plt.subplot(111)
cumvals = np.cumsum(vals)
ax.bar(ind, vals)
ax.plot(ind, cumvals)
for i in range(num_components):
ax.annotate(r"%s%%" % ((str(vals[i]*100)[:4])), (ind[i]+0.2, vals[i]), va="bottom", ha="center", fontsize=12)
ax.xaxis.set_tick_params(width=0)
ax.yaxis.set_tick_params(width=2, length=12)
ax.set_xlabel("Principal Component")
ax.set_ylabel("Variance Explained (%)")
plt.title('Explained Variance Per Principal Component')
pca_plot1(pca)
# Number of components required to maintain %75 variance:
def pca_plot2(pca):
n_components = min(np.where(np.cumsum(pca.explained_variance_ratio_)>0.85)[0]+1)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1],True)
ax2 = ax.twinx()
ax.plot(pca.explained_variance_ratio_, label='Variance',)
ax2.plot(np.cumsum(pca.explained_variance_ratio_), label='Cumulative Variance',color = 'red');
ax.set_title('n_components needed for >%85 explained variance: {}'.format(n_components));
ax.axvline(n_components, linestyle='dashed', color='grey')
ax2.axhline(np.cumsum(pca.explained_variance_ratio_)[n_components], linestyle='dashed', color='grey')
fig.legend(loc=(0.6,0.2));
pca_plot2(pca)
# Investigate the variance accounted for by each principal component.
# Re-apply PCA to the data while selecting for number of components to retain.
start_time = time.time()
pca = PCA(n_components= 28, random_state=10)
few_missing_pca = pca.fit_transform(few_missing)
print("--- Run time: %s mins ---" % np.round(((time.time() - start_time)/60),2))
#check the explained variance ratio
pca.explained_variance_ratio_.sum()
Looking at the plots above, it became clear that 28 features seemed to have the most explanatory power at 85%. I chose to go with 28 principal components and an explained variance ratio of 85 because anything after 28 components had an explanatory power that diverged on zero. 85% seemed like a sufficient percentage to capture the majority of the variability in our data without any redundant features.
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_weights(pca, i):
weight_map = {}
for counter, feature in enumerate(few_missing.columns):
weight_map[feature] = pca.components_[i][counter]
sorted_weights = sorted(weight_map.items(), key=operator.itemgetter(1), reverse=True)
return sorted_weights
weights = pca_weights(pca,1)
#pretty print
pprint.pprint(weights)
#draw plot for visualizing those weights
def plot_pca(data, pca, n_component):
'''
Plot the features with the most absolute variance for given pca component
'''
Pcomponent = pd.DataFrame(np.round(pca.components_, 4),
columns = data.keys()).iloc[n_component-1]
Pcomponent.sort_values(ascending=False, inplace=True)
Pcomponent = pd.concat([Pcomponent.head(5), Pcomponent.tail(5)])
Pcomponent.plot(kind='bar', title='Component ' + str(n_component))
ax = plt.gca()
ax.grid(linewidth='0.5', alpha=0.5)
ax.set_axisbelow(True)
plt.show()
plot_pca(few_missing, pca, 1)
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
weights = pca_weights(pca,2)
# Prints the nicely formatted dictionary
pprint.pprint(weights)
plot_pca(few_missing, pca, 2)
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.
weights = pca_weights(pca,3)
# Prints the nicely formatted dictionary
pprint.pprint(weights)
plot_pca(few_missing, pca, 3)
In the dicussion points above, I discussed the main positive and negative values that we extracted from the PCA analysis, the values are certainly explainable and are filled with very interesting and helpful information. This can already help us in detecting trends, customer groups and how to approach any new marketing campaign.
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...
def get_kmeans_score(data, center):
'''
returns the kmeans score regarding SSE for points to centers
INPUT:
data - the dataset you want to fit kmeans to
center - the number of centers you want (the k value)
OUTPUT:
score - the SSE score for the kmeans model fit to the data
'''
# run k-means clustering on the data .
kmeans = KMeans(n_clusters=center)
# fit the model
model = kmeans.fit(data)
# Obtain a score related to the model fit
# compute the average within-cluster distances
score = np.abs(model.score(data))
return score
# Over a number of different cluster counts...
# run k-means clustering on the data and...
# compute the average within-cluster distances.
#this takes a while
start_time = time.time()
scores = []
centers = list(range(1,30,2))
for center in centers:
scores.append(get_kmeans_score(few_missing_pca, center))
print("--- Run time: %s mins ---" % np.round(((time.time() - start_time)/60),2))
print(scores)
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
# SSE = sum of squared errors
plt.plot(centers, scores, linestyle='--', marker='o', color='b');
plt.xlabel('K');
plt.ylabel('SSE');
plt.title('SSE vs. K');
reduced_data = PCA(n_components=2).fit_transform(few_missing)
#clusters = KMeans(n_clusters=best_k, random_state=100).fit(reduced_data)
clusters = KMeans(n_clusters=15, random_state=100).fit(reduced_data)
x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
hx = (x_max-x_min)/1000.
hy = (y_max-y_min)/1000.
xx, yy = np.meshgrid(np.arange(x_min, x_max, hx), np.arange(y_min, y_max, hy))
Z = clusters.predict(np.c_[xx.ravel(), yy.ravel()])
centroids = clusters.cluster_centers_
def PCA_plot(Z, centroids):
Z = Z.reshape(xx.shape)
plt.figure(1, figsize=(20, 10))
plt.clf()
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=plt.cm.Paired,
aspect='auto', origin='lower')
plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2, alpha=0.1)
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=169, linewidths=3,
color='w', zorder=10)
plt.title('Clustering on the dataset (PCA-reduced data)\n'
'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()
PCA_plot(Z, centroids)
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
start_time = time.time()
kmeans = KMeans(n_clusters=15)
model_general = kmeans.fit(few_missing_pca)
print("--- Run time: %s mins ---" % np.round(((time.time() - start_time)/60),2))
predict_general = model_general.predict(few_missing_pca)
I chose 15 clusters and refit the model accordingly
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', delimiter=';')
customers.head()
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, ...
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', delimiter=';')
feat_info['missing_or_unknown'] = feat_info['missing_or_unknown'].apply(lambda x: x[1:-1].split(','))
# Identify missing or unknown data values and convert them to NaNs.
for attrib, missing_values in zip(feat_info['attribute'], feat_info['missing_or_unknown']):
if missing_values[0] != '':
for value in missing_values:
if value.isnumeric() or value.lstrip('-').isnumeric():
value = int(value)
azdias.loc[azdias[attrib] == value, attrib] = np.nan
# remove selected columns and rows, ...
#Columns
columns_removed = ['AGER_TYP', 'GEBURTSJAHR', 'TITEL_KZ',
'ALTER_HH', 'KK_KUNDENTYP', 'KBA05_BAUMAX',
'CAMEO_DEU_2015']
for col in columns_removed:
df.drop(col, axis=1, inplace=True)
#Rows
few_missing = df[df.isnull().sum(axis=1) < 10].reset_index(drop=True)
#interpolate and impute the NaNs
for col in few_missing.columns:
few_missing[col] = few_missing[col].interpolate(limit_direction='both')
# select, re-encode, and engineer column values.
#drop non categorical
non_binary_cols = ['CJT_GESAMTTYP','FINANZTYP','GFK_URLAUBERTYP','LP_FAMILIE_FEIN',
'LP_FAMILIE_GROB','LP_STATUS_FEIN','LP_STATUS_GROB','NATIONALITAET_KZ',
'VERS_TYP','ZABEOTYP','GEBAEUDETYP','CAMEO_DEUG_2015']
for col in non_binary_cols:
few_missing.drop(col, axis=1, inplace=True)
#Reencode the categorical and get dummies for the shopper type
few_missing.loc[:, 'OST_WEST_KZ'].replace({'W':0, 'O':1}, inplace=True);
few_missing['SHOPPER_TYP'] = few_missing['SHOPPER_TYP'].round()
few_missing = pd.get_dummies(data=few_missing, columns=['SHOPPER_TYP'])
# Complete the mapping process of mixed features
few_missing['PRAEGENDE_JUGENDJAHRE_decade'] = few_missing['PRAEGENDE_JUGENDJAHRE'].apply(map_gen)
few_missing['PRAEGENDE_JUGENDJAHRE_movement'] = few_missing['PRAEGENDE_JUGENDJAHRE'].apply(map_mov)
few_missing.drop('PRAEGENDE_JUGENDJAHRE', axis=1, inplace=True)
few_missing['CAMEO_INTL_2015_wealth'] = few_missing['CAMEO_INTL_2015'].apply(map_wealth)
few_missing['CAMEO_INTL_2015_lifestage'] = few_missing['CAMEO_INTL_2015'].apply(map_lifestage)
few_missing.drop('CAMEO_INTL_2015', axis=1, inplace=True)
few_missing['WOHNLAGE_rural'] = few_missing['WOHNLAGE'].apply(map_rur)
few_missing['WOHNLAGE_neigh'] = few_missing['WOHNLAGE'].apply(map_neigh)
few_missing.drop('WOHNLAGE', axis=1, inplace=True)
#drop mixed
mixed = ['LP_LEBENSPHASE_FEIN','LP_LEBENSPHASE_GROB','PLZ8_BAUMAX']
for col in mixed:
few_missing.drop(col, axis=1, inplace=True)
# interpolate again to clean the data set
for col in few_missing.columns:
few_missing[col] = few_missing[col].interpolate(limit_direction='both')
# Return the cleaned dataframe.
return few_missing
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
#this takes a while
start_time = time.time()
customers_clean = clean_data(customers)
print("--- Run time: %s mins ---" % np.round(((time.time() - start_time)/60),2))
customers_clean.head()
customers_clean.isnull().sum().sum()
customers_clean.describe()
customers_clean.drop('SHOPPER_TYP_-1', axis=1, inplace=True)
customers_clean.columns
customers_clean.head()
#normalization using StandardScaler
customers_clean[customers_clean.columns] = scaler.transform(customers_clean[customers_clean.columns].as_matrix())
#transform the customers data using pca object
customers_clean_pca = pca.transform(customers_clean)
#predict clustering using the kmeans object
predict_customers = model_general.predict(customers_clean_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.def plot_scaled_comparison(df_sample, kmeans, cluster):
X = pd.DataFrame.from_dict(dict(zip(df_sample.columns,
pca.inverse_transform(kmeans.cluster_centers_[cluster]))), orient='index').rename(
columns={0: 'feature_values'}).sort_values('feature_values', ascending=False)
X['feature_values_abs'] = abs(X['feature_values'])
pd.concat((X['feature_values'][:10], X['feature_values'][-10:]), axis=0).plot(kind='barh');
plot_scaled_comparison(customers_clean, kmeans, 14)
# 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_port = []
customers_port = []
x = [i+1 for i in range(20)]
for i in range(20):
general_port.append((predict_general == i).sum()/len(predict_general))
customers_port.append((predict_customers == i).sum()/len(predict_customers))
df_general = pd.DataFrame({'cluster' : x, 'propotion_general' : general_port, 'proportion_customers':customers_port})
#ax = sns.countplot(x='index', y = df_general['prop_1', 'prop_2'], data=df_general )
df_general.plot(x='cluster', y = ['propotion_general', 'proportion_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?
data = scaler.inverse_transform(pca.inverse_transform(customers_clean_pca[np.where(predict_customers==8)])).round()
df = pd.DataFrame(data=data,
index=np.array(range(0, data.shape[0])),
columns=few_missing.columns)
df.head(10)
data_2 = scaler.inverse_transform(pca.inverse_transform(few_missing_pca[np.where(predict_general==8)])).round()
df_2 = pd.DataFrame(data=data_2,
index=np.array(range(0, data_2.shape[0])),
columns=few_missing.columns)
df_2.head(10)
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
data_3 = scaler.inverse_transform(pca.inverse_transform(customers_clean_pca[np.where(predict_customers==13)])).round()
df = pd.DataFrame(data=data_3,
index=np.array(range(0, data_3.shape[0])),
columns=few_missing.columns)
df.head(10)
data_4 = scaler.inverse_transform(pca.inverse_transform(few_missing_pca[np.where(predict_general==13)])).round()
df = pd.DataFrame(data=data_4,
index=np.array(range(0, data_4.shape[0])),
columns=few_missing.columns)
df.head(10)
I think clusters 8, 1,and 2 are the most popular with the company. relatively speaking though, there doesn't seem to be a very clear definition of the relationship between the customers and the general population data sets. However, it is important to keep in mind that we removed a significant chunk of variables that had significant information. I think in the future, a project like should really be the result of in depth conversations and continued supervision by the client to provide better results. Nevertheless, I am still very happy with the results of the analysis and would like to believe that this work delivered significant value to the client.
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.