braintools 0.0.2__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. braintools/__init__.py +27 -0
  2. braintools/functional/__init__.py +25 -0
  3. braintools/functional/_activations.py +733 -0
  4. braintools/functional/_normalization.py +62 -0
  5. braintools/functional/_spikes.py +90 -0
  6. braintools/init/__init__.py +26 -0
  7. braintools/init/_base.py +36 -0
  8. braintools/init/_generic.py +205 -0
  9. braintools/init/_random_inits.py +489 -0
  10. braintools/init/_regular_inits.py +109 -0
  11. braintools/input/__init__.py +27 -0
  12. braintools/input/currents.py +380 -0
  13. braintools/input/currents_test.py +111 -0
  14. braintools/metric/__init__.py +46 -0
  15. braintools/metric/_classification.py +569 -0
  16. braintools/metric/_classification_test.py +625 -0
  17. braintools/metric/_correlation.py +302 -0
  18. braintools/metric/_correlation_test.py +124 -0
  19. braintools/metric/_fenchel_young.py +67 -0
  20. braintools/metric/_fenchel_young_test.py +55 -0
  21. braintools/metric/_firings.py +85 -0
  22. braintools/metric/_firings_test.py +41 -0
  23. braintools/metric/_lfp.py +139 -0
  24. braintools/metric/_ranking.py +163 -0
  25. braintools/metric/_ranking_test.py +242 -0
  26. braintools/metric/_regression.py +425 -0
  27. braintools/metric/_regression_test.py +133 -0
  28. braintools/metric/_smoothing.py +46 -0
  29. braintools/metric/_smoothing_test.py +43 -0
  30. braintools/metric/_util.py +25 -0
  31. braintools/optim/__init__.py +23 -0
  32. braintools/optim/_lr_scheduler.py +482 -0
  33. braintools/optim/_sgd_optimizer.py +1130 -0
  34. braintools-0.0.2.dist-info/LICENSE +202 -0
  35. braintools-0.0.2.dist-info/METADATA +93 -0
  36. braintools-0.0.2.dist-info/RECORD +38 -0
  37. braintools-0.0.2.dist-info/WHEEL +6 -0
  38. braintools-0.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,733 @@
1
+ # Copyright 2024- BrainPy Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+
17
+ """Shared neural network activations and other functions."""
18
+
19
+
20
+ from __future__ import annotations
21
+ from typing import Any, Union, Sequence
22
+
23
+ import jax
24
+ import jax.numpy as jnp
25
+ from jax.scipy.special import logsumexp
26
+ from jax.typing import ArrayLike
27
+ import braincore as bc
28
+
29
+ __all__ = [
30
+ "relu",
31
+ "squareplus",
32
+ "softplus",
33
+ "soft_sign",
34
+ "sigmoid",
35
+ "silu",
36
+ "swish",
37
+ "log_sigmoid",
38
+ "elu",
39
+ "leaky_relu",
40
+ "hard_tanh",
41
+ "celu",
42
+ "selu",
43
+ "gelu",
44
+ "glu",
45
+ "logsumexp",
46
+ "log_softmax",
47
+ "softmax",
48
+ "standardize",
49
+ "one_hot",
50
+ "relu6",
51
+ "hard_sigmoid",
52
+ "hard_silu",
53
+ "hard_swish",
54
+ 'hard_shrink',
55
+ 'rrelu',
56
+ 'mish',
57
+ 'soft_shrink',
58
+ 'prelu',
59
+ 'tanh_shrink',
60
+ 'softmin',
61
+ ]
62
+
63
+
64
+ def softmin(x, axis=-1):
65
+ r"""
66
+ Applies the Softmin function to an n-dimensional input Tensor
67
+ rescaling them so that the elements of the n-dimensional output Tensor
68
+ lie in the range `[0, 1]` and sum to 1.
69
+
70
+ Softmin is defined as:
71
+
72
+ .. math::
73
+ \text{Softmin}(x_{i}) = \frac{\exp(-x_i)}{\sum_j \exp(-x_j)}
74
+
75
+ Shape:
76
+ - Input: :math:`(*)` where `*` means, any number of additional
77
+ dimensions
78
+ - Output: :math:`(*)`, same shape as the input
79
+
80
+ Args:
81
+ axis (int): A dimension along which Softmin will be computed (so every slice
82
+ along dim will sum to 1).
83
+ """
84
+ unnormalized = jnp.exp(-x)
85
+ return unnormalized / unnormalized.sum(axis, keepdims=True)
86
+
87
+
88
+ def tanh_shrink(x):
89
+ r"""
90
+ Applies the element-wise function:
91
+
92
+ .. math::
93
+ \text{Tanhshrink}(x) = x - \tanh(x)
94
+ """
95
+ return x - jnp.tanh(x)
96
+
97
+
98
+ def prelu(x, a=0.25):
99
+ r"""
100
+ Applies the element-wise function:
101
+
102
+ .. math::
103
+ \text{PReLU}(x) = \max(0,x) + a * \min(0,x)
104
+
105
+ or
106
+
107
+ .. math::
108
+ \text{PReLU}(x) =
109
+ \begin{cases}
110
+ x, & \text{ if } x \geq 0 \\
111
+ ax, & \text{ otherwise }
112
+ \end{cases}
113
+
114
+ Here :math:`a` is a learnable parameter. When called without arguments, `nn.PReLU()` uses a single
115
+ parameter :math:`a` across all input channels. If called with `nn.PReLU(nChannels)`,
116
+ a separate :math:`a` is used for each input channel.
117
+ """
118
+ dtype = bc.math.get_dtype(x)
119
+ return jnp.where(x >= jnp.asarray(0., dtype),
120
+ x,
121
+ jnp.asarray(a, dtype) * x)
122
+
123
+
124
+ def soft_shrink(x, lambd=0.5):
125
+ r"""
126
+ Applies the soft shrinkage function elementwise:
127
+
128
+ .. math::
129
+ \text{SoftShrinkage}(x) =
130
+ \begin{cases}
131
+ x - \lambda, & \text{ if } x > \lambda \\
132
+ x + \lambda, & \text{ if } x < -\lambda \\
133
+ 0, & \text{ otherwise }
134
+ \end{cases}
135
+
136
+ Args:
137
+ lambd: the :math:`\lambda` (must be no less than zero) value for the Softshrink formulation. Default: 0.5
138
+
139
+ Shape:
140
+ - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
141
+ - Output: :math:`(*)`, same shape as the input.
142
+ """
143
+ dtype = bc.math.get_dtype(x)
144
+ lambd = jnp.asarray(lambd, dtype)
145
+ return jnp.where(x > lambd,
146
+ x - lambd,
147
+ jnp.where(x < -lambd, x + lambd, jnp.asarray(0., dtype)))
148
+
149
+
150
+ def mish(x):
151
+ r"""Applies the Mish function, element-wise.
152
+
153
+ Mish: A Self Regularized Non-Monotonic Neural Activation Function.
154
+
155
+ .. math::
156
+ \text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))
157
+
158
+ .. note::
159
+ See `Mish: A Self Regularized Non-Monotonic Neural Activation Function <https://arxiv.org/abs/1908.08681>`_
160
+
161
+ Shape:
162
+ - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
163
+ - Output: :math:`(*)`, same shape as the input.
164
+ """
165
+ return x * jnp.tanh(softplus(x))
166
+
167
+
168
+ def rrelu(x, lower=0.125, upper=0.3333333333333333):
169
+ r"""Applies the randomized leaky rectified liner unit function, element-wise,
170
+ as described in the paper:
171
+
172
+ `Empirical Evaluation of Rectified Activations in Convolutional Network`_.
173
+
174
+ The function is defined as:
175
+
176
+ .. math::
177
+ \text{RReLU}(x) =
178
+ \begin{cases}
179
+ x & \text{if } x \geq 0 \\
180
+ ax & \text{ otherwise }
181
+ \end{cases}
182
+
183
+ where :math:`a` is randomly sampled from uniform distribution
184
+ :math:`\mathcal{U}(\text{lower}, \text{upper})`.
185
+
186
+ See: https://arxiv.org/pdf/1505.00853.pdf
187
+
188
+ Args:
189
+ lower: lower bound of the uniform distribution. Default: :math:`\frac{1}{8}`
190
+ upper: upper bound of the uniform distribution. Default: :math:`\frac{1}{3}`
191
+
192
+ Shape:
193
+ - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
194
+ - Output: :math:`(*)`, same shape as the input.
195
+
196
+ .. _`Empirical Evaluation of Rectified Activations in Convolutional Network`:
197
+ https://arxiv.org/abs/1505.00853
198
+ """
199
+ dtype = bc.math.get_dtype(x)
200
+ a = bc.random.uniform(lower, upper, size=jnp.shape(x), dtype=dtype)
201
+ return jnp.where(x >= jnp.asarray(0., dtype), x, jnp.asarray(a, dtype) * x)
202
+
203
+
204
+ def hard_shrink(x, lambd=0.5):
205
+ r"""Applies the Hard Shrinkage (Hardshrink) function element-wise.
206
+
207
+ Hardshrink is defined as:
208
+
209
+ .. math::
210
+ \text{HardShrink}(x) =
211
+ \begin{cases}
212
+ x, & \text{ if } x > \lambda \\
213
+ x, & \text{ if } x < -\lambda \\
214
+ 0, & \text{ otherwise }
215
+ \end{cases}
216
+
217
+ Args:
218
+ lambd: the :math:`\lambda` value for the Hardshrink formulation. Default: 0.5
219
+
220
+ Shape:
221
+ - Input: :math:`(*)`, where :math:`*` means any number of dimensions.
222
+ - Output: :math:`(*)`, same shape as the input.
223
+
224
+ """
225
+ dtype = bc.math.get_dtype(x)
226
+ lambd = jnp.asarray(lambd, dtype)
227
+ return jnp.where(x > lambd,
228
+ x,
229
+ jnp.where(x < -lambd, x, jnp.asarray(0., dtype)))
230
+
231
+
232
+ def relu(x: ArrayLike) -> jax.Array:
233
+ r"""Rectified linear unit activation function.
234
+
235
+ Computes the element-wise function:
236
+
237
+ .. math::
238
+ \mathrm{relu}(x) = \max(x, 0)
239
+
240
+ except under differentiation, we take:
241
+
242
+ .. math::
243
+ \nabla \mathrm{relu}(0) = 0
244
+
245
+ For more information see
246
+ `Numerical influence of ReLU’(0) on backpropagation
247
+ <https://openreview.net/forum?id=urrcVI-_jRm>`_.
248
+
249
+ Args:
250
+ x : input array
251
+
252
+ Returns:
253
+ An array.
254
+
255
+ Example:
256
+ >>> jax.nn.relu(jax.numpy.array([-2., -1., -0.5, 0, 0.5, 1., 2.]))
257
+ Array([0. , 0. , 0. , 0. , 0.5, 1. , 2. ], dtype=float32)
258
+
259
+ See also:
260
+ :func:`relu6`
261
+
262
+ """
263
+ return jax.nn.relu(x)
264
+
265
+
266
+ def squareplus(x: ArrayLike, b: ArrayLike = 4) -> jax.Array:
267
+ r"""Squareplus activation function.
268
+
269
+ Computes the element-wise function
270
+
271
+ .. math::
272
+ \mathrm{squareplus}(x) = \frac{x + \sqrt{x^2 + b}}{2}
273
+
274
+ as described in https://arxiv.org/abs/2112.11687.
275
+
276
+ Args:
277
+ x : input array
278
+ b : smoothness parameter
279
+ """
280
+ dtype = bc.math.get_dtype(x)
281
+ return jax.nn.squareplus(x, jnp.asarray(b, dtype))
282
+
283
+
284
+ def softplus(x: ArrayLike) -> jax.Array:
285
+ r"""Softplus activation function.
286
+
287
+ Computes the element-wise function
288
+
289
+ .. math::
290
+ \mathrm{softplus}(x) = \log(1 + e^x)
291
+
292
+ Args:
293
+ x : input array
294
+ """
295
+ return jax.nn.softplus(x)
296
+
297
+
298
+ def soft_sign(x: ArrayLike) -> jax.Array:
299
+ r"""Soft-sign activation function.
300
+
301
+ Computes the element-wise function
302
+
303
+ .. math::
304
+ \mathrm{soft\_sign}(x) = \frac{x}{|x| + 1}
305
+
306
+ Args:
307
+ x : input array
308
+ """
309
+ return jax.nn.soft_sign(x)
310
+
311
+
312
+ def sigmoid(x: ArrayLike) -> jax.Array:
313
+ r"""Sigmoid activation function.
314
+
315
+ Computes the element-wise function:
316
+
317
+ .. math::
318
+ \mathrm{sigmoid}(x) = \frac{1}{1 + e^{-x}}
319
+
320
+ Args:
321
+ x : input array
322
+
323
+ Returns:
324
+ An array.
325
+
326
+ See also:
327
+ :func:`log_sigmoid`
328
+
329
+ """
330
+ return jax.nn.sigmoid(x)
331
+
332
+
333
+ def silu(x: ArrayLike) -> jax.Array:
334
+ r"""SiLU (a.k.a. swish) activation function.
335
+
336
+ Computes the element-wise function:
337
+
338
+ .. math::
339
+ \mathrm{silu}(x) = x \cdot \mathrm{sigmoid}(x) = \frac{x}{1 + e^{-x}}
340
+
341
+ :func:`swish` and :func:`silu` are both aliases for the same function.
342
+
343
+ Args:
344
+ x : input array
345
+
346
+ Returns:
347
+ An array.
348
+
349
+ See also:
350
+ :func:`sigmoid`
351
+ """
352
+ return jax.nn.silu(x)
353
+
354
+
355
+ swish = silu
356
+
357
+
358
+ def log_sigmoid(x: ArrayLike) -> jax.Array:
359
+ r"""Log-sigmoid activation function.
360
+
361
+ Computes the element-wise function:
362
+
363
+ .. math::
364
+ \mathrm{log\_sigmoid}(x) = \log(\mathrm{sigmoid}(x)) = -\log(1 + e^{-x})
365
+
366
+ Args:
367
+ x : input array
368
+
369
+ Returns:
370
+ An array.
371
+
372
+ See also:
373
+ :func:`sigmoid`
374
+ """
375
+ return jax.nn.log_sigmoid(x)
376
+
377
+
378
+ def elu(x: ArrayLike, alpha: ArrayLike = 1.0) -> jax.Array:
379
+ r"""Exponential linear unit activation function.
380
+
381
+ Computes the element-wise function:
382
+
383
+ .. math::
384
+ \mathrm{elu}(x) = \begin{cases}
385
+ x, & x > 0\\
386
+ \alpha \left(\exp(x) - 1\right), & x \le 0
387
+ \end{cases}
388
+
389
+ Args:
390
+ x : input array
391
+ alpha : scalar or array of alpha values (default: 1.0)
392
+
393
+ Returns:
394
+ An array.
395
+
396
+ See also:
397
+ :func:`selu`
398
+ """
399
+ dtype = bc.math.get_dtype(x)
400
+ alpha = jnp.asarray(alpha, dtype)
401
+ return jax.nn.elu(x, alpha)
402
+
403
+
404
+ def leaky_relu(x: ArrayLike, negative_slope: ArrayLike = 1e-2) -> jax.Array:
405
+ r"""Leaky rectified linear unit activation function.
406
+
407
+ Computes the element-wise function:
408
+
409
+ .. math::
410
+ \mathrm{leaky\_relu}(x) = \begin{cases}
411
+ x, & x \ge 0\\
412
+ \alpha x, & x < 0
413
+ \end{cases}
414
+
415
+ where :math:`\alpha` = :code:`negative_slope`.
416
+
417
+ Args:
418
+ x : input array
419
+ negative_slope : array or scalar specifying the negative slope (default: 0.01)
420
+
421
+ Returns:
422
+ An array.
423
+
424
+ See also:
425
+ :func:`relu`
426
+ """
427
+ dtype = bc.math.get_dtype(x)
428
+ negative_slope = jnp.asarray(negative_slope, dtype)
429
+ return jax.nn.leaky_relu(x, negative_slope=negative_slope)
430
+
431
+
432
+ def hard_tanh(x: ArrayLike) -> jax.Array:
433
+ r"""Hard :math:`\mathrm{tanh}` activation function.
434
+
435
+ Computes the element-wise function:
436
+
437
+ .. math::
438
+ \mathrm{hard\_tanh}(x) = \begin{cases}
439
+ -1, & x < -1\\
440
+ x, & -1 \le x \le 1\\
441
+ 1, & 1 < x
442
+ \end{cases}
443
+
444
+ Args:
445
+ x : input array
446
+
447
+ Returns:
448
+ An array.
449
+ """
450
+ return jax.nn.hard_tanh(x)
451
+
452
+
453
+ def celu(x: ArrayLike, alpha: ArrayLike = 1.0) -> jax.Array:
454
+ r"""Continuously-differentiable exponential linear unit activation.
455
+
456
+ Computes the element-wise function:
457
+
458
+ .. math::
459
+ \mathrm{celu}(x) = \begin{cases}
460
+ x, & x > 0\\
461
+ \alpha \left(\exp(\frac{x}{\alpha}) - 1\right), & x \le 0
462
+ \end{cases}
463
+
464
+ For more information, see
465
+ `Continuously Differentiable Exponential Linear Units
466
+ <https://arxiv.org/pdf/1704.07483.pdf>`_.
467
+
468
+ Args:
469
+ x : input array
470
+ alpha : array or scalar (default: 1.0)
471
+
472
+ Returns:
473
+ An array.
474
+ """
475
+ dtype = bc.math.get_dtype(x)
476
+ alpha = jnp.asarray(alpha, dtype)
477
+ return jax.nn.celu(x, alpha)
478
+
479
+
480
+ def selu(x: ArrayLike) -> jax.Array:
481
+ r"""Scaled exponential linear unit activation.
482
+
483
+ Computes the element-wise function:
484
+
485
+ .. math::
486
+ \mathrm{selu}(x) = \lambda \begin{cases}
487
+ x, & x > 0\\
488
+ \alpha e^x - \alpha, & x \le 0
489
+ \end{cases}
490
+
491
+ where :math:`\lambda = 1.0507009873554804934193349852946` and
492
+ :math:`\alpha = 1.6732632423543772848170429916717`.
493
+
494
+ For more information, see
495
+ `Self-Normalizing Neural Networks
496
+ <https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf>`_.
497
+
498
+ Args:
499
+ x : input array
500
+
501
+ Returns:
502
+ An array.
503
+
504
+ See also:
505
+ :func:`elu`
506
+ """
507
+ return jax.nn.selu(x)
508
+
509
+
510
+ def gelu(x: ArrayLike, approximate: bool = True) -> jax.Array:
511
+ r"""Gaussian error linear unit activation function.
512
+
513
+ If ``approximate=False``, computes the element-wise function:
514
+
515
+ .. math::
516
+ \mathrm{gelu}(x) = \frac{x}{2} \left(1 + \mathrm{erf} \left(
517
+ \frac{x}{\sqrt{2}} \right) \right)
518
+
519
+ If ``approximate=True``, uses the approximate formulation of GELU:
520
+
521
+ .. math::
522
+ \mathrm{gelu}(x) = \frac{x}{2} \left(1 + \mathrm{tanh} \left(
523
+ \sqrt{\frac{2}{\pi}} \left(x + 0.044715 x^3 \right) \right) \right)
524
+
525
+ For more information, see `Gaussian Error Linear Units (GELUs)
526
+ <https://arxiv.org/abs/1606.08415>`_, section 2.
527
+
528
+ Args:
529
+ x : input array
530
+ approximate: whether to use the approximate or exact formulation.
531
+ """
532
+ return jax.nn.gelu(x, approximate=approximate)
533
+
534
+
535
+ def glu(x: ArrayLike, axis: int = -1) -> jax.Array:
536
+ r"""Gated linear unit activation function.
537
+
538
+ Computes the function:
539
+
540
+ .. math::
541
+ \mathrm{glu}(x) = x\left[\ldots, 0:\frac{n}{2}, \ldots\right] \cdot
542
+ \mathrm{sigmoid} \left( x\left[\ldots, \frac{n}{2}:n, \ldots\right]
543
+ \right)
544
+
545
+ where the array is split into two along ``axis``. The size of the ``axis``
546
+ dimension must be divisible by two.
547
+
548
+ Args:
549
+ x : input array
550
+ axis: the axis along which the split should be computed (default: -1)
551
+
552
+ Returns:
553
+ An array.
554
+
555
+ See also:
556
+ :func:`sigmoid`
557
+ """
558
+ return jax.nn.glu(x, axis=axis)
559
+
560
+
561
+ def log_softmax(x: ArrayLike,
562
+ axis: int | tuple[int, ...] | None = -1,
563
+ where: ArrayLike | None = None,
564
+ initial: ArrayLike | None = None) -> jax.Array:
565
+ r"""Log-Softmax function.
566
+
567
+ Computes the logarithm of the :code:`softmax` function, which rescales
568
+ elements to the range :math:`[-\infty, 0)`.
569
+
570
+ .. math ::
571
+ \mathrm{log\_softmax}(x)_i = \log \left( \frac{\exp(x_i)}{\sum_j \exp(x_j)}
572
+ \right)
573
+
574
+ Args:
575
+ x : input array
576
+ axis: the axis or axes along which the :code:`log_softmax` should be
577
+ computed. Either an integer or a tuple of integers.
578
+ where: Elements to include in the :code:`log_softmax`.
579
+ initial: The minimum value used to shift the input array. Must be present
580
+ when :code:`where` is not None.
581
+
582
+ Returns:
583
+ An array.
584
+
585
+ See also:
586
+ :func:`softmax`
587
+ """
588
+ return jax.nn.log_softmax(x, axis, where, initial)
589
+
590
+
591
+ def softmax(x: ArrayLike,
592
+ axis: int | tuple[int, ...] | None = -1,
593
+ where: ArrayLike | None = None,
594
+ initial: ArrayLike | None = None) -> jax.Array:
595
+ r"""Softmax function.
596
+
597
+ Computes the function which rescales elements to the range :math:`[0, 1]`
598
+ such that the elements along :code:`axis` sum to :math:`1`.
599
+
600
+ .. math ::
601
+ \mathrm{softmax}(x) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
602
+
603
+ Args:
604
+ x : input array
605
+ axis: the axis or axes along which the softmax should be computed. The
606
+ softmax output summed across these dimensions should sum to :math:`1`.
607
+ Either an integer or a tuple of integers.
608
+ where: Elements to include in the :code:`softmax`.
609
+ initial: The minimum value used to shift the input array. Must be present
610
+ when :code:`where` is not None.
611
+
612
+ Returns:
613
+ An array.
614
+
615
+ See also:
616
+ :func:`log_softmax`
617
+ """
618
+ return jax.nn.softmax(x, axis, where, initial)
619
+
620
+
621
+ def standardize(x: ArrayLike,
622
+ axis: int | tuple[int, ...] | None = -1,
623
+ variance: ArrayLike | None = None,
624
+ epsilon: ArrayLike = 1e-5,
625
+ where: ArrayLike | None = None) -> jax.Array:
626
+ r"""Normalizes an array by subtracting ``mean`` and dividing by :math:`\sqrt{\mathrm{variance}}`."""
627
+ return jax.nn.standardize(x, axis, variance, epsilon, where)
628
+
629
+
630
+ def one_hot(x: Any,
631
+ num_classes: int, *,
632
+ dtype: Any = jnp.float_,
633
+ axis: Union[int, Sequence[int]] = -1) -> jax.Array:
634
+ """One-hot encodes the given indices.
635
+
636
+ Each index in the input ``x`` is encoded as a vector of zeros of length
637
+ ``num_classes`` with the element at ``index`` set to one::
638
+
639
+ >>> jax.nn.one_hot(jnp.array([0, 1, 2]), 3)
640
+ Array([[1., 0., 0.],
641
+ [0., 1., 0.],
642
+ [0., 0., 1.]], dtype=float32)
643
+
644
+ Indices outside the range [0, num_classes) will be encoded as zeros::
645
+
646
+ >>> jax.nn.one_hot(jnp.array([-1, 3]), 3)
647
+ Array([[0., 0., 0.],
648
+ [0., 0., 0.]], dtype=float32)
649
+
650
+ Args:
651
+ x: A tensor of indices.
652
+ num_classes: Number of classes in the one-hot dimension.
653
+ dtype: optional, a float dtype for the returned values (default :obj:`jnp.float_`).
654
+ axis: the axis or axes along which the function should be
655
+ computed.
656
+ """
657
+ return jax.nn.one_hot(x, num_classes, dtype=dtype, axis=axis)
658
+
659
+
660
+ def relu6(x: ArrayLike) -> jax.Array:
661
+ r"""Rectified Linear Unit 6 activation function.
662
+
663
+ Computes the element-wise function
664
+
665
+ .. math::
666
+ \mathrm{relu6}(x) = \min(\max(x, 0), 6)
667
+
668
+ except under differentiation, we take:
669
+
670
+ .. math::
671
+ \nabla \mathrm{relu}(0) = 0
672
+
673
+ and
674
+
675
+ .. math::
676
+ \nabla \mathrm{relu}(6) = 0
677
+
678
+ Args:
679
+ x : input array
680
+
681
+ Returns:
682
+ An array.
683
+
684
+ See also:
685
+ :func:`relu`
686
+ """
687
+ return jax.nn.relu6(x)
688
+
689
+
690
+ def hard_sigmoid(x: ArrayLike) -> jax.Array:
691
+ r"""Hard Sigmoid activation function.
692
+
693
+ Computes the element-wise function
694
+
695
+ .. math::
696
+ \mathrm{hard\_sigmoid}(x) = \frac{\mathrm{relu6}(x + 3)}{6}
697
+
698
+ Args:
699
+ x : input array
700
+
701
+ Returns:
702
+ An array.
703
+
704
+ See also:
705
+ :func:`relu6`
706
+ """
707
+ return jax.nn.hard_sigmoid(x)
708
+
709
+
710
+ def hard_silu(x: ArrayLike) -> jax.Array:
711
+ r"""Hard SiLU (swish) activation function
712
+
713
+ Computes the element-wise function
714
+
715
+ .. math::
716
+ \mathrm{hard\_silu}(x) = x \cdot \mathrm{hard\_sigmoid}(x)
717
+
718
+ Both :func:`hard_silu` and :func:`hard_swish` are aliases for the same
719
+ function.
720
+
721
+ Args:
722
+ x : input array
723
+
724
+ Returns:
725
+ An array.
726
+
727
+ See also:
728
+ :func:`hard_sigmoid`
729
+ """
730
+ return jax.nn.hard_silu(x)
731
+
732
+
733
+ hard_swish = hard_silu