More Deep Learning Articles…

How to Remove Outliers in Machine Learning and Deep Learning?

In building a machine learning model, after dealing with null values and turning categories into numbers to prepare them for our models, the next step is to transform the data for outliers detection and for models that require normally distributed features. In this article, I will show you how to remove outliers in machine learning with Python.

What are outliers in machine learning?

Outliers are anomalous observations that differ from the other groups. They can distort our perception of the data and the model we build. Outliers can come from data entry or human error, damaged or unsuitable measuring instruments, data manipulation, dummies added to test detection methods or to add noise, and finally genuine novelties in the data.

Even when generating random numbers from a distribution, there will be rare values that deviate from the mean of all the other examples. These are the values we want to get rid of to train a machine learning model properly.

There are two types of outliers in machine learning:

  1. Univariate Univariate Outliers: when we look at values in the space of a single feature (for example, only at the distribution of the sale price column).
  2. Multivariate Multivariate outliers: when we look at an n-dimensional space in which each dimension is a feature. Here, because there are too many features to take into account, we cannot simply plot the data and spot how far points lie from the normal groups, so we use models to do this detection for us.

Why do we need to remove outliers?

There are many reasons why someone might consider removing some examples from their dataset, even when the dataset is small and we need all the information we can get. We need to remove outliers because they can be damaging to our machine learning model and to our picture of reality.

We want our model to predict the most likely label and not be swayed by a random value in our dataset. The best approach is to remove as little as possible while making models robust enough to ignore outliers or reproduce their effect on the model's predictions.

How do you remove outliers in machine learning?

To remove outliers we first need to detect them. The best way to detect outliers is the manual method: you go through all the information and learn the trends in the data. Any point that lies far from the rest of the data signals an outlier.

However, if you want to learn how to detect outliers with the Python programming language, you can look at this tutorial. Now let us see how to remove outliers in machine learning. I will first import the dataset and do some data processing to understand it and prepare it so that I can remove the outliers:

Download the dataset

import numpy as np
import pandas as pd

# for vis
import matplotlib.pyplot as plt
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import seaborn as sns
sns.set_style("whitegrid")
from sklearn.preprocessing import LabelEncoder, OrdinalEncoder
# anomaly and skewness detection 
from scipy import stats
from scipy.stats import skew, norm
from scipy.special import boxcox1p
from numpy import mean, std

from IPython.display import HTML
from matplotlib import animation
from termcolor import colored

# Importing and concating train and test set
train = pd.read_csv('train.csv', )
test = pd.read_csv('test.csv')

train.name = 'train'
test.name = 'test'

# keeping testing id for submission in the future
test_id = test.Id
for df in [train, test]:
    df.drop(columns = ['Id'], inplace = True)
    
df_concat = pd.concat([train, test], axis = 0).reset_index(drop = True)
df_concat.name = 'both dfs'


df_concat.loc[:train.shape[0], 'which'] = 'train'
df_concat.loc[train.shape[0]:, 'which'] = 'test'

# Dropping two unuseful columns
df_concat.drop(columns = ['PoolQC', 'Utilities'], inplace = True)

# Filling missing values

# Filling with zero
# fields about the Garage
for field in ['GarageType', 'GarageFinish','GarageQual', 'GarageCond',
              'BsmtFinType1','BsmtQual','BsmtCond', 'BsmtExposure', 'BsmtFinType1', 
              'BsmtFinType2','MiscFeature','Alley','Fence','FireplaceQu',
               'MasVnrType' ] :
    df_concat[field].fillna('None',inplace=True)
    
for field in ['MasVnrArea','BsmtFullBath','BsmtHalfBath'
              ,'BsmtFinSF1','GarageCars','GarageArea','TotalBsmtSF',
             'BsmtUnfSF','BsmtFinSF2','GarageYrBlt','TotalBsmtSF']:
    df_concat[field].fillna(0,inplace=True) 


# Filling with appropriate values
df_concat['LotFrontage'] = df_concat.groupby('Neighborhood')['LotFrontage']\
                          .transform(lambda x: x.fillna(x.mean()))
for feature in ['MSZoning', 'Electrical']:
    df_concat[feature] = df_concat.groupby('Neighborhood')[feature]\
                        .transform(lambda x: x.fillna(x.mode()[0]))

for field in ['SaleType','Exterior1st','Exterior2nd',]:
    df_concat[field].fillna(df_concat[field].mode()[0],inplace=True)
    
df_concat.Functional.fillna('Typ',inplace=True)
df_concat.KitchenQual.fillna('TA',inplace=True)

# Converting categorical data into numerical

### ordinal 
ordinal_fields_with_labelencoder=['LandSlope','YearBuilt','YearRemodAdd',
                                  'CentralAir','GarageYrBlt','PavedDrive',
                                  'YrSold']

### ordinal with labelencoder...
for field in ordinal_fields_with_labelencoder:
    le = LabelEncoder()
    df_concat[field] = le.fit_transform(df_concat[field].values)

features_that_are_already_ordinal = ['OverallQual','OverallCond','MoSold',
                                     'FullBath','KitchenAbvGr','TotRmsAbvGrd']


### ordinal features that need to be sorted with ordinal encoder...
fields_that_need_to_be_ordered = [
              'MSSubClass','ExterQual','LotShape','BsmtQual','BsmtCond',
              'BsmtExposure','BsmtFinType1', 'BsmtFinType2','HeatingQC',
              'Functional','FireplaceQu','KitchenQual', 'GarageFinish',
              'GarageQual','GarageCond','Fence'
                                    ]
for field in  fields_that_need_to_be_ordered:
    df_concat[field] = df_concat[field].astype(str)


orders=[#msclass
    ['20','30','40','45','50','60','70','75','80','85', '90','120','150','160','180','190'],
    #ExterQual
    ['Po','Fa','TA','Gd','Ex'],
    #LotShape
    ['Reg','IR1' ,'IR2','IR3'],
    #BsmtQual
    ['None','Fa','TA','Gd','Ex'],
    #BsmtCond
    ['None','Po','Fa','TA','Gd','Ex'],
    #BsmtExposure
    ['None','No','Mn','Av','Gd'],
    #BsmtFinType1
    ['None','Unf','LwQ', 'Rec','BLQ','ALQ' , 'GLQ' ],
    #BsmtFinType2
   ['None','Unf','LwQ', 'Rec','BLQ','ALQ' , 'GLQ' ],
    #HeatingQC
    ['Po','Fa','TA','Gd','Ex'],
    #Functional
   ['Sev','Maj2','Maj1','Mod','Min2','Min1','Typ'],
    #FireplaceQu
    ['None','Po','Fa','TA','Gd','Ex'],
    #KitchenQual
    ['Fa','TA','Gd','Ex'],
    #GarageFinish
    ['None','Unf','RFn','Fin'],
    #GarageQual
    ['None','Po','Fa','TA','Gd','Ex'],
    #GarageCond
    ['None','Po','Fa','TA','Gd','Ex'],
    #PoolQC
    #['None','Fa','Gd','Ex'],
    #Fence
    ['None','MnWw','GdWo','MnPrv','GdPrv'] ]
   

### ordinal features with specific order.....
for i in range(len(orders)):

    ord_en = OrdinalEncoder(categories = {0:orders[i]})
    df_concat.loc[:,fields_that_need_to_be_ordered[i]] = ord_en.fit_transform(df_concat.loc[:,fields_that_need_to_be_ordered[i]].values.reshape(-1,1))

# Finally one hot encoding categorical data that are not ordinal    
df_concat=pd.get_dummies(df_concat.drop(columns = ['which']))
train = df_concat[:train.shape[0]]
test = df_concat[train.shape[0]:].drop(columns = ['SalePrice'])


def finding_over_fitting_features(df, percentage = 99.9):
    overfit=[]
    for feature in df.columns:
        most_frequent=(df[feature] .value_counts().iloc[0])
        if most_frequent/len(df) *100 >99.9:
            overfit.append(feature)
    return(overfit)
overfitted = finding_over_fitting_features(df_concat, percentage = 99.0)
df_concat.drop(columns = overfitted, inplace = True)

df = pd.read_csv('mood_swings/mood swings.csv', sep = ' ')

Now let us see how to remove the outliers:

fig, axes = plt.subplots(1, 2, figsize=(20,8),)
fig.suptitle('Before and After Manually removing outliers')
axes[0].set_title('Before')
axes[1].set_title('After')

g = sns.regplot(x=train['GrLivArea'], y=train['SalePrice'], ax = axes[0])
g.text(4500, 400000, "Outliers", horizontalalignment='left', size='large', color='black', weight='semibold')
g.axvline(4000, ls='--', color = 'red')

idx_manual = np.where(train['GrLivArea']>4000)[0]
train_NoOutlier = train.drop(idx_manual)
g = sns.regplot(x=train_NoOutlier['GrLivArea'], y=train_NoOutlier['SalePrice'], ax = axes[1])

See how the data is less spread out and more concentrated in a smaller range of floor area. If you look closely, though, you can still see a few very small values in the lower-left corner of the plot, showing properties sold at abnormally low prices.

You can go ahead and delete them and see what happens to your results. I manually removed prices below 40,000, which will indeed help the accuracy of our machine learning model.

I hope you liked this article on how to remove outliers in machine learning with Python.

 

Post links

Leave a comment

Your email address will not be published. Required fields are marked *