Debian Codegraph @

docs/source/ml.rst

raw
1 Machine Learning
2 ================
3
4 Machine learning is a broad field involving many different workflows. This
5 page lists a few of the more common ways in which Dask can help you with ML
6 workloads.
7
8 - :ref:`hpo`
9 - :ref:`boosted-trees`
10 - :ref:`batch-prediction`
11
12 .. _hpo:
13
14 Hyperparameter Optimization
15 ---------------------------
16
17 Optuna
18 ~~~~~~
19
20 For state of the art hyperparameter optimization (HPO) we recommend the
21 `Optuna <https://optuna.org/>`_ library,
22 with the associated
23 `Dask integration <https://optuna-integration.readthedocs.io/en/latest/reference/generated/optuna_integration.DaskStorage.html>`_.
24
25
26 In Optuna you construct an objective function that takes a trial object, which
27 generates parameters from distributions that you define in code. Your
28 objective function eventually produces a score. Optuna is smart about what
29 values from the distribution it suggests based on the scores it has received.
30
31 .. code-block:: python
32
33 def objective(trial):
34 params = {
35 "max_depth": trial.suggest_int("max_depth", 2, 10, step=1),
36 "learning_rate": trial.suggest_float("learning_rate", 1e-8, 1.0, log=True),
37 ...
38 }
39 model = train_model(train_data, **params)
40 result = score(model, test_data)
41 return result
42
43 Dask and Optuna are often used together by running many objective functions in
44 parallel and synchronizing the scores and parameter selection on the Dask
45 scheduler. To do this, we use the ``DaskStore`` object found in Optuna.
46
47 .. code-block:: python
48
49 import optuna
50
51 storage = optuna.integration.DaskStorage()
52
53 study = optuna.create_study(
54 direction="maximize",
55 storage=storage, # This makes the study Dask-enabled
56 )
57
58 Then we run many optimize methods in parallel.
59
60 .. code-block:: python
61
62 from dask.distributed import LocalCluster, wait
63
64 cluster = LocalCluster(processes=False) # replace this with some scalable cluster
65 client = cluster.get_client()
66
67 futures = [
68 client.submit(study.optimize, objective, n_trials=1, pure=False) for _ in range(500)
69 ]
70 wait(futures)
71
72 print(study.best_params)
73
74 For a more fully worked example see this :bdg-link-primary:`Optuna + XGBoost example <https://docs.coiled.io/user_guide/hpo.html?utm_source=dask-docs&utm_medium=ml>`.
75
76
77 Dask Futures
78 ~~~~~~~~~~~~
79
80 Additionally, for simpler situations people often use :doc:`Dask Futures <futures>` to
81 train the same model on lots of parameters. Dask Futures are a general purpose
82 API that is used to run normal Python functions on various inputs. An example
83 might look like the following:
84
85 .. code-block:: python
86
87 from dask.distributed import LocalCluster
88
89 cluster = LocalCluster(processes=False) # replace this with some scalable cluster
90 client = cluster.get_client()
91
92 def train_and_score(params: dict) -> float:
93 data = load_data()
94 model = make_model(**params)
95 train(model)
96 score = evaluate(model)
97 return score
98
99 params_list = [...]
100 futures = [
101 client.submit(train_and_score, params) for params in params_list
102 ]
103 scores = client.gather(futures)
104 best = max(scores)
105
106 best_params = params_list[scores.index(best)]
107
108 For a more fully worked example see :bdg-link-primary:`Futures Documentation <futures.html>`.
109
110 .. _boosted-trees:
111
112 Gradient Boosted Trees
113 ----------------------
114
115 Popular GBT libraries, like XGBoost and LightGBM, have native Dask support which allows you to train models
116 on very large datasets in parallel.
117
118 - `XGBoost <https://xgboost.readthedocs.io/en/stable/tutorials/dask.html>`_
119 - `LightGBM <https://lightgbm.readthedocs.io/en/latest/Parallel-Learning-Guide.html#dask>`_
120
121 For example, using Dask DataFrame, XGBoost, and a local Dask cluster looks like the following:
122
123 .. code-block:: python
124
125 import dask.dataframe as dd
126 import xgboost as xgb
127 from dask.distributed import LocalCluster
128
129 df = dask.datasets.timeseries() # Randomly generated data
130 # df = dd.read_parquet(...) # In practice, you would probably read data though
131
132 train, test = df.random_split([0.80, 0.20])
133 X_train, y_train, X_test, y_test = ...
134
135 with LocalCluster() as cluster:
136 with cluster.get_client() as client:
137 d_train = xgb.dask.DaskDMatrix(client, X_train, y_train, enable_categorical=True)
138 model = xgb.dask.train(
139 ...
140 d_train,
141 )
142 predictions = xgb.dask.predict(client, model, X_test)
143
144 For a more fully worked example see this :bdg-link-primary:`XGBoost example <https://docs.coiled.io/user_guide/xgboost.html?utm_source=dask-docs&utm_medium=ml>`.
145
146 .. _batch-prediction:
147
148 Batch Prediction
149 ----------------
150
151 Once a model is trained, it's common to want to apply the model across
152 lots of data. We see this done most often in two ways:
153
154 1. Using Dask Futures
155 2. Using :py:meth:`DataFrame.map_partitions <dask.dataframe.DataFrame.map_partitions>`
156 or :py:meth:`Array.map_blocks <dask.array.Array.map_blocks>`
157
158 We'll show examples of each approach below.
159
160 Dask Futures
161 ~~~~~~~~~~~~
162
163 Dask Futures are a general purpose API that lets you run arbitrary Python
164 functions on Python data in parallel. It's easy to apply this tool to solve the problem of
165 batch prediction.
166
167 For example, we often see this when people want to apply a model across many
168 data files.
169
170 .. code-block:: python
171
172 from dask.distributed import LocalCluster
173
174 cluster = LocalCluster(processes=False) # replace this with some scalable cluster
175 client = cluster.get_client()
176
177 filenames = [...]
178
179 def predict(filename, model):
180 data = load(filename)
181 result = model.predict(data)
182 return result
183
184 model = client.submit(load_model, path_to_model)
185 predictions = client.map(predict, filenames, model=model)
186 results = client.gather(predictions)
187
188 For a more fully worked example see :bdg-link-primary:`Batch Scoring for Computer Vision Workloads (video) <https://developer.download.nvidia.com/video/gputechconf/gtc/2019/video/S9198/s9198-dask-and-v100s-for-fast-distributed-batch-scoring-of-computer-vision-workloads.mp4>`.
189
190 Dask DataFrame
191 ~~~~~~~~~~~~~~
192
193 Sometimes we want to process our model with a higher
194 level Dask API, like Dask DataFrame or Dask Array. This is more common with
195 record data, for example if we had a set of patient records and wanted to
196 see which patients were likely to become ill.
197
198 .. code-block:: python
199
200 import dask.dataframe as dd
201
202 df = dd.read_parquet("/path/to/my/data.parquet")
203
204 model = load_model("/path/to/my/model")
205
206 # pandas code
207 # predictions = model.predict(df)
208 # predictions.to_parquet("/path/to/results.parquet")
209
210 # Dask code
211 predictions = df.map_partitions(model.predict)
212 predictions.to_parquet("/path/to/results.parquet")
213
214 For more information see :bdg-link-primary:`Dask DataFrame documentation <dataframe.html>`.