Skip to content

API reference

The package exposes its public API from the top-level fpgrowth namespace:

from fpgrowth import (
    FPNode,
    FPTree,
    mine_frequent_itemsets,
    parse_transaction_line,
    read_database,
    read_transactions,
    format_itemset,
    write_frequent_itemsets,
)

Mining

mine_frequent_itemsets

mine_frequent_itemsets(transactions: Iterable[Iterable[Hashable]], min_support: float = 0.5, *, absolute: bool = False) -> Dict[FrozenSet[Hashable], int]

Mine every frequent itemset in transactions with FP-Growth.

Parameters:

Name Type Description Default
transactions Iterable[Iterable[Hashable]]

An iterable of transactions, each an iterable of items. Duplicate items within a transaction are ignored. Items may be any hashable objects, though integers and strings are typical.

required
min_support float

The minimum support threshold. By default this is a relative frequency in [0, 1] and is multiplied by the number of transactions to obtain an absolute count. When absolute is True it is interpreted directly as an absolute count.

0.5
absolute bool

When True, treat min_support as an absolute count rather than a relative frequency.

False

Returns:

Type Description
Dict[FrozenSet[Hashable], int]

A dictionary mapping each frequent itemset (a :class:frozenset) to

Dict[FrozenSet[Hashable], int]

its absolute support count. Only non-empty itemsets are returned. An

Dict[FrozenSet[Hashable], int]

empty dictionary means no itemset met the threshold.

Raises:

Type Description
ValueError

If absolute is False and min_support is outside the closed interval [0, 1].

Examples:

>>> mine_frequent_itemsets([{1, 2}, {1, 3}, {1, 2, 3}], 2 / 3, absolute=True)
{frozenset({1}): 3, frozenset({3}): 2, frozenset({1, 3}): 2, frozenset({2}): 2, frozenset({1, 2}): 2}
Source code in src/fpgrowth/core.py
def mine_frequent_itemsets(
    transactions: Iterable[Iterable[Hashable]],
    min_support: float = 0.5,
    *,
    absolute: bool = False,
) -> Dict[FrozenSet[Hashable], int]:
    """Mine every frequent itemset in ``transactions`` with FP-Growth.

    Args:
        transactions: An iterable of transactions, each an iterable of items.
            Duplicate items within a transaction are ignored. Items may be any
            hashable objects, though integers and strings are typical.
        min_support: The minimum support threshold. By default this is a
            *relative* frequency in ``[0, 1]`` and is multiplied by the number
            of transactions to obtain an absolute count. When ``absolute`` is
            ``True`` it is interpreted directly as an absolute count.
        absolute: When ``True``, treat ``min_support`` as an absolute count
            rather than a relative frequency.

    Returns:
        A dictionary mapping each frequent itemset (a :class:`frozenset`) to
        its absolute support count. Only non-empty itemsets are returned. An
        empty dictionary means no itemset met the threshold.

    Raises:
        ValueError: If ``absolute`` is ``False`` and ``min_support`` is outside
            the closed interval ``[0, 1]``.

    Examples:
        >>> mine_frequent_itemsets([{1, 2}, {1, 3}, {1, 2, 3}], 2 / 3, absolute=True)
        {frozenset({1}): 3, frozenset({3}): 2, frozenset({1, 3}): 2, frozenset({2}): 2, frozenset({1, 2}): 2}
    """
    transactions = [frozenset(t) for t in transactions]

    if absolute:
        threshold: float = min_support
    else:
        if not 0.0 <= min_support <= 1.0:
            raise ValueError(
                "min_support must be a relative frequency between 0 and 1 when "
                "absolute=False; got {!r}".format(min_support)
            )
        threshold = min_support * len(transactions)

    if not transactions:
        return {}

    item_counts: Counter = Counter()
    for transaction in transactions:
        item_counts.update(transaction)

    frequent_items = {
        item: count for item, count in item_counts.items() if count >= threshold
    }
    if not frequent_items:
        return {}

    order = {
        item: rank
        for rank, item in enumerate(
            sorted(
                frequent_items,
                key=lambda item: (-frequent_items[item], _order_key(item)),
            )
        )
    }

    tree = FPTree()
    for transaction in transactions:
        items = sorted(
            (item for item in transaction if item in frequent_items),
            key=order.__getitem__,
        )
        if items:
            tree.add_transaction(items)

    results: Dict[FrozenSet[Hashable], int] = {}
    _mine(tree, threshold, frozenset(), results)
    return results

Tree types

FPTree

FPTree()

A prefix tree over transactions with per-item node-link chains.

Build a tree by calling :meth:add_transaction for every transaction. Each transaction must already be sorted in the global item order (conventionally descending support, with ties broken deterministically). Applying one consistent order to every transaction is what allows transactions to share prefixes; it is also what makes the conditional trees produced during mining correct.

Attributes:

Name Type Description
root

The root :class:FPNode.

header Dict[Hashable, FPNode]

Mapping from item to the first node of that item's link chain.

Source code in src/fpgrowth/core.py
def __init__(self) -> None:
    self.root = FPNode(None, 0, None)
    self.header: Dict[Hashable, FPNode] = {}
    self._tail: Dict[Hashable, FPNode] = {}

add_transaction

add_transaction(items: Iterable[Hashable], count: int = 1) -> None

Insert a single transaction into the tree.

Parameters:

Name Type Description Default
items Iterable[Hashable]

Items already sorted in the global item order.

required
count int

Weight of the transaction. 1 for a normal transaction; larger values are used when inserting weighted prefix paths while building conditional trees.

1
Source code in src/fpgrowth/core.py
def add_transaction(self, items: Iterable[Hashable], count: int = 1) -> None:
    """Insert a single transaction into the tree.

    Args:
        items: Items already sorted in the global item order.
        count: Weight of the transaction. ``1`` for a normal transaction;
            larger values are used when inserting weighted prefix paths
            while building conditional trees.
    """
    node = self.root
    for item in items:
        child = node.children.get(item)
        if child is None:
            child = FPNode(item, count, node)
            node.children[item] = child
            self._register(child)
        else:
            child.count += count
        node = child

nodes

nodes(item: Hashable) -> Iterator[FPNode]

Iterate over every node in the tree labelled with item.

Parameters:

Name Type Description Default
item Hashable

The item to search for.

required

Yields:

Name Type Description
Each FPNode

class:FPNode whose item equals item, following the

FPNode

node links. Yields nothing when the item is absent from the tree.

Source code in src/fpgrowth/core.py
def nodes(self, item: Hashable) -> Iterator[FPNode]:
    """Iterate over every node in the tree labelled with ``item``.

    Args:
        item: The item to search for.

    Yields:
        Each :class:`FPNode` whose ``item`` equals ``item``, following the
        node links. Yields nothing when the item is absent from the tree.
    """
    node = self.header.get(item)
    while node is not None:
        yield node
        node = node.link

support

support(item: Hashable) -> int

Return the total count of every node labelled with item.

Parameters:

Name Type Description Default
item Hashable

The item to measure.

required

Returns:

Type Description
int

The summed count of all matching nodes, or 0 if the item is

int

not present.

Source code in src/fpgrowth/core.py
def support(self, item: Hashable) -> int:
    """Return the total count of every node labelled with ``item``.

    Args:
        item: The item to measure.

    Returns:
        The summed ``count`` of all matching nodes, or ``0`` if the item is
        not present.
    """
    return sum(node.count for node in self.nodes(item))

prefix_paths

prefix_paths(item: Hashable) -> List[List[FPNode]]

Return the prefix paths of item.

A prefix path is the sequence of nodes from the root down to a node labelled item (the root is excluded, item's node is the last element). One path is returned per occurrence of item.

Parameters:

Name Type Description Default
item Hashable

The item whose prefix paths are wanted.

required

Returns:

Type Description
List[List[FPNode]]

A list of paths, each a list of :class:FPNode ordered from the

List[List[FPNode]]

root's child down to the matching node.

Source code in src/fpgrowth/core.py
def prefix_paths(self, item: Hashable) -> List[List[FPNode]]:
    """Return the prefix paths of ``item``.

    A prefix path is the sequence of nodes from the root down to a node
    labelled ``item`` (the root is excluded, ``item``'s node is the last
    element). One path is returned per occurrence of ``item``.

    Args:
        item: The item whose prefix paths are wanted.

    Returns:
        A list of paths, each a list of :class:`FPNode` ordered from the
        root's child down to the matching node.
    """
    paths: List[List[FPNode]] = []
    for node in self.nodes(item):
        path: List[FPNode] = []
        while node is not None and not node.is_root:
            path.append(node)
            node = node.parent
        path.reverse()
        paths.append(path)
    return paths

FPNode

FPNode(item: Hashable, count: int = 1, parent: Optional['FPNode'] = None)

A single node of an FP-tree.

A node stores an item label, the number of transactions routed through it, a pointer to its parent, a mapping of its children keyed by item, and a link to the next node in the tree that carries the same item. The chain of same-item links is called the node links; it lets the mining routine visit every occurrence of an item without walking the entire tree.

Parameters:

Name Type Description Default
item Hashable

The item label stored in this node. The root uses None.

required
count int

Number of transactions routed through this node.

1
parent Optional['FPNode']

The parent node, or None for the root.

None

Attributes:

Name Type Description
item

The item label stored in this node.

count

Number of transactions routed through this node.

parent

The parent node, or None for the root.

children Dict[Hashable, 'FPNode']

Mapping from item label to the child :class:FPNode.

link Optional['FPNode']

Next node in the same-item link chain, or None.

Source code in src/fpgrowth/core.py
def __init__(self, item: Hashable, count: int = 1, parent: Optional["FPNode"] = None):
    self.item = item
    self.count = count
    self.parent = parent
    self.children: Dict[Hashable, "FPNode"] = {}
    self.link: Optional["FPNode"] = None

is_root property

is_root: bool

bool: True when this node is the tree root (carries no item).

Reading and writing

read_database

read_database(path: str, item_parser: Callable[[str], Hashable] = int) -> Tuple[int, List[FrozenSet[Hashable]]]

Read a transaction database file in full.

Parameters:

Name Type Description Default
path str

Path to the transaction database file.

required
item_parser Callable[[str], Hashable]

Callable converting each item token to an item.

int

Returns:

Type Description
int

A tuple (declared_count, transactions). declared_count is the

List[FrozenSet[Hashable]]

integer read from the first line; transactions is the list of

Tuple[int, List[FrozenSet[Hashable]]]

parsed transactions. The two are not required to agree.

Source code in src/fpgrowth/io.py
def read_database(
    path: str,
    item_parser: Callable[[str], Hashable] = int,
) -> Tuple[int, List[FrozenSet[Hashable]]]:
    """Read a transaction database file in full.

    Args:
        path: Path to the transaction database file.
        item_parser: Callable converting each item token to an item.

    Returns:
        A tuple ``(declared_count, transactions)``. ``declared_count`` is the
        integer read from the first line; ``transactions`` is the list of
        parsed transactions. The two are not required to agree.
    """
    with open(path, "r", encoding="utf-8") as handle:
        declared_count = int(handle.readline().rstrip("\n"))
        transactions = [
            parse_transaction_line(line, item_parser=item_parser)[2]
            for line in handle
            if line.strip()
        ]
    return declared_count, transactions

read_transactions

read_transactions(path: str, item_parser: Callable[[str], Hashable] = int) -> List[FrozenSet[Hashable]]

Read only the transactions from a transaction database file.

This is a convenience wrapper around :func:read_database that discards the declared transaction count.

Parameters:

Name Type Description Default
path str

Path to the transaction database file.

required
item_parser Callable[[str], Hashable]

Callable converting each item token to an item.

int

Returns:

Type Description
List[FrozenSet[Hashable]]

The list of parsed transactions.

Source code in src/fpgrowth/io.py
def read_transactions(
    path: str,
    item_parser: Callable[[str], Hashable] = int,
) -> List[FrozenSet[Hashable]]:
    """Read only the transactions from a transaction database file.

    This is a convenience wrapper around :func:`read_database` that discards
    the declared transaction count.

    Args:
        path: Path to the transaction database file.
        item_parser: Callable converting each item token to an item.

    Returns:
        The list of parsed transactions.
    """
    return read_database(path, item_parser=item_parser)[1]

parse_transaction_line

parse_transaction_line(line: str, item_parser: Callable[[str], Hashable] = int) -> Tuple[int, int, FrozenSet[Hashable]]

Parse one transaction line from a transaction database file.

Parameters:

Name Type Description Default
line str

A single line such as "1\t3\t1 3 4". A trailing newline is ignored.

required
item_parser Callable[[str], Hashable]

Callable converting each item token to an item. Defaults to :class:int.

int

Returns:

Type Description
int

A tuple (transaction_id, item_count, items) where items is a

int

class:frozenset.

Raises:

Type Description
ValueError

If the line does not have exactly three tab-separated fields or the id/count fields are not integers.

Source code in src/fpgrowth/io.py
def parse_transaction_line(
    line: str,
    item_parser: Callable[[str], Hashable] = int,
) -> Tuple[int, int, FrozenSet[Hashable]]:
    """Parse one transaction line from a transaction database file.

    Args:
        line: A single line such as ``"1\\t3\\t1 3 4"``. A trailing newline is
            ignored.
        item_parser: Callable converting each item token to an item. Defaults to
            :class:`int`.

    Returns:
        A tuple ``(transaction_id, item_count, items)`` where ``items`` is a
        :class:`frozenset`.

    Raises:
        ValueError: If the line does not have exactly three tab-separated
            fields or the id/count fields are not integers.
    """
    fields = line.rstrip("\n").split("\t")
    if len(fields) != 3:
        raise ValueError(
            "expected 3 tab-separated fields "
            "(transaction id, item count, items); got {!r}".format(line)
        )
    transaction_id = int(fields[0])
    item_count = int(fields[1])
    items = frozenset(item_parser(token) for token in fields[2].split(" ") if token)
    return transaction_id, item_count, items

format_itemset

format_itemset(itemset: Iterable[Hashable]) -> str

Render an itemset as a stable, space-separated string.

Items are ordered by their string representation so that output is deterministic across runs and independent of set iteration order.

Parameters:

Name Type Description Default
itemset Iterable[Hashable]

The items to render.

required

Returns:

Type Description
str

The items joined by single spaces.

Source code in src/fpgrowth/io.py
def format_itemset(itemset: Iterable[Hashable]) -> str:
    """Render an itemset as a stable, space-separated string.

    Items are ordered by their string representation so that output is
    deterministic across runs and independent of set iteration order.

    Args:
        itemset: The items to render.

    Returns:
        The items joined by single spaces.
    """
    return " ".join(sorted((str(item) for item in itemset)))

write_frequent_itemsets

write_frequent_itemsets(path: str, itemsets: Mapping[FrozenSet[Hashable], int]) -> int

Write frequent itemsets and their supports to a text file.

The first line is |FPs| = <count>. Each following line is <items> : <support>. Lines are sorted by itemset size and then by their rendered text so that the file is deterministic.

Parameters:

Name Type Description Default
path str

Destination file path. Parent directories are created if needed.

required
itemsets Mapping[FrozenSet[Hashable], int]

Mapping from itemset (a :class:frozenset) to its absolute support count.

required

Returns:

Type Description
int

The number of itemsets written.

Source code in src/fpgrowth/io.py
def write_frequent_itemsets(
    path: str,
    itemsets: Mapping[FrozenSet[Hashable], int],
) -> int:
    """Write frequent itemsets and their supports to a text file.

    The first line is ``|FPs| = <count>``. Each following line is
    ``<items> : <support>``. Lines are sorted by itemset size and then by
    their rendered text so that the file is deterministic.

    Args:
        path: Destination file path. Parent directories are created if needed.
        itemsets: Mapping from itemset (a :class:`frozenset`) to its absolute
            support count.

    Returns:
        The number of itemsets written.
    """
    parent = os.path.dirname(path)
    if parent:
        os.makedirs(parent, exist_ok=True)

    rendered = [
        (sorted(str(item) for item in itemset), support)
        for itemset, support in itemsets.items()
    ]
    rendered.sort(key=lambda pair: (len(pair[0]), pair[0]))

    with open(path, "w", encoding="utf-8") as handle:
        handle.write("|FPs| = {}\n".format(len(rendered)))
        for items, support in rendered:
            handle.write("{} : {}\n".format(" ".join(items), support))
    return len(rendered)