Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e .[spark,mlflow,test,test-notebook,test-cov]
pip install -e .[spark,polars,mlflow,test,test-notebook,test-cov]
- name: Lint with pre-commit
run: |
pip install pre-commit
Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ Optionally, the EMM package can also be used to match a group of company names t
to a common company name in the ground truth. For example, all different names used to address an external bank account.
This step aggregates the name-matching scores from the supervised layer into a single match.

The package is modular in design and and works both using both Pandas and Spark. A classifier trained with the former
can be used with the latter and vice versa.
The package is modular in design and works with Pandas, Polars and Spark.

For release history see [GitHub Releases](https://github.com/ing-bank/EntityMatchingModel/releases).

Expand All @@ -33,6 +32,7 @@ For detailed examples of the code please see the notebooks under `notebooks/`.

- `01-entity-matching-pandas-version.ipynb`: Using the Pandas version of EMM for name-matching.
- `02-entity-matching-spark-version.ipynb`: Using the Spark version of EMM for name-matching.
- `02-entity-matching-polars-version.ipynb`: Using the Polars version of EMM for name-matching.
- `03-entity-matching-training-pandas-version.ipynb`: Fitting the supervised model and setting a discrimination threshold (Pandas).
- `04-entity-matching-aggregation-pandas-version.ipynb`: Using the aggregation layer and setting a discrimination threshold (Pandas).

Expand Down Expand Up @@ -61,7 +61,7 @@ where in this example the code is installed in edit mode (option -e).
Additional dependencies can be installed with, e.g.:

```shell
pip install "emm[spark,dev,test]"
pip install "emm[spark,polars,dev,test]"
```

You can now use the package in Python with:
Expand Down Expand Up @@ -127,7 +127,8 @@ best_candidates = candidates_scored_pd[candidates_scored_pd.best_match]
best_candidates.head()
```

For Spark, you can use the class `SparkEntityMatching` instead, with the same API as the Pandas version.
For Spark or Polars, you can use the class `SparkEntityMatching` or `PolarsEntityMatching` instead, with the same API as the Pandas version.
See `example_spark()` and `example_polars()` in [example.py](example.py) for their examples.
For all available examples, please see the tutorial notebooks under `notebooks/`.

## Project contributors
Expand Down
9 changes: 8 additions & 1 deletion emm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,21 @@
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from importlib.util import find_spec

from emm import parameters
from emm.helper import spark_installed
from emm.loggers.logger import set_logger
from emm.pipeline.pandas_entity_matching import PandasEntityMatching

from .version import __version__

__all__ = ["parameters", "PandasEntityMatching", "set_logger", "__version__"]
__all__ = ["PandasEntityMatching", "__version__", "parameters", "set_logger"]

if find_spec("polars") is not None:
from emm.pipeline.polars_entity_matching import PolarsEntityMatching

__all__ += ["PolarsEntityMatching"]

if spark_installed:
from emm.pipeline.spark_entity_matching import SparkEntityMatching
Expand Down
18 changes: 15 additions & 3 deletions emm/aggregation/base_entity_aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@

def _mean_score_aggregation(df, group, score_col, output_col):
# set dropna to False to keep no_candidate rows
df[output_col] = df.groupby(group, dropna=False)[score_col].transform("mean")
scores = df[score_col]
if scores.dtype == "float32":
scores = scores.astype("float64")
df[output_col] = scores.groupby([df[column] for column in group], dropna=False).transform("mean")

# Short circuit if possible
if df.shape[0] == 1:
Expand All @@ -41,6 +44,8 @@ def _mean_score_aggregation(df, group, score_col, output_col):

def is_series_unique(series: pd.Series) -> bool:
# does series consist of one value only?
if series.isna().any():
return False
a = series.to_numpy()
return (a[0] == a).all()

Expand Down Expand Up @@ -79,8 +84,13 @@ def _max_frequency_nm_score_aggregation(
best_match_df = am_df.nlargest(1, ["freq_score"], keep="first")

# 3a. pick the most frequent name of each account-grid combi: one-name summary information
group_key = tuple(best_match_df[group].to_numpy()[0])
one_accountname_df = df_grouped.get_group(group_key).sort_values(["freq_score"], ascending=False).head(1)
matching_keys = df[group].notna()
for column in group:
winner = best_match_df[column]
matching_keys[column] = df[column].isna() if winner.isna().iloc[0] else df[column].eq(winner.iloc[0])
one_accountname_df = (
df.loc[matching_keys.fillna(False).all(axis=1)].sort_values(["freq_score"], ascending=False).head(1)
)
df = one_accountname_df.drop(columns=["freq_score"]).copy()
df["agg_score"] = best_match_df["agg_score"].to_numpy()[0]
return df
Expand All @@ -100,6 +110,8 @@ def matching_max_candidate(
If aggregation_method = 'mean_score'
- Average the scores per GT and return the maximum.

Float32 scores are averaged as Float64. Missing names are not treated as identical.

Returns dataframe with a single row.

Args:
Expand Down
2 changes: 2 additions & 0 deletions emm/aggregation/pandas_entity_aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ def __init__(
- "max_frequency_nm_score": weights the nm_score with the frequency and takes the maximum to find the best
ground-truth name.

Float32 scores are averaged as Float64. Missing names are not treated as identical.

Args:
score_col: name-matching score "nm_score" or first cosine similarity score "score_0".
account_col: account column, default is "account".
Expand Down
224 changes: 224 additions & 0 deletions emm/aggregation/polars_entity_aggregation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
# Copyright (c) 2023 ING Analytics Wholesale Banking
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import annotations

from typing import Literal

import polars as pl
from sklearn.base import TransformerMixin

from emm.aggregation.base_entity_aggregation import BaseEntityAggregation
from emm.loggers import Timer


def _without_nan(df: pl.DataFrame, column: str) -> pl.Expr:
value = pl.col(column)
return value.fill_nan(None) if df.schema[column].is_float() else value


def _row_index_name(df: pl.DataFrame) -> str:
name = "__emm_aggregation_row"
while name in df.columns:
name = f"_{name}"
return name


def matching_max_candidate(
df: pl.DataFrame,
group: list[str],
score_col: str,
name_col: str,
account_col: str,
freq_col: str,
output_col: str,
aggregation_method: Literal["max_frequency_nm_score", "mean_score"] = "max_frequency_nm_score",
) -> pl.DataFrame:
"""Select one representative candidate for a group of names."""
if df.is_empty():
msg = "Provided an empty df"
raise ValueError(msg)

if aggregation_method == "mean_score":
scores = _without_nan(df, score_col)
keys = [_without_nan(df, column) for column in group]
if df.schema[score_col] == pl.Float32:
scores = scores.cast(pl.Float64)
mean = scores.mean().over(keys)
result = df.with_columns(mean.alias(output_col))
if result.height == 1:
return result
return result.sort(
[_without_nan(result, output_col), _without_nan(result, score_col)],
descending=True,
nulls_last=True,
maintain_order=True,
).head(1)

if aggregation_method != "max_frequency_nm_score":
msg = "aggregation_method not supported"
raise ValueError(msg)

if df.height == 1:
return df.with_columns(pl.col(score_col).alias(output_col))
names = df[name_col].to_list()
if names[0] is not None and all(name == names[0] for name in names):
return (
df.sort(_without_nan(df, score_col), descending=True, nulls_last=True, maintain_order=True)
.head(1)
.with_columns(pl.col(score_col).alias(output_col))
)

row_id = _row_index_name(df)
work = df.with_row_index(row_id).with_columns(
*[_without_nan(df, column).alias(column) for column in group],
(_without_nan(df, freq_col) * _without_nan(df, score_col)).alias("freq_score"),
)
grouped = (
work.group_by(group)
.agg(
_without_nan(work, freq_col).sum().alias(freq_col),
_without_nan(work, "freq_score").sum().alias("freq_score"),
)
.with_columns((pl.col("freq_score") / pl.col(freq_col)).alias(output_col))
.sort(group, nulls_last=True, maintain_order=True)
)
winner = grouped.sort(
_without_nan(grouped, "freq_score"), descending=True, nulls_last=True, maintain_order=True
).head(1)
selected = (
work.join(winner.select(group), on=group, how="semi", nulls_equal=True, maintain_order="left")
.sort(_without_nan(work, "freq_score"), descending=True, nulls_last=True, maintain_order=True)
.head(1)
)
return (
df.with_row_index(row_id)
.filter(pl.col(row_id) == selected[row_id][0])
.drop(row_id, "freq_score", strict=False)
.with_columns(pl.lit(winner[output_col][0], dtype=winner.schema[output_col]).alias(output_col))
)


class PolarsEntityAggregation(TransformerMixin, BaseEntityAggregation):
"""Aggregate candidate scores per account using native Polars operations.

Float32 scores are averaged as Float64. Missing names are not treated as identical.
"""

def __init__(
self,
score_col: str,
account_col: str = "account",
index_col: str = "entity_id",
gt_entity_id_col: str = "gt_entity_id",
uid_col: str = "uid",
gt_uid_col: str = "gt_uid",
name_col: str = "name",
freq_col: str = "counterparty_account_count_distinct",
output_col: str = "agg_score",
preprocessed_col: str = "preprocessed",
gt_name_col: str = "gt_name",
gt_preprocessed_col: str = "gt_preprocessed",
correct_col: str = "correct",
aggregation_method: Literal["max_frequency_nm_score", "mean_score"] = "max_frequency_nm_score",
blacklist: list[str] | None = None,
) -> None:
BaseEntityAggregation.__init__(
self,
score_col=score_col,
account_col=account_col,
index_col=index_col,
gt_entity_id_col=gt_entity_id_col,
uid_col=uid_col,
gt_uid_col=gt_uid_col,
name_col=name_col,
freq_col=freq_col,
output_col=output_col,
preprocessed_col=preprocessed_col,
gt_name_col=gt_name_col,
gt_preprocessed_col=gt_preprocessed_col,
correct_col=correct_col,
aggregation_method=aggregation_method,
blacklist=blacklist or [],
)

def fit(self, X: pl.DataFrame, y: pl.Series | None = None) -> PolarsEntityAggregation:
"""Return self; aggregation does not require fitting."""
return self

def fit_transform(self, X: pl.DataFrame, y: pl.Series | None = None) -> pl.DataFrame | None:
"""Aggregate the input without fitting."""
return self.transform(X)

def transform(self, X: pl.DataFrame | None) -> pl.DataFrame | None:
"""Select an aggregated candidate for each account group."""
if X is None:
return None
if not isinstance(X, pl.DataFrame):
msg = f"expected a Polars DataFrame, got {type(X).__name__}"
raise TypeError(msg)

with Timer("PolarsEntityAggregation.transform") as timer:
timer.log_param("n", X.height)
group = self.get_group(X)
gt_group = self.get_gt_group()
valid = _without_nan(X, self.gt_uid_col).is_not_null()
for column in group:
valid &= _without_nan(X, column).is_not_null()
matches = X.filter(valid)
size_col = "__emm_aggregation_size"
while size_col in matches.columns:
size_col = f"_{size_col}"
matches = matches.with_columns(pl.len().over(group).alias(size_col))
single = (
matches.filter(pl.col(size_col) == 1)
.drop(size_col)
.with_columns(
pl.col(self.score_col).alias(self.output_col),
(pl.col(self.score_col) * pl.col(self.freq_col)).alias("freq_score"),
)
)
multiple = matches.filter(pl.col(size_col) > 1).drop(size_col)
multiple = self.remove_blacklisted_names(multiple, self.preprocessed_col)
multiple = multiple.sort(group, nulls_last=True, maintain_order=True)
results = [single]
results.extend(
matching_max_candidate(
current,
group=gt_group,
score_col=self.score_col,
name_col=self.name_col,
account_col=self.account_col,
freq_col=self.freq_col,
output_col=self.output_col,
aggregation_method=self.aggregation_method,
)
for current in multiple.partition_by(group, maintain_order=True)
)
result = pl.concat(results, how="diagonal_relaxed").with_columns(
pl.lit(True).alias("best_match"), pl.lit(1, dtype=pl.Int64).alias("best_rank")
)
timer.log_param("cands", result.height)
return result

def remove_blacklisted_names(self, df: pl.DataFrame, preprocessed_col: str = "preprocessed") -> pl.DataFrame:
"""Remove empty and blacklisted preprocessed names."""
if preprocessed_col not in df.columns:
return df
return df.filter(~pl.col(preprocessed_col).is_in([*self.blacklist, ""]).fill_null(False))
Loading
Loading