Data Preprocessing
For any task in data science, Obviously, data is the most important thing. Its only that most of the time we don’t get data in its most beautiful form. Raw data is often incomplete, inconsistent and is likely to contain many errors. Most of the times Data scientists spend 70 % of their time cleaning their datasets. A cleaned dataset provides much better insights, visualizations and predictions.
Data is mostly available in 2 forms that are structured data and unstructured data.
- Structured data — The Data stored in Excel, CSV or in any database.
- Unstructured data — Images, Audio, Text and mostly everything is unstructured
In this tutorial, we will see how to work with structured data
Most of the times we face 3 major types of problem while trying to apply a Machine Learning Algorithm
- we have missing values in our data if we trained our algorithm with this data it will give an error as it cannot do computations on NULL or NaN values.
- The data has categories like YES or NO, For our Machine Learning algorithm a string type data is like a bad news as again it cannot work on string values.
- The data often have multiple attributes or in simple term columns, it is possible that one column contains large values while other column consists of very low values, this will cause the Machine Learning algorithms to give a greater importance to the column with high values when in reality both had equal importance.
These are the basic problems data scientists face, although this list, in reality, can be longer depending on your data.
In this tutorial, we will be using Pandas and SciKit-Learn libraries to handle and preprocess our data, before continuing you should go through Introduction to Pandas and the code for this post is available here.
Step 1: Importing Pandas
In [1]:
import numpy as np
import pandas as pdStep 2: Importing Dataset
Pandas library is compatible with most of the formats, it has pre-written functions to import excel files, CSV files(comma separated values), SQL and many more.
In [2]:
data = pd.read_csv("data/data.csv")# here were are importing data.csv which is in data folderIn [3]:
data.head()Out[3]:
CountryAgeSalaryPurchased0Delhi24.072000.0No1mumbai27.048000.0Yes2new york40.054000.0No3Madrid28.061000.0No4berlin40.0NaNYes
Step 3: Separating Explanatory variables and response variable
For training a supervised learning algorithm we need a input and an output in this example we used x to denote the inputs and y as output.
In [4]:
x=data.iloc[:,:-1].values
y=data.iloc[:,3].valuesIn [5]:
xOut[5]:
array([['Delhi', 24.0, 72000.0],
['mubai', 27.0, 48000.0],
['new york', 40.0, 54000.0],
['Madrid', 28.0, 61000.0],
['berlin', 40.0, nan],
['hong kong', 55.0, 58000.0],
['delhi', nan, 52000.0],
['new york', 48.0, 79000.0],
['mubai', 50.0, 83000.0],
['paris', 37.0, 67000.0]], dtype=object)In [6]:
yOut[6]:
array(['No', 'Yes', 'No', 'No', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes'],
dtype=object)Step 4: Handling Missing values
For handling missing data SKlearn provides a class called Imputer. We simply have to make an object of this imputer class and specify which type of missing value do we have in our data, what strategy we want to use to replace these missing values which can be mean, median or with the most frequent value present in that column or row. for complete information on imputer, class check here.
In [7]:
from sklearn.preprocessing import Imputer #importing imputer classIn [8]:
imputer = Imputer(missing_values='NaN', strategy ='mean',axis=0)
imputer = imputer.fit(x[:,1:3])
x[:,1:3] = imputer.transform(x[:,1:3])In [9]:
xSee how all the missing values which are now replaced with the mean values of that column
Out[9]:
array([['Delhi', 24.0, 72000.0],
['mubai', 27.0, 48000.0],
['new york', 40.0, 54000.0],
['Madrid', 28.0, 61000.0],
['berlin', 40.0, 63777.77777777778],
['hong kong', 55.0, 58000.0],
['delhi', 38.77777777777778, 52000.0],
['new york', 48.0, 79000.0],
['mubai', 50.0, 83000.0],
['paris', 37.0, 67000.0]], dtype=object)Step 5: Handling Categorical Data
Earlier we saw how categorical data can be a problem for algorithms. Here, our data also have categorical data, in columns labelled as Country and Purchased the data is in categorical form.
Get Yash Upadhyay’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s see how SKlearn helps us deal with these.
SKlearn library provides us with 2 classes that are LabelEncoder and OneHotEncoder
LabelEncoder
This class converts the categorical data to numerical data by assigning a numeric value to each level for example if data has three categories like Delhi, Mumbai and new york, it will assign 0 to Delhi, 1 to Mumbai and 2 to New York. This does help in converting strings of different categories to numeric values but it creates a problem when assigned with 0, 1 and 2 the ML algorithm thinks that New York has a higher value than Mumbai and Delhi whereas, in reality, they have equal importance. to deal with this we have another class called OneHotEncoder.
OneHotEncoder
what OneHotEncoder does is it creates a binary column for each category and returns a sparse matrix or dense array, hence giving equal importance to each value.
In [10]:
from sklearn.preprocessing import LabelEncoder, OneHotEncoderIn [11]:
labelencoderX = LabelEncoder()
x[:,0] = labelencoderX.fit_transform(x[:,0])In [12]:
xOut[12]:
array([[0, 24.0, 72000.0],
[5, 27.0, 48000.0],
[6, 40.0, 54000.0],
[1, 28.0, 61000.0],
[2, 40.0, 63777.77777777778],
[4, 55.0, 58000.0],
[3, 38.77777777777778, 52000.0],
[6, 48.0, 79000.0],
[5, 50.0, 83000.0],
[7, 37.0, 67000.0]], dtype=object)OneHotEncoder
what OneHotEncoder does is it creates a binary column for each category and returns a sparse matrix or dense array, hence giving equal importance to each value.
In [13]:
onehotencoder = OneHotEncoder(categorical_features=[0])
x=onehotencoder.fit_transform(x).toarray()In [14]:
xOut[14]:
array([[1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
2.40000000e+01, 7.20000000e+04],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00,
2.70000000e+01, 4.80000000e+04],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00,
4.00000000e+01, 5.40000000e+04],
[0.00000000e+00, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
2.80000000e+01, 6.10000000e+04],
[0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
4.00000000e+01, 6.37777778e+04],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
5.50000000e+01, 5.80000000e+04],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
3.87777778e+01, 5.20000000e+04],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00,
4.80000000e+01, 7.90000000e+04],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00,
5.00000000e+01, 8.30000000e+04],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00,
3.70000000e+01, 6.70000000e+04]])In [15]:
labelencoderY = LabelEncoder()
y = labelencoderY.fit_transform(y)In [16]:
yOut[16]:
array([0, 1, 0, 0, 1, 1, 0, 1, 0, 1], dtype=int64)Step 6: Splitting Data into training and test set
The training set is used to train the machine learning algorithm and the test set is used to test our predictions
In [17]:
from sklearn.cross_validation import train_test_splitD:\anaconda\lib\site-packages\sklearn\cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
In [18]:
X_train,x_test , Y_train, y_test = train_test_split(x,y, test_size=0.2, random_state=0)Step 7: Scaling data
As discussed before the large difference in values of different attributes or columns can be a problem to deal with this we need to scale the values, sklearn provides multiple classes that can be used to scale the data depending on what methods they use to scale it. here we used StandardScaler class, which scales data by subtracting the sample mean from each value of the data and then be divided by the standard deviation of the entire dataset.
In [19]:
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
x_test = sc_X.transform(x_test)In [21]:
X_trainOut[21]:
array([[-0.37796447, -0.37796447, 2.64575131, -0.37796447, -0.37796447,
-0.37796447, -0.37796447, -0.37796447, 0.27661062, 0.12381479],
[-0.37796447, -0.37796447, -0.37796447, -0.37796447, -0.37796447,
-0.37796447, -0.37796447, 2.64575131, -0.02212885, 0.46175632],
[-0.37796447, -0.37796447, -0.37796447, -0.37796447, -0.37796447,
2.64575131, -0.37796447, -0.37796447, -1.01792709, -1.53093341],
[-0.37796447, -0.37796447, -0.37796447, 2.64575131, -0.37796447,
-0.37796447, -0.37796447, -0.37796447, 0.15490195, -1.11141978],
[-0.37796447, -0.37796447, -0.37796447, -0.37796447, -0.37796447,
-0.37796447, 2.64575131, -0.37796447, 1.07324921, 1.7202972 ],
[-0.37796447, 2.64575131, -0.37796447, -0.37796447, -0.37796447,
-0.37796447, -0.37796447, -0.37796447, -0.91834726, -0.16751412],
[ 2.64575131, -0.37796447, -0.37796447, -0.37796447, -0.37796447,
-0.37796447, -0.37796447, -0.37796447, -1.31666656, 0.98614835],
[-0.37796447, -0.37796447, -0.37796447, -0.37796447, 2.64575131,
-0.37796447, -0.37796447, -0.37796447, 1.77030798, -0.48214934]])In [22]:
x_testOut[22]:
array([[-0.37796447, -0.37796447, -0.37796447, -0.37796447, -0.37796447,
-0.37796447, 2.64575131, -0.37796447, 0.27661062, -0.90166297],
[-0.37796447, -0.37796447, -0.37796447, -0.37796447, -0.37796447,
2.64575131, -0.37796447, -0.37796447, 1.27240886, 2.13981082]])






