pipeline_transform.py 6.34 KB
Newer Older
1
2
3
4
5
6
7
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Tiago de Freitas Pereira <tiago.pereira@idiap.ch>


import logging

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
8
import click
9

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
10
11
12
13
14
from bob.extension.scripts.click_helper import (
    ConfigCommand,
    ResourceOption,
    verbosity_option,
)
15
from bob.pipelines import is_pipeline_wrapped
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
16
17
18
19
from bob.pipelines.distributed import (
    VALID_DASK_CLIENT_STRINGS,
    dask_get_partition_size,
)
20
21

logger = logging.getLogger(__name__)
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
22
from bob.pipelines.wrappers import CheckpointWrapper, DaskWrapper, wrap
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

EPILOG = """\b
Command line examples\n
---------------------\n


Follow below an example on how to extract arcface features from a database:\n

`bob bio transform my_database iresnet100 -vv`\n\n

To "dask" the execution of the pipeline, you can use the `--dask-client` option.\n
In the example below we show how to use the `--dask-client` option to start a dask cluster on SGE.\n

`bob bio transform my_database iresnet100 --dask-client sge -vv`\n\n

\b

Creating my own transformer\n
---------------------------\n

This command accepts configuration file as input.\n
44
For example, if you desire to customize your transformer, you can use the following configuration file:\n
45
46
47
48
49
50
51
52
53
54
\b\b


```py\n
from sklearn.base import BaseEstimator, TransformerMixin \n
from sklearn.pipeline import make_pipeline  \n
from bob.pipelines import wrap \n

class MyTransformer(TransformerMixin, BaseEstimator): \n
    def _more_tags(self): \n
55
        return {"requires_fit": False} \n
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
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
    def transform(self, X): \n
        # do something \n
        return X \n

transformer = wrap(["sample"],make_pipeline(MyTransformer())) \n
```

Then, you can use above configuration file to run the command:

\b
`bob bio pipelines transform my_database my_transformer.py --dask-client sge -vv`

\b\b

Leveraging from FunctionTransformer\n
-----------------------------------\n

You can also benefit from `FunctionTransformer` to create a transformer

```py \n
from sklearn.preprocessing import FunctionTransformer \n
from sklearn.pipeline import make_pipeline \n
from bob.pipelines import wrap \n

\b

def my_transformer(X): \n
    # do something \n
    return X \n


transformer = wrap(["sample"],make_pipeline(FunctionTransformer(my_transformer))) \n
```

Then, you can use above configuration file to run the command:\n

`bob bio pipelines transform my_database my_transformer.py --dask-client sge -vv`


\b\b
"""


@click.command(
101
    name="transform",
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    entry_point_group="bob.bio.config",
    cls=ConfigCommand,
    epilog=EPILOG,
)
@click.option(
    "--transformer",
    "-t",
    required=True,
    entry_point_group="bob.bio.transformer",
    help="A scikit-learn Pipeline containing the set of transformations",
    cls=ResourceOption,
)
@click.option(
    "--database",
    "-d",
    entry_point_group="bob.bio.database",
    required=True,
    help="Biometric Database connector (class that implements the methods: `background_model_samples`, `references` and `probes`)",
    cls=ResourceOption,
)
@click.option(
    "--dask-client",
    "-l",
    entry_point_group="dask.client",
    string_exceptions=VALID_DASK_CLIENT_STRINGS,
    default="single-threaded",
    help="Dask client for the execution of the pipeline.",
    cls=ResourceOption,
)
@click.option(
    "-c",
    "--checkpoint-dir",
    show_default=True,
    default="./checkpoints",
    help="Name of output directory where the checkpoints will be saved.",
    cls=ResourceOption,
)
@click.option(
    "--force",
    "-f",
    is_flag=True,
    help="If set, it will force generate all the checkpoints of an experiment. This option doesn't work if `--memory` is set",
    cls=ResourceOption,
)
@click.option(
    "--dask-partition-size",
    "-s",
    help="If using Dask, this option defines the size of each dask.bag.partition."
    "Use this option if the current heuristic that sets this value doesn't suit your experiment."
    "(https://docs.dask.org/en/latest/bag-api.html?highlight=partition_size#dask.bag.from_sequence).",
    default=None,
    type=click.INT,
    cls=ResourceOption,
)
@verbosity_option(cls=ResourceOption)
157
def pipeline_transform(
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    transformer,
    database,
    dask_client,
    checkpoint_dir,
    force,
    dask_partition_size,
    **kwargs,
):
    """
    This CLI command will execute a pipeline (a scikit learn Pipeline)  on a given database.

    This command can be used, for example, to extract features, face-crops, preprocess audio files and so on.

    """

    logger.info(f"Transforming samples from {database}")

    # save_func = bob.io.base.save

    # Idiap SETUP. This avoids having directories with more than 1000 files/directories
    hash_fn = database.hash_fn if hasattr(database, "hash_fn") else None

    # If NONE of the items are checkpointed, we checkpoint them all
    if not any(is_pipeline_wrapped(transformer, CheckpointWrapper)):
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
182
        logger.info("Checkpointing it")
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
        transformer = wrap(
            ["checkpoint"],
            transformer,
            features_dir=checkpoint_dir,
            hash_fn=hash_fn,
            force=force,
        )
    else:
        # If there is only one item that is checkpointed, we don't need to wrap the pipeline
        logger.warning(
            f"{transformer}"
            f"The pipeline contains elements that are already checkpointed."
            "Hence, we are not checkpointing them again."
        )

    # Fetching all samples
    samples = database.all_samples()

    # The number of dasked elements has to be the number of
    # elements in the pipeline - 1 (the ToDaskBag doesn't count)
    dasked_elements = is_pipeline_wrapped(transformer, DaskWrapper)

    if any(dasked_elements):
        logger.warning(
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
207
            "The pipeline is already dasked, hence, we are not dasking it again."
208
209
210
211
212
213
214
215
216
217
218
219
        )
    else:

        if not isinstance(dask_client, str):
            dask_partition_size = (
                dask_get_partition_size(
                    dask_client.cluster, len(samples), lower_bound=200
                )
                if dask_partition_size is None
                else dask_partition_size
            )

Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
220
221
222
223
224
225
        logger.info(
            f"Dask wrapping it with partition size {dask_partition_size}"
        )
        transformer = wrap(
            ["dask"], transformer, partition_size=dask_partition_size
        )
226
227
228
229
230
231

    transformer.transform(samples).compute(
        scheduler="single-threaded" if dask_client is None else dask_client
    )

    logger.info("Transformation finished !")