miceforest: Fast Imputation with Random Forests in Python

miceforest: Fast Imputation with Random Forests in Python

Fast, memory efficient Multiple Imputation by Chained Equations (MICE) with random forests. It can impute categorical and numeric data without much setup, and has an array of diagnostic plots available. The R version of this package may be found here.

This document contains a thorough walkthrough of the package, benchmarks, and an introduction to multiple imputation. More information on MICE can be found in Stef van Buuren’s excellent online book, which you can find here.

Table of Contents:

Package Meta

miceforest has 4 main classes which the user will interact with:

  • KernelDataSet - a kernel data set is a dataset on which the mice algorithm is performed. Models are saved inside the instance, which can also be called on to impute new data. Several plotting methods are included to run diagnostics on the imputed data.
  • MultipleImputedKernel - a collection of KernelDataSets. Has additional methods for accessing and comparing multiple kernel datasets together.
  • ImputedDataSet - a single dataset that has been imputed. These are returned after impute_new_data() is called.
  • MultipleImputedDataSet - A collection of datasets that have been imputed. Has additional methods for comparing the imputations between datasets.

This package can be installed using either pip or conda, through conda-forge:

# Using pip
$ pip install miceforest

# Using conda
$ conda install -c conda-forge miceforest

You can also download the latest development version from this repository. If you want to install from github with conda, you must first run conda install pip git.

$ pip install git+https://github.com/AnotherSamWilson/miceforest.git

Using miceforest

We will be looking at a few simple examples of imputation. We need to load the packages, and define the data:

import miceforest as mf
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np

# Load data and introduce missing values
iris = pd.concat(load_iris(as_frame=True,return_X_y=True),axis=1)
iris['target'] = iris['target'].astype('category')
iris_amp = mf.ampute_data(iris,perc=0.25,random_state=1991)

Imputing a Single Dataset

If you only want to create a single imputed dataset, you can use KernelDataSet:

# Create kernel. 
kds = mf.KernelDataSet(

# Run the MICE algorithm for 3 iterations

# Return the completed kernel data
completed_data = kds.complete_data()

There are also an array of plotting functions available, these are discussed below in the section Diagnostic Plotting. The plotting behavior between single imputed datasets and multi-imputed datasets is slightly different.

Simple Example of Multiple Imputation

We can also create a class which contains multiple KernelDataSets, along with easy ways to compare them:

# Create kernel. 
kernel = mf.MultipleImputedKernel(

# Run the MICE algorithm for 3 iterations on each of the datasets

Printing the MultipleImputedKernel object will tell you some high level information:

##               Class: MultipleImputedKernel
##        Models Saved: Last Iteration
##            Datasets: 4
##          Iterations: 3
##   Imputed Variables: 5
## save_all_iterations: True

Controlling Tree Growth

A very nice thing about random forests is that they are trivially parallelizable. We can save a lot of time by setting the n_jobs parameter in both the fit and predict methods for the random forests:

# Run the MICE algorithm for 2 more iterations on the kernel 

Any other arguments may be passed to either class (RandomForestClassifier,RandomForestRegressor). In our example, we may not have saved much (if any) time. This is because there is overhead with using multiple cores, and our data is very small.

Creating a Custom Imputation Schema

It is possible to customize our imputation procedure by variable. By passing a named list to variable_schema, you can specify the predictors for each variable to impute. You can also select which variables should be imputed using mean matching, as well as the mean matching candidates, by passing a dict tomean_match_candidates:

var_sch = {
    'sepal width (cm)': ['target','petal width (cm)'],
    'petal width (cm)': ['target','sepal length (cm)']
var_mmc = {
    'sepal width (cm)': 5,
    'petal width (cm)': 0

cust_kernel = mf.MultipleImputedKernel(

Imputing New Data with Existing Models

Multiple Imputation can take a long time. If you wish to impute a dataset using the MICE algorithm, but don’t have time to train new models, it is possible to impute new datasets using a MultipleImputedKernel object. The impute_new_data() function uses the random forests collected by MultipleImputedKernel to perform multiple imputation without updating the random forest at each iteration:

# Our 'new data' is just the first 15 rows of iris_amp
new_data = iris_amp.iloc[range(15)]
new_data_imputed = kernel.impute_new_data(new_data=new_data)
##               Class: MultipleImputedDataSet
##            Datasets: 4
##          Iterations: 5
##   Imputed Variables: 5
## save_all_iterations: False

All of the imputation parameters (variable_schema, mean_match_candidates, etc) will be carried over from the original MultipleImputedKernel object. When mean matching, the candidate values are pulled from the original kernel dataset. To impute new data, the save_models parameter in MultipleImputedKernel must be > 0. If save_models == 1, the model from the latest iteration is saved for each variable. If save_models > 1, the model from each iteration is saved. This allows for new data to be imputed in a more similar fashion to the original mice procedure.

Diagnostic Plotting

As of now, miceforest has four diagnostic plots available.

Distribution of Imputed-Values

We probably want to know how the imputed values are distributed. We can plot the original distribution beside the imputed distributions in each dataset by using the plot_imputed_distributions method of an MultipleImputedKernel object:


The red line is the original data, and each black line are the imputed values of each dataset.

Convergence of Correlation

We are probably interested in knowing how our values between datasets converged over the iterations. The plot_correlations method shows you a boxplot of the correlations between imputed values in every combination of datasets, at each iteration. This allows you to see how correlated the imputations are between datasets, as well as the convergence over iterations:


Variable Importance

We also may be interested in which variables were used to impute each variable. We can plot this information by using the plot_feature_importance method.

kernel.plot_feature_importance(annot=True,cmap="YlGnBu",vmin=0, vmax=1)

The numbers shown are returned from the sklearn random forest _feature_importance attribute. Each square represents the importance of the column variable in imputing the row variable.

Mean Convergence

If our data is not missing completely at random, we may see that it takes a few iterations for our models to get the distribution of imputations right. We can plot the average value of our imputations to see if this is occurring:

kernel.plot_mean_convergence(wspace=0.3, hspace=0.4)

Our data was missing completely at random, so we don’t see any convergence occurring here.

Using the Imputed Data

To return the imputed data simply use the complete_data method:

dataset_1 = kernel.complete_data(0)

This will return a single specified dataset. Multiple datasets are typically created so that some measure of confidence around each prediction can be created.

Since we know what the original data looked like, we can cheat and see how well the imputations compare to the original data:

acclist = []
for iteration in range(kernel.iteration_count()+1):
    target_na_count = kernel.na_counts['target']
    compdat = kernel.complete_data(dataset=0,iteration=iteration)

    # Record the accuract of the imputations of target.
      round(1-sum(compdat['target'] != iris['target'])/target_na_count,2)

# acclist shows the accuracy of the imputations
# over the iterations.
## [0.32, 0.76, 0.78, 0.81, 0.86, 0.86]

In this instance, we went from a ~32% accuracy (which is expected with random sampling) to an accuracy of ~86%. We managed to replace the missing target values with a pretty high degree of accuracy!

The MICE Algorithm

Multiple Imputation by Chained Equations ‘fills in’ (imputes) missing data in a dataset through an iterative series of predictive models. In each iteration, each specified variable in the dataset is imputed using the other variables in the dataset. These iterations should be run until it appears that convergence has been met.

This process is continued until all specified variables have been imputed. Additional iterations can be run if it appears that the average imputed values have not converged, although no more than 5 iterations are usually necessary.

Common Use Cases

Data Leakage:

MICE is particularly useful if missing values are associated with the target variable in a way that introduces leakage. For instance, let’s say you wanted to model customer retention at the time of sign up. A certain variable is collected at sign up or 1 month after sign up. The absence of that variable is a data leak, since it tells you that the customer did not retain for 1 month.

Funnel Analysis:

Information is often collected at different stages of a ‘funnel’. MICE can be used to make educated guesses about the characteristics of entities at different points in a funnel.

Confidence Intervals:

MICE can be used to impute missing values, however it is important to keep in mind that these imputed values are a prediction. Creating multiple datasets with different imputed values allows you to do two types of inference:

  • Imputed Value Distribution: A profile can be built for each imputed value, allowing you to make statements about the likely distribution of that value.
  • Model Prediction Distribution: With multiple datasets, you can build multiple models and create a distribution of predictions for each sample. Those samples with imputed values which were not able to be imputed with much confidence would have a larger variance in their predictions.

Predictive Mean Matching

miceforest can make use of a procedure called predictive mean matching (PMM) to select which values are imputed. PMM involves selecting a datapoint from the original, nonmissing data which has a predicted value close to the predicted value of the missing sample. The closest N (mean_match_candidates parameter) values are chosen as candidates, from which a value is chosen at random. This can be specified on a column-by-column basis. Going into more detail from our example above, we see how this works in practice:

This method is very useful if you have a variable which needs imputing which has any of the following characteristics:

  • Multimodal
  • Integer
  • Skewed

Effects of Mean Matching

As an example, let’s construct a dataset with some of the above characteristics:

randst = np.random.RandomState(1991)
# random uniform variable
nrws = 1000
uniform_vec = randst.uniform(size=nrws)

def make_bimodal(mean1,mean2,size):
    bimodal_1 = randst.normal(size=nrws, loc=mean1)
    bimodal_2 = randst.normal(size=nrws, loc=mean2)
    bimdvec = []
    for i in range(size):
        bimdvec.append(randst.choice([bimodal_1[i], bimodal_2[i]]))
    return np.array(bimdvec)

# Make 2 Bimodal Variables
close_bimodal_vec = make_bimodal(2,-2,nrws)
far_bimodal_vec = make_bimodal(3,-3,nrws)

# Highly skewed variable correlated with Uniform_Variable
skewed_vec = np.exp(uniform_vec*randst.uniform(size=nrws)*3) + randst.uniform(size=nrws)*3

# Integer variable correlated with Close_Bimodal_Variable and Uniform_Variable
integer_vec = np.round(uniform_vec + close_bimodal_vec/3 + randst.uniform(size=nrws)*2)

# Make a DataFrame
dat = pd.DataFrame(

# Ampute the data.
ampdat = mf.ampute_data(dat,perc=0.25,random_state=randst)

# Plot the original data
import seaborn as sns
import matplotlib.pyplot as plt
g = sns.PairGrid(dat)

We can see how our variables are distributed and correlated in the graph above. Now let’s run our imputation process twice, once using mean matching, and once using the model prediction.

kernelmeanmatch <- mf.MultipleImputedKernel(ampdat,mean_match_candidates=5)
kernelmodeloutput <- mf.MultipleImputedKernel(ampdat,mean_match_candidates=0)


Let’s look at the effect on the different variables.

With Mean Matching

Without Mean Matching

You can see the effects that mean matching has, depending on the distribution of the data. Simply returning the value from the model prediction, while it may provide a better ‘fit’, will not provide imputations with a similair distribution to the original. This may be beneficial, depending on your goal.

Download Details:

Author: AnotherSamWilson
Download Link: Download The Source Code
Official Website: https://github.com/AnotherSamWilson/miceforest
License: MIT

Shirts and Gifts for Your Friends & Loved ☞ https://bit.ly/36PHvXY

#algorithms #python #data-science

What is GEEK

Buddha Community

miceforest: Fast Imputation with Random Forests in Python
Shardul Bhatt

Shardul Bhatt


Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.


Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

August  Larson

August Larson


Random Forest Algorithm in Python from Scratch

Coding the powerful algorithm in python using (mainly) arrays and loops

This article aims to demystify the popular random forest (here and throughout the text —** RF**) algorithm and show its principles by using graphs, code snippets and code outputs.

The full implementation of the RF algorithm written by me in python can be accessed via: https://github.com/Eligijus112/decision-tree-python

I highly encourage anyone who stumbled upon this article to dive deep into the code because the understanding of the code will make any future documentation reading about **RF **much more straightforward and less stressful.

Any suggestions about optimizations are highly encouraged and are welcomed via a pull request on GitHub.

The building blocks of RF are simple decision trees. This article will be much easier to read if the reader is familiar with the concept of a classification decision tree. It is highly recommended to go through the following article before going any further:

#coding #machine-learning #random-forest #python #python from scratch #random forest algorithm

Art  Lind

Art Lind


Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind


How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.


In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips

August  Larson

August Larson


Generate Random Numbers in Python

There are two types of random number generators: pseudo-random number generator and true random number generator.

Pseudorandom numbers depend on computer algorithms. The computer uses algorithms to generate random numbers. These random numbers are not truly random because they are predictable like the generated numbers using NumPy random seed.

Whereas, truly random numbers are generated by measuring truly physical random parameters so we can ensure that the generated numbers are truly random.

The pseudo-random numbers are not safe to use in cryptography because they can be guessed by attackers.

In Python, the built-in random module generates pseudo-random numbers. In this tutorial, we will discuss both types. So let’s get started.

Table of Contents

#python #random #generate random numbers #random numbers #generate random numbers in python