"src/targets/vscode:/vscode.git/clone" did not exist on "f8bf7bd30249352721f69e08605cd726cf0f88f0"
tabular_data_classification_in_AML.ipynb 11.5 KB
Newer Older
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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tabular Data Classification with NNI in AML"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This simple example is to use NNI NAS 2.0(Retiarii) framework to search for the best neural architecture for tabular data classification task in Azure Machine Learning training platform.\n",
    "\n",
    "The video demo is https://www.youtube.com/watch?v=PDVqBmm7Cro and https://www.bilibili.com/video/BV1oy4y1W7GF."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Prepare the dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first step is to prepare the dataset. Here we use the Titanic dataset as an example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import torch\n",
    "import pandas as pd\n",
    "\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from torchvision.datasets.utils import download_url\n",
    "\n",
    "class TitanicDataset(torch.utils.data.Dataset):\n",
    "    def __init__(self, root: str, train: bool = True):\n",
    "        filename = 'train.csv' if train else 'eval.csv'\n",
    "        if not os.path.exists(os.path.join(root, filename)):\n",
    "            download_url(os.path.join(\n",
    "                'https://storage.googleapis.com/tf-datasets/titanic/', filename), root, filename)\n",
    "\n",
    "        df = pd.read_csv(os.path.join(root, filename))\n",
    "        object_colunmns = df.select_dtypes(include='object').columns.values\n",
    "        for idx in df.columns:\n",
    "            if idx in object_colunmns:\n",
    "                df[idx] = LabelEncoder().fit_transform(df[idx])\n",
    "        \n",
    "        self.x = torch.tensor(df.iloc[:, 1:].values)\n",
    "        self.y = torch.tensor(df.iloc[:, 0].values)\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.y)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        return self.x[idx], self.y[idx]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_dataset = TitanicDataset('./data', train=True)\n",
    "test_dataset = TitanicDataset('./data', train=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Define the Model Space"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Model space is defined by users to express a set of models that they want to explore, which contains potentially good-performing models. In Retiarii(NNI NAS 2.0) framework, a model space is defined with two parts: a base model and possible mutations on the base model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 2.1: Define the Base Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Defining a base model is almost the same as defining a PyTorch (or TensorFlow) model. Usually, you only need to replace the code ``import torch.nn as nn`` with ``import nni.retiarii.nn.pytorch as nn`` to use NNI wrapped PyTorch modules. Below is a very simple example of defining a base model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nni.retiarii.nn.pytorch as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "class Net(nn.Module):\n",
    "\n",
    "    def __init__(self, input_size):\n",
    "        super().__init__()\n",
    "\n",
    "        self.fc1 = nn.Linear(input_size, 16)\n",
    "        self.bn1 = nn.BatchNorm1d(16)\n",
    "        self.dropout1 = nn.Dropout(0.0)\n",
    "\n",
    "        self.fc2 = nn.Linear(16, 16)\n",
    "        self.bn2 = nn.BatchNorm1d(16)\n",
    "        self.dropout2 = nn.Dropout(0.0)\n",
    "\n",
    "        self.fc3 = nn.Linear(16, 2)\n",
    "\n",
    "    def forward(self, x):\n",
    "\n",
    "        x = self.dropout1(F.relu(self.bn1(self.fc1(x))))\n",
    "        x = self.dropout2(F.relu(self.bn2(self.fc2(x))))\n",
    "        x = F.sigmoid(self.fc3(x))\n",
    "        return x\n",
    "    \n",
    "model_space = Net(len(train_dataset.__getitem__(0)[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 2.2: Define the Model Mutations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A base model is only one concrete model, not a model space. NNI provides APIs and primitives for users to express how the base model can be mutated, i.e., a model space that includes many models. The following will use inline Mutation APIs as a simple example. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nni.retiarii.nn.pytorch as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "class Net(nn.Module):\n",
    "\n",
    "    def __init__(self, input_size):\n",
    "        super().__init__()\n",
    "\n",
    "        self.hidden_dim1 = nn.ValueChoice(\n",
    "            [16, 32, 64, 128, 256, 512, 1024], label='hidden_dim1')\n",
    "        self.hidden_dim2 = nn.ValueChoice(\n",
    "            [16, 32, 64, 128, 256, 512, 1024], label='hidden_dim2')\n",
    "\n",
    "        self.fc1 = nn.Linear(input_size, self.hidden_dim1)\n",
    "        self.bn1 = nn.BatchNorm1d(self.hidden_dim1)\n",
    "        self.dropout1 = nn.Dropout(nn.ValueChoice([0.0, 0.25, 0.5]))\n",
    "\n",
    "        self.fc2 = nn.Linear(self.hidden_dim1, self.hidden_dim2)\n",
    "        self.bn2 = nn.BatchNorm1d(self.hidden_dim2)\n",
    "        self.dropout2 = nn.Dropout(nn.ValueChoice([0.0, 0.25, 0.5]))\n",
    "\n",
    "        self.fc3 = nn.Linear(self.hidden_dim2, 2)\n",
    "\n",
    "    def forward(self, x):\n",
    "\n",
    "        x = self.dropout1(F.relu(self.bn1(self.fc1(x))))\n",
    "        x = self.dropout2(F.relu(self.bn2(self.fc2(x))))\n",
    "        x = F.sigmoid(self.fc3(x))\n",
    "        return x\n",
    "\n",
    "model_space = Net(len(train_dataset.__getitem__(0)[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Besides inline mutations, Retiarii also provides ``mutator``, a more general approach to express complex model space."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: Explore the Defined Model Space"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the NAS process, the search strategy repeatedly generates new models, and the model evaluator is for training and validating each generated model. The obtained performance of a generated model is collected and sent to the search strategy for generating better models.\n",
    "\n",
    "Users can choose a proper search strategy to explore the model space, and use a chosen or user-defined model evaluator to evaluate the performance of each sampled model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 3.1: Choose a Search Strategy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nni.retiarii.strategy as strategy\n",
    "\n",
    "simple_strategy = strategy.TPEStrategy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 3.2: Choose or Write a Model Evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the context of PyTorch, Retiarii has provided two built-in model evaluators, designed for simple use cases: classification and regression. These two evaluators are built upon the awesome library PyTorch-Lightning."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nni.retiarii.evaluator.pytorch.lightning as pl\n",
    "\n",
    "trainer = pl.Classification(train_dataloader=pl.DataLoader(train_dataset, batch_size=16),\n",
    "                                val_dataloaders=pl.DataLoader(\n",
    "                                test_dataset, batch_size=16),\n",
    "                                max_epochs=20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Configure the Experiment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After all the above are prepared, it is time to configure an experiment to do the model search. The basic experiment configuration is as follows: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nni.retiarii.experiment.pytorch import RetiariiExeConfig, RetiariiExperiment\n",
    "\n",
    "exp = RetiariiExperiment(model_space, trainer, [], simple_strategy)\n",
    "\n",
    "exp_config = RetiariiExeConfig('aml')\n",
    "exp_config.experiment_name = 'titanic_example'\n",
    "exp_config.trial_concurrency = 2\n",
    "exp_config.max_trial_number = 20\n",
    "exp_config.max_experiment_duration = '2h'\n",
    "exp_config.trial_gpu_number = 1\n",
    "exp_config.nni_manager_ip = '' # your nni_manager_ip"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Running NNI experiments on the AML(Azure Machine Learning) training service is also simple, you only need to configure the following additional fields:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "exp_config.training_service.use_active_gpu = True\n",
    "exp_config.training_service.subscription_id = '' # your subscription id\n",
    "exp_config.training_service.resource_group = '' # your resource group\n",
    "exp_config.training_service.workspace_name = '' # your workspace name\n",
    "exp_config.training_service.compute_target = '' # your compute target\n",
    "exp_config.training_service.docker_image = ''  # your docker image"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5: Run and View the Experiment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can launch the experiment now! \n",
    "\n",
    "Besides, NNI provides WebUI to help users view the experiment results and make more advanced analysis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "exp.run(exp_config, 8081 + random.randint(0, 100))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 6: Export the top Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Exporting the top model script is also very convenient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Final model:')\n",
    "for model_code in exp.export_top_models():\n",
    "    print(model_code)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}