Scikit-learn
human-activity-recognition
wearable
wrist
time-series
cpu
scikit-learn
File size: 4,922 Bytes
4731b11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""WISPRepresentation, wisp.blocks and HMMSmoother on fixture windows (E4 and E7 in-process)."""
import numpy as np
import pytest
from numpy.testing import assert_array_equal
from sklearn.base import BaseEstimator, TransformerMixin

from wisp import HMMSmoother, WISPRepresentation, blocks, recipes
from wisp._engine import build_kernel


def family_features(model, recipe, X):
    """Feature matrix computed inside a fitted reference family object."""
    if recipe.family == "rocket_sketch_ridge_hmm":
        return model.sketch_.transform(X)
    if recipe.family in ("har_sculpt_forest_hmm", "symbolic_interval_forest"):
        return model.feature_extractor_.transform(X)
    return model._features(X)


@pytest.mark.parametrize("name", ["ss", "rc", "so", "gis", "cis", "cis:R", "cis:I", "cis:S", "cis:RI",
                                  "cis:RS", "cis:IS", "best:adl", "best:capture24", "best:paal_adl"])
@pytest.mark.parametrize("seed", [42, 7])
def test_e4_features_bit_identical_to_family(name, seed, train_windows, test_windows):
    X, y, g, t = train_windows
    Xq = test_windows[0]
    recipe = recipes.get(name)
    rep = WISPRepresentation(name, random_state=seed).fit(X)
    model = build_kernel(recipe, use_hmm=True, engine="reference", seed=seed).fit(X, y, groups=g, time_index=t,
                                                                                    n_classes=3)
    assert_array_equal(rep.transform(Xq), family_features(model, recipe, Xq))
    assert_array_equal(rep.transform(X), family_features(model, recipe, X))
    assert rep.n_features_out_ == rep.transform(Xq).shape[1]
    assert len(rep.get_feature_names_out()) == rep.n_features_out_


@pytest.mark.parametrize("name", ["cse", "ese"])
def test_ensembles_have_no_single_representation(name, train_windows):
    with pytest.raises(ValueError, match="predict_proba"):
        WISPRepresentation(name).fit(train_windows[0])


class MeanBlock(TransformerMixin, BaseEstimator):
    def fit(self, X, y=None):
        self.fitted_ = True
        return self

    def transform(self, X):
        return np.asarray(X).mean(axis=1)


def test_extra_blocks_and_slices(train_windows):
    X = train_windows[0]
    rep = WISPRepresentation("cis:RS", extra_blocks=[MeanBlock(), ("energy", MeanBlock())]).fit(X)
    sl = rep.block_slices_
    assert list(sl) == ["R", "S", "extra0", "energy"]
    Z = rep.transform(X)
    assert_array_equal(Z[:, sl["extra0"]], X.mean(axis=1))
    assert sl["energy"].stop == Z.shape[1] == rep.n_features_out_
    assert rep.is_catalog_representation_ is False
    plain = WISPRepresentation("cis:RS").fit(X)
    assert_array_equal(Z[:, :plain.n_features_out_], plain.transform(X))
    assert rep.extra_blocks[0] is not rep.extra_blocks_[0][1]  # parameters are not fitted in place


def test_dtype_and_layout(train_windows):
    X = train_windows[0]
    a = WISPRepresentation("rc").fit(X)
    b = WISPRepresentation("rc", layout="NCT", dtype="float32").fit(X.transpose(0, 2, 1))
    Zb = b.transform(X.transpose(0, 2, 1))
    assert Zb.dtype == np.float32
    assert_array_equal(Zb, a.transform(X).astype(np.float32))


def test_blocks_match_cis_blocks(train_windows):
    X = train_windows[0]
    rep = WISPRepresentation("cis", random_state=11).fit(X)
    Z = rep.transform(X)
    for name, block in (("R", blocks.RandomConvolution(random_state=11)), ("I", blocks.IntervalSummary(random_state=11)),
                        ("S", blocks.StateSpectral())):
        assert_array_equal(block.fit(X).transform(X), Z[:, rep.block_slices_[name]])


@pytest.mark.parametrize("with_time", [True, False])
def test_e7_hmm_smoother_equals_kernel(with_time, train_windows, test_windows):
    from wisp.cpu.hmm import TransitionSmoother
    _, y, g, t = train_windows
    _, yq, gq, tq = test_windows
    rng = np.random.default_rng(3)
    scores = rng.dirichlet(np.ones(4), size=len(yq))
    labels = np.array(["a", "b", "c", "d"])
    sm = HMMSmoother().fit(labels[y], groups=g, time_index=t if with_time else None, classes=labels)
    ref = TransitionSmoother().fit(y, groups=g, time_index=t if with_time else None, n_classes=4)
    assert_array_equal(sm.transition_, ref.transition_)
    got = sm.decode(scores, groups=gq, time_index=tq if with_time else None)
    exp = ref.predict_from_proba(scores, groups=gq, time_index=tq if with_time else None)
    assert_array_equal(got, labels[exp])
    assert_array_equal(sm.decode(scores), labels[ref.predict_from_proba(scores)])


def test_hmm_smoother_validation(train_windows):
    _, y, g, t = train_windows
    sm = HMMSmoother().fit(y, groups=g)
    with pytest.raises(ValueError, match="shape"):
        sm.decode(np.ones((5, 4)))
    with pytest.raises(ValueError, match="one entry per window"):
        sm.decode(np.ones((5, 3)) / 3, groups=[1, 2])
    with pytest.raises(ValueError, match="one entry per window"):
        HMMSmoother().fit(y, groups=g[:-1])