Pre-Processing and Model Training using Python
Understanding data pre-processing and it’s importance in model training
Pre-processing and model training go hand in hand in machine learning to mean that one cannot do without the other. The thing is, we humans interact with data we can understand, that is data written in natural language, and we expect our machine learning models to take in the same data and give us some insights. Well, machines only understand binary language (0s and 1s) and there must be a way for the machines to understand this same data. That’s where pre-processing comes in. Pre-processing is basically transforming the data in natural language to a form the machine can understand. This process is also referred to as encoding.
So how do we do pre-processing and model training to get insights from data? There are multiple ways to pre-process data and train machine learning models, for sure I don’t know all of them. In this post, we’ll look at some of the pre-processing methods and explore three machine learning algorithms we can use to train a model. Therefore, we’ll look into:
Pre-Processing
- Data Cleaning
- Categorical features encoding using OneHotEncoder
- Numerical features scaling using StandardScaler
- Dimensionality reduction using PCA, T-SNE and Autoencoders
- Balancing classes by oversampling
- Feature Extraction
Model Training
- Logistic Regression
- Random Forests
- Decision Trees
For this post, we will be using bank campaign data which can be found here. In addition to the data, the source gives a full description of the features in the data. In brief, our data consist of 20 features describing a customer, 10 categorical features and 10 numerical features, and the target variable. Our target variable is a representation of whether a customer subscribed to a term deposit or not. The goal of this project would be to predict on which future customers will subscribe to the term deposits. For a full Exploratory Data Analysis of our dataset you can check my Tableau Dashboard or go through the same on this GitHub repository. This post will only focus on pre-processing and model training.
Pre-Processing
Data Cleaning
Data cleaning involves checking for missing values in a dataset and dropping the null rows or imputing the missing values depending on how many they are and their significance in our data. Data cleaning also involves looking for duplicates in our data and dropping them as they may significantly affect the effectiveness of the model. Data cleaning also involves checking for outliers in our data and replacing the data with median or mean based on how frequent they occur. This are just some of the few ways of data cleaning that we will explore in this post.
Missing Values
We can check for missing values in our data by calling dataset.info() and inspecting all the features in our dataset or simply running dataset.isnull().values.any() which will return True if there’s any null values in our dataset or False if there is none. We can then decide to drop values which contain unique data, or impute categorical features with mode data and numerical features with mean data. Our bank dataset has no missing values and we therefore, proceed to the next step.
Duplicated Data
Check for duplicated rows in your data using dataset[dataset.duplicated()] . Our bank data has 12 duplicated rows, therefore, we can go ahead and drop the rows using dataset = dataset.drop_duplicates() and assigning the resulting data to our dataset variable as the new dataset.
Outlier Detection
It is easy to detect outliers in numerical features by simply ploting a box plot of the features. I have defined a function that can help you plot all the boxplots of your numerical features, you just have to pass your dataset and the name of the features to the function. The function is:
def plot_outliers(data, features):
fig, ax = plt.subplots(len(features), figsize = (8, 40))
for i, feature in enumerate(features):
sns.boxplot(y = data[feature], ax = ax[i])
ax[i].set_title('Box plot - {}'.format(feature), fontsize = 10)
ax[i].set_xlabel(feature, fontsize = 8)
plt.show()We can then go ahead and replace the outliers with median value if the outliers are many and with the mean value if the outliers are not many. The following function will automate this process for you. You just need to pass in your data, the features with outliers to be replaced and indicate whether you’re replacing with mean or with median.
def replace_outlier(data, features, with_median=False, with_mean=False):
for feature in features:
Q1 = data[feature].quantile(0.25)
Q3 = data[feature].quantile(0.75)
median = data[feature].quantile(0.50)
mean = data[feature].mean()
IQR = Q3 - Q1
upper_whisker = Q3 + (1.5 * IQR)
lower_whisker = Q1 - (1.5 * IQR)
if with_median:
data[feature] = np.where(data[feature] > upper_whisker, median, data[feature])
data[feature] = np.where(data[feature] < lower_whisker, median, data[feature])
if with_mean:
data[feature] = np.where(data[feature] > upper_whisker, mean, data[feature])
data[feature] = np.where(data[feature] < lower_whisker, mean, data[feature])Categorical Features Encoding using OneHotEncoder
Encoding of categorical features is done by transforming the categorical values to binary values. OneHotEncoder achieves this by creating a separate column with binary values for each category in a feature. In the new column, the value 1 represents that the catogory is present and 0 indicates its absence. For instance in our bank data, one of the categorical features is marital which has four possible categories; ‘married’, ‘single’, ‘divorced’ and ‘unknown’. For each of these categories, OneHotEncoder creates a new column and uses 1 where the category was present and 0 for otherwise.
OneHotEncoding can be achieved through a number of ways such as using get_dummies in pandas. However, this post will use CountVectorizer, a better approach in comparison to get_dummies since get_dummies returns data with different dimensions.
Once again, using the following functions you can easily OneHotEncode your categorical features, you only need to pass in the naes of your categorical features, the X_train set and the X_test set.
from sklearn.feature_extraction.text import CountVectorizerdef add_onehot_to_dataframe(sparse, df, vectorizer, name):
'''
This function will add the one hot encoded to the dataframe.
'''
for i, col in enumerate(vectorizer.get_feature_names()):
colname = name+"_"+col
# df[colname] = pd.SparseSeries(sparse[:, i].toarray().flatten(), fill_value=0)
df[colname] = sparse[:, i].toarray().ravel().tolist()
return dfdef OneHotEncoder(categorical_cols, X_train, X_test):
'''
This function takes categorical column names as inputs. The objective of this function is to take the column names iteratively and encode the features using One hot Encoding mechanism and also adding the encoded feature to the respective dataframe.
'''for i in categorical_cols:
Vectorizer = CountVectorizer(token_pattern="[A-Za-z0-9-.]+")
print("Encoding for feature: ", i)
# Encoding training dataset
temp_cols = Vectorizer.fit_transform(X_train[i])
X_train = add_onehot_to_dataframe(temp_cols, X_train, Vectorizer, i)
# Encoding Test dataset
temp_cols = Vectorizer.transform(X_test[i])
X_test = add_onehot_to_dataframe(temp_cols, X_test, Vectorizer, i)
Numerical Features Scaling using StandardScaler()
Each numerical feature in a dataset is usually measured on different scales and this may cause some biasness while training the model. Therefore it is advisable to always normalize your data by either using MinMaxScaler() or StandardScaler() In this post, we will use the StandardScaler() with the code snippet below to achieve normalization in our numerical features.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()numerical_cols = ['age', 'duration', 'campaign', 'pdays', 'previous', 'emp.var.rate', 'cons.price.idx', 'cons.conf.idx', 'euribor3m', 'nr.employed']
#normalizing train set
X_train = X_train.reset_index()
temp_df = X_train.filter(numerical_cols, axis = 1)
X_train = X_train.drop(numerical_cols, axis = 1)
cols = temp_df.values
temp_cols = scaler.fit_transform(cols)
temp_df = pd.DataFrame(temp_cols, columns = numerical_cols)
X_train = X_train.merge(temp_df, left_index=True, right_index=True)
X_train = X_train.drop(['index'], axis=1)
#normalizing test set
X_test = X_test.reset_index()
temp_df = X_test.filter(numerical_cols, axis = 1)
X_test = X_test.drop(numerical_cols, axis = 1)
cols = temp_df.values
temp_cols = scaler.fit_transform(cols)
temp_df = pd.DataFrame(temp_cols, columns = numerical_cols)
X_test = X_test.merge(temp_df, left_index=True, right_index=True)
X_test = X_test.drop(['index'], axis=1)
Dimensionality Reduction
This pre-processing technique involves transforming high dimensional data to a low dimensional data while still maintaining a good representation of the entire dataset. There are several dimensionality reduction techniques but this post will only go through PCA (Principal Component Analysis), t-SNE (t-distributed Stochastic Neighbor Embedding) and Autoencoders.
PCA (Principal Component Analysis)
The following code reduced the dimension of our data to a 2D. the n_components attribute is the section used to specify the number of components the data should be reduced to.
from sklearn.decomposition import PCApca = PCA(n_components=2)
X_pca_2train = pca.fit_transform(X_train)
PCA_df_2train = pd.DataFrame(data = X_pca_2train, columns = ['PC1', 'PC2'])
PCA_df_2train = pd.concat([PCA_df_2train, y_train], axis = 1)
PCA also offers a way of inspecting the variance ratio preserved by the selected components and this can be done through : pca.explained_variance_ratio_ For our code above the output of this variance is out[]: [0.29620347 0.09104375] indicating that 29.62% of our data is represented by component 1 and only 9.10% is represented by component 2.
We can also plot the resulting distribution of our PCA using the following code:
plt.figure(figsize=(8, 8))classes = [1, 0]
colors = ['r', 'b']
for clas, color in zip(classes, colors):
plt.scatter(PCA_df_2train.loc[PCA_df_2train['y'] == clas, 'PC1'],
PCA_df_2train.loc[PCA_df_2train['y'] == clas, 'PC2'],
c = color)
plt.xlabel('Principal Component 1', fontsize = 12)
plt.ylabel('Principal Component 2', fontsize = 12)
plt.title('2D PCA', fontsize = 15)
plt.legend(['Subscription', 'No Subscription'])
plt.grid()
The above code gave us the following plot:
You can see from the above plot that the distinction between the two outputs is not as clear and therefore using two components may not be the best option.
To get the ideal number of components to use for your dimensionality reduction you can use PCA without asigning a value to n_components and plot the explained variance ratio of the data as illustred by the code snippet below:
pca = PCA()
pca_data = pca.fit_transform(X_train)
plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')This code resulted in the following plot:
We can see from the above plot that using close to 30 components is what will give us 100% representation of the data. 10 componenets also have a good representation at nearly 80%. After analyzing this plot you can then run PCA again, this time assigning n_components to the ideal number of components for better data representation.
t-SNE (t-distributed Stochastic Neighbor Embedding)
Get Anastasia Kiiru’s stories in your inbox
Join Medium for free to get updates from this writer.
Unlike PCA, t-SNE is a non-linear dimensionality reduction technique. To apply t-SNE dimensionality reduction to your data, use the following code snippet and specify the number of components using n_components.
tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=300)
X_tsne_2train = tsne.fit_transform(X_train)To inspect the distribution of the t-SNE using visualization use the following code:
plt.figure(figsize=(8,8))
plt.scatter(X_tsne_2train[:, 0], X_tsne_2train[:, 1], c=y_train.values)
plt.show()The above code gives us a plot like the one below:
The distinction is also not as clear between the two classes just as indicated by PCA and it might therefore be better using more components.
Autoencoders
Autoencoders are machine learning algorithms which can be used for dimensionality reduction. They use non-linear transformations to project data from high dimensions to lower dimensions. There are different types of autoencoders such as; Variational Autoencoder, Convolutional Autoencoder, Denoising Autoencoder, and Sparse Autoencoder. In this post, we’ll just build a basic Autoencoder which contains 2 main components: encoder and decoder.
Autoencoders use Keras API in python, therefore, ensure you have Keras and tensorflow installed in your environment before running the following code. Installation of the two can easily be done on Jupyter notebook by running !pip install keras and !pip install tensorflow for python 3.7 and anaconda3 environment.
from keras.layers import Input, Dense
from keras.models import ModelX = pd.concat([X_train, X_test], ignore_index=True)input_layer = Input(shape=(X.shape[1],))
encoded = Dense(3, activation='relu')(input_layer)
decoded = Dense(X.shape[1], activation='softmax')(encoded)
autoencoder = Model(input_layer, decoded)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')X1, X2, Y1, Y2 = train_test_split(X, X, test_size=0.3, random_state=101)autoencoder.fit(X1, Y1,
epochs=100,
batch_size=300,
shuffle=True,
verbose = 30,
validation_data=(X2, Y2))encoder = Model(input_layer, encoded)
X_ae3 = encoder.predict(X)
Notice that I concat my train and test set because Autoencoders take the input feature (X) as both the feature and the label. We’ve also used ReLu activation function for our encoder and Softmax for our decoder to achieve a non-linear transformation.
Balancing Classes by Oversampling
From our data exploration, we noticed that our target variable was imbalanced with a ratio of 89:11 for no subscription to subscription. Class imbalance also affectcs model training and we’ll therefore have to balance our target variable. Some ML algorithms like the Logistic Regression algorithms comes with an attribute for balancing the class; that is LogisticRegression(class_weight='balanced') and we can use this option for such models, otherwise, we have to balance our clases by other methods such as undersamplin and oversampling. In this scenario will use use SMOTE to oversample our class as shown in the code below:
from imblearn.over_sampling import SMOTEos = SMOTE(random_state = 0)columns = X_train.columns
os_data_X, os_data_y = os.fit_sample(X_train, y_train)
os_data_X = pd.DataFrame(data=os_data_X, columns=columns)
os_data_y = pd.DataFrame(data=os_data_y, columns=['y'])
Feature Extraction
Feature extraction involves selecting a few features from the entire dataset to be used for model training. This features are selected based on their importance in predicting the target variable. This post will explore RFE method for feature extraction. The code below selects the top 20 important features by repeatedly fiting the training data and seleceting the top feature then droping it in the next round until 20 features are selected.
from sklearn.feature_selection import RFErfe = RFE(logreg, n_features_to_select=20)
rfe = rfe.fit(X_train, y_train)
rank = rfe.ranking_
Model Training
Next we move on to model training where we will explore three machine learning algorithms as listed earlier.
Logistic Regression
First, it is important to note that for our dataset, the ‘duration’ column should not be used for model training, therefore, we drop it from our training data simply by using the following code:
#Removing duration feature from dataset#From train
X_train = X_train.drop('duration', axis=1)#From test
X_test = X_test.drop('duration', axis=1)
Then we apply a logistic regression algorithm to our data. Remember, this model has an inbuilt method for handling imbalanced data and therefore, we’ll use it.
from sklearn.linear_model import LinearRegressionlogreg = LogisticRegression(class_weight='balanced')
logreg.fit(X_train, y_train)
y_pred_logreg = logreg.predict_proba(X_test)
We can test the accuracy of our model by using the ROC (Receiver Operating Characteristic) score
from sklearn.metrics import roc_auc_scoreprint('AUC score without duration columns : ', roc_auc_score(y_test, y_pred_logreg[:, 1]))
We can also plot the ROC curve for more insights from the model using the code below.
from sklearn.metrics import roc_curvelogit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))
fpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig('Log_ROC')
plt.show()
The above code generates the following plot:
The dotted line is a representation of a ROC curve for a purely random classifier. A good classifier should be far from this line.
Random Forests
Random forests are among the classifiers that come with the scikit-learn library, therefore, to run this model we just call the classifier form the library as shown below:
from sklearn.ensemble import RandomForestClassifierrfclf = RandomForestClassifier(class_weight='balanced', max_depth=2, random_state=0)
rf_model = rfclf.fit(X_train, y_train)y_pred_rf=rfclf.predict(X_test)
We can test the accuracy of the model by generating a confusion matrix as well as computing Accuracy, Precision, Recall, Fmeasure and support as shown below:
target = np.array(y_test)
rf_prediction = np.array(y_pred_rf)print('Confusion matrix : ', confusion_matrix(target, rf_prediction))
print(classification_report(y_test, y_pred_rf))
Decision Trees
Decision trees also come with the scikit-library, therefore, implmenting a decision tree model is as easy as importing the library and fitting your training data as shown below:
from sklearn.tree import DecisionTreeClassifierdt = DecisionTreeClassifier(class_weight='balanced')dt_model = dt.fit(X_train, y_train)y_pred_dt = dt.predict(X_test)
Just like the Random forests, we can also test the accuracy of our decision tree model by generating a confusion matrix and computing the Accuracy, Recall, Precision, Fmeasure and Support.
The post gives a general overview of data pre-processing and model training in machine learning. It has provided a number of ways to perform pre-processing on data and explained how and when to use them. The post has also touched on three machine learning algorithms which can be used for model training and the basics in running the model with these algorithms as well as different ways of getting the accuracy of the model. To follow with the code, you can download the data used in the links provided or access the full code in the GitHub link provided.
References
[1]: L. Susan, Building a logistic regression in python, step by step (2017), https://towardsdatascience.com/building-a-logistic-regression-in-python-step-by-step-becd4d56c9c8
[2]: R.Sukanta, Machine Learning case study: A data-driven approach to predict the success of bank telemarketing (2019), https://towardsdatascience.com/machine-learning-case-study-a-data-driven-approach-to-predict-the-success-of-bank-telemarketing-20e37d46c31c









