#!/usr/bin/env python # coding: utf-8 # Open In Colab # How to impute missing values in Python ? # # **Aude Sportisse** # The problem of missing data is ubiquitous in the practice of data analysis. Main approaches for handling missing data include imputation methods. In this Notebook, we first describe the main imputation methods available in Python on synthetic data. Then, we compare them on both synthetic data for different missing-data mechanisms and percentage of missing values. Finally, we propose a function giving the comparison of the methods in one particular setting (missing-data mechanism, percentage of missing values) for a list of (complete) real datasets. # ## Description of imputation methods on synthetic data # In this section we provide, for some of the main classes and functions in Python (the list is of course not thorough) to impute missing values, links to tutorials if any, as well as a description of their main functionalities and reusable code. The goal is not to describe all the methods precisely, as many resources are already available, but rather to provide an overview of several imputation options. The methods we focus on are gathered in the table below. # | Class (or function) | Data Types | Underlying Method | Imputation | Comments | # | ------------- |:--------------| ------------------- |------------|--------------| # | SingleImputer with strategy='mean' (default), sklearn.impute | quantitative |imputation by the mean| single| Easiest method | # | softImpute function (mimics R into Python) | quantitative |low-rank matrix completion | single| Strong theoretical guarantees, regularization parameter to tune | # | IterativeImputer with BayesianRidge (default), sklearn.impute | mixed |imputation by chained equations | single | Very flexible to data types, no parameter to tune | # | IterativeImputer with ExtraTreesRegressor, sklearn.impute | mixed |random forests| single| Requires large sample sizes, no parameter to tune | # | Sinkhorn imputation | quantitative |optimal transport| single| | # # # In[1]: get_ipython().system('pip install wget') get_ipython().system('pip install geomloss') from sklearn.impute import SimpleImputer from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer from sklearn.ensemble import ExtraTreesRegressor from sklearn.linear_model import BayesianRidge ## Downoald additional code import wget wget.download('https://raw.githubusercontent.com/BorisMuzellec/MissingDataOT/master/softimpute.py') wget.download('https://raw.githubusercontent.com/BorisMuzellec/MissingDataOT/master/imputers.py') wget.download('https://raw.githubusercontent.com/BorisMuzellec/MissingDataOT/master/data_loaders.py') wget.download('https://raw.githubusercontent.com/BorisMuzellec/MissingDataOT/master/utils.py') wget.download('https://raw.githubusercontent.com/R-miss-tastic/website/master/static/how-to/python/produceNA.py') wget.download('https://raw.githubusercontent.com/R-miss-tastic/website/master/static/how-to/python/tools.py') wget.download('https://raw.githubusercontent.com/R-miss-tastic/website/master/static/how-to/python/MIWAE_functions.py') from softimpute import softimpute, cv_softimpute from imputers import OTimputer from data_loaders import * import numpy as np import pandas as pd from utils import * import torch import torchvision import torch.nn as nn import torch.distributions as td from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image import scipy.stats import scipy.io import scipy.sparse from scipy.io import loadmat import matplotlib.pyplot as plt from produceNA import * from tools import color_imputedvalues_orange from itertools import product from sklearn.preprocessing import scale import os from MIWAE_functions import * def warn(*args, **kwargs): pass import warnings warnings.warn = warn # Let us consider a Gaussian data matrix of size $n$ times $p$. # In[2]: #### Simulation of the data matrix #### np.random.seed(0) # fix the seed n = 1000 p = 10 mean = np.repeat(0, p) cov = 0.5 * (np.ones((p,p)) + np.eye(p)) x_comp = np.random.multivariate_normal(mean, cov, size = n) # In[3]: pd.DataFrame(x_comp).head() # We introduce some missing (here MCAR) values in the data matrix using the function `produce_NA` given in the Python Notebook [How to generate missing values in Python ?](https://rmisstastic.netlify.app/how-to/python/generate_html/how%20to%20generate%20missing%20values). # In[4]: #### Introduction of missing values #### perc_miss = 0.3 # 30% NA XproduceNA = produce_NA(x_comp, p_miss=perc_miss, mecha="MCAR") X_miss = XproduceNA['X_incomp'] x_miss = X_miss.numpy() Mask = XproduceNA['mask'] # True for missing values, False for others # In[6]: pd.DataFrame(x_miss).head().style.highlight_null(null_color='orange') # ### Imputation by the mean # The [SimpleImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html#sklearn.impute.SimpleImputer) class provides basic strategies for imputing missing values as the mean imputation. This is a naive imputation, which serves as benchmark in the sequel. # In[5]: x_mean = SimpleImputer().fit_transform(x_miss) # In[6]: pd.DataFrame(x_mean).head().style.applymap(color_imputedvalues_orange, x_miss=x_miss) # ### softimpute # The function softimpute (original article of [Hastie and al.](http://jmlr.org/papers/volume16/hastie15a/hastie15a.pdf)) can be used to impute quantitative data. The function coded here in Python mimics the function softimpute of the [R package softImpute](https://cran.r-project.org/web/packages/softImpute/index.html). It fits a low-rank matrix approximation to a matrix with missing values via nuclear-norm regularization. The main arguments are the following. # # * `X`: the data set with missing values (matrix). # # * `lambda`: the nuclear-norm regularization parameter. # # To calibrate the parameter lambda, one may perform cross-validation, coded in the function cv_softimpute which takes in argument the data set with missing values and the length of the grid on which cross-validation is performed. # In[7]: cv_error, grid_lambda = cv_softimpute(x_miss, grid_len=15) lbda = grid_lambda[np.argmin(cv_error)] x_soft = softimpute((x_miss), lbda)[1] # In[8]: pd.DataFrame(x_soft).head().style.applymap(color_imputedvalues_orange, x_miss=x_miss) # ### Iterative chained equations # Iterative chained equations methods consist in (iterative) imputation using conditional expectation. The [IterativeImputer](https://scikit-learn.org/stable/modules/generated/sklearn.impute.IterativeImputer.html#sklearn.impute.IterativeImputer) class provides such methods and is inspired by the [mice](https://cran.r-project.org/web/packages/mice/index.html) package in R but differs from it by returning a single imputation instead of multiple imputations. # # The main arguments are # # * `estimator`: the estimator to use for the imputation. By default, it is the BayesianRidge estimator which does a regularized linear regression. # # * `random_state`: maximum number of imputation rounds to perform. (The last imputations are returned.) # # * `max_iter`: seed of the pseudo random number generator to use. # # The method fit_transform allows to fit the imputer on the incomplete matrix and return the complete matrix. # In[9]: x_ice = IterativeImputer(random_state=0, max_iter=50).fit_transform(x_miss) # In[10]: pd.DataFrame(x_ice).head().style.applymap(color_imputedvalues_orange, x_miss=x_miss) # Another estimor can be used, the ExtraTreesRegressor estimator, which trains iterative random forest instead of doing iterative regression and mimics the [missForest](https://cran.r-project.org/web/packages/missForest/missForest.pdf) in R. [ExtraTreesRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesRegressor.html#sklearn.ensemble.ExtraTreesRegressor) fits a number of randomized extra-trees and averages the results. It comes from the module sklearn.ensemble. Its main arguments are the number of trees in the forest and the random state which allows to control the sources of randomness. # In[11]: estimator_rf = ExtraTreesRegressor(n_estimators=10, random_state=0) x_rf = IterativeImputer(estimator=estimator_rf, random_state=0, max_iter=50).fit_transform(x_miss) # In[12]: pd.DataFrame(x_rf).head().style.applymap(color_imputedvalues_orange, x_miss=x_miss) # ### Sinkhorn imputation # Sinkhorn imputation can be used to impute quantitative data. It relies on the idea that two batches extracted randomly from the same dataset should share the same distribution and consists in minimizing OT distances between batches. More details can be found in the original [article](https://arxiv.org/pdf/2002.03860.pdf) and the code is provided [here](https://github.com/BorisMuzellec/MissingDataOT). # # The main argument are # # * `eps`: sinkhorn regularization parameter. If the batch size is larger than half the dataset's size, it will be redefined in the imputation methods. # # * `lr` : learning rate. # # * `batchsize` : size of the batches on which the sinkhorn divergence is evaluated. # # * `niter`: number of gradient updates for each model within a cycle. # # # To set the regularization, one uses the function `pick_epsilon` which takes a multiple of the median distance. # The method fit_transform allows to fit the imputer on the incomplete matrix and return the complete matrix. # # # In[13]: X_true = torch.from_numpy(x_comp).double() eps = pick_epsilon(X_miss) sk_imputer = OTimputer(eps=eps, batchsize=128, lr=0.01, niter=15) sk_imp, _, _ = sk_imputer.fit_transform(X_miss, X_true=X_true) # In[14]: sk_imp_np = sk_imp.detach().numpy() pd.DataFrame(sk_imp_np).head().style.applymap(color_imputedvalues_orange, x_miss=x_miss) # ### MIWAE # MIWAE imputes missing values with a deep latent variable model based on importance weighted variational inference. The original article is [here](http://proceedings.mlr.press/v97/mattei19a/mattei19a.pdf) and its code is available [here](https://github.com/pamattei/miwae). # # The main arguments are # # * `X_miss`: the data set with missing values (tensor). # # * `h`: number of hidden units in multi-layer # perceptrons (by default, $h=128$). # # * `d`: dimension of the latent space (by default $d=1$). # # * `K`: number of importance sampling during training (by default $K=20$). # # * `bs`: batch size (by default $bs=64$). # # * `n_epochs`: number of epochs (by default $n_epochs=2002$). # # In[15]: x_miwae = MIWAE(X_miss) # In[16]: pd.DataFrame(x_miwae).head().style.applymap(color_imputedvalues_orange, x_miss=x_miss) # ## Numerical experiments to compare the different methods # ### Synthetic data # # # We compare the methods presented above for different percentage of missing values and for different missing-data mechanisms: # # * Missing Completely At Random (MCAR) if the probability of being missing is the same for all observations # # * Missing At Random (MAR) if the probability of being missing only depends on observed values. # # * Missing Not At Random (MNAR) if the unavailability of the data depends on both observed and unobserved data such as its value itself. # # We compare the methods in terms of mean squared error (MSE), i.e.: # $$MSE(X^{imp}) = \frac{1}{n_{NA}}\sum_{i}\sum_{j} 1_{X^{NA}_{ij}=NA}(X^{imp}_{ij} - X_{ij})^2$$ # where $n_{NA} = \sum_{i}\sum_{j} 1_{X^{NA}_{ij}=NA}$ is the number of missing entries in $X^{NA}$. # # Note that in order to evaluate this error, we need to know the true values of the missing entries. # # The function **HowToImpute** compares the methods above with the naive imputation by the mean in terms of MSE on a complete dataset. More particularly, the function allows to introduce missing values on the complete dataset using different percentages of missing values and missing-data mechanisms and gives the MSE of the methods for the different missing-value settings. The final MSE for one specific missing-value setting is computed by aggregating the MSE's obtained for several simulations, where the stochasticity comes from the process of drawing several times the missing-data pattern. # # The arguments are the following. # # * `X`: the complete data set where the missing values will be introduced (matrix). # # * `perc.list`: list containing the different percentage of missing values. # # * `mecha.list`: list containing the different missing-data mechanisms ("MCAR","MAR", "MNAR"). # # * `nbsim`: number of simulations performed. # # It returns a table containing the mean of the results for the simulations performed. # In[17]: def HowToImpute(x_comp , perc_list , mecha_list , nbsim): """ Compare in terms of MSE several imputation methods for different percentages of missing values and missing-data mechanisms. Parameters ---------- x_comp : the complete data set where the missing values will be introduced (numpy array). perc_list : list containing the different percentage of missing values. mecha_list : list containing the different missing-data mechanisms ("MCAR","MAR" or "MNAR"). nbsim : number of simulations performed. Returns ------- df: dataframe containing the mean of the MSEs for the simulations performed. """ mecha_perc_list = pd.DataFrame([(mecha,perc) for mecha, perc in product(mecha_list,perc_list)]) df = mecha_perc_list.apply(ComparMethods, axis=1, x_comp=x_comp, nbsim=nbsim) df.index = mecha_perc_list.apply(lambda x : x[0] + " " + str(x[1]), axis=1) return df def ComparMethods(mecha_perc, x_comp, nbsim): """ Compare in terms of MSE several imputation methods for a given percentage of missing values and a given missing-data mechanism. Parameters ---------- mecha_perc : list containing the missing-data mechanism and the percentage of missing values to be used for introducing missing values. x_comp : the complete data set where the missing values will be introduced (matrix). nbsim : number of simulations performed. Returns ------- df: dataframe containing the mean of the MSEs. """ mecha = mecha_perc[0] perc = mecha_perc[1] RMSE_results = pd.DataFrame() Methods = ['mean', 'softimpute', 'ice', 'rf','sk','miwae'] for meth in Methods: RMSE_results[meth]=[] for sim in range(0,nbsim): ## Introduction NA if mecha == "MAR": XproduceNA = produce_NA(x_comp, perc, mecha, p_obs=0.5) elif mecha == "MNAR": XproduceNA = produce_NA(x_comp, perc, mecha, p_obs=0.5, opt="logistic") else: XproduceNA = produce_NA(x_comp, perc, mecha) mask = XproduceNA['mask'].numpy() x_miss = XproduceNA['X_incomp'].numpy() ## Mean x_mean = SimpleImputer().fit_transform(x_miss) rmse_mean = RMSE(x_mean, x_comp, mask) ## SoftImpute cv_error, grid_lambda = cv_softimpute(x_miss, grid_len=15) lbda = grid_lambda[np.argmin(cv_error)] x_soft = softimpute((x_miss), lbda)[1] rmse_soft = RMSE(x_soft, x_comp, mask) ## Ice x_ice = IterativeImputer(random_state=0, max_iter=50).fit_transform(x_miss) rmse_ice = RMSE(x_ice, x_comp, mask) ## Random Forests estimator_rf = ExtraTreesRegressor(n_estimators=10, random_state=0) x_rf = IterativeImputer(estimator=estimator_rf, random_state=0, max_iter=50).fit_transform(x_miss) rmse_rf = RMSE(x_rf, x_comp, mask) ## Sinkhorn imputation X_true = torch.from_numpy(x_comp).double() X_miss = XproduceNA['X_incomp'] batchsize = 128 lr = 1e-2 epsilon = pick_epsilon(X_miss) sk_imputer = OTimputer(eps=epsilon, batchsize=batchsize, lr=lr, niter=2000) sk_imp, _, _ = sk_imputer.fit_transform(X_miss, verbose=True, report_interval=500, X_true=X_true) rmse_sk_imp = RMSE(sk_imp.detach().numpy(), x_comp, mask) ## MIWAE x_miwae = MIWAE(X_miss) rmse_miwae = RMSE(x_miwae, x_comp, mask) new_rmse = {'mean': rmse_mean, 'softimpute': rmse_soft, 'ice': rmse_ice, 'rf': rmse_rf, 'sk': rmse_sk_imp, 'miwae': rmse_miwae} RMSE_results = RMSE_results.append(new_rmse, ignore_index=True) return RMSE_results.mean() # In[18]: perc_list = [0.1, 0.3, 0.5] mecha_list = ["MCAR", "MAR", "MNAR"] results_how_to_impute = HowToImpute(x_comp, perc_list , mecha_list , nbsim=2) # In[19]: results_how_to_impute # In[27]: ax = results_how_to_impute.plot(kind="bar",rot=30) ax.get_legend().set_bbox_to_anchor((1, 1)) # ### Real datasets # We will now compare the methods on real complete data set taken from [the UCI repository](http://archive.ics.uci.edu/ml) in which we will introduce missing values. In the present workflow, we propose a selection of several data sets (here, the data sets contain only quantitative variables): # # - Wine Quality - Red (1599x11) # - Wine Quality - White (4898x11) # - Slump (103x9) # # But you can test the methods on any complete dataset you want. # # In[20]: if not os.path.isdir('datasets'): os.mkdir('datasets') wine_red = dataset_loader('wine_quality_red') wine_white = dataset_loader('wine_quality_white') slump = dataset_loader('concrete_slump') # You can choose to scale data prior to running the experiments, which implies that the variable have the same weight in the analysis. Scaling data may be performed on complete data sets but is more difficult for incomplete data sets. (For MCAR values, the estimations of the standard deviation can be unbiased. However, for MNAR values, the estimators will suffer from biases.) # In[21]: sc = True if sc: wine_white = scale(wine_white) wine_red = scale(wine_red) slump = scale(slump) # In[22]: datasets_list = dict(wine_white=wine_white, wine_red=wine_red, slump=slump) names_dataset = ['wine_white','wine_red','slump'] perc = [0.1] mecha = ["MCAR"] nbsim = 2 # We can then apply the **HowToImpute_real** function. It compares in terms of MSE several imputation methods for different complete datasets where missing values are introduced with a given percentage of missing values and a given missing-data mechanism. # # The arguments are the following. # # * `datasets_list`: dictionnary of complete datasets. # # * `perc`: percentage of missing values. # # * `mecha`: missing-data mechanism ("MCAR","MAR" or "MNAR"). # # * `nbsim`: number of simulations performed. # # * `names_dataset`: list containing the names of the datasets (for plotting results). # # It returns a table containing the mean of the MSEs for the simulations performed. # In[23]: def HowToImpute_real(datasets_list, perc, mecha, nbsim, names_dataset): """ Compare in terms of MSE several imputation methods for different complete datasets where missing values are introduced with a given percentage of missing values and a given missing-data mechanism. Parameters ---------- datasets_list : dictionnary of complete datasets. perc : percentage of missing values. mecha_list : missing-data mechanism ("MCAR","MAR" or "MNAR"). nbsim : number of simulations performed. names_dataset : vector of the names of datasets. Returns ------- res: dataframe containing the mean of the MSEs for the simulations performed. """ for dat in range(0,len(datasets_list)): df = HowToImpute(datasets_list[names_dataset[dat]], perc, mecha, nbsim) if dat==0: res = df else: res = pd.concat([res,df]) res.index = names_dataset return(res) # In[24]: results_how_to_impute_real = HowToImpute_real(datasets_list, perc, mecha, nbsim, names_dataset) # In[25]: results_how_to_impute_real # In[26]: ax = results_how_to_impute_real.plot(kind="bar",rot=30) ax.get_legend().set_bbox_to_anchor((1, 1))