saiph 3.0.2__tar.gz → 3.0.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {saiph-3.0.2 → saiph-3.0.3}/PKG-INFO +1 -1
- {saiph-3.0.2 → saiph-3.0.3}/pyproject.toml +1 -6
- {saiph-3.0.2 → saiph-3.0.3}/saiph/__init__.py +1 -1
- {saiph-3.0.2 → saiph-3.0.3}/saiph/projection_test.py +42 -15
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/famd.py +38 -35
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/famd_test.py +60 -1
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/utils/common.py +17 -7
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/utils/common_test.py +37 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/streaming.py +6 -7
- {saiph-3.0.2 → saiph-3.0.3}/uv.lock +240 -213
- {saiph-3.0.2 → saiph-3.0.3}/.github/dependabot.yml +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/.github/workflows/pr-title.yml +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/.github/workflows/prepare-release.yml +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/.github/workflows/release.yml +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/.github/workflows/saiph-ci.yml +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/.gitignore +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/.pre-commit-config.yaml +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/.readthedocs.yaml +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/.tool-versions +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/CONTRIBUTING.md +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/LICENSE +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/README.md +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/bin/create_csv.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/docs/conf.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/docs/index.rst +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/docs/requirements.txt +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/docs/source/example/README.rst +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/docs/source/example/plot_example.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/docs/source/reference.rst +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/fixtures/iris.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/fixtures/wbcd.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/justfile +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/release.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/ruff.toml +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/conftest.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/contribution.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/contribution_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/exception.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/inverse_transform.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/inverse_transform_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/lib/size.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/models.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/projection.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/py.typed +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/__init__.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/famd_sparse.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/famd_sparse_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/mca.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/mca_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/pca.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/pca_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/utils/__init__.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/utils/svd.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/reduction/utils/svd_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/serializer.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/serializer_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/streaming_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/tests/__init_.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/tests/benchmark_test.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/tests/profile_cpu.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/tests/profile_memory.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/saiph/visualization.py +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/setup.cfg +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/tests/fixtures/breast_cancer_wisconsin.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/tests/fixtures/breast_cancer_wisconsin_supplemental.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/tests/fixtures/iris.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/tests/fixtures/iris_factomineR_contributions.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/tests/fixtures/iris_factomineR_cos2.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/tests/fixtures/wbcd_supplemental_coordinates_famd.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/tests/fixtures/wbcd_supplemental_coordinates_mca.csv +0 -0
- {saiph-3.0.2 → saiph-3.0.3}/tests/fixtures/wbcd_supplemental_coordinates_pca.csv +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "saiph"
|
|
3
3
|
# Also modify in saiph/__init__.py
|
|
4
|
-
version = "3.0.
|
|
4
|
+
version = "3.0.3"
|
|
5
5
|
description = "A projection package"
|
|
6
6
|
authors = [
|
|
7
7
|
{name = "Octopize", email = "help@octopize.io"}
|
|
@@ -35,7 +35,6 @@ dev = [
|
|
|
35
35
|
"Faker>=13.6.0",
|
|
36
36
|
"tqdm>=4.64.0",
|
|
37
37
|
"pytest-benchmark>=4.0.0",
|
|
38
|
-
"doubles>=1.5.3",
|
|
39
38
|
"ipdb>=0.13.9",
|
|
40
39
|
]
|
|
41
40
|
doc = [
|
|
@@ -94,7 +93,3 @@ ignore_missing_imports = true
|
|
|
94
93
|
module = "toolz.*"
|
|
95
94
|
ignore_missing_imports = true
|
|
96
95
|
|
|
97
|
-
[[tool.mypy.overrides]]
|
|
98
|
-
module = "doubles.*"
|
|
99
|
-
ignore_missing_imports = true
|
|
100
|
-
|
|
@@ -4,7 +4,6 @@ from typing import Any
|
|
|
4
4
|
import numpy as np
|
|
5
5
|
import pandas as pd
|
|
6
6
|
import pytest
|
|
7
|
-
from doubles import expect
|
|
8
7
|
from numpy.testing import assert_allclose
|
|
9
8
|
from pandas.testing import assert_frame_equal
|
|
10
9
|
|
|
@@ -353,43 +352,71 @@ def test_get_variable_contribution_are_similar_with_reduced_nf() -> None:
|
|
|
353
352
|
assert percentage_difference < 20
|
|
354
353
|
|
|
355
354
|
|
|
355
|
+
class _RecordingStub:
|
|
356
|
+
"""Stand-in for a function that records its calls and returns a fixed value."""
|
|
357
|
+
|
|
358
|
+
def __init__(self, return_value: Any) -> None:
|
|
359
|
+
self.return_value = return_value
|
|
360
|
+
self.calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
|
|
361
|
+
|
|
362
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
363
|
+
self.calls.append((args, kwargs))
|
|
364
|
+
return self.return_value
|
|
365
|
+
|
|
366
|
+
def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None:
|
|
367
|
+
assert len(self.calls) == 1
|
|
368
|
+
called_args, called_kwargs = self.calls[0]
|
|
369
|
+
assert len(called_args) == len(args)
|
|
370
|
+
assert all(called is expected for called, expected in zip(called_args, args))
|
|
371
|
+
assert called_kwargs == kwargs
|
|
372
|
+
|
|
373
|
+
|
|
356
374
|
def test_get_variable_contributions_calls_correct_subfunction(
|
|
357
|
-
quanti_df: pd.DataFrame,
|
|
375
|
+
quanti_df: pd.DataFrame,
|
|
376
|
+
quali_df: pd.DataFrame,
|
|
377
|
+
mixed_df: pd.DataFrame,
|
|
378
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
358
379
|
) -> None:
|
|
359
380
|
"""Verify that projection.get_variable_contributions calls the correct subfunction."""
|
|
360
381
|
# FAMD
|
|
361
382
|
model = fit(mixed_df)
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
).once().and_return((None, None))
|
|
383
|
+
famd_stub = _RecordingStub((None, None))
|
|
384
|
+
monkeypatch.setattr(saiph.reduction.famd, "get_variable_contributions", famd_stub)
|
|
365
385
|
projection.get_variable_contributions(model, mixed_df)
|
|
386
|
+
famd_stub.assert_called_once_with(model, mixed_df, explode=False)
|
|
366
387
|
|
|
367
388
|
# MCA
|
|
368
389
|
model = fit(quali_df)
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
).once().and_return(None)
|
|
390
|
+
mca_stub = _RecordingStub(None)
|
|
391
|
+
monkeypatch.setattr(saiph.reduction.mca, "get_variable_contributions", mca_stub)
|
|
372
392
|
projection.get_variable_contributions(model, quali_df)
|
|
393
|
+
mca_stub.assert_called_once_with(model, quali_df, explode=False)
|
|
373
394
|
|
|
374
395
|
# PCA
|
|
375
396
|
model = fit(quanti_df)
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
)
|
|
397
|
+
pca_stub = _RecordingStub(pd.DataFrame([1, 2, 3]))
|
|
398
|
+
monkeypatch.setattr(saiph.projection, "get_variable_correlation", pca_stub)
|
|
379
399
|
projection.get_variable_contributions(model, quanti_df)
|
|
400
|
+
pca_stub.assert_called_once_with(model, quanti_df)
|
|
380
401
|
|
|
381
402
|
|
|
382
|
-
def test_stats_calls_correct_subfunction(
|
|
403
|
+
def test_stats_calls_correct_subfunction(
|
|
404
|
+
quali_df: pd.DataFrame, mixed_df: pd.DataFrame, monkeypatch: pytest.MonkeyPatch
|
|
405
|
+
) -> None:
|
|
383
406
|
"""Verify that projection.stats calls the correct subfunction."""
|
|
384
407
|
# FAMD
|
|
385
408
|
model = fit(mixed_df)
|
|
386
|
-
|
|
409
|
+
famd_stub = _RecordingStub(model)
|
|
410
|
+
monkeypatch.setattr(saiph.reduction.famd, "stats", famd_stub)
|
|
411
|
+
projection.stats(model, mixed_df)
|
|
412
|
+
famd_stub.assert_called_once_with(model, mixed_df, explode=False)
|
|
387
413
|
|
|
388
414
|
# MCA
|
|
389
|
-
projection.stats(model, mixed_df)
|
|
390
415
|
model = fit(quali_df)
|
|
391
|
-
|
|
416
|
+
mca_stub = _RecordingStub(model)
|
|
417
|
+
monkeypatch.setattr(saiph.reduction.mca, "stats", mca_stub)
|
|
392
418
|
projection.stats(model, quali_df)
|
|
419
|
+
mca_stub.assert_called_once_with(model, quali_df, explode=False)
|
|
393
420
|
|
|
394
421
|
# FIXME: Can't test PCA as it has no subfunction associated to it
|
|
395
422
|
|
|
@@ -388,14 +388,7 @@ def compute_categorical_cos2(model: Model, df: pd.DataFrame, min_nf: int) -> pd.
|
|
|
388
388
|
prefix_sep=DUMMIES_SEPARATOR,
|
|
389
389
|
dtype=np.uint8,
|
|
390
390
|
)
|
|
391
|
-
|
|
392
|
-
all_category_cos = {}
|
|
393
|
-
for original_col, dummy_columns in mapping.items():
|
|
394
|
-
# FIXME: Kept this for legacy: Why - 1 ? nb_modalities += [nb_dummy_columns - 1] #
|
|
395
|
-
# for each dimension
|
|
396
|
-
all_category_cos[original_col] = _compute_cos2_single_category(
|
|
397
|
-
dummy[dummy_columns], model, model_coords
|
|
398
|
-
)
|
|
391
|
+
all_category_cos = _compute_cos2_of_each_category(mapping, dummy, model, model_coords)
|
|
399
392
|
|
|
400
393
|
# FIXME: Why - 1 ?
|
|
401
394
|
nb_modalities = df[model.original_categorical].nunique() - 1
|
|
@@ -477,44 +470,54 @@ def _compute_svd(
|
|
|
477
470
|
return s, weighted_U, eigenvalues
|
|
478
471
|
|
|
479
472
|
|
|
480
|
-
def
|
|
481
|
-
|
|
482
|
-
) -> NDArray[np.float64]:
|
|
483
|
-
"""Compute cos2
|
|
473
|
+
def _compute_cos2_of_each_category(
|
|
474
|
+
mapping: dict[str, list[str]], dummy: pd.DataFrame, model: Model, coords: pd.DataFrame
|
|
475
|
+
) -> dict[str, NDArray[np.float64]]:
|
|
476
|
+
"""Compute the cos2 of each original categorical variable, for each axis.
|
|
477
|
+
|
|
478
|
+
For one axis and one modality, the squared weighted sum of the coordinates of the
|
|
479
|
+
individuals that hold the modality, over the proportion of the modality; summed over the
|
|
480
|
+
modalities of a variable, over the weighted sum of the squared coordinates. Every modality
|
|
481
|
+
is read in one matrix product, not one pandas column at a time.
|
|
484
482
|
|
|
485
483
|
Parameters
|
|
486
484
|
----------
|
|
487
|
-
|
|
488
|
-
dummy
|
|
485
|
+
mapping :
|
|
486
|
+
the dummy columns of each original categorical variable, in order
|
|
487
|
+
dummy :
|
|
488
|
+
the dummy dataframe of the original categorical variables
|
|
489
489
|
model :
|
|
490
|
-
|
|
490
|
+
model
|
|
491
491
|
coords :
|
|
492
|
-
projections of the data used to
|
|
492
|
+
projections of the data used to create the axes
|
|
493
493
|
|
|
494
494
|
Returns:
|
|
495
495
|
-------
|
|
496
|
-
cos2 of
|
|
496
|
+
the cos2 of each original categorical variable, one value per axis
|
|
497
497
|
"""
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
for coord_col in coords.columns:
|
|
501
|
-
weighted_coord = coords[coord_col].values * model.row_weights
|
|
502
|
-
p_values = np.zeros(n_cols)
|
|
503
|
-
|
|
504
|
-
for i, col in enumerate(single_category_df.columns):
|
|
505
|
-
dummy_values = single_category_df[col].values
|
|
506
|
-
if model.prop is not None:
|
|
507
|
-
p_values[i] = (dummy_values * weighted_coord).sum() ** 2 / model.prop[col]
|
|
508
|
-
|
|
509
|
-
p = p_values.sum()
|
|
510
|
-
cos2.append(p)
|
|
511
|
-
|
|
512
|
-
all_weighted_coords = (coords.values**2).T * model.row_weights
|
|
513
|
-
summed_weights = all_weighted_coords.sum(axis=1)
|
|
498
|
+
row_weights = np.asarray(model.row_weights, dtype=np.float64)
|
|
499
|
+
weighted_coords = coords.to_numpy(dtype=np.float64) * row_weights[:, None]
|
|
514
500
|
|
|
501
|
+
summed_weights = ((coords.to_numpy(dtype=np.float64) ** 2) * row_weights[:, None]).sum(axis=0)
|
|
515
502
|
# Remove zeros to avoid division by zero when a df contains a constant variable
|
|
516
503
|
summed_weights_without_zeros = np.where(
|
|
517
504
|
summed_weights <= sys.float_info.min, 1, summed_weights
|
|
518
505
|
)
|
|
519
|
-
|
|
520
|
-
|
|
506
|
+
|
|
507
|
+
dummy_columns = [col for columns in mapping.values() for col in columns]
|
|
508
|
+
if model.prop is not None and dummy_columns:
|
|
509
|
+
values = dummy[dummy_columns].to_numpy(dtype=np.float64)
|
|
510
|
+
prop = model.prop[dummy_columns].to_numpy(dtype=np.float64)
|
|
511
|
+
scores = (values.T @ weighted_coords) ** 2 / prop[:, None]
|
|
512
|
+
else:
|
|
513
|
+
scores = np.zeros((len(dummy_columns), coords.shape[1]), dtype=np.float64)
|
|
514
|
+
|
|
515
|
+
all_category_cos: dict[str, NDArray[np.float64]] = {}
|
|
516
|
+
start = 0
|
|
517
|
+
for original_col, columns in mapping.items():
|
|
518
|
+
end = start + len(columns)
|
|
519
|
+
all_category_cos[original_col] = (
|
|
520
|
+
scores[start:end].sum(axis=0) / summed_weights_without_zeros
|
|
521
|
+
)
|
|
522
|
+
start = end
|
|
523
|
+
return all_category_cos
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import sys
|
|
1
2
|
from pathlib import Path
|
|
2
3
|
from typing import Any, cast
|
|
3
4
|
|
|
@@ -13,6 +14,7 @@ from saiph.models import Model
|
|
|
13
14
|
from saiph.reduction import DUMMIES_SEPARATOR
|
|
14
15
|
from saiph.reduction.famd import (
|
|
15
16
|
center,
|
|
17
|
+
compute_categorical_cos2,
|
|
16
18
|
fit,
|
|
17
19
|
fit_transform,
|
|
18
20
|
get_individual_coordinates,
|
|
@@ -23,7 +25,11 @@ from saiph.reduction.famd import (
|
|
|
23
25
|
from saiph.reduction.pca import center as center_pca
|
|
24
26
|
from saiph.reduction.pca import fit_transform as fit_pca
|
|
25
27
|
from saiph.reduction.pca import scaler as scaler_pca
|
|
26
|
-
from saiph.reduction.utils.common import
|
|
28
|
+
from saiph.reduction.utils.common import (
|
|
29
|
+
get_dummies_mapping,
|
|
30
|
+
get_projected_column_names,
|
|
31
|
+
row_division,
|
|
32
|
+
)
|
|
27
33
|
from saiph.reduction.utils.svd import get_svd
|
|
28
34
|
|
|
29
35
|
|
|
@@ -505,3 +511,56 @@ def test_get_individual_coordinates_equals_the_left_singular_vectors() -> None:
|
|
|
505
511
|
rebuilt = get_individual_coordinates(model, df, nf)
|
|
506
512
|
|
|
507
513
|
assert_allclose(rebuilt.to_numpy(), expected, atol=1e-14)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _cos2_of_one_category_by_modality(
|
|
517
|
+
single_category_df: pd.DataFrame, model: Model, coords: pd.DataFrame
|
|
518
|
+
) -> NDArray[np.float64]:
|
|
519
|
+
"""The categorical cos2 as it was computed before, one modality at a time."""
|
|
520
|
+
_, n_cols = single_category_df.shape
|
|
521
|
+
cos2 = []
|
|
522
|
+
for coord_col in coords.columns:
|
|
523
|
+
weighted_coord = coords[coord_col].values * model.row_weights
|
|
524
|
+
p_values = np.zeros(n_cols)
|
|
525
|
+
for i, col in enumerate(single_category_df.columns):
|
|
526
|
+
dummy_values = single_category_df[col].values
|
|
527
|
+
if model.prop is not None:
|
|
528
|
+
p_values[i] = (dummy_values * weighted_coord).sum() ** 2 / model.prop[col]
|
|
529
|
+
cos2.append(p_values.sum())
|
|
530
|
+
all_weighted_coords = (coords.values**2).T * model.row_weights
|
|
531
|
+
summed_weights = all_weighted_coords.sum(axis=1)
|
|
532
|
+
summed_weights_without_zeros = np.where(
|
|
533
|
+
summed_weights <= sys.float_info.min, 1, summed_weights
|
|
534
|
+
)
|
|
535
|
+
result: NDArray[np.float64] = np.array(cos2) / summed_weights_without_zeros
|
|
536
|
+
return result
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def test_compute_categorical_cos2_is_the_one_computed_modality_by_modality(
|
|
540
|
+
wbcd_mixed_df: pd.DataFrame,
|
|
541
|
+
) -> None:
|
|
542
|
+
"""The cos2 read in one matrix product is the one of the loop over the modalities."""
|
|
543
|
+
df = wbcd_mixed_df
|
|
544
|
+
nf = 4
|
|
545
|
+
_, model = fit_transform(df, nf=nf)
|
|
546
|
+
cos2 = compute_categorical_cos2(model, df, nf)
|
|
547
|
+
|
|
548
|
+
coords = get_individual_coordinates(model, df, nf)
|
|
549
|
+
mapping = get_dummies_mapping(model.original_categorical, model.dummy_categorical)
|
|
550
|
+
dummy = pd.get_dummies(
|
|
551
|
+
df[model.original_categorical].astype("category"),
|
|
552
|
+
prefix_sep=DUMMIES_SEPARATOR,
|
|
553
|
+
dtype=np.uint8,
|
|
554
|
+
)
|
|
555
|
+
nb_modalities = df[model.original_categorical].nunique() - 1
|
|
556
|
+
expected = pd.DataFrame.from_dict(
|
|
557
|
+
{
|
|
558
|
+
col: _cos2_of_one_category_by_modality(dummy[dummies], model, coords)
|
|
559
|
+
for col, dummies in mapping.items()
|
|
560
|
+
},
|
|
561
|
+
orient="index",
|
|
562
|
+
columns=get_projected_column_names(nf),
|
|
563
|
+
)
|
|
564
|
+
expected = row_division(expected**2, nb_modalities)
|
|
565
|
+
|
|
566
|
+
assert_frame_equal(cos2, expected)
|
|
@@ -65,13 +65,23 @@ def get_modalities_types(df: pd.DataFrame) -> dict[str, str]:
|
|
|
65
65
|
|
|
66
66
|
|
|
67
67
|
def get_dummies_mapping(columns: list[str], dummy_columns: list[str]) -> dict[str, list[str]]:
|
|
68
|
-
"""Get mapping between original column and all dummy columns.
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
)
|
|
68
|
+
"""Get mapping between original column and all dummy columns.
|
|
69
|
+
|
|
70
|
+
A dummy column belongs to every column whose name, followed by the separator, starts its
|
|
71
|
+
own name, in the order of `dummy_columns`. The dummy columns are read once: thousands of
|
|
72
|
+
columns and thousands of dummy columns cost their sum, not their product.
|
|
73
|
+
"""
|
|
74
|
+
mapping: dict[str, list[str]] = OrderedDict((col, []) for col in columns)
|
|
75
|
+
prefixes = {f"{col}{DUMMIES_SEPARATOR}": col for col in columns}
|
|
76
|
+
for dummy in dummy_columns:
|
|
77
|
+
# Every prefix of the dummy that ends with the separator names a candidate column.
|
|
78
|
+
end = dummy.find(DUMMIES_SEPARATOR)
|
|
79
|
+
while end != -1:
|
|
80
|
+
col = prefixes.get(dummy[: end + len(DUMMIES_SEPARATOR)])
|
|
81
|
+
if col is not None:
|
|
82
|
+
mapping[col].append(dummy)
|
|
83
|
+
end = dummy.find(DUMMIES_SEPARATOR, end + 1)
|
|
84
|
+
return mapping
|
|
75
85
|
|
|
76
86
|
|
|
77
87
|
def expand_column_weights(
|
|
@@ -108,3 +108,40 @@ def test_expand_column_weights_ignores_modalities_without_a_dummy_column() -> No
|
|
|
108
108
|
dummy_categorical=[f"tool{sep}hammer", f"tool{sep}wrench"],
|
|
109
109
|
)
|
|
110
110
|
assert list(expanded) == [4.0, 4.0]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_get_dummies_mapping_keeps_the_order_and_the_ambiguous_prefixes() -> None:
|
|
114
|
+
"""A dummy belongs to every column whose name and the separator start its own name, in
|
|
115
|
+
the order of the dummy columns; a column with no dummy maps to an empty list."""
|
|
116
|
+
sep = DUMMIES_SEPARATOR
|
|
117
|
+
columns = ["tool", f"tool{sep}kind", "fruit", "empty"]
|
|
118
|
+
dummy_columns = [
|
|
119
|
+
f"fruit{sep}pear",
|
|
120
|
+
f"tool{sep}kind{sep}saw",
|
|
121
|
+
f"tool{sep}hammer",
|
|
122
|
+
f"fruit{sep}apple",
|
|
123
|
+
f"other{sep}x",
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
result = get_dummies_mapping(columns, dummy_columns)
|
|
127
|
+
|
|
128
|
+
assert list(result) == columns
|
|
129
|
+
assert result == {
|
|
130
|
+
"tool": [f"tool{sep}kind{sep}saw", f"tool{sep}hammer"],
|
|
131
|
+
f"tool{sep}kind": [f"tool{sep}kind{sep}saw"],
|
|
132
|
+
"fruit": [f"fruit{sep}pear", f"fruit{sep}apple"],
|
|
133
|
+
"empty": [],
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def test_get_dummies_mapping_reads_the_dummies_once() -> None:
|
|
138
|
+
"""Thousands of columns and of dummies cost their sum, not their product."""
|
|
139
|
+
sep = DUMMIES_SEPARATOR
|
|
140
|
+
nb_columns, nb_modalities = 3000, 3
|
|
141
|
+
columns = [f"col{i}" for i in range(nb_columns)]
|
|
142
|
+
dummy_columns = [f"col{i}{sep}{m}" for i in range(nb_columns) for m in range(nb_modalities)]
|
|
143
|
+
|
|
144
|
+
result = get_dummies_mapping(columns, dummy_columns)
|
|
145
|
+
|
|
146
|
+
assert len(result) == nb_columns
|
|
147
|
+
assert all(len(dummies) == nb_modalities for dummies in result.values())
|
|
@@ -43,6 +43,7 @@ from saiph.models import Model
|
|
|
43
43
|
from saiph.reduction import DUMMIES_SEPARATOR, famd, pca
|
|
44
44
|
from saiph.reduction.utils.common import (
|
|
45
45
|
expand_column_weights,
|
|
46
|
+
get_dummies_mapping,
|
|
46
47
|
get_explained_variance,
|
|
47
48
|
get_modalities_types,
|
|
48
49
|
get_uniform_row_weights,
|
|
@@ -107,15 +108,13 @@ class ScalingParams:
|
|
|
107
108
|
dependent and costs one direction. A null takes no dummy column, leaving a row that
|
|
108
109
|
sums to zero, which breaks the dependency and gives that variable its rank back.
|
|
109
110
|
"""
|
|
110
|
-
|
|
111
|
+
mapping = get_dummies_mapping(self.quali, list(self.modality_counts.index))
|
|
112
|
+
complete = sum(1 for dummies in mapping.values() if self._is_complete(dummies))
|
|
111
113
|
return min(self.n - 1, self.n_scaled_columns - complete)
|
|
112
114
|
|
|
113
|
-
def _is_complete(self,
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
[name for name in self.modality_counts.index if name.startswith(prefix)]
|
|
117
|
-
]
|
|
118
|
-
return bool(counts.sum() == self.n)
|
|
115
|
+
def _is_complete(self, dummies: list[str]) -> bool:
|
|
116
|
+
"""Whether the modalities of one column count every row: no row holds a null."""
|
|
117
|
+
return bool(self.modality_counts[dummies].sum() == self.n)
|
|
119
118
|
|
|
120
119
|
def to_model(self) -> Model:
|
|
121
120
|
"""Build the model, leaving the decomposition fields for `finalize` to fill in.
|