Utilities

Data

mlarena.utils.data_utils.clean_dollar_cols(data, cols_to_clean)[source]

Clean specified columns of a Pandas DataFrame by removing ‘$’ symbols, commas, and converting to floating-point numbers.

Parameters:
  • data (pd.DataFrame) – The DataFrame to clean.

  • cols_to_clean (List[str]) – List of column names to clean.

Returns:

DataFrame with specified columns cleaned of ‘$’ symbols and commas, and converted to floating-point numbers.

Return type:

pd.DataFrame

Examples

>>> df = pd.DataFrame({
...     'price': ['$1,234.56', '$789.00', '$2,000'],
...     'revenue': ['$50,000', '$75,000.50', '$100,000'],
...     'name': ['A', 'B', 'C']
... })
>>> clean_dollar_cols(df, ['price', 'revenue'])
   price  revenue name
0  1234.56  50000.00    A
1   789.00  75000.50    B
2  2000.00 100000.00    C
mlarena.utils.data_utils.value_counts_with_pct(data, cols, dropna=False, decimals=2)[source]

Calculate the count and percentage of occurrences for unique values or value combinations.

Parameters:
  • data (pd.DataFrame) – The DataFrame containing the data.

  • cols (str or List[str]) – Column name or list of column names to analyze. If multiple columns are provided, counts unique combinations of values across these columns.

  • dropna (bool, default=False) – Whether to exclude NA/null values.

  • decimals (int, default=2) – Number of decimal places to round the percentage.

Returns:

A DataFrame with: - For single column: unique values, their counts, and percentages - For multiple columns: unique value combinations, their counts, and percentages

Return type:

pd.DataFrame

Examples

>>> df = pd.DataFrame({
...     'category': ['A', 'A', 'B', 'B', 'B', None],
...     'status': ['Active', 'Active', 'Inactive', None, None, None]
... })
>>> # Single column
>>> value_counts_with_pct(df, 'category')
  category  count   pct
0       B      3  50.0
1       A      2  33.3
2    None      1  16.7
>>> # Multiple columns - counts combinations
>>> value_counts_with_pct(df, ['category', 'status'])
  category   status  count   pct
0       B     None      2  33.3
1       A   Active      2  33.3
2       B Inactive      1  16.7
3    None     None      1  16.7
mlarena.utils.data_utils.transform_date_cols(data, date_cols, str_date_format='%Y%m%d')[source]

Transforms specified columns in a Pandas DataFrame to datetime format.

Parameters:
  • data (pd.DataFrame) – The input DataFrame.

  • date_cols (Union[str, List[str]]) – A column name or list of column names to be transformed to dates.

  • str_date_format (str, default="%Y%m%d") –

    The string format of the dates, using Python’s strftime/strptime directives. Common directives include:

    %d: Day of the month as a zero-padded decimal (e.g., 25)
    %m: Month as a zero-padded decimal number (e.g., 08)
    %b: Abbreviated month name (e.g., Aug)
    %B: Full month name (e.g., August)
    %Y: Four-digit year (e.g., 2024)
    %y: Two-digit year (e.g., 24)
    

    Example formats:

    "%Y%m%d"   → '20240825'
    "%d-%m-%Y" → '25-08-2024'
    "%d%b%Y"   → '25Aug2024'
    "%d%B%Y"   → '25August2024'
    "%d%b%y"   → '25Aug24'
    

    If the format uses %b or %B (month names), strings like ‘25AUG2024’ or ‘25august2024’ will be automatically converted to title case before parsing.

Returns:

The DataFrame with specified columns transformed to datetime format (datetime64[ns]). When only date information is provided (no time component), the time will be set to midnight (00:00:00).

To extract just the date component later, you can use:

  • df[‘date_col’].dt.date # Returns datetime.date objects

  • df[‘date_col’].dt.normalize() # Returns datetime64[ns] at midnight

  • df[‘date_col’].dt.floor(‘D’) # Returns datetime64[ns] at midnight

Return type:

pd.DataFrame

Raises:

ValueError – If date_cols is empty.

Examples

>>> df = pd.DataFrame({
...     'date': ['25Aug2024', '26AUG2024', '27aug2024']
... })
>>> # Convert to datetime
>>> df = transform_date_cols(df, 'date', str_date_format='%d%b%Y')
>>> print(df['date'].dtype)
datetime64[ns]
>>>
>>> # Extract date-only if needed
>>> df['date_only'] = df['date'].dt.date
>>> print(df['date_only'].iloc[0])
2024-08-25
mlarena.utils.data_utils.drop_fully_null_cols(data, verbose=False)[source]

Drops columns where all values are missing/null in a pandas DataFrame.

This function is particularly useful when working with Databricks’ display() function, which can break when encountering columns that are entirely null as it cannot infer the schema. Running this function before display() helps prevent such issues.

Parameters:
  • data (pd.DataFrame) – Input DataFrame to check for missing columns.

  • verbose (bool, default=False) – If True, prints information about which columns were dropped.

Returns:

A new DataFrame with fully-null columns removed.

Return type:

pd.DataFrame

Examples

>>> # In Databricks notebook:
>>> drop_fully_null_cols(df).display()  # this won't affect the original df, just ensure .display() work
>>> # To see which columns were dropped:
>>> drop_fully_null_cols(df, verbose=True)
mlarena.utils.data_utils.print_schema_alphabetically(data)[source]

Prints the schema (column names and dtypes) of the DataFrame with columns sorted alphabetically.

This is particularly useful when comparing schemas between different DataFrames or versions of the same DataFrame, as the alphabetical ordering makes it easier to spot differences.

Parameters:

data (pd.DataFrame) – The DataFrame whose schema is to be printed.

Returns:

Prints the schema to stdout.

Return type:

None

Examples

>>> df = pd.DataFrame({'c': [1], 'a': [2], 'b': ['text']})
>>> print_schema_alphabetically(df)
a    int64
b    object
c    int64
mlarena.utils.data_utils.is_primary_key(data, cols, verbose=True)[source]

Check if the combination of specified columns forms a primary key in the DataFrame.

A primary key traditionally requires: 1. Uniqueness: Each combination of values must be unique across all rows 2. No null values: Primary key columns cannot contain null/missing values

This implementation will: 1. Alert if there are any missing values in the potential key columns 2. Check if the columns form a unique identifier after removing rows with missing values

This approach is practical for real-world data analysis where some missing values might exist but we want to understand the column(s)’ potential to serve as a key.

Parameters:
  • data (pd.DataFrame) – The DataFrame to check.

  • cols (str or List[str]) – Column name or list of column names to check for forming a primary key.

  • verbose (bool, default=True) – If True, print detailed information.

Returns:

True if the combination of columns forms a primary key (after removing nulls), False otherwise.

Return type:

bool

Examples

>>> df = pd.DataFrame({
...     'id': [1, 2, None, 4],
...     'date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02'],
...     'value': [10, 20, 30, 40]
... })
>>> is_primary_key(df, 'id')  # Single column as string
>>> is_primary_key(df, ['id', 'date'])  # Multiple columns as list
mlarena.utils.data_utils.select_existing_cols(data, cols, verbose=False, case_sensitive=True)[source]

Select columns from a DataFrame if they exist.

Parameters:
  • data (pd.DataFrame) – The input DataFrame.

  • cols (Union[str, List[str]]) – Column name or list of column names to select.

  • verbose (bool, default=False) – If True, print which columns exist vs. are missing.

  • case_sensitive (bool, default=True) – If True, match column names exactly (case-sensitive). If False, match case-insensitively by lowering both data columns and input list. Returned DataFrame will still use original column names.

Returns:

DataFrame with only the matched columns (with original column casing).

Return type:

pd.DataFrame

Examples

>>> df = pd.DataFrame({'A': [1], 'B': [2], 'C': [3]})
>>> select_existing_cols(df, ['A', 'D', 'b'], case_sensitive=True)  # Only returns 'A'
>>> select_existing_cols(df, ['A', 'D', 'b'], case_sensitive=False)  # Returns 'A' and 'B'
>>> select_existing_cols(df, ['A', 'D'], verbose=True)  # Shows found/missing columns
mlarena.utils.data_utils.filter_rows_by_substring(data, column, substring, case_sensitive=False)[source]

Filter rows in a DataFrame where a specified column contains a given substring.

Parameters:
  • data (pd.DataFrame) – The DataFrame to filter.

  • column (str) – The name of the column to search within.

  • substring (str) – The substring to search for in the column values.

  • case_sensitive (bool, default=False) – Whether the matching should be case-sensitive.

Returns:

A filtered DataFrame containing only the rows where the column values contain the specified substring.

Return type:

pd.DataFrame

Raises:

KeyError – If the specified column does not exist in the DataFrame.

Examples

>>> df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie', 'alice']})
>>> filter_rows_by_substring(df, 'name', 'alice')
     name
0    Alice
3    alice
>>> filter_rows_by_substring(df, 'name', 'alice', case_sensitive=True)
     name
3    alice
mlarena.utils.data_utils.filter_columns_by_substring(data, substring, case_sensitive=False)[source]

Filter columns in a DataFrame by keeping only those whose names contain a given substring.

Parameters:
  • data (pd.DataFrame) – The DataFrame whose columns are to be filtered.

  • substring (str) – The substring to search for in column names.

  • case_sensitive (bool, default=False) – Whether the matching should be case-sensitive.

Returns:

A DataFrame with only the columns whose names contain the specified substring.

Return type:

pd.DataFrame

Raises:

ValueError – If no columns match the substring.

Examples

>>> df = pd.DataFrame({
...     'price_usd': [100, 200],
...     'price_eur': [90, 180],
...     'name': ['A', 'B']
... })
>>> filter_columns_by_substring(df, 'price')
   price_usd  price_eur
0        100         90
1        200        180
>>> filter_columns_by_substring(df, 'USD', case_sensitive=True)
Empty DataFrame
Columns: []
Index: [0, 1]
>>> filter_columns_by_substring(df, 'usd', case_sensitive=False)
   price_usd
0        100
1        200
mlarena.utils.data_utils.find_duplicates(df, cols)[source]

Function to find duplicate rows based on specified columns.

Parameters:
  • df (pd.DataFrame) – The DataFrame to check.

  • cols (str or List[str]) – Column name or list of column names to check for duplicates.

Returns:

DataFrame containing duplicate rows based on the specified columns, with the specified columns and the ‘count’ column as the first columns, along with the rest of the columns from the original DataFrame, ordered by the specified columns.

Return type:

pd.DataFrame

Examples

>>> df = pd.DataFrame({
...     'id': [1, 2, 3, 4, 5],
...     'name': ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob'],
...     'age': [25, 30, 25, 35, 35]
... })
>>> # Single column as string
>>> find_duplicates(df, 'name')
   count   name  id  age
0      2  Alice   1   25
1      2  Alice   3   25
2      2    Bob   2   30
3      2    Bob   5   35
>>> # Multiple columns as list
>>> find_duplicates(df, ['name', 'age'])
   count   name  age  id
0      2  Alice   25   1
1      2  Alice   25   3
mlarena.utils.data_utils.deduplicate_by_rank(df, id_cols, ranking_col, ascending=False, tiebreaker_col=None, verbose=False)[source]

Deduplicate rows by keeping the best-ranked row per group of id_cols, optionally breaking ties by preferring non-missing tiebreaker_col.

Parameters:
  • df (pd.DataFrame) – The DataFrame to deduplicate.

  • id_cols (Union[str, List[str]]) – Column(s) defining the unique entity (e.g., customer_id, product_id).

  • ranking_col (str) – The column to rank within each group (e.g., ‘date’, ‘score’, ‘priority’).

  • ascending (bool, default=False) – Sort order for ranking_col: - True: smallest value kept (e.g., earliest date) - False: largest value kept (e.g., most recent date, highest score)

  • tiebreaker_col (Optional[str], default=None) – Column where non-missing values are preferred in case of ties. Useful when ranking_col has identical values.

  • verbose (bool, default=False) – If True, print information about the deduplication process.

Returns:

Deduplicated DataFrame with one row per unique combination of id_cols.

Return type:

pd.DataFrame

Examples

>>> df = pd.DataFrame({
...     'customer_id': ['C001', 'C001', 'C002', 'C002', 'C003'],
...     'transaction_date': ['2024-01-01', '2024-01-15', '2024-01-05', '2024-01-10', '2024-01-20'],
...     'amount': [100, 200, 150, 150, 300],
...     'email': ['old@email.com', 'new@email.com', None, 'email@test.com', 'test@email.com']
... })
>>> # Keep most recent transaction per customer
>>> deduplicate_by_rank(df, 'customer_id', 'transaction_date', ascending=False)
   customer_id transaction_date  amount           email
0        C001       2024-01-15     200   new@email.com
1        C002       2024-01-10     150  email@test.com
2        C003       2024-01-20     300  test@email.com
>>> # Keep highest amount, break ties by preferring non-null email
>>> deduplicate_by_rank(df, 'customer_id', 'amount', ascending=False, tiebreaker_col='email')
   customer_id transaction_date  amount           email
0        C001       2024-01-15     200   new@email.com
1        C002       2024-01-10     150  email@test.com
2        C003       2024-01-20     300  test@email.com
mlarena.utils.data_utils.pivot_by_group(data, id_column='id', group_column='group', separator='_', agg_func='first', sort_columns=True, handle_duplicates='raise')[source]

Pivot a DataFrame by group values, transforming data from long to wide format.

Parameters:
  • data (pd.DataFrame) – Input DataFrame with separate ID and group columns

  • id_column (str, default='id') – Name of the column that uniquely identifies each entity

  • group_column (str, default='group') – Name of the column containing the values to be used as column suffixes

  • separator (str, default='_') – Separator to use between column name and group value

  • agg_func (str, default='first') – Aggregation function to use when there are duplicate id-group combinations. Options: ‘first’, ‘last’, ‘mean’, ‘sum’, ‘min’, ‘max’

  • sort_columns (bool, default=True) – Whether to sort the output columns alphabetically

  • handle_duplicates (str, default='raise') – How to handle duplicate id-group combinations: - ‘raise’: Raise an error with details about duplicates - ‘warn’: Print warning with duplicate details and apply agg_func

Returns:

Pivoted DataFrame with ID as primary key and grouped columns

Return type:

pd.DataFrame

Raises:

ValueError –

  • If required columns are not found in DataFrame - If group_column contains null values - If handle_duplicates=’raise’ and duplicates are found - If agg_func is not one of the supported functions - If handle_duplicates is not one of ‘raise’ or ‘warn’

Examples

>>> df = pd.DataFrame({
...     'id': ['aaa', 'aaa', 'bbb'],
...     'group': [1, 2, 1],
...     'surname': ['smith', 'cook', 'jones'],
...     'age': [25, 30, 35]
... })
>>> pivot_by_group(df)
   id  surname_1  surname_2  age_1  age_2
0  aaa     smith      cook     25     30
1  bbb     jones      NaN     35    NaN
>>> # Handle duplicates with aggregation
>>> df_dups = pd.DataFrame({
...     'id': ['aaa', 'aaa', 'bbb'],
...     'group': [1, 1, 1],
...     'value': [10, 20, 30]
... })
>>> pivot_by_group(df_dups, handle_duplicates='warn', agg_func='mean')
   id  value_1
0  aaa     15.0
1  bbb     30.0
mlarena.utils.data_utils.clean_null_representations(data, numeric_sentinel_values=None, numeric_range_limits=None, replace_inf=True, zero_as_null_cols=None, custom_string_nulls=None, verbose=False)[source]

Clean null representations in both numeric and categorical columns.

This function standardizes various null representations across different data types: - Categorical columns: Converts string nulls (‘nan’, ‘NULL’, etc.) to None - Numeric columns: Converts inf, sentinel values, and out-of-range values to NaN

Parameters:
  • data (pd.DataFrame) – Input DataFrame to clean

  • numeric_sentinel_values (dict, optional) – Dictionary mapping column names to lists of values that should be treated as null. Example: {‘age’: [-1, 999], ‘score’: [-999, 9999]}

  • numeric_range_limits (dict, optional) – Dictionary mapping column names to min/max valid ranges. Values outside these ranges will be converted to NaN. Example: {‘age’: {‘min’: 0, ‘max’: 150}, ‘percentage’: {‘min’: 0, ‘max’: 100}}

  • replace_inf (bool, default True) – Whether to replace infinite values (inf, -inf) with NaN in numeric columns

  • zero_as_null_cols (List[str], optional) – List of numeric column names where zero values should be treated as null. Example: [‘optional_id’, ‘bonus_amount’]

  • custom_string_nulls (List[str], optional) – Additional string representations to treat as null beyond the default list. Default nulls: [‘nan’, ‘NaN’, ‘None’, ‘null’, ‘NULL’, ‘’, ‘<NA>’, ‘N/A’, ‘n/a’] Example: [‘missing’, ‘unknown’, ‘–’, ‘TBD’]

  • verbose (bool, default False) – If True, print information about the cleaning process.

Returns:

DataFrame with standardized null representations

Return type:

pd.DataFrame

Examples

>>> df = pd.DataFrame({
...     'name': ['John', 'nan', None, 'Alice'],
...     'age': [25, -1, 30, np.inf],
...     'score': [85.5, -999, np.nan, 88.0],
...     'status': ['active', 'NULL', '', 'inactive']
... })
>>> # Define custom cleaning rules
>>> sentinel_values = {
...     'age': [-1, 999],
...     'score': [-999, 9999]
... }
>>> range_limits = {
...     'age': {'min': 0, 'max': 120},
...     'score': {'min': 0, 'max': 100}
... }
>>> custom_nulls = ['missing', 'unknown', '--']
>>>
>>> cleaned_df = clean_null_representations(
...     df,
...     numeric_sentinel_values=sentinel_values,
...     numeric_range_limits=range_limits,
...     custom_string_nulls=custom_nulls,
...     verbose=True
... )

Notes

  • The function preserves original data types where possible

  • Numeric columns use np.nan for null values

  • Categorical columns use None for null values

  • The function creates a copy of the input DataFrame

  • Processing order: inf replacement → sentinel values → range limits → zero replacement

See also

drop_fully_null_cols

Drop columns where all values are missing/null

value_counts_with_pct

Calculate value counts including null values

mlarena.utils.data_utils.read_csv_with_encoding(file_path, encodings=None, nrows=None, verbose=False, **read_csv_kwargs)[source]

Attempt to read a CSV file using multiple encodings.

This function tries to read a CSV file with different character encodings, which is particularly useful when working with data from various sources or regions where the encoding might be unknown.

Parameters:
  • file_path (str) – Path to the CSV file.

  • encodings (List[str], optional) – Encodings to try in order. If None, uses a comprehensive list of common encodings starting with UTF-8.

  • nrows (int, optional) – Read only first n rows while testing. Useful for large files. If None, reads the entire file.

  • verbose (bool, default=False) – If True, print information about encoding attempts and success.

  • **read_csv_kwargs – Additional arguments forwarded to pandas.read_csv.

Returns:

The loaded DataFrame.

Return type:

pd.DataFrame

Raises:
  • FileNotFoundError – If the specified file does not exist.

  • UnicodeDecodeError – If none of the encodings succeed in reading the file.

Examples

>>> # Basic usage with default encodings
>>> df = read_csv_with_encoding('data.csv')
>>> # Custom encodings with verbose output
>>> df = read_csv_with_encoding(
...     'international_data.csv',
...     encodings=['utf-8', 'latin-1', 'cp1252'],
...     verbose=True
... )
>>> # Test with limited rows for large files
>>> df = read_csv_with_encoding(
...     'large_file.csv',
...     nrows=1000,
...     verbose=True
... )

Notes

The default encoding list prioritizes common encodings: - UTF-8 variants (most common modern encoding) - Western European encodings (latin-1, cp1252, iso-8859-1) - ASCII (basic compatibility) - Other regional encodings (Asian, Cyrillic, etc.)

When nrows is specified, only the first n rows are read during encoding detection, which can significantly speed up the process for large files.

Plotting

mlarena.utils.plot_utils.plot_box_scatter(data, x, y, title='Box Plot with Scatter Overlay', xlabel=None, ylabel=None, point_hue=None, point_size=30, point_alpha=0.6, jitter=0.1, box_alpha=0.3, single_color_box=False, figsize=(10, 6), palette=None, xticklabel_rotation=45, stat_test=None, stats_only=False, show_stat_test=None, return_stats=False, stat_annotation_pos=(0.02, 0.98), stat_annotation_fontsize=10, stat_annotation_bbox=True)[source]

Draws a box plot with optional scatter overlay and customizable coloring behavior.

Parameters:
  • data (pd.DataFrame) – DataFrame containing the data.

  • x (str) – Column name for categorical items.

  • y (str) – Column name for numerical values.

  • title (str, default="Box Plot with Scatter Overlay") – Title of the plot.

  • xlabel (str, optional) – Label for x-axis. If None, uses the x column name.

  • ylabel (str, optional) – Label for y-axis. If None, uses the y column name.

  • point_hue (str, optional) – Column name to color points by. If set, overrides color-by-x behavior. If column does not exist, a warning will be issued and the plot will be created without point_hue coloring.

  • point_size (int, default=30) – Size of the overlaid scatter points.

  • point_alpha (float, default=0.6) – Transparency level for points.

  • jitter (float, default=0.1) – Amount of horizontal jitter for points.

  • box_alpha (float, default=0.3) – Transparency level for box fill.

  • single_color_box (bool, default=False) – Whether to use a single color for all boxes and points (if point_hue is None).

  • figsize (tuple, default=(10, 6)) – Size of the figure as (width, height) in inches.

  • palette (List[str], optional) – List of colors. If None, uses Matplotlib’s default color cycle.

  • xticklabel_rotation (float, default=45) – Rotation angle for x-axis tick labels in degrees.

  • stat_test (str, optional) – Statistical test to perform across groups. Supported: “anova”, “welch”, “kruskal”. If not specified but show_stat_test=True or stats_only=True, defaults to “anova”. If specified, automatically sets show_stat_test=True unless explicitly set to False.

  • stats_only (bool, default=False) – If True, skip plotting and return only statistical results. Automatically sets stat_test=”anova” if not specified.

  • show_stat_test (bool, optional) – If True, display statistical test results as an annotation on the plot. If None (default), automatically set to True when stat_test is specified. If False, statistical test is computed but not displayed.

  • return_stats (bool, default=False) – If True, return statistical results. When False, only returns (fig, ax) even if statistical tests are computed.

  • stat_annotation_pos (Tuple[float, float], default=(0.02, 0.98)) – Position of the statistical annotation as (x, y) in axes coordinates (0-1). (0, 0) is bottom-left, (1, 1) is top-right.

  • stat_annotation_fontsize (int, default=10) – Font size for the statistical annotation.

  • stat_annotation_bbox (bool, default=True) – Whether to add a background box to the statistical annotation.

Returns:

  • When stats_only=True: Dictionary containing statistical results only

  • When stats_only=False and return_stats=False: (fig, ax)

  • When stats_only=False and return_stats=True: (fig, ax, results)

  • results dict contains:
    • ’summary_table’: DataFrame with count, mean, median, std per category.

    • ’stat_test’: Dictionary with keys ‘method’, ‘statistic’, ‘p_value’, ‘effect_size’.

Return type:

Union[Tuple[plt.Figure, plt.Axes], Tuple[plt.Figure, plt.Axes, dict], dict]

Note

Statistical test parameters have been designed with intelligent defaults to optimize user experience. The following scenarios are automatically handled:

  1. Plot only (default): Just call the function with data - no statistical tests performed.

  2. Plot with statistical annotation: - Specify stat_test=”anova”/”kruskal” → automatically shows test results on plot - Or set show_stat_test=True → automatically uses default test method - Returns only (fig, ax) unless explicitly requested otherwise

  3. Access statistical results: - Add return_stats=True → returns (fig, ax, results) - Or use stats_only=True → returns only results (no plotting)

This design seeks to support common use cases withou minimal manual configuration.

mlarena.utils.plot_utils.plot_metric_event_over_time(data, x, y, event_dates=None, title='Metric(s) Time Series with Events', xlabel=None, ylabel=None, figsize=(12, 6), show_minmax=True, alternate_years=True, event_line_color=None, event_line_style='--', event_line_alpha=0.7, event_label_color=None, event_label_y_pos=0.85, event_label_x_offset=0.01, event_label_fontsize=8, event_label_background=True, date_format=None)[source]

Plot 1-2 metrics over time with event markers and annotations.

Parameters:
  • data (pd.DataFrame) – DataFrame containing the time series data

  • x (str) – Name of the datetime column

  • y (Union[str, List[str]]) – Single metric column name or list of up to 2 metric column names e.g., ‘iron’ or [‘iron’, ‘ferritin’]

  • event_dates (Dict[str, List[str]], optional) – Dictionary of event dates e.g., {‘Iron Infusion’: [‘2022-09-01’, ‘2024-03-28’]}

  • title (str) – Plot title. Default is “Metric(s) Time Series with Events”

  • xlabel (str, optional) – Label for x-axis. If None, uses “Date”.

  • ylabel (Union[str, List[str]], optional) – Label for y-axis. If None, uses metric names. Can be a single string for one metric or a list of up to 2 strings for two metrics. e.g., ‘Iron Level’ or [‘Iron Level’, ‘Ferritin Level’]

  • figsize (tuple) – Figure size as (width, height) in inches. Default is (12, 6).

  • show_minmax (bool) – Whether to show min/max annotations. Default is True.

  • alternate_years (bool) – Whether to show alternating year backgrounds. Default is True.

  • event_line_color (str, optional) – Color of the event lines. If None, uses MPL_GREEN.

  • event_line_style (str) – Style of the event marker lines. Default is “–“.

  • event_line_alpha (float) – Alpha/transparency of event lines. Default is 0.7.

  • event_label_color (str, optional) – Color of the event labels. If None, uses MPL_GREEN.

  • event_label_y_pos (float) – Vertical position of event labels as fraction of y-axis (0-1). Default is 0.85.

  • event_label_x_offset (float) – Horizontal offset from event line, as fraction of x-axis width. Default is 0.01 (1% of plot width).

  • event_label_fontsize (int) – Font size for event labels. Default is 8.

  • event_label_background (bool) – Whether to add a background to event labels. Default is True.

  • date_format (str, optional) – Format for date labels. If None, format is auto-detected based on date range. Auto-detection thresholds: - ≤ 3 days: Hourly format (“%Y-%m-%d %H:%M”) - ≤ 60 days: Daily format (“%Y-%m-%d”) - ≤ 1 year: Monthly format (“%Y-%m”) - ≤ 3 years: Quarterly format (“%Y-%m”) - > 3 years: Yearly format (“%Y”)

Returns:

  • Figure object for further customization

  • List of Axes objects (1-2 axes depending on number of metrics)

Return type:

Tuple[plt.Figure, List[plt.Axes]]

mlarena.utils.plot_utils.plot_stacked_bar_over_time(data, x, y, freq='MS', label_dict=None, is_pct=True, title='Time Series Stacked Bar Chart', xlabel=None, ylabel=None, figsize=(12, 6), palette=None)[source]

Plot a stacked bar chart showing the distribution of a categorical variable over time, either in percentage or actual counts.

Parameters:
  • data (pd.DataFrame) – Input DataFrame.

  • x (str) – Name of the datetime column.

  • y (str) – Name of the categorical column.

  • freq (str) – Frequency for time grouping (‘m’=minute, ‘h’=hour, ‘D’=day, ‘MS’=month start, ‘ME’ = month end, ‘YS’=year start).

  • label_dict (Dict[str, str], optional) – Mapping of original category values to display labels.

  • is_pct (bool) – Whether to display percentage (True) or actual count (False).

  • title (str) – Title of the plot.

  • xlabel (str, optional) – Label for the x-axis. If None, will be set based on frequency.

  • ylabel (str, optional) – Label for the y-axis (default is auto-set based on is_pct).

  • figsize (tuple) – Figure size as (width, height) in inches. Default is (12, 6).

  • palette (List[str], optional) – List of colors for the bars. If None, uses matplotlib’s default color cycle.

mlarena.utils.plot_utils.plot_distribution_over_time(data, x, y, freq='MS', point_hue=None, title='Distribution Over Time', xlabel=None, ylabel=None, figsize=(12, 6), box_alpha=0.3, point_size=50, point_alpha=0.8, jitter=0.08, return_summary=False)[source]

Plot the distribution of a continuous variable over time, showing box plots with scatter overlay. Users can optionally color the points with point_hue, otherwise all the boxes and points will be in one color.

Parameters:
  • data (pd.DataFrame) – Input DataFrame.

  • x (str) – Name of the datetime column.

  • y (str) – Name of the continuous column.

  • freq (str) – Frequency for time grouping (‘m’=minute, ‘h’=hour, ‘D’=day, ‘MS’=month start, ‘ME’ = month end, ‘YS’=year start).

  • point_hue (str, optional) – Column name to use for coloring the scatter points. If provided, points will be colored according to this variable. If column does not exist, a warning will be issued and the plot will be created without point_hue coloring.

  • title (str) – Title of the plot.

  • xlabel (str, optional) – Label for the x-axis. If None, will be set based on frequency.

  • ylabel (str, optional) – Label for the y-axis. If None, uses the y column name.

  • figsize (tuple) – Figure size as (width, height) in inches. Default is (12, 6).

  • box_alpha (float) – Transparency level for box fill (default 0.3).

  • point_size (int) – Size of the overlaid scatter points (default 50).

  • point_alpha (float) – Transparency level for points (default 0.8).

  • jitter (float) – Amount of horizontal jitter for points (default 0.08).

  • return_summary (bool) – Whether to return a DataFrame of summary statistics (default False).

Returns:

  • Figure and axis objects for further customization

  • (Optional) DataFrame with count, mean, median, std per time period if return_summary=True

Return type:

Tuple[plt.Figure, plt.Axes] or Tuple[plt.Figure, plt.Axes, pd.DataFrame]

mlarena.utils.plot_utils.plot_stacked_bar(data, x, y, label_dict=None, is_pct=True, title='Stacked Bar Chart', xlabel=None, ylabel=None, figsize=(10, 6), palette=None, xticklabel_rotation=45, bar_alpha=0.7, stat_test=None, stats_only=False, show_stat_test=None, return_stats=False, stat_annotation_pos=(0.02, 0.98), stat_annotation_fontsize=10, stat_annotation_bbox=True)[source]

Plot a stacked bar chart showing the distribution of a categorical variable, either in percentage or actual counts.

Parameters:
  • data (pd.DataFrame) – Input DataFrame.

  • x (str) – Name of the categorical column for x-axis.

  • y (str) – Name of the categorical column for stacking.

  • label_dict (Dict[str, str], optional) – Mapping of original category values to display labels.

  • is_pct (bool) – Whether to display percentage (True) or actual count (False).

  • title (str) – Title of the plot.

  • xlabel (str, optional) – Label for the x-axis. If None, uses the x column name.

  • ylabel (str, optional) – Label for the y-axis (default is auto-set based on is_pct).

  • figsize (tuple) – Figure size as (width, height) in inches. Default is (10, 6).

  • palette (List[str], optional) – List of colors for the bars. If None, uses matplotlib’s default color cycle.

  • xticklabel_rotation (float) – Rotation angle for x-axis tick labels in degrees. Default is 45.

  • bar_alpha (float) – Transparency level for the bars (0-1). Default is 0.7.

  • stat_test (str, optional) – Statistical test to perform on the contingency table. Supported: - “chi2”: Pearson’s chi-square test (works for any contingency table) - “g_test”: G-test of independence (likelihood ratio test) If not specified but show_stat_test=True or stats_only=True, defaults to “chi2”. If specified, automatically sets show_stat_test=True unless explicitly set to False.

  • stats_only (bool) – If True, skip plotting and return only statistical results. Automatically sets stat_test=”chi2” if not specified.

  • show_stat_test (bool, optional) – If True, display statistical test results as an annotation. If None (default), automatically set to True when stat_test is specified. If False, statistical test is computed but not displayed.

  • return_stats (bool) – If True, return statistical results along with plot objects. When False, only returns (fig, ax) even if statistical tests are computed.

  • stat_annotation_pos (Tuple[float, float]) – Position of statistical annotation (0-1, 0-1).

  • stat_annotation_fontsize (int) – Font size for the statistical annotation.

  • stat_annotation_bbox (bool) – Whether to add a background box to the statistical annotation.

Returns:

  • When stats_only=True: Dictionary containing statistical results only

  • When stats_only=False and return_stats=False: (fig, ax)

  • When stats_only=False and return_stats=True: (fig, ax, results)

  • results dict contains:
    • ’summary_table’: Dictionary with contingency table, percentage table, and sample size

    • ’stat_test’: Dictionary with keys ‘method’, ‘statistic’, ‘p_value’, ‘effect_size’

Return type:

Union[Tuple[plt.Figure, plt.Axes], Tuple[plt.Figure, plt.Axes, dict], dict]

Note

Statistical test parameters have been designed with intelligent defaults to optimize user experience. The following scenarios are automatically handled:

  1. Plot only (default): Just call the function with data - no statistical tests performed.

  2. Plot with statistical annotation: - Specify stat_test=”chi2”/”g_test” → automatically shows test results on plot - Or set show_stat_test=True → automatically uses default test method - Returns only (fig, ax) unless explicitly requested otherwise

  3. Access statistical results: - Add return_stats=True → returns (fig, ax, results) - Or use stats_only=True → returns only results (no plotting)

This design seeks to support common use cases withou minimal manual configuration.

Statistics

mlarena.utils.stats_utils.compare_groups(data, grouping_col, target_cols, weights=None, num_test='anova', cat_test='chi2', alpha=0.05, visualize=False)[source]

Compare groups across specified target variables using statistical tests.

Evaluates whether groups defined by grouping_col have equivalent distributions across target variables, useful for A/B testing and stratification validation.

Parameters:
  • data (pd.DataFrame) – The input DataFrame.

  • grouping_col (str) – Column used to divide groups. For A/B testing, should have two unique values.

  • target_cols (List[str]) – List of column names to compare across the groups.

  • weights (Optional[Dict[str, float]], optional) – Optional dictionary of weights for each target column.

  • num_test (str, default="anova") – Statistical test for numeric variables. Supported: “anova”, “welch”, “kruskal”.

  • cat_test (str, default="chi2") – Statistical test for categorical variables.

  • alpha (float, default=0.05) – Significance threshold for flagging imbalance.

  • visualize (bool, default=False) – If True, generate plots for numeric and categorical variables.

Returns:

  • effect_size_sum (float) – Weighted sum of effect sizes across all target variables.

  • summary_df (pd.DataFrame) – Summary statistics and test results for each target variable.

Return type:

Tuple[float, DataFrame]

Examples

>>> df = pd.DataFrame({
...     'group': ['A', 'A', 'B', 'B', 'A', 'B'],
...     'metric1': [10, 12, 15, 13, 11, 14],
...     'metric2': [1.2, 1.5, 2.1, 1.8, 1.3, 2.0],
...     'category': ['X', 'Y', 'X', 'Y', 'X', 'Y']
... })
>>> effect_size_sum, summary = compare_groups(
...     df, 'group', ['metric1', 'metric2', 'category']
... )
mlarena.utils.stats_utils.add_stratified_groups(data, stratifier_col, random_seed=42, group_col_name=None, group_labels=(0, 1))[source]

Add a column to stratify a DataFrame into two equal groups based on specified column(s).

This function maintains the distribution of the stratifier column(s) across both groups, making it useful for creating balanced train/test splits or A/B testing groups. Use with compare_groups() to validate stratification effectiveness.

Parameters:
  • data (pd.DataFrame) – The input DataFrame to be stratified.

  • stratifier_col (Union[str, List[str]]) – The column name or list of column names to use as stratification factors. If a list is provided, the columns are combined for stratification.

  • random_seed (int, default=42) – Random seed for reproducibility.

  • group_col_name (str, optional) – Name for the new group column. If None, defaults to ‘stratified_group’.

  • group_labels (Tuple[Union[str, int], Union[str, int]], default=(0, 1)) – Labels for the two groups. First label for group 0, second for group 1.

Returns:

A copy of the input DataFrame with an additional column indicating group membership using the specified group_labels.

Return type:

pd.DataFrame

Raises:

ValueError – If stratifier_col contains column names that don’t exist in the DataFrame.

Examples

>>> df = pd.DataFrame({
...     'category': ['A', 'B', 'A', 'B', 'A', 'C', 'C', 'C'],
...     'value_1': [10, 20, 30, 40, 50, 60, 70, 80],
...     'value_2': [15, 70, 37, 80, 90, 40, 70, 20],
... })
>>> # Create stratified groups
>>> result = add_stratified_groups(df, 'category')
>>> # Validate stratification worked
>>> from mlarena.utils.stats_utils import compare_groups
>>> effect_size, summary = compare_groups(
...     result, 'stratified_group', ['value_1', 'value_2']
... )
mlarena.utils.stats_utils.optimize_stratification_strategy(data, candidate_stratifiers, target_metrics, weights=None, max_combinations=3, alpha=0.05, significance_penalty=0.2, num_test='anova', cat_test='chi2', visualize_best_strategy=False, include_random_baseline=True, random_seed=42)[source]

Find the best stratification strategy by testing different combinations of stratifier columns.

Evaluates each candidate stratifier by creating stratified groups and measuring how well balanced the groups are across target metrics using compare_groups(). Automatically generates combinations of candidate columns up to max_combinations.

Parameters:
  • data (pd.DataFrame) – The input DataFrame.

  • candidate_stratifiers (List[str]) – List of column names to test as stratifiers. Function will automatically generate combinations up to max_combinations length.

  • target_metrics (List[str]) – List of target variables to evaluate balance across.

  • weights (Optional[Dict[str, float]], optional) – Optional weights for target metrics in the comparison.

  • max_combinations (int, default=3) – Maximum number of columns to combine when testing multi-column stratifiers.

  • alpha (float, default=0.05) – Significance threshold for counting significant differences.

  • significance_penalty (float, default=0.2) – Penalty weight applied per significant difference in composite scoring. Higher values more heavily penalize strategies with significant imbalances. Set to 0 to ignore significance count and use only effect sizes.

  • num_test (str, default="anova") – Statistical test for numeric variables. Supported: “anova”, “welch”, “kruskal”.

  • cat_test (str, default="chi2") – Statistical test for categorical variables. Supported: “chi2”, “g_test”.

  • visualize_best_strategy (bool, default=False) – If True, generates visualizations for the best stratification strategy only.

  • include_random_baseline (bool, default=True) – If True, includes a random baseline strategy in the comparison. This creates a random 50/50 group assignment to serve as a baseline for evaluating whether stratification strategies perform better than chance.

  • random_seed (int, default=42) – Random seed for reproducibility.

Returns:

Dictionary with results: - ‘best_stratifier’: The stratifier with best balance (lowest composite score) - ‘results’: Dict mapping each stratifier to its detailed metrics and summary DataFrame - ‘rankings’: List of stratifiers ranked by effectiveness (best to worst) - ‘summary’: DataFrame with overview of all tested strategies, ranked by performance

Return type:

Dict

Examples

>>> df = pd.DataFrame({
...     'region': ['North', 'South', 'North', 'South'] * 50,
...     'segment': ['A', 'B', 'A', 'B'] * 50,
...     'metric1': np.random.normal(100, 15, 200),
...     'metric2': np.random.normal(50, 10, 200)
... })
>>> results = optimize_stratification_strategy(
...     df, ['region', 'segment'], ['metric1', 'metric2']
... )
>>> print(f"Best stratifier: {results['best_stratifier']}")
>>> # View performance overview of all strategies
>>> print(results['summary'])
>>>
>>> # Advanced analysis with custom penalty and tests
>>> results_strict = optimize_stratification_strategy(
...     df, ['region', 'segment'], ['metric1', 'metric2'],
...     significance_penalty=0.5,  # Heavily penalize significant differences
...     num_test='kruskal',       # Use non-parametric test
...     visualize_best_strategy=True  # Generate plots for best strategy
... )
>>> # Compare top 3 strategies
>>> top_3 = results_strict['summary'].head(3)
>>> print(top_3[['stratifier', 'composite_score', 'n_significant']])
>>>
>>> # Check if any stratifier beats random baseline
>>> summary = results['summary']
>>> random_score = summary[summary['stratifier'] == 'random_baseline']['composite_score'].iloc[0]
>>> best_stratified_score = summary[summary['stratifier'] != 'random_baseline']['composite_score'].min()
>>> improvement = (random_score - best_stratified_score) / random_score * 100
>>> print(f"Best stratification improves over random by {improvement:.1f}%")
mlarena.utils.stats_utils.calculate_threshold_stats(data, n_std=2.0, threshold_method='std', visualize=False)[source]

Calculate frequency statistics and threshold based on statistical criteria.

This function computes basic statistics (mean, median, std, count) and determines a threshold based on the specified method. Useful for outlier detection and frequency analysis.

Parameters:
  • data (Union[pd.Series, np.ndarray, List[Union[int, float]]]) – Input data containing frequency or numeric values.

  • n_std (float, default=2.0) – Number of standard deviations to use for threshold calculation when threshold_method is “std”.

  • threshold_method (str, default="std") – Method to calculate threshold: - “std”: mean + n_std * std - “iqr”: Q3 + 1.5 * IQR (Interquartile Range) - “percentile”: 95th percentile

  • visualize (bool, default=False) – If True, creates a histogram with marked statistics.

Returns:

Dictionary containing: - ‘mean’: mean of the data - ‘median’: median of the data - ‘std’: standard deviation - ‘count’: number of observations - ‘threshold’: calculated threshold value - ‘method’: threshold calculation method used

Return type:

Dict[str, Union[float, int]]

Examples

>>> data = [1, 2, 2, 3, 3, 3, 4, 4, 10]
>>> stats = calculate_frequency_stats(data, n_std=2, visualize=True)
>>> print(f"Mean: {stats['mean']:.2f}")
>>> print(f"Threshold: {stats['threshold']:.2f}")
>>> # Using different threshold method
>>> stats_iqr = calculate_frequency_stats(
...     data, threshold_method='iqr', visualize=True
... )
mlarena.utils.stats_utils.calculate_group_thresholds(df, group_col, value_col, methods=['std', 'iqr', 'percentile'], n_std=2.0, visualize_first_group=True, min_group_size=1)[source]

Calculate thresholds for values grouped by any categorical column.

Parameters:
  • df (pd.DataFrame) – Input DataFrame containing the data

  • group_col (str) – Name of the column to group by

  • value_col (str) – Name of the column containing the values to analyze

  • methods (List[str], default=['std', 'iqr', 'percentile']) – List of threshold methods to use

  • n_std (float, default=2.0) – Number of standard deviations to use for threshold calculation when threshold_method is “std”.

  • visualize_first_group (bool, default=True) – Whether to show visualizations for the first group

  • min_group_size (int)

Returns:

DataFrame containing threshold statistics for each group and method

Return type:

pd.DataFrame

Examples

>>> # Example with products and prices
>>> df = pd.DataFrame({
...     'product': ['A', 'B', 'A', 'B'],
...     'price': [10, 20, 15, 25]
... })
>>> results = calculate_group_thresholds(df, 'product', 'price')
>>> # Example with locations and temperatures
>>> weather_df = pd.DataFrame({
...     'location': ['NY', 'LA', 'NY', 'LA'],
...     'temperature': [75, 85, 72, 88]
... })
>>> results = calculate_group_thresholds(weather_df, 'location', 'temperature')
mlarena.utils.stats_utils.power_analysis_numeric(effect_size, sample_size_per_group, alpha=0.05, test_type='two_sample', alternative='two-sided')[source]

Calculate statistical power for numeric outcomes (t-tests).

Parameters:
  • effect_size (float) – Cohen’s d effect size (standardized difference between groups)

  • sample_size_per_group (int) – Sample size per group

  • alpha (float, default=0.05) – Type I error rate (significance level)

  • test_type (str, default="two_sample") – Type of test: “two_sample”, “one_sample”, “paired”

  • alternative (str, default="two-sided") – Alternative hypothesis: “two-sided”, “greater”, “less”

Returns:

Dictionary containing power, effect_size, alpha, sample_size_per_group

Return type:

Dict[str, float]

mlarena.utils.stats_utils.power_analysis_proportion(baseline_rate, treatment_rate, sample_size_per_group, alpha=0.05, alternative='two-sided')[source]

Calculate statistical power for proportion/conversion rate tests.

Parameters:
  • baseline_rate (float) – Baseline conversion rate (between 0 and 1)

  • treatment_rate (float) – Treatment conversion rate (between 0 and 1)

  • sample_size_per_group (int) – Sample size per group

  • alpha (float, default=0.05) – Type I error rate

  • alternative (str, default="two-sided") – Alternative hypothesis: “two-sided”, “larger”, “smaller”

Returns:

Dictionary containing power, effect_size, rates, and sample size

Return type:

Dict[str, float]

mlarena.utils.stats_utils.sample_size_numeric(effect_size, power=0.8, alpha=0.05, test_type='two_sample', alternative='two-sided')[source]

Calculate required sample size for A/B testing with numeric outcomes to achieve desired power.

Parameters:
  • effect_size (float) – Cohen’s d effect size to detect

  • power (float, default=0.8) – Desired statistical power (1 - Type II error rate). Common values: 0.7 (exploration), 0.8 (standard), 0.9 (high-stakes)

  • alpha (float, default=0.05) – Type I error rate

  • test_type (str, default="two_sample") – Type of test: “two_sample”, “one_sample”, “paired”

  • alternative (str, default="two-sided") – Alternative hypothesis: “two-sided”, “greater”, “less”

Returns:

Dictionary containing required sample_size_per_group and input parameters

Return type:

Dict[str, Union[int, float]]

Examples

>>> # Sample size needed to detect medium effect (d=0.5) with 80% power
>>> sample_size_numeric(effect_size=0.5)
{'sample_size_per_group': 64, 'total_sample_size': 128, 'power': 0.8, ...}
mlarena.utils.stats_utils.sample_size_proportion(baseline_rate, treatment_rate, power=0.8, alpha=0.05, alternative='two-sided')[source]

Calculate required sample size for A/B testing with proportion targets to achieve desired power.

Parameters:
  • baseline_rate (float) – Baseline conversion rate (between 0 and 1)

  • treatment_rate (float) – Treatment conversion rate to detect (between 0 and 1)

  • power (float, default=0.8) – Desired statistical power (1 - Type II error rate). Common values: 0.7 (exploration), 0.8 (standard), 0.9 (high-stakes)

  • alpha (float, default=0.05) – Type I error rate

  • alternative (str, default="two-sided") – Alternative hypothesis: “two-sided”, “larger”, “smaller”

Returns:

Dictionary containing required sample sizes and effect size metrics

Return type:

Dict[str, Union[int, float]]

Examples

>>> # Sample size to detect 5% -> 6% improvement with 80% power
>>> sample_size_proportion(0.05, 0.06)
{'sample_size_per_group': 23506, 'total_sample_size': 47012, ...}
mlarena.utils.stats_utils.numeric_effectsize(mean_diff=None, mean1=None, mean2=None, std=None, std1=None, std2=None, n1=None, n2=None)[source]

Compute Cohen’s d for independent samples in a power analysis context.

Parameters:
  • mean_diff (float, optional) – Mean difference (mean1 - mean2). Optional if mean1 and mean2 are provided.

  • mean1 (float, optional) – Mean of group 1 (e.g., treatment group).

  • mean2 (float, optional) – Mean of group 2 (e.g., control group).

  • std (float, optional) – Common standard deviation (assumed equal for both groups).

  • std1 (float, optional) – Standard deviation of group 1 (optional if std is provided).

  • std2 (float, optional) – Standard deviation of group 2 (optional if std is provided).

  • n1 (int, optional) – Sample size of group 1 (used only if std1 and std2 are provided).

  • n2 (int, optional) – Sample size of group 2 (used only if std1 and std2 are provided).

Returns:

Cohen’s d (standardized effect size)

Return type:

float

Raises:
  • ValueError – If required parameters are missing or invalid

  • Assumptions: –

  • -------- –

  • - Groups are independent –

  • - Standard deviations are assumed equal unless both std1/std2 and n1/n2 are provided –

  • - Appropriate for planning two-sample t-tests (e.g., A/B testing) –

  • - Not suitable for paired-sample designs or ANOVA with 3+ groups without modification –

Examples

>>> # Using mean difference and common std
>>> d = numeric_effectsize(mean_diff=0.5, std=2.0)
>>> print(f"Cohen's d: {d:.3f}")  # 0.250
>>> # Using separate means and standard deviations
>>> d = numeric_effectsize(
...     mean1=100, mean2=95,  # 5-point difference
...     std1=10, std2=12,     # Different spreads
...     n1=50, n2=50          # Equal sample sizes
... )
>>> print(f"Cohen's d: {d:.3f}")  # ~0.455
>>> # Using means with common standard deviation
>>> d = numeric_effectsize(mean1=10, mean2=8, std=3)
>>> print(f"Cohen's d: {d:.3f}")  # ~0.667
mlarena.utils.stats_utils.calculate_cooks_d_like_influence(model_class, X, y, visualize=True, save_path=None, max_loo_points=None, influence_outlier_method='percentile', influence_outlier_threshold=99, random_state=None, **model_params)[source]

Calculates a Cook’s-D-like influence score for each data point for any scikit-learn compatible model. This is an extension of Cook’s Distance that works with any ML model, not just linear regression.

The influence score is calculated by:

  1. Training a model on the full dataset

  2. For each point (or selected points):

    • Remove the point

    • Train a new model

    • Calculate how much the predictions change across all points

  3. The influence score is the mean squared difference in predictions between the full model and the leave-one-out model.

Parameters:
  • model_class (type) – The class of the ML model to use (e.g., LinearRegression, LGBMRegressor). Must be scikit-learn compatible with fit() and predict() methods.

  • X (Union[pd.DataFrame, np.ndarray]) – The feature matrix.

  • y (Union[pd.Series, np.ndarray]) – The target vector.

  • visualize (bool, default=True) – If True, plots the influence scores.

  • save_path (Optional[str], default=None) – If provided, saves the plot to this file path. Requires visualize=True.

  • max_loo_points (Optional[int], default=None) – If specified, only perform LOO calculations for this many points. Points are selected based on having the highest absolute residuals. This is purely for computational efficiency and does not affect which points are considered influential. Scores for unexamined points are set to zero and should not be interpreted literally.

  • influence_outlier_method (str, default='percentile') –

    Method to identify influential points (outliers) based on influence scores. Options:

    • ’percentile’: Select points above a percentile threshold

    • ’zscore’: Select points beyond N standard deviations from the mean

    • ’top_k’: Select the K points with highest influence scores

    • ’iqr’: Select points above Q3 + k * IQR threshold

    • ’mean_multiple’: Select points with influence scores > N times the mean

    Note: When max_loo_points is set, only ‘percentile’ and ‘top_k’ methods are available since other methods require all influence scores to be calculated.

  • influence_outlier_threshold (float or int, default=99) –

    Threshold for identifying influential points:

    • For ‘percentile’: Points above this percentile are marked influential (e.g., 95 means top 5% most influential points)

    • For ‘zscore’: Points with absolute z-scores above this value are marked influential (e.g., 3 means points more than 3 standard deviations from the mean)

    • For ‘top_k’: Number of most influential points to select (integer)

    • For ‘iqr’: Multiplier k for Q3 + k*IQR threshold (typically 1.5 or 3.0)

    • For ‘mean_multiple’: Points with influence scores > N times the mean (e.g., 3 as suggested in literature regarding diagnostics of linear regression)

    Note: When max_loo_points is set:

    • The number of influential points will be capped at max_loo_points

    • Uncalculated points are assumed to have zero influence

  • random_state (Optional[int], default=None) – Random state for reproducibility, passed to model if supported.

  • **model_params (Any) – Additional parameters passed to the model constructor.

Returns:

  • influence_scores: Array of influence scores, one for each data point. Higher scores indicate more influential points.

  • influential_indices: Array of indices for points identified as influential based on the specified method and threshold, and are capped at max_loo_points.

  • normal_indices: Array of indices for non-influential points (complement of influential_indices). When max_loo_points is set, this properly accounts for uncalculated points.

Return type:

Tuple[np.ndarray, np.ndarray, np.ndarray]

Examples

>>> from lightgbm import LGBMRegressor
>>> # Example 1: Using percentile method with max_loo_points
>>> scores1, infl_idx1, normal_idx1 = calculate_cooks_d_like_influence(
...     LGBMRegressor,
...     X,
...     y,
...     max_loo_points=20,  # Only analyze top 20 points with highest residuals
...     influence_outlier_threshold=95  # Mark top 5% as influential (but capped at max_loo_points)
... )
>>> # Example 2: Using z-score method on all points
>>> scores2, infl_idx2, normal_idx2 = calculate_cooks_d_like_influence(
...     LGBMRegressor,
...     X,
...     y,
...     influence_outlier_method='zscore',
...     influence_outlier_threshold=3  # Mark points > 3 std devs from mean as influential
... )
>>> print(f"Points with influence scores > 3 std devs: {infl_idx2}")

Notes

  • Understand the theory and implementation design to better harness the power of this function: https://towardsdatascience.com/help-your-model-learn-the-true-signal/

  • For large datasets, consider using max_loo_points to reduce computation time.

  • User can set influence_outlier_threshold, but it is capped at max_loo_points.

  • Consider using the same estimator you will use after managing the influential points, as this ensures consistency and makes the influence detection more relevant to your final analysis.

  • Use this function for diagnostic exploration rather than removing influential points automatically.

mlarena.utils.stats_utils.get_normal_data(model_class, X, y, influence_outlier_method='percentile', influence_outlier_threshold=99, max_loo_points=None, random_state=None, **model_params)[source]

Identifies and removes influential points from the dataset using Cook’s D-like influence scores.

Warning

This function is deprecated and will be removed in a future version. Use calculate_cooks_d_like_influence() instead, which returns both influence scores and indices, allowing more flexibility in how you handle influential points.

Parameters:
  • model_class (type) – The class of the ML model to use (e.g., LinearRegression, LGBMRegressor). Must be scikit-learn compatible with fit() and predict() methods.

  • X (Union[pd.DataFrame, np.ndarray]) – The feature matrix.

  • y (Union[pd.Series, np.ndarray]) – The target vector.

  • influence_outlier_method (str, default='percentile') – Method to identify influential points. See calculate_cooks_d_like_influence().

  • influence_outlier_threshold (float, default=99) – Threshold for identifying influential points. See calculate_cooks_d_like_influence().

  • max_loo_points (Optional[int], default=None) – If specified, only calculate influence scores for this many points. See calculate_cooks_d_like_influence().

  • random_state (Optional[int], default=None) – Random state for reproducibility, passed to model if supported.

  • **model_params (Any) – Additional parameters passed to the model constructor.

Returns:

A tuple containing: - X_normal: Features of non-influential points - y_normal: Target values of non-influential points

Return type:

Tuple[Union[pd.DataFrame, np.ndarray], Union[pd.Series, np.ndarray]]

Examples

>>> from sklearn.linear_model import LinearRegression
>>> X = pd.DataFrame({'feature1': [1, 2, 3, 4, 100], 'feature2': [1, 2, 3, 4, 0]})
>>> y = pd.Series([1, 2, 3, 4, 100])
>>> # This will show a deprecation warning
>>> X_normal, y_normal = get_normal_data(
...     LinearRegression,
...     X,
...     y,
...     influence_outlier_threshold=99  # Remove top 1% influential points
... )
>>> print(f"Original data size: {len(y)}, Normal data size: {len(y_normal)}")

# Recommended way using calculate_cooks_d_like_influence: >>> scores, infl_idx, normal_idx = calculate_cooks_d_like_influence( … LinearRegression, X, y, influence_outlier_threshold=99 … ) >>> X_normal, y_normal = X.iloc[normal_idx], y.iloc[normal_idx]

Notes

This function is deprecated. Use calculate_cooks_d_like_influence() instead, which provides more flexibility in how you handle influential points.

Model diagnostics

Model utilities for MLArena package.

This module contains helper functions for model-related operations that are shared across different components of the package.

mlarena.utils.model_utils.get_cv_strategy(cv=5, task='classification', random_state=42)[source]

Returns a cross-validation splitter object based on user input.

Parameters:
  • cv (int or CV splitter object, default=5) –

    • If int: number of folds for default CV strategy (StratifiedKFold or KFold).

    • If object with .split(): used directly as the CV splitter.

  • task (str, default="classification") – “classification” or “regression” — used to choose default CV type.

  • random_state (int, default=42) – Ensures reproducibility for default splitters.

Returns:

splitter – Configured CV splitter ready for use in model selection or feature selection.

Return type:

object

Examples

>>> get_cv_strategy()
StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
>>> from sklearn.model_selection import GroupKFold
>>> get_cv_strategy(GroupKFold(n_splits=4))
GroupKFold(n_splits=4)

Input and output

mlarena.utils.io_utils.save_object(obj, directory, basename, use_date=True, backend='pickle', compress=True, compression_level=None, pickle_protocol=None)[source]

Save a Python object to disk using either pickle or joblib.

Parameters:
  • obj (Any) – The Python object to save.

  • directory (Union[str, Path]) – Directory to save the file.

  • basename (str) – Base name for the file (without extension, e.g., ‘my_model’). The extension will be added based on the backend.

  • use_date (bool, default=True) – Whether to append the current date to the file name stem.

  • backend (str, default="pickle") – Storage backend to use (‘pickle’ or ‘joblib’). This determines the file extension.

  • compress (bool, default=True) – Whether to use compression for joblib backend.

  • compression_level (Optional[int], default=None) – Compression level (0-9, joblib only). None uses backend default.

  • pickle_protocol (Optional[int], default=None) – The protocol version to use for pickling. The default (None) uses pickle’s default protocol. Only specify if needed for backward compatibility.

Returns:

The full filepath to the saved object. This path can be directly used as the filepath argument for the load_object function.

Return type:

Path

Examples

>>> # model = RandomForestClassifier() # Assuming model is trained
>>> # model.fit(X_train, y_train)
>>> # Save with date and pickle backend (default)
>>> # save_object(model, directory="models", basename="my_model") # -> models/my_model_YYYY-MM-DD.pkl
>>> # Save without date and with joblib backend
>>> # save_object(model, directory="output/data", basename="raw_features", use_date=False, backend="joblib") # -> output/data/raw_features.joblib
>>> # Save with joblib and specific compression level
>>> # save_object(model, directory="models", basename="compressed_model", backend="joblib", compression_level=5)
>>> # Save with specific pickle protocol
>>> # save_object(model, directory="models", basename="old_model", pickle_protocol=4)
mlarena.utils.io_utils.load_object(filepath)[source]

Load a Python object from disk, inferring backend from file extension.

Parameters:

filepath (Union[str, Path]) – Full path to the file to load (e.g., “models/model.pkl” or “models/model.joblib”). This should be the full path, including the directory, basename and extension.

Returns:

The loaded object.

Return type:

Any

Examples

>>> # saved_filepath = save_object(my_data, directory="data_dir", basename="my_data_file")
>>> # loaded_data = load_object(filepath=saved_filepath)
>>> # Load a pickle file directly by path
>>> # model = load_object(filepath="models/model_2024-02-27.pkl")
>>> # Load a joblib file directly by path
>>> # model = load_object(filepath="models/archive/old_model.joblib")