[1113] | 1 | from abc import ABC |
---|
| 2 | |
---|
[1185] | 3 | from evolalg_steps.base.step import Step |
---|
[1113] | 4 | import numpy as np |
---|
| 5 | |
---|
| 6 | |
---|
| 7 | class Dissimilarity(Step, ABC): |
---|
| 8 | |
---|
[1145] | 9 | def __init__(self, reduction="mean", output_field="dissim", knn=None, *args, **kwargs): |
---|
[1113] | 10 | super(Dissimilarity, self).__init__(*args, **kwargs) |
---|
| 11 | |
---|
| 12 | self.output_field = output_field |
---|
[1182] | 13 | self.fn_reduce = Dissimilarity.get_reduction_by_name(reduction) |
---|
[1145] | 14 | self.knn = knn |
---|
[1113] | 15 | |
---|
[1182] | 16 | |
---|
| 17 | @staticmethod |
---|
| 18 | def reduce(dissim_matrix, fn_reduce, knn): |
---|
| 19 | if fn_reduce is None: |
---|
[1113] | 20 | return dissim_matrix |
---|
[1182] | 21 | elif fn_reduce is Dissimilarity.knn_mean: |
---|
| 22 | return fn_reduce(dissim_matrix, 1, knn) |
---|
| 23 | else: |
---|
| 24 | return fn_reduce(dissim_matrix, axis=1) |
---|
[1145] | 25 | |
---|
[1182] | 26 | |
---|
| 27 | @staticmethod |
---|
| 28 | def knn_mean(dissim_matrix, axis, knn): |
---|
| 29 | return np.mean(np.partition(dissim_matrix, knn)[:, :knn], axis=axis) |
---|
| 30 | |
---|
| 31 | |
---|
| 32 | @staticmethod |
---|
| 33 | def get_reduction_by_name(reduction: str): |
---|
| 34 | |
---|
| 35 | if reduction not in REDUCTION_FUNCTION: |
---|
| 36 | raise ValueError(f"Unknown reduction type '{reduction}'. Supported: {','.join(REDUCTION_FUNCTION.keys())}") |
---|
| 37 | |
---|
| 38 | return REDUCTION_FUNCTION[reduction] |
---|
| 39 | |
---|
| 40 | |
---|
| 41 | |
---|
| 42 | REDUCTION_FUNCTION = { |
---|
| 43 | "mean": np.mean, |
---|
| 44 | "max": np.max, |
---|
| 45 | "min": np.min, |
---|
| 46 | "sum": np.sum, |
---|
| 47 | "knn_mean": Dissimilarity.knn_mean, |
---|
| 48 | "none": None |
---|
| 49 | } |
---|