-
Notifications
You must be signed in to change notification settings - Fork 1
/
NN.html
675 lines (626 loc) · 49.5 KB
/
NN.html
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: module NN</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head><body bgcolor="#f0f0f8">
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="#7799ee">
<td valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"> <br><big><big><strong>NN</strong></big></big></font></td
><td align=right valign=bottom
><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:e%3A%5Cmyproject%5Cws_20_21%5Cknowledgedistillation%5Cnn.py">e:\myproject\ws_20_21\knowledgedistillation\nn.py</a></font></td></tr></table>
<p></p>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#aa55cc">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr>
<tr><td bgcolor="#aa55cc"><tt> </tt></td><td> </td>
<td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="numpy.html">numpy</a><br>
</td><td width="25%" valign=top><a href="matplotlib.pyplot.html">matplotlib.pyplot</a><br>
</td><td width="25%" valign=top></td><td width="25%" valign=top></td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ee77aa">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
<tr><td bgcolor="#ee77aa"><tt> </tt></td><td> </td>
<td width="100%"><dl>
<dt><font face="helvetica, arial"><a href="torch.nn.modules.module.html#Module">torch.nn.modules.module.Module</a>(<a href="builtins.html#object">builtins.object</a>)
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="NN.html#MLP">MLP</a>
</font></dt></dl>
</dd>
</dl>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="MLP">class <strong>MLP</strong></a>(<a href="torch.nn.modules.module.html#Module">torch.nn.modules.module.Module</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt><a href="#MLP">MLP</a>(n_inputs)<br>
<br>
Define a class that extends <a href="torch.nn.modules.module.html#Module">Module</a> class.<br> </tt></td></tr>
<tr><td> </td>
<td width="100%"><dl><dt>Method resolution order:</dt>
<dd><a href="NN.html#MLP">MLP</a></dd>
<dd><a href="torch.nn.modules.module.html#Module">torch.nn.modules.module.Module</a></dd>
<dd><a href="builtins.html#object">builtins.object</a></dd>
</dl>
<hr>
Methods defined here:<br>
<dl><dt><a name="MLP-__init__"><strong>__init__</strong></a>(self, n_inputs)</dt><dd><tt>The constructor of <a href="#MLP">MLP</a> class defines the layers. We define <a href="#MLP">MLP</a><br>
with input layer(n_inputs = 13 neurons), first hidden layer(26 neurons),<br>
second hidden layer(13 neurons) and output layer. That gives us 689<br>
weights to be adjusted. We are using Kaiming for the weight initialisation<br>
strategy for hidden1 - > hidden2, hidden2 - > output layer, according to the<br>
fact that we are using ReLU() activation function for the both hidden layers.<br>
For the output layer, we are using Sigmoid() activation function, suitable<br>
for our binary classification task. We are using Xavier initialization for<br>
the weights from hidden2 -> output, because it can solve Sigmoid() vanishing<br>
gradient problem.</tt></dd></dl>
<dl><dt><a name="MLP-forward"><strong>forward</strong></a>(self, X)</dt><dd><tt>This function takes the input data (rows of heart.csv, without original<br>
target labels). The input data is fed in the forward direction through<br>
the network. Each hidden layer accepts the input data, processes it, as per<br>
the activation function and passes to the successive layer.<br>
<br>
Parameters<br>
----------<br>
X : input values from heart.csv dataset (without the last "target column")<br>
<br>
Returns<br>
-------<br>
X : calculated output(target) value for the given input</tt></dd></dl>
<dl><dt><a name="MLP-forwardLastHiddenLayer"><strong>forwardLastHiddenLayer</strong></a>(self, X)</dt><dd><tt>This function takes the input data (rows of heart.csv, without original<br>
target labels). The input data is fed in the forward direction through<br>
the network. Each hidden layer accepts the input data, processes it, as per<br>
the activation function and passes to the successive layer. This function<br>
returns the output of the second hidden layer. The goal is to extract the<br>
learned features from the last hidden layer (in our case - second hidden layer)<br>
<br>
Parameters<br>
----------<br>
X : input values from heart.csv dataset (without the last "target column")<br>
<br>
Returns<br>
-------<br>
X : learned features from the second hidden layer</tt></dd></dl>
<hr>
Methods inherited from <a href="torch.nn.modules.module.html#Module">torch.nn.modules.module.Module</a>:<br>
<dl><dt><a name="MLP-__call__"><strong>__call__</strong></a> = <a href="#MLP-_call_impl">_call_impl</a>(self, *input, **kwargs)</dt></dl>
<dl><dt><a name="MLP-__delattr__"><strong>__delattr__</strong></a>(self, name)</dt><dd><tt>Implement delattr(self, name).</tt></dd></dl>
<dl><dt><a name="MLP-__dir__"><strong>__dir__</strong></a>(self)</dt><dd><tt>Default dir() implementation.</tt></dd></dl>
<dl><dt><a name="MLP-__getattr__"><strong>__getattr__</strong></a>(self, name: str) -> Union[torch.Tensor, ForwardRef('Module')]</dt></dl>
<dl><dt><a name="MLP-__repr__"><strong>__repr__</strong></a>(self)</dt><dd><tt>Return repr(self).</tt></dd></dl>
<dl><dt><a name="MLP-__setattr__"><strong>__setattr__</strong></a>(self, name: str, value: Union[torch.Tensor, ForwardRef('Module')]) -> None</dt><dd><tt>Implement setattr(self, name, value).</tt></dd></dl>
<dl><dt><a name="MLP-__setstate__"><strong>__setstate__</strong></a>(self, state)</dt></dl>
<dl><dt><a name="MLP-add_module"><strong>add_module</strong></a>(self, name: str, module: Union[ForwardRef('Module'), NoneType]) -> None</dt><dd><tt>Adds a child module to the current module.<br>
<br>
The module can be accessed as an attribute using the given name.<br>
<br>
Args:<br>
name (string): name of the child module. The child module can be<br>
accessed from this module using the given name<br>
module (<a href="torch.nn.modules.module.html#Module">Module</a>): child module to be added to the module.</tt></dd></dl>
<dl><dt><a name="MLP-apply"><strong>apply</strong></a>(self: ~T, fn: Callable[[ForwardRef('Module')], NoneType]) -> ~T</dt><dd><tt>Applies ``fn`` recursively to every submodule (as returned by ``.<a href="#MLP-children">children</a>()``)<br>
as well as self. Typical use includes initializing the parameters of a model<br>
(see also :ref:`nn-init-doc`).<br>
<br>
Args:<br>
fn (:class:`<a href="torch.nn.modules.module.html#Module">Module</a>` -> None): function to be applied to each submodule<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self<br>
<br>
Example::<br>
<br>
>>> @torch.no_grad()<br>
>>> def init_weights(m):<br>
>>> print(m)<br>
>>> if <a href="#MLP-type">type</a>(m) == nn.Linear:<br>
>>> m.weight.fill_(1.0)<br>
>>> print(m.weight)<br>
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))<br>
>>> net.<a href="#MLP-apply">apply</a>(init_weights)<br>
Linear(in_features=2, out_features=2, bias=True)<br>
Parameter containing:<br>
tensor([[ 1., 1.],<br>
[ 1., 1.]])<br>
Linear(in_features=2, out_features=2, bias=True)<br>
Parameter containing:<br>
tensor([[ 1., 1.],<br>
[ 1., 1.]])<br>
Sequential(<br>
(0): Linear(in_features=2, out_features=2, bias=True)<br>
(1): Linear(in_features=2, out_features=2, bias=True)<br>
)<br>
Sequential(<br>
(0): Linear(in_features=2, out_features=2, bias=True)<br>
(1): Linear(in_features=2, out_features=2, bias=True)<br>
)</tt></dd></dl>
<dl><dt><a name="MLP-bfloat16"><strong>bfloat16</strong></a>(self: ~T) -> ~T</dt><dd><tt>Casts all floating point parameters and buffers to ``bfloat16`` datatype.<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-buffers"><strong>buffers</strong></a>(self, recurse: bool = True) -> Iterator[torch.Tensor]</dt><dd><tt>Returns an iterator over module buffers.<br>
<br>
Args:<br>
recurse (bool): if True, then yields buffers of this module<br>
and all submodules. Otherwise, yields only buffers that<br>
are direct members of this module.<br>
<br>
Yields:<br>
torch.Tensor: module buffer<br>
<br>
Example::<br>
<br>
>>> for buf in model.<a href="#MLP-buffers">buffers</a>():<br>
>>> print(<a href="#MLP-type">type</a>(buf), buf.size())<br>
<class 'torch.Tensor'> (20L,)<br>
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)</tt></dd></dl>
<dl><dt><a name="MLP-children"><strong>children</strong></a>(self) -> Iterator[ForwardRef('Module')]</dt><dd><tt>Returns an iterator over immediate children modules.<br>
<br>
Yields:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: a child module</tt></dd></dl>
<dl><dt><a name="MLP-cpu"><strong>cpu</strong></a>(self: ~T) -> ~T</dt><dd><tt>Moves all model parameters and buffers to the CPU.<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-cuda"><strong>cuda</strong></a>(self: ~T, device: Union[int, torch.device, NoneType] = None) -> ~T</dt><dd><tt>Moves all model parameters and buffers to the GPU.<br>
<br>
This also makes associated parameters and buffers different objects. So<br>
it should be called before constructing optimizer if the module will<br>
live on GPU while being optimized.<br>
<br>
Arguments:<br>
device (int, optional): if specified, all parameters will be<br>
copied to that device<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-double"><strong>double</strong></a>(self: ~T) -> ~T</dt><dd><tt>Casts all floating point parameters and buffers to ``double`` datatype.<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-eval"><strong>eval</strong></a>(self: ~T) -> ~T</dt><dd><tt>Sets the module in evaluation mode.<br>
<br>
This has any effect only on certain modules. See documentations of<br>
particular modules for details of their behaviors in training/evaluation<br>
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,<br>
etc.<br>
<br>
This is equivalent with :meth:`self.<a href="#MLP-train">train</a>(False) <torch.nn.<a href="torch.nn.modules.module.html#Module">Module</a>.train>`.<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-extra_repr"><strong>extra_repr</strong></a>(self) -> str</dt><dd><tt>Set the extra representation of the module<br>
<br>
To print customized extra information, you should re-implement<br>
this method in your own modules. Both single-line and multi-line<br>
strings are acceptable.</tt></dd></dl>
<dl><dt><a name="MLP-float"><strong>float</strong></a>(self: ~T) -> ~T</dt><dd><tt>Casts all floating point parameters and buffers to float datatype.<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-half"><strong>half</strong></a>(self: ~T) -> ~T</dt><dd><tt>Casts all floating point parameters and buffers to ``half`` datatype.<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-load_state_dict"><strong>load_state_dict</strong></a>(self, state_dict: Dict[str, torch.Tensor], strict: bool = True)</dt><dd><tt>Copies parameters and buffers from :attr:`state_dict` into<br>
this module and its descendants. If :attr:`strict` is ``True``, then<br>
the keys of :attr:`state_dict` must exactly match the keys returned<br>
by this module's :meth:`~torch.nn.<a href="torch.nn.modules.module.html#Module">Module</a>.state_dict` function.<br>
<br>
Arguments:<br>
state_dict (dict): a dict containing parameters and<br>
persistent buffers.<br>
strict (bool, optional): whether to strictly enforce that the keys<br>
in :attr:`state_dict` match the keys returned by this module's<br>
:meth:`~torch.nn.<a href="torch.nn.modules.module.html#Module">Module</a>.state_dict` function. Default: ``True``<br>
<br>
Returns:<br>
``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:<br>
* **missing_keys** is a list of str containing the missing keys<br>
* **unexpected_keys** is a list of str containing the unexpected keys</tt></dd></dl>
<dl><dt><a name="MLP-modules"><strong>modules</strong></a>(self) -> Iterator[ForwardRef('Module')]</dt><dd><tt>Returns an iterator over all modules in the network.<br>
<br>
Yields:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: a module in the network<br>
<br>
Note:<br>
Duplicate modules are returned only once. In the following<br>
example, ``l`` will be returned only once.<br>
<br>
Example::<br>
<br>
>>> l = nn.Linear(2, 2)<br>
>>> net = nn.Sequential(l, l)<br>
>>> for idx, m in enumerate(net.<a href="#MLP-modules">modules</a>()):<br>
print(idx, '->', m)<br>
<br>
0 -> Sequential(<br>
(0): Linear(in_features=2, out_features=2, bias=True)<br>
(1): Linear(in_features=2, out_features=2, bias=True)<br>
)<br>
1 -> Linear(in_features=2, out_features=2, bias=True)</tt></dd></dl>
<dl><dt><a name="MLP-named_buffers"><strong>named_buffers</strong></a>(self, prefix: str = '', recurse: bool = True) -> Iterator[Tuple[str, torch.Tensor]]</dt><dd><tt>Returns an iterator over module buffers, yielding both the<br>
name of the buffer as well as the buffer itself.<br>
<br>
Args:<br>
prefix (str): prefix to prepend to all buffer names.<br>
recurse (bool): if True, then yields buffers of this module<br>
and all submodules. Otherwise, yields only buffers that<br>
are direct members of this module.<br>
<br>
Yields:<br>
(string, torch.Tensor): Tuple containing the name and buffer<br>
<br>
Example::<br>
<br>
>>> for name, buf in self.<a href="#MLP-named_buffers">named_buffers</a>():<br>
>>> if name in ['running_var']:<br>
>>> print(buf.size())</tt></dd></dl>
<dl><dt><a name="MLP-named_children"><strong>named_children</strong></a>(self) -> Iterator[Tuple[str, ForwardRef('Module')]]</dt><dd><tt>Returns an iterator over immediate children modules, yielding both<br>
the name of the module as well as the module itself.<br>
<br>
Yields:<br>
(string, <a href="torch.nn.modules.module.html#Module">Module</a>): Tuple containing a name and child module<br>
<br>
Example::<br>
<br>
>>> for name, module in model.<a href="#MLP-named_children">named_children</a>():<br>
>>> if name in ['conv4', 'conv5']:<br>
>>> print(module)</tt></dd></dl>
<dl><dt><a name="MLP-named_modules"><strong>named_modules</strong></a>(self, memo: Union[Set[ForwardRef('Module')], NoneType] = None, prefix: str = '')</dt><dd><tt>Returns an iterator over all modules in the network, yielding<br>
both the name of the module as well as the module itself.<br>
<br>
Yields:<br>
(string, <a href="torch.nn.modules.module.html#Module">Module</a>): Tuple of name and module<br>
<br>
Note:<br>
Duplicate modules are returned only once. In the following<br>
example, ``l`` will be returned only once.<br>
<br>
Example::<br>
<br>
>>> l = nn.Linear(2, 2)<br>
>>> net = nn.Sequential(l, l)<br>
>>> for idx, m in enumerate(net.<a href="#MLP-named_modules">named_modules</a>()):<br>
print(idx, '->', m)<br>
<br>
0 -> ('', Sequential(<br>
(0): Linear(in_features=2, out_features=2, bias=True)<br>
(1): Linear(in_features=2, out_features=2, bias=True)<br>
))<br>
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))</tt></dd></dl>
<dl><dt><a name="MLP-named_parameters"><strong>named_parameters</strong></a>(self, prefix: str = '', recurse: bool = True) -> Iterator[Tuple[str, torch.Tensor]]</dt><dd><tt>Returns an iterator over module parameters, yielding both the<br>
name of the parameter as well as the parameter itself.<br>
<br>
Args:<br>
prefix (str): prefix to prepend to all parameter names.<br>
recurse (bool): if True, then yields parameters of this module<br>
and all submodules. Otherwise, yields only parameters that<br>
are direct members of this module.<br>
<br>
Yields:<br>
(string, Parameter): Tuple containing the name and parameter<br>
<br>
Example::<br>
<br>
>>> for name, param in self.<a href="#MLP-named_parameters">named_parameters</a>():<br>
>>> if name in ['bias']:<br>
>>> print(param.size())</tt></dd></dl>
<dl><dt><a name="MLP-parameters"><strong>parameters</strong></a>(self, recurse: bool = True) -> Iterator[torch.nn.parameter.Parameter]</dt><dd><tt>Returns an iterator over module parameters.<br>
<br>
This is typically passed to an optimizer.<br>
<br>
Args:<br>
recurse (bool): if True, then yields parameters of this module<br>
and all submodules. Otherwise, yields only parameters that<br>
are direct members of this module.<br>
<br>
Yields:<br>
Parameter: module parameter<br>
<br>
Example::<br>
<br>
>>> for param in model.<a href="#MLP-parameters">parameters</a>():<br>
>>> print(<a href="#MLP-type">type</a>(param), param.size())<br>
<class 'torch.Tensor'> (20L,)<br>
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)</tt></dd></dl>
<dl><dt><a name="MLP-register_backward_hook"><strong>register_backward_hook</strong></a>(self, hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, torch.Tensor]]) -> torch.utils.hooks.RemovableHandle</dt><dd><tt>Registers a backward hook on the module.<br>
<br>
.. warning ::<br>
<br>
The current implementation will not have the presented behavior<br>
for complex :class:`<a href="torch.nn.modules.module.html#Module">Module</a>` that perform many operations.<br>
In some failure cases, :attr:`grad_input` and :attr:`grad_output` will only<br>
contain the gradients for a subset of the inputs and outputs.<br>
For such :class:`<a href="torch.nn.modules.module.html#Module">Module</a>`, you should use :func:`torch.Tensor.register_hook`<br>
directly on a specific input or output to get the required gradients.<br>
<br>
The hook will be called every time the gradients with respect to module<br>
inputs are computed. The hook should have the following signature::<br>
<br>
hook(module, grad_input, grad_output) -> Tensor or None<br>
<br>
The :attr:`grad_input` and :attr:`grad_output` may be tuples if the<br>
module has multiple inputs or outputs. The hook should not modify its<br>
arguments, but it can optionally return a new gradient with respect to<br>
input that will be used in place of :attr:`grad_input` in subsequent<br>
computations. :attr:`grad_input` will only correspond to the inputs given<br>
as positional arguments.<br>
<br>
Returns:<br>
:class:`torch.utils.hooks.RemovableHandle`:<br>
a handle that can be used to remove the added hook by calling<br>
``handle.remove()``</tt></dd></dl>
<dl><dt><a name="MLP-register_buffer"><strong>register_buffer</strong></a>(self, name: str, tensor: Union[torch.Tensor, NoneType], persistent: bool = True) -> None</dt><dd><tt>Adds a buffer to the module.<br>
<br>
This is typically used to register a buffer that should not to be<br>
considered a model parameter. For example, BatchNorm's ``running_mean``<br>
is not a parameter, but is part of the module's state. Buffers, by<br>
default, are persistent and will be saved alongside parameters. This<br>
behavior can be changed by setting :attr:`persistent` to ``False``. The<br>
only difference between a persistent buffer and a non-persistent buffer<br>
is that the latter will not be a part of this module's<br>
:attr:`state_dict`.<br>
<br>
Buffers can be accessed as attributes using given names.<br>
<br>
Args:<br>
name (string): name of the buffer. The buffer can be accessed<br>
from this module using the given name<br>
tensor (Tensor): buffer to be registered.<br>
persistent (bool): whether the buffer is part of this module's<br>
:attr:`state_dict`.<br>
<br>
Example::<br>
<br>
>>> self.<a href="#MLP-register_buffer">register_buffer</a>('running_mean', torch.zeros(num_features))</tt></dd></dl>
<dl><dt><a name="MLP-register_forward_hook"><strong>register_forward_hook</strong></a>(self, hook: Callable[..., NoneType]) -> torch.utils.hooks.RemovableHandle</dt><dd><tt>Registers a forward hook on the module.<br>
<br>
The hook will be called every time after :func:`forward` has computed an output.<br>
It should have the following signature::<br>
<br>
hook(module, input, output) -> None or modified output<br>
<br>
The input contains only the positional arguments given to the module.<br>
Keyword arguments won't be passed to the hooks and only to the ``forward``.<br>
The hook can modify the output. It can modify the input inplace but<br>
it will not have effect on forward since this is called after<br>
:func:`forward` is called.<br>
<br>
Returns:<br>
:class:`torch.utils.hooks.RemovableHandle`:<br>
a handle that can be used to remove the added hook by calling<br>
``handle.remove()``</tt></dd></dl>
<dl><dt><a name="MLP-register_forward_pre_hook"><strong>register_forward_pre_hook</strong></a>(self, hook: Callable[..., NoneType]) -> torch.utils.hooks.RemovableHandle</dt><dd><tt>Registers a forward pre-hook on the module.<br>
<br>
The hook will be called every time before :func:`forward` is invoked.<br>
It should have the following signature::<br>
<br>
hook(module, input) -> None or modified input<br>
<br>
The input contains only the positional arguments given to the module.<br>
Keyword arguments won't be passed to the hooks and only to the ``forward``.<br>
The hook can modify the input. User can either return a tuple or a<br>
single modified value in the hook. We will wrap the value into a tuple<br>
if a single value is returned(unless that value is already a tuple).<br>
<br>
Returns:<br>
:class:`torch.utils.hooks.RemovableHandle`:<br>
a handle that can be used to remove the added hook by calling<br>
``handle.remove()``</tt></dd></dl>
<dl><dt><a name="MLP-register_parameter"><strong>register_parameter</strong></a>(self, name: str, param: Union[torch.nn.parameter.Parameter, NoneType]) -> None</dt><dd><tt>Adds a parameter to the module.<br>
<br>
The parameter can be accessed as an attribute using given name.<br>
<br>
Args:<br>
name (string): name of the parameter. The parameter can be accessed<br>
from this module using the given name<br>
param (Parameter): parameter to be added to the module.</tt></dd></dl>
<dl><dt><a name="MLP-requires_grad_"><strong>requires_grad_</strong></a>(self: ~T, requires_grad: bool = True) -> ~T</dt><dd><tt>Change if autograd should record operations on parameters in this<br>
module.<br>
<br>
This method sets the parameters' :attr:`requires_grad` attributes<br>
in-place.<br>
<br>
This method is helpful for freezing part of the module for finetuning<br>
or training parts of a model individually (e.g., GAN training).<br>
<br>
Args:<br>
requires_grad (bool): whether autograd should record operations on<br>
parameters in this module. Default: ``True``.<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-share_memory"><strong>share_memory</strong></a>(self: ~T) -> ~T</dt></dl>
<dl><dt><a name="MLP-state_dict"><strong>state_dict</strong></a>(self, destination=None, prefix='', keep_vars=False)</dt><dd><tt>Returns a dictionary containing a whole state of the module.<br>
<br>
Both parameters and persistent buffers (e.g. running averages) are<br>
included. Keys are corresponding parameter and buffer names.<br>
<br>
Returns:<br>
dict:<br>
a dictionary containing a whole state of the module<br>
<br>
Example::<br>
<br>
>>> module.<a href="#MLP-state_dict">state_dict</a>().keys()<br>
['bias', 'weight']</tt></dd></dl>
<dl><dt><a name="MLP-to"><strong>to</strong></a>(self, *args, **kwargs)</dt><dd><tt>Moves and/or casts the parameters and buffers.<br>
<br>
This can be called as<br>
<br>
.. function:: <a href="#MLP-to">to</a>(device=None, dtype=None, non_blocking=False)<br>
<br>
.. function:: <a href="#MLP-to">to</a>(dtype, non_blocking=False)<br>
<br>
.. function:: <a href="#MLP-to">to</a>(tensor, non_blocking=False)<br>
<br>
.. function:: <a href="#MLP-to">to</a>(memory_format=torch.channels_last)<br>
<br>
Its signature is similar to :meth:`torch.Tensor.to`, but only accepts<br>
floating point desired :attr:`dtype` s. In addition, this method will<br>
only cast the floating point parameters and buffers to :attr:`dtype`<br>
(if given). The integral parameters and buffers will be moved<br>
:attr:`device`, if that is given, but with dtypes unchanged. When<br>
:attr:`non_blocking` is set, it tries to convert/move asynchronously<br>
with respect to the host if possible, e.g., moving CPU Tensors with<br>
pinned memory to CUDA devices.<br>
<br>
See below for examples.<br>
<br>
.. note::<br>
This method modifies the module in-place.<br>
<br>
Args:<br>
device (:class:`torch.device`): the desired device of the parameters<br>
and buffers in this module<br>
dtype (:class:`torch.dtype`): the desired floating point type of<br>
the floating point parameters and buffers in this module<br>
tensor (torch.Tensor): Tensor whose dtype and device are the desired<br>
dtype and device for all parameters and buffers in this module<br>
memory_format (:class:`torch.memory_format`): the desired memory<br>
format for 4D parameters and buffers in this module (keyword<br>
only argument)<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self<br>
<br>
Example::<br>
<br>
>>> linear = nn.Linear(2, 2)<br>
>>> linear.weight<br>
Parameter containing:<br>
tensor([[ 0.1913, -0.3420],<br>
[-0.5113, -0.2325]])<br>
>>> linear.<a href="#MLP-to">to</a>(torch.double)<br>
Linear(in_features=2, out_features=2, bias=True)<br>
>>> linear.weight<br>
Parameter containing:<br>
tensor([[ 0.1913, -0.3420],<br>
[-0.5113, -0.2325]], dtype=torch.float64)<br>
>>> gpu1 = torch.device("cuda:1")<br>
>>> linear.<a href="#MLP-to">to</a>(gpu1, dtype=torch.half, non_blocking=True)<br>
Linear(in_features=2, out_features=2, bias=True)<br>
>>> linear.weight<br>
Parameter containing:<br>
tensor([[ 0.1914, -0.3420],<br>
[-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')<br>
>>> cpu = torch.device("cpu")<br>
>>> linear.<a href="#MLP-to">to</a>(cpu)<br>
Linear(in_features=2, out_features=2, bias=True)<br>
>>> linear.weight<br>
Parameter containing:<br>
tensor([[ 0.1914, -0.3420],<br>
[-0.5112, -0.2324]], dtype=torch.float16)</tt></dd></dl>
<dl><dt><a name="MLP-train"><strong>train</strong></a>(self: ~T, mode: bool = True) -> ~T</dt><dd><tt>Sets the module in training mode.<br>
<br>
This has any effect only on certain modules. See documentations of<br>
particular modules for details of their behaviors in training/evaluation<br>
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,<br>
etc.<br>
<br>
Args:<br>
mode (bool): whether to set training mode (``True``) or evaluation<br>
mode (``False``). Default: ``True``.<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-type"><strong>type</strong></a>(self: ~T, dst_type: Union[torch.dtype, str]) -> ~T</dt><dd><tt>Casts all parameters and buffers to :attr:`dst_type`.<br>
<br>
Arguments:<br>
dst_type (type or string): the desired type<br>
<br>
Returns:<br>
<a href="torch.nn.modules.module.html#Module">Module</a>: self</tt></dd></dl>
<dl><dt><a name="MLP-zero_grad"><strong>zero_grad</strong></a>(self, set_to_none: bool = False) -> None</dt><dd><tt>Sets gradients of all model parameters to zero. See similar function<br>
under :class:`torch.optim.Optimizer` for more context.<br>
<br>
Arguments:<br>
set_to_none (bool): instead of setting to zero, set the grads to None.<br>
See :meth:`torch.optim.Optimizer.zero_grad` for details.</tt></dd></dl>
<hr>
Data descriptors inherited from <a href="torch.nn.modules.module.html#Module">torch.nn.modules.module.Module</a>:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
<hr>
Data and other attributes inherited from <a href="torch.nn.modules.module.html#Module">torch.nn.modules.module.Module</a>:<br>
<dl><dt><strong>T_destination</strong> = ~T_destination</dl>
<dl><dt><strong>__annotations__</strong> = {'__call__': typing.Callable[..., typing.Any], '_version': <class 'int'>, 'dump_patches': <class 'bool'>, 'forward': typing.Callable[..., typing.Any], 'training': <class 'bool'>}</dl>
<dl><dt><strong>dump_patches</strong> = False</dl>
</td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#eeaa77">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
<tr><td bgcolor="#eeaa77"><tt> </tt></td><td> </td>
<td width="100%"><dl><dt><a name="-evaluate_model"><strong>evaluate_model</strong></a>(test_dl, model)</dt><dd><tt>After we have trained our model, we are calculating the accuracy of<br>
trained model on the test dataset - percentage of samples that are<br>
classified correctly.<br>
<br>
Parameters<br>
----------<br>
test_dl : test dataset<br>
model : object of <a href="#MLP">MLP</a> class<br>
<br>
Returns<br>
-------<br>
acc : model accuracy on test dataset</tt></dd></dl>
<dl><dt><a name="-get_last_layer"><strong>get_last_layer</strong></a>(data, model)</dt><dd><tt>For implementing the second pipeline, we are using logistic regression<br>
as helper classifier. We are extracting activations from the last hidden<br>
layer and feed them into the helper classifier to predict the original<br>
task. This function returns the activations from the last hidden layer.<br>
We keep track on the inputs for which we extract activations, along with<br>
the target(original) labels.<br>
<br>
Parameters<br>
----------<br>
data : training dataset<br>
model : object of <a href="#MLP">MLP</a> class<br>
<br>
Returns<br>
-------<br>
xinputs : activations from the last hidden layer<br>
oinputs : inputs in the order in which we calculate activations<br>
true : original (true) target values</tt></dd></dl>
<dl><dt><a name="-get_soft_labels"><strong>get_soft_labels</strong></a>(data, model)</dt><dd><tt>For implementing the first pipeline, we are using predicted soft labels<br>
for GBT training. This function returns predicted soft labels, along<br>
with inputs, we keep track on the inputs for which we make predictions,<br>
along with the target(original) labels.<br>
Parameters<br>
----------<br>
data : training dataset<br>
model : object of <a href="#MLP">MLP</a> class<br>
Returns<br>
-------<br>
xinputs : inputs in the order in which we calculate predictions<br>
predictions : soft labels, without rounding<br>
true : original (true) target values</tt></dd></dl>
<dl><dt><a name="-train_model"><strong>train_model</strong></a>(train_dl, test_dl, model)</dt><dd><tt>For training of defined <a href="#MLP">MLP</a> model, we have to define loss function<br>
and optimization algorithm that will be used. Binary cross entropy<br>
loss is used as loss function. Stochastic gradient descent is used<br>
for optimization. SGD class provides standard algorithm. In the outer<br>
loop, we are defining the number of training epochs. In each epoch,<br>
the inner loop is required for enumerating the mini batches for SGD.<br>
Each update of the model consists of the following steps: clear the<br>
gradients, feed the inputs to the network, calculate loss, backpropagate<br>
the error through the network, update model weights.Additionaly, this<br>
function plots training and validation learning curves.<br>
<br>
Parameters<br>
----------<br>
train_dl : training dataset<br>
test_dl : test dataset<br>
model : object of <a href="#MLP">MLP</a> class<br>
<br>
Returns<br>
-------<br>
None.</tt></dd></dl>
</td></tr></table>
</body></html>