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).
azdias_shape=azdias.shape
feat_shape=feat_info.shape
print(f'azdias shape is {azdias_shape}. feat shape is {feat_shape}')
azdias.head(10)
feat_info.head(5)
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 --> badds a new cell after the active cell. If you need to convert an active cell to a markdown cell, useesc --> mand 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.
The following will replace the indexes with np.na in the dataframe:
feat_list = feat_info['missing_or_unknown'].tolist()
missing_list = []
for i in feat_list:
subcount = 0
i = i.replace('[', '')
i = i.replace(']', '')
i = i.split(',')
missing_list.append(i)
def replace(value, items, **kwargs):
for i in items:
try:
if value == np.int(i):
return np.nan
else:
pass
except ValueError:
if value == str(i):
return np.nan
else:
pass
return value
for col, index in zip(azdias, range(len(missing_list))):
print(col, index)
azdias.iloc[:,index] = azdias.iloc[:,index].apply(replace, items=missing_list[index], axis=1)
azdias.head(20)
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?
Rather than using a histogram which is cumbersome to plot, we can achieve the same result by finding how many missing values make up the entire column. We can sort this in descending order and we can see which columns have the most missing values.
# Perform an assessment of how much missing data there is in each column of the
# dataset.
import seaborn as sns
import matplotlib.pyplot as plt
null_col_count = azdias.isnull().sum(axis=0)
# print(null_col_count)
ax_rows = azdias.shape[0]
def findTotal(value, total):
return value/total
anomalies = null_col_count.apply(findTotal, total=ax_rows).sort_values(ascending=False)
There are six columns that I would consdier to be anomalies in terms of missing values, they are:
anomalies[0:6]
We can drop these columns:
azdias.drop(['TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX', 'GEBURTSJAHR', 'ALTER_HH'], axis=1, inplace=True)
assert azdias_shape[1]-6 == azdias.shape[1]
To find patterns we can use seaborn heatmap with pd.isnull()
azdias.shape[1]
plt.subplots(figsize=(20,15))
sns.heatmap(azdias.iloc[:,0:30].isnull(), cbar=False)
plt.subplots(figsize=(20,15))
sns.heatmap(azdias.iloc[:,30:60].isnull(), cbar=False)
plt.subplots(figsize=(20,15))
sns.heatmap(azdias.iloc[:,60:80].isnull(), cbar=False)
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
columnList = azdias.columns.values
columnPatternIndexes = [12, 13, 14, 15 ,16 , 19, 20, 36, 37, 38, 40, 41, 43, 44, 46,
46, 47, 48, 49, 50 ,51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78]
print(f'Total no. of columns with pattern in nan values: {len(columnPatternIndexes)}')
print(f'Total no. of columns without pattern in nan values: {len(columnList)-len(columnPatternIndexes)}')
# print(f'{anomalies[6:]}')
In total I found 6 columns that I determined to have unusually high levels of nan values for the data and as such I dropped them from the dataframe.
I found 47 columns that appear to have a pattern in missing data. We can see that this pattern is fairly consistent throughout the dataset.
There are a lot of columns in this data set, however looking through the data dictionary I can see that many of the categories are of the form:
N (detailed scale) or (rough scale)
where N could be anything from Wealth status to family. As the data is looking at regional areas, it makes sense that if data is missing for one area, it would be missing for all the other categories as well.
For example, PLZ8_ANTG1, PLZ8_ANTG2 and PLZ8_ANTG3 all describe the number of family houses in the PLZ8 region by size of family (1-2 people, 3-5 people etc). If this information is missing in PLZ8_ANTG1, then it makes sense that is also missing in the same region for the other categories. This could explain why we see patterns throughout the entire 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.
We can repeat what we did above but for the rows. I will transpose the dataframe and repeat the same steps as before.
## Testing ignore this cell
# How much data is missing in each row of the dataset?
null_row_count = azdias.isnull().sum(axis=1)
null_row_count = pd.DataFrame(null_row_count)
null_row_count.columns = ['null_count']
# null_row_count.sample(frac=1).head(30)
# null_row_count.groupby('null_count').agg({'null_count': 'count'})
azdiasT = azdias.transpose()
azdiasT.head(2)
null_row_count = azdiasT.isnull().sum(axis=0)
axT_rows = azdiasT.shape[0]
print(axT_rows)
print(null_row_count.head(5))
print()
print(null_row_count.shape)
anomaliesT_f = null_row_count.apply(findTotal, total=axT_rows).sort_values(ascending=False)
anomaliesT_f.head(5)
anomaliesT_f = pd.DataFrame(anomaliesT_f)
# anomaliesT.iloc[0:5,0]
print(anomaliesT_f.describe())
for i in range(85, 92):
print(f'{i}% percentile: {anomaliesT_f.quantile(q=i*0.01)[0]:.4f}')
limit = anomaliesT_f.quantile(q=0.9)[0]
print(f'\nLimit is {limit}')
As there is a much larger jump from the 89th to 90th percentile (a factor of around 113%) I would say our threshold for the split for the rows should be those which have 43% or higher missing values of the total data in the top category (denoted as anomaliesU), and those that are less than 43% in the bottom category (denoted as anomaliesL).
import collections
print(collections.Counter(null_row_count))
We will now split the dataframe into 2 categories, and then compare the columns of the original matrix like before
# Write code to divide the data into two subsets based on the number of missing
# values in each row.a
anomaliesU = anomaliesT_f[(anomaliesT_f>=limit)]
anomaliesU.dropna(inplace=True)
print(anomaliesU.describe())
anomaliesL = anomaliesT_f[(anomaliesT_f<limit)]
anomaliesL.dropna(inplace=True)
print(anomaliesL.describe())
We check that our dataframes match the original row totals:
assert ((anomaliesL.shape[0] + anomaliesU.shape[0]) == azdias.shape[0])
print(f'We have droped {100*anomaliesU.shape[0]/azdias.shape[0]:.0f}% of rows')
As we took the 90th percentile, this confirms we have dropped the right amount. I am unsure at this stage if we have dropped too much. For the sake of the project I will commit to the values I initially chose, and only revise this later if we see a huge detriment to the model.
# anomaliesT.iloc[anomaliesU.index]
anomaliesU = azdias.iloc[anomaliesU.index]
print(anomaliesU.shape)
print(anomaliesU.sample(frac=True).head(10))
anomaliesL = azdias.iloc[anomaliesL.index]
print(anomaliesL.shape)
print(anomaliesL.sample(frac=True).head(10))
As directed, we will now look at collumns against these two groups. Recall that we have columnPatternIndexes as a list of columns that have a lot of missing values from before, we can drop these columns and sample at random against the remaining columns to see if we can see anything interesting.
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
print(f'Number of cols to drop: {len(columnPatternIndexes)}')
anomaliesL_compare = anomaliesL.drop(anomaliesL.iloc[:,columnPatternIndexes], axis=1)
print(f'Number of cols kept: {anomaliesL_compare.shape[1]}')
anomaliesL_compare.head(10)
import random
def dataComparison(df):
cols = random.sample(list(df.columns.values), 5)
f, axes = plt.subplots(1, 5, figsize=(25,4))
for i in range(0, 5):
sns.countplot(x=cols[i], data=df.fillna('Missing'), ax=axes[i])
Let's look at the data distribution for the Lower group (those that don't have many zero values across the rows)
import itertools
for _ in itertools.repeat(None, 5):
dataComparison(anomaliesL_compare)
Now the same for the upper group
print(f'Number of cols to drop: {len(columnPatternIndexes)}')
anomaliesU_compare = anomaliesU.drop(anomaliesU.iloc[:,columnPatternIndexes], axis=1)
print(f'Number of cols kept: {anomaliesU_compare.shape[1]}')
anomaliesU_compare.head(10)
for _ in itertools.repeat(None, 5):
dataComparison(anomaliesU_compare)
There is a huge distance that is faily easy to visualise from the above graphs. We can see that the group that is below the threshold looks very reasonable. Without doing any specific statistical analysis we can see that across most columns, the data is fairly evenly spread. With a good mix between the columns - the point to take away is across the columns, the data doesn't look to follow a pattern.
Looking at the group which contains the rows above the threshold we can see immediately the data is largely dominated by a single value in each column. Looking at the column ANZ_HAUSHALTE_AKTIV we can see that this column is dominated with missing values exlusively from this rows. This means that all the information we have for this column will come from the other set of rows.
This is a very interesting factor in our data. If we think about it, if a row has a large number of missing values, then there must be only a few cells in that row that contain the information. If we take the columns that we know contain mostly data and not many nan values (as we have exlucded both of these earlier on), then we can see that these rows account for the dominating value.
We can see this from the above graph where SEMIO_Lust is dominated with the value 5 in these upper rows, whereas in the lower group SEMIO_Lust is fairly evenly spread out, with 6, 7 being the two highest values and 5 actually being second from the bottom.
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?
collections.Counter(feat_info['type'].values)
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?
feat_info_cat = feat_info[(feat_info['type']=='categorical')]
feat_info_cat
We pick the attribute column, which gives us the columns for our data.
We need to remember to drop the columns from this list that we removed at the start of the project, as they were mostly missing values.
categorical_cols = feat_info_cat['attribute'].tolist()
drop_cols = ['AGER_TYP', 'TITEL_KZ', 'KK_KUNDENTYP']
for i in drop_cols:
categorical_cols.remove(i)
print(categorical_cols)
print(len(categorical_cols))
We will drop from this list the columns that contain just two values. Note I am dropping them if the length of their unique values is equal to 2. This is because we know that we do not have any columns that have a length of two with non numeric values. This method would not extend to a case where we have 2 non-numeric values
# Re-encode categorical variable(s) to be kept in the analysis.
for i in categorical_cols:
print(f'{i}\nValues: {azdias[i].unique()}\nLength: {len(azdias[i].unique())}')
if len(azdias[i].unique()) == 2:
categorical_cols.remove(i)
print('\n Columns to reencode as dummies:', categorical_cols)
len(categorical_cols)
azdias[categorical_cols].head(5)
azdias_cat_dummies = pd.get_dummies(azdias[categorical_cols].astype(str))
azdias_cat_dummies.head(5)
There were 18 of the type 'categorical' that we needed to work with. They were:
['ANREDE_KZ', 'CJT_GESAMTTYP', 'FINANZTYP', 'GFK_URLAUBERTYP', 'GREEN_AVANTGARDE', 'LP_FAMILIE_FEIN', 'LP_FAMILIE_GROB', 'LP_STATUS_FEIN', 'LP_STATUS_GROB', 'NATIONALITAET_KZ', 'SHOPPER_TYP', 'SOHO_KZ', 'VERS_TYP', 'ZABEOTYP', 'GEBAEUDETYP', 'OST_WEST_KZ', 'CAMEO_DEUG_2015', 'CAMEO_DEU_2015']
ANREDE_KZ was binary numerical so we were able to drop it.
CAMEO_DEU_2015 had multiple strings as its values. We will use dummy variables on this.
The remaining 16 columns were multi-level categoricals. I used pd.get_dummies() to convert these to dummy variables.
These 16 become 148 columns of dummy variables. All we need to do now is to drop the columns from the original dataframe, and replace them with these.
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.
feat_info_mixed = feat_info[(feat_info['type']=='mixed')]
feat_info_mixed
mixed_cols = feat_info_mixed['attribute'].tolist()
# drop_cols = ['AGER_TYP', 'TITEL_KZ', 'KK_KUNDENTYP']
# for i in drop_cols:
# mixed_cols.remove(i)
print(mixed_cols)
print(len(mixed_cols))
def PRAEGENDE_JUGENDJAHRE_decade(value, **kwargs):
if (value == 1) or (value == 2):
return 40
elif (value == 3) or (value == 4):
return 50
elif (value == 5) or (value == 6) or (value == 7):
return 60
elif (value == 8) or (value == 9):
return 70
elif (value == 10) or (value == 11):
return 80
elif (value == 12) or (value == 13):
return 80
elif (value == 14) or (value == 15):
return 90
else:
return value
azdias['PRAEGENDE_JUGENDJAHRE_decade'] = azdias.loc[:,'PRAEGENDE_JUGENDJAHRE'].apply(PRAEGENDE_JUGENDJAHRE_decade, axis=1)
azdias['PRAEGENDE_JUGENDJAHRE_decade'].head(5)
def PRAEGENDE_JUGENDJAHRE_movement(value, **kwargs):
if (value == 1) or (value == 3) or (value == 5) or (value == 8) or (value == 10) or (value == 12) or (value == 14):
return 'mainstream'
elif (value == 2) or (value == 4) or (value == 6) or (value == 7) or (value == 9) or (value == 11) or (value == 13) or (value == 15):
return 'avantgarde'
else:
return value
azdias['PRAEGENDE_JUGENDJAHRE_movement'] = azdias.loc[:,'PRAEGENDE_JUGENDJAHRE'].apply(PRAEGENDE_JUGENDJAHRE_movement, axis=1)
azdias['PRAEGENDE_JUGENDJAHRE_movement'].head(5)
azdias.iloc[0:5, -2:]
Similar process to the one above
def CAMEO_INTL_2015_wealth(value, **kwargs):
if pd.isnull(value):
return value
else:
return value[0]
def CAMEO_INTL_2015_life(value, **kwargs):
if pd.isnull(value):
return value
else:
return value[-1]
azdias['CAMEO_INTL_2015_wealth'] = azdias.loc[:,'CAMEO_INTL_2015'].apply(CAMEO_INTL_2015_wealth, axis=1)
azdias['CAMEO_INTL_2015_wealth'].head(5)
azdias['CAMEO_INTL_2015_life'] = azdias.loc[:,'CAMEO_INTL_2015'].apply(CAMEO_INTL_2015_life, axis=1)
azdias['CAMEO_INTL_2015_life'].head(5)
Let's verify that we did it correctly:
azdias['CAMEO_INTL_2015'].iloc[0:5][:]
Let's create our dummy variables form these new columns
newCols = ['PRAEGENDE_JUGENDJAHRE_movement', 'PRAEGENDE_JUGENDJAHRE_decade', 'CAMEO_INTL_2015_wealth', 'CAMEO_INTL_2015_life']
azdias[newCols].head(5)
azdias_mixed_dummies = pd.get_dummies(azdias[newCols].astype(str))
azdias_mixed_dummies.head(5)
(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?)
I performed the following steps:
We converted the remaining categories to dummy variables
For the mixed data
All that remains is to drop the columns in categorical_cols and mixed_cols and replace them with azdias_cat_dummies and azdias_mixed_dummies
For the sake of simplicity I will drop the remaining mixed columns and not do any further work on them
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.)
azdias.head(2)
azdias.drop(['PRAEGENDE_JUGENDJAHRE_movement', 'PRAEGENDE_JUGENDJAHRE_decade', 'CAMEO_INTL_2015_wealth', 'CAMEO_INTL_2015_life'], axis=1)
We need to drop ['PRAEGENDE_JUGENDJAHRE_movement', 'PRAEGENDE_JUGENDJAHRE_decade', 'CAMEO_INTL_2015_wealth', 'CAMEO_INTL_2015_life']
azdias.drop(['PRAEGENDE_JUGENDJAHRE_movement', 'PRAEGENDE_JUGENDJAHRE_decade',
'CAMEO_INTL_2015_wealth', 'CAMEO_INTL_2015_life'], axis=1, inplace=True)
len(azdias.columns)
print(len(categorical_cols))
print(len(mixed_cols))
print()
print(len(azdias_cat_dummies.columns))
print(len(azdias_mixed_dummies.columns))
We have 79 cols which is what we started with after we dropped the mostly empty cols.
We need to do the following:
We know we need to drop 16+6 = 22 columns from azdias (It's 6 because we dropped one of these right at the start)
We know we need to add 148+22 = 170 columns to azdias
We know we will end up with 79-22+170=227 columns at the end
mixed_cols.remove('KBA05_BAUMAX')
mixed_cols
azdias.drop(categorical_cols, axis=1, inplace=True)
azdias.drop(mixed_cols, axis=1, inplace=True)
azdiastemp = azdias
azdiastemp.head(2)
azdiastemp = azdiastemp.join(azdias_cat_dummies)
azdiastemp = azdiastemp.join(azdias_mixed_dummies)
azdiastemp.head(5)
We have 227 cols as expected
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, ...
# remove selected columns and rows, ...
# select, re-encode, and engineer column values.
# Return the cleaned dataframe.
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.# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
# from sklearn.impute import SimpleImputer
To keep things simple I will drop any row with a null value. As long as we know that our final result may suffer because of the lack of information I am happy to do this for the sake of the project. In reality I would spend more time using an Imputer (which isn't a simple thing to do if you want to do it properly), or using another ML algorithm to predict the values we are missing.
azdiastemp.shape[0] - azdiastemp.dropna().shape[0]
azdiastemp_noNa = azdiastemp.dropna()
azdiastemp_noNa.shape
We will lose 259,095 (30%) of our rows by dropping null values
As we encoded our features from before into dummy variables, we do not need to scale these now. These are contained in the lists azdias_cat_dummies and azdias_mixed_dummies. In addition we don't need to scale GREEN_AVANTGARDE as it is a binary column with 1,0. We do need to scale ANREDE_KZ, as it is not a binary numbered value.
azdiastemp.shape
azdiastemp_noNa.drop(azdias_cat_dummies.columns, axis=1, inplace=True)
azdiastemp_noNa.drop(azdias_mixed_dummies.columns, axis=1, inplace=True)
azdiastemp_noNa.drop('GREEN_AVANTGARDE', axis=1, inplace=True)
azdiastemp_noNa.head(4)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(azdiastemp_noNa)
azdiastemp_noNa_scaled = pd.DataFrame(scaler.transform(azdiastemp_noNa), columns=azdiastemp_noNa.columns)
azdiastemp_noNa_scaled.isnull().values.any()
azdiastemp_noNa_scaled.shape
azdiastemp_noNa.shape
azdiastemp_noNa = azdiastemp.dropna()
azdiastemp_noNa.shape
azdiastemp_noNa.drop(azdiastemp_noNa_scaled.columns, axis=1, inplace=True)
azdiastemp_noNa.isnull().values.any()
azdiastemp_noNa.index
print(azdiastemp_noNa.shape)
print(azdiastemp_noNa_scaled.shape)
azdiastemp_noNa_final = pd.merge(azdiastemp_noNa.reset_index(), azdiastemp_noNa_scaled.reset_index(), right_index=True, left_index=True)
azdiastemp_noNa_final.isnull().values.any()
azdiastemp_noNa_final.drop(['index_x', 'index_y'], axis=1, inplace=True)
print(azdiastemp_noNa_final.shape)
azdiastemp_noNa_final.head(10)
My process has been explained above but we can recap here
The idea was:
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.azdiastemp_noNa_final.isnull().values.any()
Reusing some of the code from the videos here, really good way to plot the pca variance!
# Apply PCA to the data.
from sklearn.decomposition import PCA
def do_pca(n_components, data):
'''
Transforms data using PCA to create n_components, and provides back the results of the
transformation.
INPUT: n_components - int - the number of principal components to create
data - the data you would like to transform
OUTPUT: pca - the pca object created after fitting the data
X_pca - the transformed X matrix with new number of components
'''
# X = StandardScaler().fit_transform(data)
pca = PCA(n_components)
# X_pca = pca.fit_transform(X)
X_pca = pca.fit_transform(data)
return pca, X_pca
pca, df_pca = do_pca(50, azdiastemp_noNa_final)
def scree_plot(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')
scree_plot(pca)
# Re-apply PCA to the data while selecting for number of components to retain.
import copy
pca, df_pca = do_pca(30, azdiastemp_noNa_final)
df_pca_orig = copy.deepcopy(df_pca)
(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?)
Reusing the code from the videos, we can see that the first 3 features account for around 35% of the variance of the data. We see that this variance quickly falls off as we have more and more features. From the above graph I think 30 features seems a fair number of features to retain, as this should account for around 80% of the variance in the data.
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 getWeights(df, pca, weightIndex, N):
weights = pd.DataFrame(pca.components_, columns=df.columns)
weights = weights.iloc[weightIndex:weightIndex+1, :].transpose()
posWeights = weights.sort_values(weights.columns[0], ascending=False).head(N)
negWeights = weights.sort_values(weights.columns[0], ascending=True).head(N)
return posWeights, negWeights
# 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.
# and then print the linked values, sorted by weight.
p, n = getWeights(azdiastemp_noNa_final, pca, 0, 10)
p
n
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
p, n = getWeights(azdiastemp_noNa_final, pca, 1, 10)
p
n
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.
p, n = getWeights(azdiastemp_noNa_final, pca, 2, 10)
p
n
(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?)
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.from sklearn.cluster import KMeans
from joblib import dump, load
# cluster0 = KMeans(10)
# result0 = cluster0.fit_transform(df_pca)
# distance0 = np.min(result0, axis=1)
# dump(cluster0, 'cluster0')
# print(distance0)
# cluster1 = KMeans(11)
# result1 = cluster1.fit_transform(df_pca)
# distance1 = np.min(result1, axis=1)
# dump(cluster1, 'cluster1')
# print(distance1)
# cluster2 = KMeans(12)
# result2 = cluster2.fit_transform(df_pca)
# distance2 = np.min(result2, axis=1)
# dump(cluster2, 'cluster2')
# print(distance2)
# cluster3 = KMeans(13)
# result3 = cluster3.fit_transform(df_pca)
# distance3 = np.min(result3, axis=1)
# dump(cluster3, 'cluster3')
# print(distance3)
# cluster4 = KMeans(14)
# result4 = cluster4.fit_transform(df_pca)
# distance4 = np.min(result4, axis=1)
# dump(cluster4, 'cluster4')
# print(distance4)
# cluster5 = KMeans(15)
# result5 = cluster5.fit_transform(df_pca)
# distance5 = np.min(result5, axis=1)
# dump(cluster5, 'cluster5')
# print(distance5)
# cluster6 = KMeans(16)
# result6 = cluster6.fit_transform(df_pca)
# distance6 = np.min(result6, axis=1)
# dump(cluster6, 'cluster6')
# print(distance6)
# cluster7 = KMeans(17)
# result7 = cluster7.fit_transform(df_pca)
# distance7 = np.min(result7, axis=1)
# dump(cluster7, 'cluster7')
# print(distance7)
# cluster8 = KMeans(18)
# result8 = cluster8.fit_transform(df_pca)
# distance8 = np.min(result8, axis=1)
# dump(cluster8, 'cluster8')
# print(distance8)
# cluster9 = KMeans(19)
# result9 = cluster9.fit_transform(df_pca)
# distance9 = np.min(result9, axis=1)
# dump(cluster9, 'cluster9')
# print(distance9)
cluster0 = load('cluster0')
cluster1 = load('cluster1')
cluster2 = load('cluster2')
cluster3 = load('cluster3')
cluster4 = load('cluster4')
cluster5 = load('cluster5')
cluster6 = load('cluster6')
cluster7 = load('cluster7')
cluster8 = load('cluster8')
cluster9 = load('cluster9')
result0 = cluster0.transform(df_pca)
distance0 = np.min(result0, axis=1)
print(distance0)
result1 = cluster1.transform(df_pca)
distance1 = np.min(result1, axis=1)
print(distance1)
result2 = cluster2.transform(df_pca)
distance2 = np.min(result2, axis=1)
print(distance2)
result3 = cluster3.transform(df_pca)
distance3 = np.min(result3, axis=1)
print(distance3)
result4 = cluster4.transform(df_pca)
distance4 = np.min(result4, axis=1)
print(distance4)
result5 = cluster5.transform(df_pca)
distance5 = np.min(result5, axis=1)
print(distance5)
result6 = cluster6.transform(df_pca)
distance6 = np.min(result6, axis=1)
print(distance6)
result7 = cluster7.transform(df_pca)
distance7 = np.min(result7, axis=1)
print(distance7)
result8 = cluster8.transform(df_pca)
distance8 = np.min(result8, axis=1)
print(distance8)
result9 = cluster9.transform(df_pca)
distance9 = np.min(result9, axis=1)
print(distance9)
resultList = [distance0, distance1, distance2, distance3, distance4, distance5, distance6, distance7, distance8, distance9]
resultListAvg = []
for i, j in zip(resultList, range(0, len(resultList))):
resultListAvg.append(np.mean(i))
print(f'Average of {j} is: {resultListAvg[j]}')
x = range(10, 20)
plt.plot(x, resultListAvg)
plt.xlabel('Num of Clusters')
plt.ylabel('Distance to nearest cluster centre')
Unfortunately I ran into memory issues on this VM I couldn't get any further even with refreshing the workspace. If this were a real piece of work - I would go back and optimise my code (I suspect I am wasting a lot of memory here) however I don't want to go back and change things as it currently works for this project.
I am on my work laptop which is not powerful and I am unable to access my desktop at home. I hope you can see that the average distance to the centres is decreasing for increasing clusters!.
I suspect that we will soon see this decrease slow down and eventually reach an optimum number of clusters.
As such I am choosing 19 clusters for the model.
We have already got the results for this:
result9
I have explained above what I've done but I will recap.
We fitted KMeans to our final dataset starting at k=5 to k=14. Unfortunately I had to stop at k=14 due to memory problems but we can see that as we are increasing k the distance to the nearest cluster centre is decreasing. For higher k we will eventually find a sweet spot for our data.
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=';')
print(customers.shape)
customers.head(3)
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
# Fill in missing values:
for col, index in zip(customers, range(len(missing_list))):
print(col, index)
customers.iloc[:,index] = customers.iloc[:,index].apply(replace, items=missing_list[index], axis=1)
customers.head(10)
# Find missing data by col
null_col_count_cust = customers.isnull().sum(axis=0)
ax_rows_cust = customers.shape[0]
anomalies_cust = null_col_count_cust.apply(findTotal, total=ax_rows_cust).sort_values(ascending=False)
anomalies_cust[0:10]
In the original dataset we dropped anything below 34.8%, I will do the same here so we will drop the first six of the above list
As we did above, I am keeping all rows regardless of how much is missing
customers.drop(['TITEL_KZ', 'KK_KUNDENTYP', 'KBA05_BAUMAX', 'AGER_TYP', 'GEBURTSJAHR', 'ALTER_HH'], axis=1, inplace=True)
assert customers.shape[1]+6 == 85
We can now look at reencoding our categorical features
categorical_cols = feat_info_cat['attribute'].tolist()
drop_cols = ['AGER_TYP', 'TITEL_KZ', 'KK_KUNDENTYP']
for i in drop_cols:
categorical_cols.remove(i)
print(categorical_cols)
print(len(categorical_cols))
# Re-encode categorical variable(s) to be kept in the analysis.
for i in categorical_cols:
print(f'{i}\nValues: {customers[i].unique()}\nLength: {len(customers[i].unique())}')
if len(customers[i].unique()) == 2:
categorical_cols.remove(i)
print('\n Columns to reencode as dummies:', categorical_cols)
len(categorical_cols)
customers[categorical_cols].head(5)
customers_cat_dummies = pd.get_dummies(customers[categorical_cols].astype(str))
customers_cat_dummies.head(5)
feat_info_mixed = feat_info[(feat_info['type']=='mixed')]
feat_info_mixed
mixed_cols = feat_info_mixed['attribute'].tolist()
# drop_cols = ['AGER_TYP', 'TITEL_KZ', 'KK_KUNDENTYP']
# for i in drop_cols:
# mixed_cols.remove(i)
print(mixed_cols)
print(len(mixed_cols))
customers['PRAEGENDE_JUGENDJAHRE_decade'] = customers.loc[:,'PRAEGENDE_JUGENDJAHRE'].apply(PRAEGENDE_JUGENDJAHRE_decade, axis=1)
customers['PRAEGENDE_JUGENDJAHRE_decade'].head(5)
customers['PRAEGENDE_JUGENDJAHRE_movement'] = customers.loc[:,'PRAEGENDE_JUGENDJAHRE'].apply(PRAEGENDE_JUGENDJAHRE_movement, axis=1)
customers['PRAEGENDE_JUGENDJAHRE_movement'].head(5)
customers.iloc[0:5, -2:]
customers['CAMEO_INTL_2015_wealth'] = customers.loc[:,'CAMEO_INTL_2015'].apply(CAMEO_INTL_2015_wealth, axis=1)
customers['CAMEO_INTL_2015_wealth'].head(5)
customers['CAMEO_INTL_2015_life'] = customers.loc[:,'CAMEO_INTL_2015'].apply(CAMEO_INTL_2015_life, axis=1)
customers['CAMEO_INTL_2015_life'].head(5)
customers['CAMEO_INTL_2015'].iloc[0:5][:]
newCols = ['PRAEGENDE_JUGENDJAHRE_movement', 'PRAEGENDE_JUGENDJAHRE_decade', 'CAMEO_INTL_2015_wealth', 'CAMEO_INTL_2015_life']
customers[newCols].head(5)
customers_mixed_dummies = pd.get_dummies(customers[newCols].astype(str))
customers_mixed_dummies.head(5)
customers.drop(['PRAEGENDE_JUGENDJAHRE_movement', 'PRAEGENDE_JUGENDJAHRE_decade',
'CAMEO_INTL_2015_wealth', 'CAMEO_INTL_2015_life'], axis=1, inplace=True)
len(customers.columns)
print(len(categorical_cols))
print(len(mixed_cols))
print()
print(len(customers_cat_dummies.columns))
print(len(customers_mixed_dummies.columns))
mixed_cols.remove('KBA05_BAUMAX')
mixed_cols
customers.drop(categorical_cols, axis=1, inplace=True)
customers.drop(mixed_cols, axis=1, inplace=True)
customerstemp = customers
customerstemp.head(2)
customerstemp = customerstemp.join(customers_cat_dummies)
customerstemp = customerstemp.join(customers_mixed_dummies)
customerstemp.head(5)
We will now apply feature scaling
print(customerstemp.shape[0] - customerstemp.dropna().shape[0])
customerstemp_noNa = customerstemp.dropna()
customerstemp_noNa.shape
customerstemp_noNa.drop(customers_cat_dummies.columns, axis=1, inplace=True)
customerstemp_noNa.drop(customers_mixed_dummies.columns, axis=1, inplace=True)
customerstemp_noNa.drop('GREEN_AVANTGARDE', axis=1, inplace=True)
customerstemp_noNa.head(4)
scalerCust = StandardScaler()
scalerCust.fit(customerstemp_noNa)
customers_noNa_scaled = pd.DataFrame(scaler.transform(customerstemp_noNa), columns=customerstemp_noNa.columns)
customers_noNa_scaled.isnull().values.any()
customerstemp_noNa = customerstemp.dropna()
customerstemp_noNa.drop(customers_noNa_scaled.columns, axis=1, inplace=True)
customerstemp_noNa.isnull().values.any()
customerstemp_noNa_final = pd.merge(customerstemp_noNa.reset_index(), customers_noNa_scaled.reset_index(), right_index=True, left_index=True)
customerstemp_noNa_final.isnull().values.any()
customerstemp_noNa_final.drop(['index_x', 'index_y'], axis=1, inplace=True)
print(customerstemp_noNa_final.shape)
customerstemp_noNa_final.head(10)
pca, df_pca = do_pca(30, customerstemp_noNa_final)
df_pca.shape
Now we can apply kmeans on our fitted model from before!
cluster9
resultCust = cluster9.transform(df_pca)
customerClusters = cluster9.predict(df_pca)
popClusters = cluster9.labels_
This plot shows us the number of points in each cluster. It is not very useful as we need to scale them so they represent a percentage which we will do below
testDf = pd.DataFrame(customerClusters, columns=['Cluster'])
print(testDf.nunique())
testDf[testDf['Cluster'] == 18]
pd.value_counts(testDf['Cluster'])
f, axes = plt.subplots(1, 2, figsize=(25, 10))
sns.countplot(x=customerClusters, ax=axes[0])
sns.countplot(popClusters, ax=axes[1])
index_cust=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18]
print(len(customerClusters))
print(len(df_pca))
def findClusterPerc(clusterSeries, df_pca, index=False):
testDf = pd.DataFrame(clusterSeries, columns=['Cluster'])
if index is False:
return pd.DataFrame((pd.DataFrame(pd.value_counts((testDf['Cluster'].values))).values/len(df_pca)), columns=['Cluster'])
else:
return pd.DataFrame((pd.DataFrame(pd.value_counts((testDf['Cluster'].values))).values/len(df_pca)), columns=['Cluster'], index=index)
customerClustersPerc = findClusterPerc(customerClusters, df_pca, index=index_cust)
popClustersPerc = findClusterPerc(popClusters, df_pca_orig)
customerClustersPerc
# popClustersPerc
f, axes = plt.subplots(1, 2, figsize=(25, 10))
sns.barplot(y=customerClustersPerc['Cluster'], x=customerClustersPerc.index, ax=axes[0])
sns.barplot(y=popClustersPerc['Cluster'], x=popClustersPerc.index, ax=axes[1])
We can see that in the left graph which represents the customer data, there are relatively more people towards the first clusters. On the right which represents our population data, it is more evenly spread out between the clusters.
print(pd.DataFrame(df_pca_orig).index.max())
print(anomaliesU_compare.index.max())
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.
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
(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?)
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.