Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: more hash, sizeof and eq implementations #609

Merged
merged 16 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
46 changes: 46 additions & 0 deletions src/safeds/data/tabular/transformation/_imputer.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import annotations

import sys
import warnings
from typing import Any

import pandas as pd
import xxhash
from sklearn.impute import SimpleImputer as sk_SimpleImputer

from safeds.data.tabular.containers import Table
Expand Down Expand Up @@ -47,9 +49,29 @@ class Constant(ImputerStrategy):
The given value to impute missing values.
"""

def __eq__(self, other: object) -> bool:
if not isinstance(other, Imputer.Strategy.Constant):
return NotImplemented
if self is other:
return True
return self._value == other._value

def __hash__(self) -> int:
return xxhash.xxh3_64(self.__class__.__qualname__.encode("utf-8")).intdigest()
lars-reimann marked this conversation as resolved.
Show resolved Hide resolved

def __init__(self, value: Any):
self._value = value

def __sizeof__(self) -> int:
"""
Return the complete size of this object.

Returns
-------
Size of this object in bytes.
"""
return sys.getsizeof(self._value)

def __str__(self) -> str:
return f"Constant({self._value})"

Expand All @@ -60,6 +82,14 @@ def _augment_imputer(self, imputer: sk_SimpleImputer) -> None:
class Mean(ImputerStrategy):
"""An imputation strategy for imputing missing data with mean values."""

def __eq__(self, other: object) -> bool:
if not isinstance(other, Imputer.Strategy.Mean):
return NotImplemented
return True

def __hash__(self) -> int:
return xxhash.xxh3_64(self.__class__.__qualname__.encode("utf-8")).intdigest()
lars-reimann marked this conversation as resolved.
Show resolved Hide resolved

def __str__(self) -> str:
return "Mean"

Expand All @@ -69,6 +99,14 @@ def _augment_imputer(self, imputer: sk_SimpleImputer) -> None:
class Median(ImputerStrategy):
"""An imputation strategy for imputing missing data with median values."""

def __eq__(self, other: object) -> bool:
if not isinstance(other, Imputer.Strategy.Median):
return NotImplemented
return True

def __hash__(self) -> int:
return xxhash.xxh3_64(self.__class__.__qualname__.encode("utf-8")).intdigest()
lars-reimann marked this conversation as resolved.
Show resolved Hide resolved

def __str__(self) -> str:
return "Median"

Expand All @@ -78,6 +116,14 @@ def _augment_imputer(self, imputer: sk_SimpleImputer) -> None:
class Mode(ImputerStrategy):
"""An imputation strategy for imputing missing data with mode values. The lowest value will be used if there are multiple values with the same highest count."""

def __eq__(self, other: object) -> bool:
if not isinstance(other, Imputer.Strategy.Mode):
return NotImplemented
return True

def __hash__(self) -> int:
return xxhash.xxh3_64(self.__class__.__qualname__.encode("utf-8")).intdigest()
lars-reimann marked this conversation as resolved.
Show resolved Hide resolved

def __str__(self) -> str:
return "Mode"

Expand Down
13 changes: 12 additions & 1 deletion src/safeds/data/tabular/transformation/_table_transformer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import functools
import operator
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING

Expand All @@ -21,7 +23,16 @@ def __hash__(self) -> int:
hash : int
The hash value.
"""
return xxhash.xxh3_64(self.__class__.__qualname__.encode("utf-8") + (1 if self.is_fitted() else 0).to_bytes(1)).intdigest()
added = self.get_names_of_added_columns() if self.is_fitted() else []
changed = self.get_names_of_changed_columns() if self.is_fitted() else []
removed = self.get_names_of_removed_columns() if self.is_fitted() else []
return xxhash.xxh3_64(
self.__class__.__qualname__.encode("utf-8")
+ (1 if self.is_fitted() else 0).to_bytes(1)
+ functools.reduce(operator.add, [feature.encode("utf-8") for feature in added], b"A")
+ functools.reduce(operator.add, [feature.encode("utf-8") for feature in changed], b"C")
+ functools.reduce(operator.add, [feature.encode("utf-8") for feature in removed], b"R"),
).intdigest()
WinPlay02 marked this conversation as resolved.
Show resolved Hide resolved

@abstractmethod
def fit(self, table: Table, column_names: list[str] | None) -> TableTransformer:
Expand Down
27 changes: 27 additions & 0 deletions src/safeds/data/tabular/typing/_imputer_strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,30 @@ def _augment_imputer(self, imputer: sk_SimpleImputer) -> None:
imputer: SimpleImputer
The imputer to augment.
"""

@abstractmethod
def __eq__(self, other: object) -> bool:
"""
Compare two imputer strategies.

Parameters
----------
other:
other object to compare to

Returns
-------
equals:
Whether the two imputer strategies are equal
"""

@abstractmethod
def __hash__(self) -> int:
"""
Return a deterministic hash value for this imputer strategy.

Returns
-------
hash : int
The hash value.
"""
17 changes: 17 additions & 0 deletions src/safeds/ml/classical/classification/_ada_boost.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from __future__ import annotations

import functools
import operator
import struct
from typing import TYPE_CHECKING

import xxhash
from sklearn.ensemble import AdaBoostClassifier as sk_AdaBoostClassifier

from safeds.exceptions import ClosedBound, OpenBound, OutOfBoundsError
Expand Down Expand Up @@ -36,6 +40,19 @@ class AdaBoostClassifier(Classifier):
If `maximum_number_of_learners` or `learning_rate` are less than or equal to 0.
"""

def __hash__(self) -> int:
return xxhash.xxh3_64(
Classifier.__hash__(self).to_bytes(8)
+ (self._target_name.encode("utf-8") if self._target_name is not None else b"\0")
+ (
functools.reduce(operator.add, [feature.encode("utf-8") for feature in self._feature_names], b"")
if self._feature_names is not None
else b"\0"
)
+ struct.pack("d", self._learning_rate)
+ self._maximum_number_of_learners.to_bytes(8),
).intdigest()

def __init__(
self,
*,
Expand Down
14 changes: 14 additions & 0 deletions src/safeds/ml/classical/classification/_decision_tree.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import annotations

import functools
import operator
from typing import TYPE_CHECKING

import xxhash
from sklearn.tree import DecisionTreeClassifier as sk_DecisionTreeClassifier

from safeds.ml.classical._util_sklearn import fit, predict
Expand All @@ -17,6 +20,17 @@
class DecisionTreeClassifier(Classifier):
"""Decision tree classification."""

def __hash__(self) -> int:
return xxhash.xxh3_64(
Classifier.__hash__(self).to_bytes(8)
+ (self._target_name.encode("utf-8") if self._target_name is not None else b"\0")
+ (
functools.reduce(operator.add, [feature.encode("utf-8") for feature in self._feature_names], b"")
if self._feature_names is not None
else b"\0"
),
).intdigest()

def __init__(self) -> None:
# Internal state
self._wrapped_classifier: sk_DecisionTreeClassifier | None = None
Expand Down
17 changes: 17 additions & 0 deletions src/safeds/ml/classical/classification/_gradient_boosting.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from __future__ import annotations

import functools
import operator
import struct
from typing import TYPE_CHECKING

import xxhash
from sklearn.ensemble import GradientBoostingClassifier as sk_GradientBoostingClassifier

from safeds.exceptions import ClosedBound, OpenBound, OutOfBoundsError
Expand Down Expand Up @@ -34,6 +38,19 @@ class GradientBoostingClassifier(Classifier):
If `number_of_trees` or `learning_rate` is less than or equal to 0.
"""

def __hash__(self) -> int:
return xxhash.xxh3_64(
Classifier.__hash__(self).to_bytes(8)
+ (self._target_name.encode("utf-8") if self._target_name is not None else b"\0")
+ (
functools.reduce(operator.add, [feature.encode("utf-8") for feature in self._feature_names], b"")
if self._feature_names is not None
else b"\0"
)
+ struct.pack("d", self._learning_rate)
+ self._number_of_trees.to_bytes(8),
).intdigest()

def __init__(self, *, number_of_trees: int = 100, learning_rate: float = 0.1) -> None:
# Validation
if number_of_trees < 1:
Expand Down
15 changes: 15 additions & 0 deletions src/safeds/ml/classical/classification/_k_nearest_neighbors.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import annotations

import functools
import operator
from typing import TYPE_CHECKING

import xxhash
from sklearn.neighbors import KNeighborsClassifier as sk_KNeighborsClassifier

from safeds.exceptions import ClosedBound, DatasetMissesDataError, OutOfBoundsError
Expand Down Expand Up @@ -31,6 +34,18 @@ class KNearestNeighborsClassifier(Classifier):
If `number_of_neighbors` is less than 1.
"""

def __hash__(self) -> int:
return xxhash.xxh3_64(
Classifier.__hash__(self).to_bytes(8)
+ (self._target_name.encode("utf-8") if self._target_name is not None else b"\0")
+ (
functools.reduce(operator.add, [feature.encode("utf-8") for feature in self._feature_names], b"")
if self._feature_names is not None
else b"\0"
)
+ self._number_of_neighbors.to_bytes(8),
).intdigest()

def __init__(self, number_of_neighbors: int) -> None:
# Validation
if number_of_neighbors < 1:
Expand Down
14 changes: 14 additions & 0 deletions src/safeds/ml/classical/classification/_logistic_regression.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import annotations

import functools
import operator
from typing import TYPE_CHECKING

import xxhash
from sklearn.linear_model import LogisticRegression as sk_LogisticRegression

from safeds.ml.classical._util_sklearn import fit, predict
Expand All @@ -17,6 +20,17 @@
class LogisticRegressionClassifier(Classifier):
"""Regularized logistic regression."""

def __hash__(self) -> int:
return xxhash.xxh3_64(
Classifier.__hash__(self).to_bytes(8)
+ (self._target_name.encode("utf-8") if self._target_name is not None else b"\0")
+ (
functools.reduce(operator.add, [feature.encode("utf-8") for feature in self._feature_names], b"")
if self._feature_names is not None
else b"\0"
),
).intdigest()

def __init__(self) -> None:
# Internal state
self._wrapped_classifier: sk_LogisticRegression | None = None
Expand Down
15 changes: 15 additions & 0 deletions src/safeds/ml/classical/classification/_random_forest.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import annotations

import functools
import operator
from typing import TYPE_CHECKING

import xxhash
from sklearn.ensemble import RandomForestClassifier as sk_RandomForestClassifier

from safeds.exceptions import ClosedBound, OutOfBoundsError
Expand Down Expand Up @@ -29,6 +32,18 @@ class RandomForestClassifier(Classifier):
If `number_of_trees` is less than 1.
"""

def __hash__(self) -> int:
return xxhash.xxh3_64(
Classifier.__hash__(self).to_bytes(8)
+ (self._target_name.encode("utf-8") if self._target_name is not None else b"\0")
+ (
functools.reduce(operator.add, [feature.encode("utf-8") for feature in self._feature_names], b"")
if self._feature_names is not None
else b"\0"
)
+ self._number_of_trees.to_bytes(8),
).intdigest()

def __init__(self, *, number_of_trees: int = 100) -> None:
# Validation
if number_of_trees < 1:
Expand Down
Loading