File size: 1,727 Bytes
f8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Small executable example; it is not a claimed state-of-the-art baseline."""

from __future__ import annotations

from typing import Callable

import numpy as np
from datasets import Dataset
from sklearn.ensemble import RandomForestClassifier


def _features(dataset: Dataset, preprocess: Callable) -> np.ndarray:
    rows: list[np.ndarray] = []
    for row in dataset:
        signal = preprocess(row["signal"])
        diff = np.diff(signal, axis=0)
        rows.append(
            np.concatenate(
                [
                    signal.min(axis=0),
                    signal.max(axis=0),
                    np.median(signal, axis=0),
                    np.quantile(signal, 0.25, axis=0),
                    np.quantile(signal, 0.75, axis=0),
                    np.mean(signal**2, axis=0),
                    diff.mean(axis=0),
                    diff.std(axis=0),
                ]
            )
        )
    return np.vstack(rows)


class ExampleStatsRF:
    def __init__(self, *, seed: int, task_view_id: str):
        self.task_view_id = task_view_id
        self.model = RandomForestClassifier(
            n_estimators=200,
            class_weight="balanced",
            random_state=seed,
            n_jobs=-1,
        )

    def fit(self, train: Dataset, validation: Dataset, *, preprocess: Callable) -> None:
        del validation
        self.model.fit(_features(train, preprocess), np.asarray(train["label"], dtype=object))

    def predict(self, test: Dataset, *, preprocess: Callable) -> np.ndarray:
        return self.model.predict(_features(test, preprocess))


def build(*, seed: int, task_view_id: str) -> ExampleStatsRF:
    return ExampleStatsRF(seed=seed, task_view_id=task_view_id)