Skip to content

Function Documentation

This page provides reference documentation for the available tools and functions in mechanism_viewer.

Data Generation

mechanism_viewer.dataset_generator

This module provides tools for generating synthetic datasets and applying various missing-data mechanisms.

It allows the generation of complete datasets with customizable properties, such as the number of rows, columns, and data types.

In addition to defining the missing-data mechanism for each column of the dataset, users can specify each column's missing rates and dependencies.

This module enables users to simulate datasets with missing-data patterns for visualizing missing-data and testing the capabilities of other module tools.

apply_mar(column_data, observable_df, missing_rate=0.1, missingness_ascending=True)

Applies MAR mechanism to one column.

Parameters:

Name Type Description Default
column_data Series

The column to transform

required
observable_df DataFrame

The column(s) that are observable and will be used as missingness dependency

required
missing_rate float = 0.1

The missing rate of the column

0.1
missingness_ascending bool = True

Indicates whether the highest/lowest values must become missing

True

Returns:

Type Description
new_column (pd.Series): A copy of the column with the MAR mechanism applied

apply_mcar(column_data, missing_rate=0.1, random_state=DEFAULT_RANDOM_STATE)

Applies MCAR mechanism to one column.

Parameters:

Name Type Description Default
column_data Series

The column to transform

required
missing_rate float = 0.1

The missing rate of the column

0.1
random_state int

Seed used in stochastic routines for reproducible results.

= 42

Returns:

Type Description
new_column (pd.Series): A copy of the column with the MCAR mechanism applied

apply_missingness(df, n_complete_cols, missing_mechanism_array, missing_rate_array, missingness_ascending=True, random_state=DEFAULT_RANDOM_STATE)

Applies multiple missing-data mechanisms to a dataframe

Parameters:

Name Type Description Default
df DataFrame

The dataframe that will be transformed

required
n_complete_cols int

The number of the first columns of the dataframe that won't have the missing mechanism applied

required
missing_mechanism_array list[str]

The list containing the missing mechanism that needs to be applied for each column (excluding the complete columns)

required
missing_rate_array list[float]

The missing rate of each column with missing mechanism applied

required
missingness_ascending bool = True

Indicates whether the highest/lowest values must become missing

True
random_state int

Seed used in stochastic routines for reproducible results.

= 42

Returns:

Type Description
new_data (pd.DataFrame): A copy of the dataframe with the missing-data mechanisms applied

apply_mnar(column_data, missing_rate=0.1, missingness_ascending=True)

Applies MNAR mechanism to one column.

Parameters:

Name Type Description Default
column_data Series

The column to transform

required
missing_rate float = 0.1

The missing rate of the column

0.1
missingness_ascending bool = True

Indicates whether the highest/lowest values must become missing

True

Returns:

Type Description
new_column (pd.Series): A copy of the column with the MNAR mechanism applied

generate_dataset_with_missingness(n_rows, type_array, n_complete_cols, missing_mechanism_array, missing_rate_array, missingness_ascending=True, random_state=DEFAULT_RANDOM_STATE)

Generates a dataset with missing-data mechanisms. Applies the above functions for user usability.

Parameters:

Name Type Description Default
n_rows int

Indicates the number of rows the dataset must have

required
type_array list[str]

Indicates the type of each column

required
n_complete_cols int

The number of the first columns of the dataframe that won't have the missing mechanism applied

required
missing_mechanism_array list[str]

The list containing the missing mechanism that needs to be applied for each column (excluding the complete columns)

required
missing_rate_array list[float]

The missing rate of each column with missing mechanism applied

required
missingness_ascending bool = True

Indicates whether the highest/lowest values must become missing

True
random_state int

Seed used in stochastic routines for reproducible results.

= 42

Returns:

Type Description
new_data (pd.DataFrame): A copy of the dataframe with the missing-data mechanisms applied

generate_synthetic_dataset(n_rows, type_array, random_state=DEFAULT_RANDOM_STATE)

Generates a synthetic dataset according to the properties given.

Parameters:

Name Type Description Default
n_rows int

The number of rows the dataset must have.

required
type_array list[str]

The array with the type of each column.

required
random_state int

Seed used in stochastic routines for reproducible results.

= 42

Returns:

Type Description
synthetic_df (pd.DataFrame): A dataframe with the given properties

Data Types

mechanism_viewer.ColType

Column data types supported by the synthetic dataset generator and imputation diagnostics.

It specifies the type of synthetic column to generate and the imputation strategy to apply.

Type Meaning Example use
ColType.CONTINUOUS Numeric values with continuous variation height, age, temperature
ColType.DISC_CATEGORICAL Discrete values representing categories score group, stage, class label
ColType.DISCRETE Integer numeric values number of visits, count values
ColType.BINARY Binary values represented as 0 and 1 yes/no, positive/negative

Missingness Visualization

mechanism_viewer.viewer_simple

The functions below plot simple visualization content, as a way to aid in the profiling of the dataset in the early stages of identifying the missing data mechanism.

plot_missing_rate(df, display_plot=False)

Plots the missing rate of each column.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used for plotting

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_missing_rate, ax_missing_rate) reobserveding the plot available for display.

plot_missingness_distribution(df, missing_col, display_plot=False)

Creates multiple plots showing the distribution of each column based on the missingness of missing_col. If the existence of red bars appear throughout the plot, then missing_col does not see any relationship with the column at hand, in regards to the way its missing values appear. In the other hand, if most red bars appear in a zone of the plot, then it is likely that missing_col has a MAR missing mechanism, and depends on the column at hand.

If a column has non-numeric data, then the distribution plot is created using countplot instead of histplot

Parameters:

Name Type Description Default
df DataFrame

The dataframe that will be used for plotting

required
missing_col str

The column with missing values, that will be used to group the other columns into 2 groups: rows that have NaN in missing_col, and rows that have a value in missing_col.

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig1, ax1, fig2, ax2, ..., figN, axN) reobserveding all plots available for display, Order follows df.columns, skipping missing_col.

plot_total_missingness(df, display_plot=False)

Plot the total number and percentage of every observed and missing cells in the dataset.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used for plotting

required
display_plot bool

If True, displays the figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_total_missingness, ax_total_missingness) reobserveding the plot available for display.

mechanism_viewer.viewer_matrix

The methods plot matrices with multiple missing and complete columns, with a focus on the missing rows and the missing rate.

missing_rate_matrix(df, column_name, sort_by_column=True, display_plot=False)

Plots a matrix of missing rate. It uses column_name to group the values of the other columns, and checks for each group the missing rate of the column. The darker the cells are, the higher the missing rate will be of a column for that particular value of column_name. If the color of a column is similar all over column_name, then the column is likely to not depend on column_name for its missing values. In contrast, if there is a darker region, the column is likely having MAR mechanism.

Its best to use this plot when column_name is not continuous or when it does not contain multiple values. Perfect for multivariate missing columns.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot.

required
column_name str

The observed column name that will be used for comparison

required
sort_by_column bool

To sort the column_name values in ascending order for better visualization

= True
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_miss_matrix, ax_miss_matrix) representing the plot available for display.

missing_rows_matrix(df, sort_by_complete=False, display_plot=False)

Plots a matrix of all missing rows. It enables to check which rows depend on which values of complete columns. Besides, rows with the same attributes missing can as well be viewed.

Columns with missing rows that have mostly high/low values for complete columns, indicate a missingness dependency on that complete column, giving indication for a MAR mechanism.

Complete columns will be displayed in green hues (light green = low value, dark green = high value), while missing columns will have their missingness displayed in red (white = not missing, red = missing).

Perfect for continuous or numeric complete columns, and for multivariate missing columns.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot.

required
sort_by_complete bool

To sort the complete columns for better visualization

= False
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_dep_matrix, ax_dep_matrix) representing the plot available for display.

mechanism_viewer.viewer_upset

The visualization tool on this module focuses on plotting a similar UpSet plot for rows with the same attributes missing.

upset_missing_rows(df, min_rows_display=0, display_plot=False)

Creates a plot similar to UpSet plot. It retrieves which rows have the same attributes missing, by indicating the count of those rows, and which are the missing attributes.

The plot can be filtered to show only the bars that have at least the minimum number of rows.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot.

required
min_rows_display int

The minimum number of rows that a bar must have to be displayed on the plot.

0
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_similar_miss, ax_similar_miss) representing the plot available for display.

mechanism_viewer.viewer_dendrogram

This module provides a dendrogram for grouping columns with similar missingness patterns.

missingness_dendrogram(df, linkage_method='average', display_plot=False)

Plot a dendrogram that groups columns with similar missingness patterns.

Each column is converted into a binary missingness indicator, where 1 represents a missing value and 0 represents an observed value. The correlation between these indicators is used to calculate the distance between columns. Columns that tend to contain missing values in the same rows are therefore joined closer together in the dendrogram.

Complete columns and columns containing only missing values are excluded because their missingness does not vary.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used for plotting.

required
linkage_method (single, complete, average, weighted)

default = "average" The linkage method used to calculate the distance between clusters.

"single"
display_plot bool

If True, displays the figure with plt.show().

= False

Returns:

Type Description
tuple

(fig_dendrogram, ax_dendrogram) representing the plot available for display.

mechanism_viewer.viewer_correlation

This file includes correlation heatmaps that use missingness of missing columns.

complete_and_misscol_corr(df, display_plot=False)

Plots a correlation heatmap showing whether there are missing columns with missing values in similar rows. Besides, it shows whether the complete columns' values will correlate with the missing rows in the missing columns. Therefore, it works with both complete columns and missing columns.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot the correlation heatmap

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_comp_corr, ax_comp_corr) representing the plot available for display.

misscol_vs_all_corr(df, missing_col, display_plot=False)

Plots a correlation heatmap showing whether the missing column has its missingness correlated with values from the other columns, no matter if they are complete or missing.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot the correlation heatmap

required
missing_col str

The missing column name that will be used for correlation

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_vs_corr, ax_vs_corr) representing the plot available for display.

missingness_misscol_corr(df, display_plot=False)

Plots a correlation heatmap showing whether there are missing columns with missing values in similar rows. Therefore, it only works with columns with missing data.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot the missingness correlation heatmap

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_mssng_corr, ax_mssng_corr) representing the plot available for display.

value_misscol_corr(df, display_plot=False)

Plots a correlation heatmap for the values of the missing columns. It is focused on only plotting the correlation for columns with missing data.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot the value correlation heatmap of missing columns

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_miss_corr, ax_miss_corr) representing the plot available for display.

mechanism_viewer.viewer_comparison

The visualization tools described below can be used to compare observed columns with the missingness of a column. For best visualization, the first two should be used with an observed column with continuous data type.

boxplot_comparison(df, column_name, missing_col, display_plot=False)

Shows three boxplots: the boxplot of column_name when missing_col has values, the boxplot of column_name when the values of missing_col are missing, and the general boxplot of column_name no matter the missingness of missing_col.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot.

required
column_name str

The observed column name that will be used for comparison

required
missing_col str

The missing column name that will be used for comparison

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_boxplot, ax_boxplot) representing the plot available for display.

parallel_comparison(df, missing_col, display_plot=False)

Plot a parallel coordinates chart that compares the values of all numeric observed columns according to whether missing_col is missing.

Each line represents one row of the dataset. Blue lines correspond to rows where missing_col is observed, while red lines correspond to rows where missing_col is missing.

If the red lines cluster in a different region from the blue lines for one or more columns, this suggests that the missingness of missing_col may be associated with the values of those columns, providing evidence consistent with a MAR mechanism.

Only numeric columns are included in the plot because parallel coordinates require numerical values for normalization. All numeric columns are normalized to the range [0, 1] so that they can be displayed on the same scale.

Due to overplotting, this visualization is most useful for datasets with a moderate number of rows.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot.

required
missing_col str

The name of the column whose missingness will be compared against the values of the other columns

required
display_plot bool

If True, displays the figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_parallel, ax_parallel) representing the plot available for display.

scatter_missingness_comparison(df, column_name, missing_col, display_plot=False)

Plots a scatterplot for the data points (column_name, is_not_missing(missing_col))

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot.

required
column_name str

The observed column name that will be used for comparison

required
missing_col str

The missing column name that will be used for comparison

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_comp, ax_comp) representing the plot available for display.

scatter_missingness_comparison_line(df, column_name, missing_col, display_plot=False)

Plots a scatterplot for the data points (column_name, is_not_missing(missing_col)) in a single line.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to plot.

required
column_name str

The observed column name that will be used for comparison

required
missing_col str

The missing column name that will be used for comparison

required
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_comp_line, ax_comp_line) representing the plot available for display.

Imputation Diagnostics

mechanism_viewer.viewer_imputation

The below code implements imputation models to generate values for missing data in a specific missing column, depending on its data type. The imputed data can then be used to find hidden missing patterns, when comparing to other observed columns.

plot_imputation_distribution(df, missing_col, missing_col_type='normal', random_state=DEFAULT_RANDOM_STATE, display_plot=False)

Plots a kdeplot comparing the distribution of a column with the distribution of the same column with imputed values.

This does not offer much aid in figuring the data missing mechanism. It only serves the purpose of showcasing each imputation model working for the correct data type.

Parameters:

Name Type Description Default
df DataFrame

The dataframe that will be used for imputation

required
missing_col str

The name of the column with missing data, that will have its values imputed

required
missing_col_type str

The type of data that missing_col is, to better select the imputation model

= "normal"
random_state int

Seed used in stochastic imputation routines for reproducible results.

= 42
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_imput_dist, ax_imput_dist, imputed_df) representing the plot available for display, and the dataframe with imputed values on missing_col, along with the complete data used for imputation.

scatter_imputation_comparison(df, column_name, missing_col, missing_col_type='normal', random_state=DEFAULT_RANDOM_STATE, display_plot=False)

Plot a scatterplot that compares the values of a column with missing values, and the imputed values of those missing values. A different column (an observed column) will be used to compare the values. All complete columns of the dataset will help the imputation algorithm guess the missing values.

If the imputed values appear consistently distributed uniformly, then the missing data mechanism is plausible to be MCAR/MNAR. If the imputed values appear in a specific zone of the plot, then the missing_col is most likely to have a MAR mechanism and be dependent on column_name.

Note: If missing_col does not depend on column_name to have its values missing, then, even if missing_col has a MAR mechanism, the imputed values might appear to have an uniform distribution. Therefore, it is advisable to run more tests, before concluding the column missing mechanism.

Parameters:

Name Type Description Default
df DataFrame

The dataframe that will be used for imputation

required
column_name str

The name of the complete column that will be on the x axis

required
missing_col str

The name of the column with missing data, that will have its values imputed

required
missing_col_type str

The type of data that missing_col is, to better select the imputation model

= "normal"
random_state int

Seed used in stochastic imputation routines for reproducible results.

= 42
display_plot bool

If True, displays figure with plt.show()

= False

Returns:

Type Description
tuple

(fig_imput_comp, ax_imput_comp) representing the plot available for display.

Parameter missing_col_type for Imputation

The imputation model to be used in missing_col is determined by missing_col_type. In other words, the function selects the model that is best suited for the data type of the missing column. However, the default value of the parameter, missing_col_type="normal", can be used for a MICE model imputation.

Moreover, the columns used for imputation depend on the selected missing_col_type. For continuous/MICE imputation, numeric columns are used, including numeric columns with missing values. This is useful for real-world datasets, where incomplete numeric columns may still help explain each other. For binary, discrete, and categorical imputation, only complete columns are used, because the current models cannot handle missing values.

Ultimately, always select the appropriate ColType value when using the Imputation module.

from mechanism_viewer import ColType
mv.plot_imputation_distribution(df_missing, "Col3", missing_col_type=ColType.DISCRETE)

Statistical Diagnostics

mechanism_viewer.accuracy_mar

These algorithms run models to obtain a prediction accuracy value.

By splitting the dataset into training and testing sets, and then training a predictive model, we can evaluate how accurately the model predicts the missing values. As a consequence, an high prediction accuracy suggests that the missingness can be explained by the observed variables, which indicates that the underlying mechanism is likely MAR.

For an average accuracy value that is 5% (which can be changed in parameter threshold) higher than the baseline ( max(1-missing_rate, missing_rate) ), it is likely that underlying mechanism is MAR. In contrast, if the difference between the average accuracy and the baseline is close to 0 or negative, then it is likely to be MCAR/MNAR.

Common Pitfalls and Limitations The models works best at identifying MAR/MCAR/MNAR when the datasets have continuous data. Other types of data may have a smaller difference between the missing mechanisms. Non-numeric data cannot be used due to the nature of the models.

interpret_mar_abd(accuracy_baseline_diff, threshold=5.0)

Return the interpretation of an Accuracy Baseline Difference (ABD) value in a human readable way.

Parameters:

Name Type Description Default
accuracy_baseline_diff float

The Accuracy Baseline Difference (ABD) value

required
threshold float

Threshold (in percentage points) used to classify likely MAR vs MCAR/MNAR

= 5.0

Returns:

Type Description
str

The string containing a human readable interpretation of the ABD value.

run_logistic_regression(df, missing_col, random_state=DEFAULT_RANDOM_STATE, print_result=True)

Trains a Logistic Regression model to obtain the test accuracy value.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to train and test the model.

required
missing_col str

The missing column to be used on the model.

required
random_state int

Seed used in stochastic model routines for reproducible results.

= 42
print_result bool = True

The boolean indicating whether to print the result.

True

Returns:

Type Description
float

The prediction accuracy of the model when train with the dataset.

run_random_forest(df, missing_col, random_state=DEFAULT_RANDOM_STATE, print_result=True)

Trains a Random Forest model to obtain the test accuracy value. The model uses 100 estimators.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to train and test the model.

required
missing_col str

The missing column to be used on the model.

required
random_state int

Seed used in stochastic model routines for reproducible results.

= 42
print_result bool = True

The boolean indicating whether to print the result.

True

Returns:

Type Description
float

The prediction accuracy of the model when train with the dataset.

test_mar_from_model_accuracy(df, missing_col, threshold=5.0, random_state=DEFAULT_RANDOM_STATE, print_result=True)

Calculates the Accuracy Baseline Difference (ABD), an heuristic that estimates whether the missingness mechanism of a column is likely MAR (Missing At Random) by comparing the average model accuracy with a baseline.

The function trains a Random Forest and a Logistic Regression model to predict the missingness of the specified column. It then compares the average accuracy of these models with a baseline based on the missing rate of the column.

If the model accuracy exceeds the baseline by more than the threshold, (in percentage points), it suggests that the missingness can be predicted from other variables, indicating that the mechanism is likely MAR. Otherwise, the missingness is more likely MCAR/MNAR.

Formula
ABD = ((RF_accuracy + LR_accuracy) / 2 - baseline) * 100
where
baseline = max(p, 1 - p)
p = missing_rate(missing_col)

Parameters:

Name Type Description Default
df DataFrame

The dataset containing the column with missing values

required
missing_col str

The name of the column whose missingness mechanism will be assessed

required
threshold float

Threshold (in percentage points) used to classify likely MAR vs MCAR/MNAR

= 5.0
random_state int

Seed used in stochastic model routines for reproducible results

= 42
print_result bool = True

The boolean indicating whether to print the results of the models and print the accuracy result of the most likely missing data mechanism

True

Returns:

Type Description
float

The Accuracy Baseline Difference (ABD), which represents the difference (in percentage points) between the average model accuracy and the baseline accuracy. Result rounded to 2 decimal places.

mechanism_viewer.little_mcar

These algorithms run the Little's MCAR Test.

Little's MCAR (Missing Completely At Random) test evaluates whether the probability of data being missing is unrelated to observed or unobserved data. When data is MCAR, missingness does not introduce bias, making it safe to use techniques like listwise deletion.

Key Assumptions of Little's MCAR Test - Data missingness is random across all variables. - The sample is representative of the population under study. - Sufficient sample size exists to compute reliable statistics.

Common Pitfalls and Limitations - Low Power: Small sample sizes or subtle data patterns can lead to inconclusive results. - Misinterpretation: A non-significant result does not confirm data is MCAR; it only indicates insufficient evidence against the null hypothesis. - Numerical Data Dependency: The test is designed for numerical data, limiting its applicability to categorical datasets.

Best Practices - Use covariates relevant to the context of missing data. - Ensure adequate sample size to boost test reliability. - Use visualization tools like missingness heatmaps for preliminary insights.

Reference

https://www.linkedin.com/pulse/understanding-littles-mcar-test-comprehensive-guide-data-debasish-deb-fbmpf

Documentation: https://rianneschouten.github.io/pyampute/build/html/pyampute.exploration.html

interpret_mcar_p_value(p_value, alpha=0.05)

Return the results of the Little's MCAR chi-square test in a human readable way, including the potential missing data mechanism in the dataset.

Parameters:

Name Type Description Default
p_value float

The p-value obtained from the Little's MCAR chi-square test

required
alpha float

The alpha value that will be used for the rejection of the null hypothesis

= 0.05

Returns:

Type Description
str

The string containing a human readable interpretation of a Little's MCAR p-value.

little_mcar_global(df)

Runs the Little's MCAR Test. It performs a chi-square test on the entire dataset.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to run the test

required

Returns:

Type Description
float

The p-value of the test based on the entire dataset

little_mcar_pairwise(df)

Runs the Little's MCAR Test. It performs a separate t-test for every pair of columns possible. Since each t-test returns a p-value, the function returns every pair combination and its p-value.

Notes

This function does not plot or print. Use plot_mcar_pairwise to visualize the returned matrix.

Parameters:

Name Type Description Default
df DataFrame

The dataset to be used to run the test

required

Returns:

Type Description
DataFrame

A p_value matrix dataframe with every p-value of each pair combination

plot_mcar_pairwise(p_values, alpha=0.05, display_plot=False)

Return the plots of p-values obtained from Little's MCAR t-test, including the potential missing data mechanism in the dataset. The plots are available for display.

Parameters:

Name Type Description Default
p_values DataFrame

The output obtained from the Little's MCAR t-test

required
alpha float

The alpha value that will be used for the rejection of the null hypothesis

= 0.05
display_plot bool

If True, displays figures with plt.show()

= False

Returns:

Type Description
tuple

(fig_p_values, ax_p_values, fig_reject, ax_reject) representing the 2 plots available for display.