NeuralNetworks 0.2.0__tar.gz → 0.2.3__tar.gz
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.
- neuralnetworks-0.2.3/PKG-INFO +172 -0
- neuralnetworks-0.2.3/README.md +142 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/Dependances/__init__.py +75 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/Dependances/matplot.py +25 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/Dependances/pytorch.py +111 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/MLP/FourierFeatures.py +89 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/MLP/Layers.py +31 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/MLP/__init__.py +99 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/MLP/inference.py +26 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/Trainer/__init__.py +51 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/Trainer/dynamic_learning_rate.py +79 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/Trainer/sample_data.py +19 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/Trainer/train.py +75 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/UI/Learnings.py +45 -0
- neuralnetworks-0.2.3/src/NeuralNetworks/UI/Losses.py +45 -0
- neuralnetworks-0.2.0/src/NeuralNetworks/tools/VKI-LS59.py → neuralnetworks-0.2.3/src/NeuralNetworks/UI/__init__.py +4 -2
- neuralnetworks-0.2.3/src/NeuralNetworks/__init__.py +18 -0
- neuralnetworks-0.2.3/src/NeuralNetworks.egg-info/PKG-INFO +172 -0
- neuralnetworks-0.2.3/src/NeuralNetworks.egg-info/SOURCES.txt +23 -0
- neuralnetworks-0.2.0/PKG-INFO +0 -190
- neuralnetworks-0.2.0/README.md +0 -160
- neuralnetworks-0.2.0/src/NeuralNetworks/Dependances.py +0 -319
- neuralnetworks-0.2.0/src/NeuralNetworks/Latent.py +0 -51
- neuralnetworks-0.2.0/src/NeuralNetworks/MLP.py +0 -601
- neuralnetworks-0.2.0/src/NeuralNetworks/__init__.py +0 -127
- neuralnetworks-0.2.0/src/NeuralNetworks/tools/AirfRANS.py +0 -36
- neuralnetworks-0.2.0/src/NeuralNetworks/tools/MNIST.py +0 -118
- neuralnetworks-0.2.0/src/NeuralNetworks/tools/image.py +0 -249
- neuralnetworks-0.2.0/src/NeuralNetworks.egg-info/PKG-INFO +0 -190
- neuralnetworks-0.2.0/src/NeuralNetworks.egg-info/SOURCES.txt +0 -17
- neuralnetworks-0.2.0/tests/test_MLP.py +0 -91
- {neuralnetworks-0.2.0 → neuralnetworks-0.2.3}/LICENSE +0 -0
- {neuralnetworks-0.2.0 → neuralnetworks-0.2.3}/pyproject.toml +0 -0
- {neuralnetworks-0.2.0 → neuralnetworks-0.2.3}/setup.cfg +0 -0
- {neuralnetworks-0.2.0 → neuralnetworks-0.2.3}/src/NeuralNetworks.egg-info/dependency_links.txt +0 -0
- {neuralnetworks-0.2.0 → neuralnetworks-0.2.3}/src/NeuralNetworks.egg-info/requires.txt +0 -0
- {neuralnetworks-0.2.0 → neuralnetworks-0.2.3}/src/NeuralNetworks.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: NeuralNetworks
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: Multi-Layer Perceptrons with multi-Fourier encoding, variable learning rate, visualization and PyTorch compilation
|
|
5
|
+
Author-email: Alexandre Brun <alexandre51160@gmail.com>
|
|
6
|
+
License: GPL-3.0-or-later
|
|
7
|
+
Project-URL: Documentation, https://xxxfetraxxx.github.io/NeuralNetworks/
|
|
8
|
+
Project-URL: Source, https://github.com/xXxFetraxXx/NeuralNetworks
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: numpy>=1.25
|
|
16
|
+
Requires-Dist: matplotlib>=3.10
|
|
17
|
+
Requires-Dist: tqdm>=4.66
|
|
18
|
+
Requires-Dist: torch<3.0,>=2.9.1
|
|
19
|
+
Requires-Dist: torchvision<1.0,>=0.24
|
|
20
|
+
Requires-Dist: torchaudio<3.0,>=2.9
|
|
21
|
+
Requires-Dist: torchmetrics>=1.8
|
|
22
|
+
Requires-Dist: visualtorch>=0.2
|
|
23
|
+
Requires-Dist: random-fourier-features-pytorch>=1.0
|
|
24
|
+
Requires-Dist: IPython>=8.16
|
|
25
|
+
Requires-Dist: requests
|
|
26
|
+
Requires-Dist: airfrans
|
|
27
|
+
Requires-Dist: scipy
|
|
28
|
+
Requires-Dist: pandas
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# NeuralNetworks Module
|
|
32
|
+
|
|
33
|
+
Module complet pour la création et l'entraînement de [MultiLayer Perceptrons](https://en.wikipedia.org/wiki/Multilayer_perceptron) (MLP)
|
|
34
|
+
avec encodage optionnel [Fourier Features](https://en.wikipedia.org/wiki/Random_feature#Random_Fourier_feature) et gestion automatique des pertes.
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Contenu principal
|
|
39
|
+
|
|
40
|
+
### Classes
|
|
41
|
+
|
|
42
|
+
#### `MLP` {#MLP}
|
|
43
|
+
|
|
44
|
+
Cette classe fournit :
|
|
45
|
+
|
|
46
|
+
- Un [MLP](https://en.wikipedia.org/wiki/Multilayer_perceptron) entièrement configurable (dimensions, activation).
|
|
47
|
+
- Option d'encodage [Fourier Features](https://en.wikipedia.org/wiki/Random_feature#Random_Fourier_feature) sur les entrées.
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
##### Paramètres
|
|
52
|
+
|
|
53
|
+
| **Paramètres** | **Type** | **Optionnel** | **Description** |
|
|
54
|
+
|----------------------|--------------------------------------------------------------------------------------------------|---------------|--------------------------------------------------------------------------------|
|
|
55
|
+
| `input_size` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Taille des données en entrée au réseau. Default: `1` |
|
|
56
|
+
| `output_size` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Taille des données en sortie au réseau. Default: `1` |
|
|
57
|
+
| `hidden_layers` | [`list[int]`](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range) | Oui | Dimensions successives des couches intermédiaires du réseau. Default: `[1]` |
|
|
58
|
+
| `sigmas` | [`list[float]`](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range) | Oui | Liste de sigma pour encodages RFF. Si None : passthrough. Default: `None` |
|
|
59
|
+
| `fourier_input_size` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | WIP. Default: `2` |
|
|
60
|
+
| `nb_fourier` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Nombre de fréquences utilisées pour les Fourier Features. Default: `8` |
|
|
61
|
+
| `norm` | [`norm`](#norms) | Oui | Type de normalisation / activation pour les couches cachées. Default: `'Relu'` |
|
|
62
|
+
| `name` | [`str`](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str) | Oui | Nom du réseau pour identification ou affichage. Default: `'Net'` |
|
|
63
|
+
|
|
64
|
+
##### Attributs
|
|
65
|
+
|
|
66
|
+
- `losses : list[float]` — Historique des pertes cumulées lors de l'entraînement
|
|
67
|
+
- `learnings : list[float]` — Historique des taux d'apprentissage utilisées lors de l'entraînement
|
|
68
|
+
- `model : nn.Sequential` — MLP complet construit dynamiquement
|
|
69
|
+
- `name : str` — Nom du réseau
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
#### `Trainer`
|
|
74
|
+
|
|
75
|
+
Cette classe fournit :
|
|
76
|
+
|
|
77
|
+
- Méthode pour entraîner des réseaux avec mini-batchs et [Automatic Mixed Precision](https://docs.pytorch.org/tutorials/recipes/recipes/amp_recipe.html)
|
|
78
|
+
|
|
79
|
+
##### Paramètres
|
|
80
|
+
|
|
81
|
+
| **Paramètres** | **Type** | **Optionnel** | **Description** |
|
|
82
|
+
|----------------|-------------------------------------------------------------------------------------------------|---------------|-----------------------------------------------------------------------------------------------------------------|
|
|
83
|
+
| `*nets` | [`MLP`](#MLP) | Non | Réseaux pour lesquels le trainer va entrainer. |
|
|
84
|
+
| `inputs` | [`numpy.array(list[float])`](https://numpy.org/doc/stable/reference/generated/numpy.array.html) | Non | Données en entrée au réseau. |
|
|
85
|
+
| `outputs` | [`numpy.array(list[float])`](https://numpy.org/doc/stable/reference/generated/numpy.array.html) | Non | Données en sortie au réseau. |
|
|
86
|
+
| `test_size` | [`float`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Proportion des données à utiliser pendant l'entrainement. Si None : utilise toutes les données. Default: `None` |
|
|
87
|
+
| `optim` | [`optim`](#optims) | Oui | Nom de l’optimiseur à utiliser (doit exister dans `optims()`). Default: `'Adam'` |
|
|
88
|
+
| `init_lr` | [`float`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Taux d’apprentissage initial pour l’optimiseur. Default: `1e-3` |
|
|
89
|
+
| `crit` | [`crit`](#crits) | Oui | Fonction de perte à utiliser (doit exister dans `crits()`). Default: `MSE'` |
|
|
90
|
+
| `batch_size` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Taille des minibatchs. Default: `1024` |
|
|
91
|
+
|
|
92
|
+
##### `Trainer.train`
|
|
93
|
+
|
|
94
|
+
Lancement d'un entrainement avec le trainer définit
|
|
95
|
+
|
|
96
|
+
| **Paramètres** | **Type** | **Optionnel** | **Description** |
|
|
97
|
+
|-----------------|------------------------------------------------------------------------------------------|---------------|-----------------------------------------|
|
|
98
|
+
| `num_epochs` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Nombres d'itérations à effectuer. |
|
|
99
|
+
| `activate_tqdm` | [`boolean`](https://docs.python.org/3/library/stdtypes.html#boolean-type-bool) | Oui | Utilisation d'une barre de progression. |
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
### Dictionnaires
|
|
104
|
+
|
|
105
|
+
#### `norms()` {#norms}
|
|
106
|
+
|
|
107
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
108
|
+
|---------------|--------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
|
|
109
|
+
| `'ReLU'` | [`nn.ReLU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.ReLU.html) | Fonction d'activation ReLU classique (Rectified Linear Unit). |
|
|
110
|
+
| `'LeakyReLU'` | [`nn.LeakyReLU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html) | ReLU avec un petit coefficient pour les valeurs négatives (paramètre `negative_slope`). |
|
|
111
|
+
| `'ELU'` | [`nn.ELU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.ELU.html) | Fonction d'activation ELU (Exponential Linear Unit), qui a une meilleure gestion des valeurs négatives. |
|
|
112
|
+
| `'SELU'` | [`nn.SELU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.SELU.html) | SELU (Scaled Exponential Linear Unit), une version améliorée de l'ELU pour des réseaux auto-normalisants. |
|
|
113
|
+
| `'GELU'` | [`nn.GELU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.GELU.html) | GELU (Gaussian Error Linear Unit), une activation probabiliste basée sur une fonction gaussienne. |
|
|
114
|
+
| `'Mish'` | [`nn.Mish()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Mish.html) | ReLU différentiable en tout points avec passage négatif. |
|
|
115
|
+
| `'Softplus'` | [`nn.Softplus()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Softplus.html) | Fonction d'activation qui approxime ReLU mais de manière lissée. |
|
|
116
|
+
| `'Sigmoid'` | [`nn.Sigmoid()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Sigmoid.html) | Fonction d'activation Sigmoid, qui produit une sortie entre 0 et 1. |
|
|
117
|
+
| `'Tanh'` | [`nn.Tanh()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Tanh.html) | Fonction d'activation Tanh, avec une sortie dans l'intervalle [-1, 1]. |
|
|
118
|
+
| `'Hardtanh'` | [`nn.Hardtanh()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Hardtanh.html) | Variante de Tanh, avec des sorties limitées entre une plage spécifiée. |
|
|
119
|
+
| `'Softsign'` | [`nn.Softsign()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Softsign.html) | Fonction d'activation similaire à Tanh mais plus souple, avec des valeurs dans [-1, 1]. |
|
|
120
|
+
|
|
121
|
+
#### `crits()` {#crits}
|
|
122
|
+
|
|
123
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
124
|
+
|--------------------------|--------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|
|
|
125
|
+
| `'MSE'` | [`nn.MSELoss`](https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html) | Perte utilisée pour les régressions. |
|
|
126
|
+
| `'L1'` | [`nn.L1Loss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.L1Loss.html) | Perte utilisée pour la régularisation. |
|
|
127
|
+
| `'SmoothL1'` | [`nn.SmoothL1Loss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html) | Perte moins sensible aux outliers. |
|
|
128
|
+
| `'Huber'` | [`nn.HuberLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.HuberLoss.html) | Perte moins affectée par les grands écarts. |
|
|
129
|
+
| `'CrossEntropy'` | [`nn.CrossEntropyLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) | Perte utilisée pour les problèmes de classification multi-classes. |
|
|
130
|
+
| `'KLDiv'` | [`nn.KLDivLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html) | Perte utilisée pour des modèles probabilistes. |
|
|
131
|
+
| `'PoissonNLL'` | [`nn.PoissonNLLLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.PoissonNLLLoss.html) | Perte utilisée pour la modélisation de comptages. |
|
|
132
|
+
| `'MultiLabelSoftMargin'` | [`nn.MultiLabelSoftMarginLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.MultiLabelSoftMarginLoss.html) | Perte utilisée pour les problèmes de classification multi-étiquettes. |
|
|
133
|
+
|
|
134
|
+
#### `optims()` {#optims}
|
|
135
|
+
|
|
136
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
137
|
+
|---------------|--------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------|
|
|
138
|
+
| `'Adadelta'` | [`optim.Adadelta()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adadelta.html) | Optimiseur basé sur les gradients adaptatifs, sans nécessité de réglage du taux d'apprentissage. |
|
|
139
|
+
| `'Adafactor'` | [`optim.Adafactor()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adafactor.html) | Optimiseur variant d'Adam avec une mise à jour plus efficace de la mémoire pour de grands modèles. |
|
|
140
|
+
| `'Adam'` | [`optim.Adam()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adam.html) | Optimiseur utilisant un gradient stochastique adaptatif avec des moyennes mobiles des gradients. |
|
|
141
|
+
| `'AdamW'` | [`optim.AdamW()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.AdamW.html) | Optimiseur avec une régularisation L2 (weight decay) distincte. |
|
|
142
|
+
| `'Adamax'` | [`optim.Adamax()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adamax.html) | Optimiseur utilisant une norme infinie pour les gradients, plus stable pour certaines configurations. |
|
|
143
|
+
| `'ASGD'` | [`optim.ASGD()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.ASGD.html) | Optimiseur utilisé pour de grandes données avec une moyenne des gradients. |
|
|
144
|
+
| `'NAdam'` | [`optim.NAdam()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.NAdam.html) | Optimiseur avec une adaptation des moments de second ordre. |
|
|
145
|
+
| `'RAdam'` | [`optim.RAdam()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.RAdam.html) | Optimiseur qui ajuste dynamiquement les moments pour stabiliser l'entraînement. |
|
|
146
|
+
| `'RMSprop'` | [`optim.RMSprop()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.RMSprop.html) | Optimiseur utilisant une moyenne mobile des carrés des gradients pour réduire les oscillations. |
|
|
147
|
+
| `'Rprop'` | [`optim.Rprop()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Rprop.html) | Optimiseur basé sur les mises à jour des poids indépendantes des gradients. |
|
|
148
|
+
| `'SGD'` | [`optim.SGD()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.SGD.html) | Optimiseur souvent utilisée avec un taux d'apprentissage constant ou ajusté. |
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
### `device`
|
|
153
|
+
|
|
154
|
+
variable principale d'allocation des performances
|
|
155
|
+
|
|
156
|
+
#### **Apple Silicon (macOS)**
|
|
157
|
+
- Si le système d'exploitation est macOS (nommé `darwin` dans `platform.system()`), la fonction vérifie si l'accélérateur **Metal Performance Shaders** (MPS) est disponible sur l'appareil.
|
|
158
|
+
- Si MPS est disponible (`torch.backends.mps.is_available()`), l'appareil cible sera défini sur `'MPS'` (c'est un équivalent de CUDA pour les appareils Apple Silicon).
|
|
159
|
+
|
|
160
|
+
#### **Windows**
|
|
161
|
+
- Si le système d'exploitation est Windows, la fonction vérifie d'abord si **CUDA** (NVIDIA) est disponible avec `torch.cuda.is_available()`. Si c'est le cas, le périphérique sera défini sur **CUDA**.
|
|
162
|
+
|
|
163
|
+
#### **Linux**
|
|
164
|
+
- Si le système d'exploitation est Linux, plusieurs vérifications sont effectuées :
|
|
165
|
+
1. **CUDA** (NVIDIA) : Si `torch.cuda.is_available()` renvoie `True`, le périphérique sera défini sur `'CUDA'`.
|
|
166
|
+
2. **ROCm** (AMD) : Si le système supporte **ROCm** via `torch.backends.hip.is_available()`, l'appareil sera défini sur `'CUDA'` (ROCm est utilisé pour les cartes AMD dans le cadre de l'API CUDA).
|
|
167
|
+
3. **Intel oneAPI / XPU** : Si le système prend en charge **Intel oneAPI** ou **XPU** via `torch.xpu.is_available()`, le périphérique sera défini sur **XPU**.
|
|
168
|
+
|
|
169
|
+
#### **Système non reconnu**
|
|
170
|
+
- Si aucune des conditions ci-dessus n'est remplie, la fonction retourne `'CPU'` comme périphérique par défaut.
|
|
171
|
+
|
|
172
|
+
---
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# NeuralNetworks Module
|
|
2
|
+
|
|
3
|
+
Module complet pour la création et l'entraînement de [MultiLayer Perceptrons](https://en.wikipedia.org/wiki/Multilayer_perceptron) (MLP)
|
|
4
|
+
avec encodage optionnel [Fourier Features](https://en.wikipedia.org/wiki/Random_feature#Random_Fourier_feature) et gestion automatique des pertes.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Contenu principal
|
|
9
|
+
|
|
10
|
+
### Classes
|
|
11
|
+
|
|
12
|
+
#### `MLP` {#MLP}
|
|
13
|
+
|
|
14
|
+
Cette classe fournit :
|
|
15
|
+
|
|
16
|
+
- Un [MLP](https://en.wikipedia.org/wiki/Multilayer_perceptron) entièrement configurable (dimensions, activation).
|
|
17
|
+
- Option d'encodage [Fourier Features](https://en.wikipedia.org/wiki/Random_feature#Random_Fourier_feature) sur les entrées.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
##### Paramètres
|
|
22
|
+
|
|
23
|
+
| **Paramètres** | **Type** | **Optionnel** | **Description** |
|
|
24
|
+
|----------------------|--------------------------------------------------------------------------------------------------|---------------|--------------------------------------------------------------------------------|
|
|
25
|
+
| `input_size` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Taille des données en entrée au réseau. Default: `1` |
|
|
26
|
+
| `output_size` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Taille des données en sortie au réseau. Default: `1` |
|
|
27
|
+
| `hidden_layers` | [`list[int]`](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range) | Oui | Dimensions successives des couches intermédiaires du réseau. Default: `[1]` |
|
|
28
|
+
| `sigmas` | [`list[float]`](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range) | Oui | Liste de sigma pour encodages RFF. Si None : passthrough. Default: `None` |
|
|
29
|
+
| `fourier_input_size` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | WIP. Default: `2` |
|
|
30
|
+
| `nb_fourier` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Nombre de fréquences utilisées pour les Fourier Features. Default: `8` |
|
|
31
|
+
| `norm` | [`norm`](#norms) | Oui | Type de normalisation / activation pour les couches cachées. Default: `'Relu'` |
|
|
32
|
+
| `name` | [`str`](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str) | Oui | Nom du réseau pour identification ou affichage. Default: `'Net'` |
|
|
33
|
+
|
|
34
|
+
##### Attributs
|
|
35
|
+
|
|
36
|
+
- `losses : list[float]` — Historique des pertes cumulées lors de l'entraînement
|
|
37
|
+
- `learnings : list[float]` — Historique des taux d'apprentissage utilisées lors de l'entraînement
|
|
38
|
+
- `model : nn.Sequential` — MLP complet construit dynamiquement
|
|
39
|
+
- `name : str` — Nom du réseau
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
#### `Trainer`
|
|
44
|
+
|
|
45
|
+
Cette classe fournit :
|
|
46
|
+
|
|
47
|
+
- Méthode pour entraîner des réseaux avec mini-batchs et [Automatic Mixed Precision](https://docs.pytorch.org/tutorials/recipes/recipes/amp_recipe.html)
|
|
48
|
+
|
|
49
|
+
##### Paramètres
|
|
50
|
+
|
|
51
|
+
| **Paramètres** | **Type** | **Optionnel** | **Description** |
|
|
52
|
+
|----------------|-------------------------------------------------------------------------------------------------|---------------|-----------------------------------------------------------------------------------------------------------------|
|
|
53
|
+
| `*nets` | [`MLP`](#MLP) | Non | Réseaux pour lesquels le trainer va entrainer. |
|
|
54
|
+
| `inputs` | [`numpy.array(list[float])`](https://numpy.org/doc/stable/reference/generated/numpy.array.html) | Non | Données en entrée au réseau. |
|
|
55
|
+
| `outputs` | [`numpy.array(list[float])`](https://numpy.org/doc/stable/reference/generated/numpy.array.html) | Non | Données en sortie au réseau. |
|
|
56
|
+
| `test_size` | [`float`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Proportion des données à utiliser pendant l'entrainement. Si None : utilise toutes les données. Default: `None` |
|
|
57
|
+
| `optim` | [`optim`](#optims) | Oui | Nom de l’optimiseur à utiliser (doit exister dans `optims()`). Default: `'Adam'` |
|
|
58
|
+
| `init_lr` | [`float`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Taux d’apprentissage initial pour l’optimiseur. Default: `1e-3` |
|
|
59
|
+
| `crit` | [`crit`](#crits) | Oui | Fonction de perte à utiliser (doit exister dans `crits()`). Default: `MSE'` |
|
|
60
|
+
| `batch_size` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Taille des minibatchs. Default: `1024` |
|
|
61
|
+
|
|
62
|
+
##### `Trainer.train`
|
|
63
|
+
|
|
64
|
+
Lancement d'un entrainement avec le trainer définit
|
|
65
|
+
|
|
66
|
+
| **Paramètres** | **Type** | **Optionnel** | **Description** |
|
|
67
|
+
|-----------------|------------------------------------------------------------------------------------------|---------------|-----------------------------------------|
|
|
68
|
+
| `num_epochs` | [`int`](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) | Oui | Nombres d'itérations à effectuer. |
|
|
69
|
+
| `activate_tqdm` | [`boolean`](https://docs.python.org/3/library/stdtypes.html#boolean-type-bool) | Oui | Utilisation d'une barre de progression. |
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
### Dictionnaires
|
|
74
|
+
|
|
75
|
+
#### `norms()` {#norms}
|
|
76
|
+
|
|
77
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
78
|
+
|---------------|--------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
|
|
79
|
+
| `'ReLU'` | [`nn.ReLU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.ReLU.html) | Fonction d'activation ReLU classique (Rectified Linear Unit). |
|
|
80
|
+
| `'LeakyReLU'` | [`nn.LeakyReLU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html) | ReLU avec un petit coefficient pour les valeurs négatives (paramètre `negative_slope`). |
|
|
81
|
+
| `'ELU'` | [`nn.ELU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.ELU.html) | Fonction d'activation ELU (Exponential Linear Unit), qui a une meilleure gestion des valeurs négatives. |
|
|
82
|
+
| `'SELU'` | [`nn.SELU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.SELU.html) | SELU (Scaled Exponential Linear Unit), une version améliorée de l'ELU pour des réseaux auto-normalisants. |
|
|
83
|
+
| `'GELU'` | [`nn.GELU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.GELU.html) | GELU (Gaussian Error Linear Unit), une activation probabiliste basée sur une fonction gaussienne. |
|
|
84
|
+
| `'Mish'` | [`nn.Mish()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Mish.html) | ReLU différentiable en tout points avec passage négatif. |
|
|
85
|
+
| `'Softplus'` | [`nn.Softplus()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Softplus.html) | Fonction d'activation qui approxime ReLU mais de manière lissée. |
|
|
86
|
+
| `'Sigmoid'` | [`nn.Sigmoid()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Sigmoid.html) | Fonction d'activation Sigmoid, qui produit une sortie entre 0 et 1. |
|
|
87
|
+
| `'Tanh'` | [`nn.Tanh()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Tanh.html) | Fonction d'activation Tanh, avec une sortie dans l'intervalle [-1, 1]. |
|
|
88
|
+
| `'Hardtanh'` | [`nn.Hardtanh()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Hardtanh.html) | Variante de Tanh, avec des sorties limitées entre une plage spécifiée. |
|
|
89
|
+
| `'Softsign'` | [`nn.Softsign()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Softsign.html) | Fonction d'activation similaire à Tanh mais plus souple, avec des valeurs dans [-1, 1]. |
|
|
90
|
+
|
|
91
|
+
#### `crits()` {#crits}
|
|
92
|
+
|
|
93
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
94
|
+
|--------------------------|--------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|
|
|
95
|
+
| `'MSE'` | [`nn.MSELoss`](https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html) | Perte utilisée pour les régressions. |
|
|
96
|
+
| `'L1'` | [`nn.L1Loss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.L1Loss.html) | Perte utilisée pour la régularisation. |
|
|
97
|
+
| `'SmoothL1'` | [`nn.SmoothL1Loss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html) | Perte moins sensible aux outliers. |
|
|
98
|
+
| `'Huber'` | [`nn.HuberLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.HuberLoss.html) | Perte moins affectée par les grands écarts. |
|
|
99
|
+
| `'CrossEntropy'` | [`nn.CrossEntropyLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) | Perte utilisée pour les problèmes de classification multi-classes. |
|
|
100
|
+
| `'KLDiv'` | [`nn.KLDivLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html) | Perte utilisée pour des modèles probabilistes. |
|
|
101
|
+
| `'PoissonNLL'` | [`nn.PoissonNLLLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.PoissonNLLLoss.html) | Perte utilisée pour la modélisation de comptages. |
|
|
102
|
+
| `'MultiLabelSoftMargin'` | [`nn.MultiLabelSoftMarginLoss()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.MultiLabelSoftMarginLoss.html) | Perte utilisée pour les problèmes de classification multi-étiquettes. |
|
|
103
|
+
|
|
104
|
+
#### `optims()` {#optims}
|
|
105
|
+
|
|
106
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
107
|
+
|---------------|--------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------|
|
|
108
|
+
| `'Adadelta'` | [`optim.Adadelta()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adadelta.html) | Optimiseur basé sur les gradients adaptatifs, sans nécessité de réglage du taux d'apprentissage. |
|
|
109
|
+
| `'Adafactor'` | [`optim.Adafactor()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adafactor.html) | Optimiseur variant d'Adam avec une mise à jour plus efficace de la mémoire pour de grands modèles. |
|
|
110
|
+
| `'Adam'` | [`optim.Adam()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adam.html) | Optimiseur utilisant un gradient stochastique adaptatif avec des moyennes mobiles des gradients. |
|
|
111
|
+
| `'AdamW'` | [`optim.AdamW()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.AdamW.html) | Optimiseur avec une régularisation L2 (weight decay) distincte. |
|
|
112
|
+
| `'Adamax'` | [`optim.Adamax()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Adamax.html) | Optimiseur utilisant une norme infinie pour les gradients, plus stable pour certaines configurations. |
|
|
113
|
+
| `'ASGD'` | [`optim.ASGD()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.ASGD.html) | Optimiseur utilisé pour de grandes données avec une moyenne des gradients. |
|
|
114
|
+
| `'NAdam'` | [`optim.NAdam()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.NAdam.html) | Optimiseur avec une adaptation des moments de second ordre. |
|
|
115
|
+
| `'RAdam'` | [`optim.RAdam()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.RAdam.html) | Optimiseur qui ajuste dynamiquement les moments pour stabiliser l'entraînement. |
|
|
116
|
+
| `'RMSprop'` | [`optim.RMSprop()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.RMSprop.html) | Optimiseur utilisant une moyenne mobile des carrés des gradients pour réduire les oscillations. |
|
|
117
|
+
| `'Rprop'` | [`optim.Rprop()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.Rprop.html) | Optimiseur basé sur les mises à jour des poids indépendantes des gradients. |
|
|
118
|
+
| `'SGD'` | [`optim.SGD()`](https://docs.pytorch.org/docs/stable/generated/torch.optim.SGD.html) | Optimiseur souvent utilisée avec un taux d'apprentissage constant ou ajusté. |
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
### `device`
|
|
123
|
+
|
|
124
|
+
variable principale d'allocation des performances
|
|
125
|
+
|
|
126
|
+
#### **Apple Silicon (macOS)**
|
|
127
|
+
- Si le système d'exploitation est macOS (nommé `darwin` dans `platform.system()`), la fonction vérifie si l'accélérateur **Metal Performance Shaders** (MPS) est disponible sur l'appareil.
|
|
128
|
+
- Si MPS est disponible (`torch.backends.mps.is_available()`), l'appareil cible sera défini sur `'MPS'` (c'est un équivalent de CUDA pour les appareils Apple Silicon).
|
|
129
|
+
|
|
130
|
+
#### **Windows**
|
|
131
|
+
- Si le système d'exploitation est Windows, la fonction vérifie d'abord si **CUDA** (NVIDIA) est disponible avec `torch.cuda.is_available()`. Si c'est le cas, le périphérique sera défini sur **CUDA**.
|
|
132
|
+
|
|
133
|
+
#### **Linux**
|
|
134
|
+
- Si le système d'exploitation est Linux, plusieurs vérifications sont effectuées :
|
|
135
|
+
1. **CUDA** (NVIDIA) : Si `torch.cuda.is_available()` renvoie `True`, le périphérique sera défini sur `'CUDA'`.
|
|
136
|
+
2. **ROCm** (AMD) : Si le système supporte **ROCm** via `torch.backends.hip.is_available()`, l'appareil sera défini sur `'CUDA'` (ROCm est utilisé pour les cartes AMD dans le cadre de l'API CUDA).
|
|
137
|
+
3. **Intel oneAPI / XPU** : Si le système prend en charge **Intel oneAPI** ou **XPU** via `torch.xpu.is_available()`, le périphérique sera défini sur **XPU**.
|
|
138
|
+
|
|
139
|
+
#### **Système non reconnu**
|
|
140
|
+
- Si aucune des conditions ci-dessus n'est remplie, la fonction retourne `'CPU'` comme périphérique par défaut.
|
|
141
|
+
|
|
142
|
+
---
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# NeuralNetworks - Multi-Layer Perceptrons avec encodage Fourier
|
|
2
|
+
# Copyright (C) 2026 Alexandre Brun
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
|
|
8
|
+
from .matplot import *
|
|
9
|
+
from .pytorch import *
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from PIL import Image
|
|
13
|
+
|
|
14
|
+
import copy
|
|
15
|
+
import subprocess
|
|
16
|
+
import requests
|
|
17
|
+
from io import BytesIO
|
|
18
|
+
from tqdm import tqdm
|
|
19
|
+
import plotly.graph_objects as go
|
|
20
|
+
from IPython.display import display, clear_output
|
|
21
|
+
|
|
22
|
+
from scipy.interpolate import griddata
|
|
23
|
+
from sklearn.model_selection import train_test_split
|
|
24
|
+
|
|
25
|
+
import math
|
|
26
|
+
pi = math.pi
|
|
27
|
+
e = math.e
|
|
28
|
+
|
|
29
|
+
norms = lambda: print("""
|
|
30
|
+
"Relu"
|
|
31
|
+
"LeakyRelu"
|
|
32
|
+
"ELU"
|
|
33
|
+
"SELU"
|
|
34
|
+
"GELU"
|
|
35
|
+
"Mish"
|
|
36
|
+
"Sigmoid"
|
|
37
|
+
"Tanh"
|
|
38
|
+
"Hardtanh"
|
|
39
|
+
"Softplus"
|
|
40
|
+
"Softsign"
|
|
41
|
+
"""
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
crits = lambda: print("""
|
|
45
|
+
"MSE"
|
|
46
|
+
"L1"
|
|
47
|
+
"SmoothL1"
|
|
48
|
+
"Huber"
|
|
49
|
+
"CrossEntropy"
|
|
50
|
+
"KLDiv"
|
|
51
|
+
"PoissonNLL"
|
|
52
|
+
"MultiLabelSoftMargin"
|
|
53
|
+
"""
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
optims = lambda: print("""
|
|
57
|
+
"Adadelta"
|
|
58
|
+
"Adafactor"
|
|
59
|
+
"Adam"
|
|
60
|
+
"AdamW"
|
|
61
|
+
"Adamax"
|
|
62
|
+
"ASGD"
|
|
63
|
+
"NAdam"
|
|
64
|
+
"RAdam"
|
|
65
|
+
"RMSprop"
|
|
66
|
+
"Rprop"
|
|
67
|
+
"SGD"
|
|
68
|
+
"""
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def rglen(list):
|
|
72
|
+
return range(len(list))
|
|
73
|
+
|
|
74
|
+
def fPrintDoc(obj):
|
|
75
|
+
return lambda: print(obj.__doc__)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# NeuralNetworks - Multi-Layer Perceptrons avec encodage Fourier
|
|
2
|
+
# Copyright (C) 2026 Alexandre Brun
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
from matplotlib.gridspec import GridSpec
|
|
10
|
+
|
|
11
|
+
plt.rcParams['figure.facecolor'] = (0,0,0,0)
|
|
12
|
+
plt.rcParams['axes.facecolor'] = (0,0,0,0)
|
|
13
|
+
grey_color = "#888888"
|
|
14
|
+
|
|
15
|
+
# Style général du texte et axes
|
|
16
|
+
plt.rcParams['text.color'] = grey_color
|
|
17
|
+
plt.rcParams['axes.labelcolor'] = grey_color
|
|
18
|
+
plt.rcParams['xtick.color'] = grey_color
|
|
19
|
+
plt.rcParams['ytick.color'] = grey_color
|
|
20
|
+
plt.rcParams['axes.edgecolor'] = grey_color
|
|
21
|
+
plt.rcParams['axes.titlecolor'] = grey_color
|
|
22
|
+
|
|
23
|
+
# Activation de la grille globale
|
|
24
|
+
plt.rcParams['axes.grid'] = True
|
|
25
|
+
plt.rcParams['grid.color'] = grey_color
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# NeuralNetworks - Multi-Layer Perceptrons avec encodage Fourier
|
|
2
|
+
# Copyright (C) 2026 Alexandre Brun
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
|
10
|
+
|
|
11
|
+
import platform
|
|
12
|
+
|
|
13
|
+
import torch
|
|
14
|
+
import torch.optim as optim
|
|
15
|
+
import torch.nn as nn
|
|
16
|
+
import torch.quantization as tq
|
|
17
|
+
from torch.amp import autocast, GradScaler
|
|
18
|
+
from torch.utils.data import TensorDataset, DataLoader
|
|
19
|
+
|
|
20
|
+
from torchmetrics.image import PeakSignalNoiseRatio as PSNR
|
|
21
|
+
from torchvision.transforms import ToTensor, Resize, Compose
|
|
22
|
+
|
|
23
|
+
torch.cuda.empty_cache()
|
|
24
|
+
def get_best_device():
|
|
25
|
+
|
|
26
|
+
os_name = platform.system().lower()
|
|
27
|
+
|
|
28
|
+
# =========== APPLE SILICON (macOS) ===========
|
|
29
|
+
if os_name == "darwin":
|
|
30
|
+
if torch.backends.mps.is_available():
|
|
31
|
+
return torch.device("mps")
|
|
32
|
+
|
|
33
|
+
# =========== WINDOWS ===========
|
|
34
|
+
if os_name == "windows":
|
|
35
|
+
# 1) CUDA
|
|
36
|
+
if torch.cuda.is_available():
|
|
37
|
+
return torch.device("cuda")
|
|
38
|
+
|
|
39
|
+
# =========== LINUX ===========
|
|
40
|
+
if os_name == "linux":
|
|
41
|
+
# 1) CUDA (Nvidia)
|
|
42
|
+
if torch.cuda.is_available():
|
|
43
|
+
return torch.device("cuda")
|
|
44
|
+
# 2) ROCm (AMD)
|
|
45
|
+
elif hasattr(torch.backends, "hip") and torch.backends.hip.is_available():
|
|
46
|
+
return torch.device("cuda")
|
|
47
|
+
|
|
48
|
+
# 3) Intel oneAPI / XPU
|
|
49
|
+
elif hasattr(torch, "xpu") and torch.xpu.is_available():
|
|
50
|
+
return torch.device("xpu")
|
|
51
|
+
|
|
52
|
+
# =========== Unknown OS ===========
|
|
53
|
+
return torch.device("cpu")
|
|
54
|
+
device = get_best_device()
|
|
55
|
+
|
|
56
|
+
# --- Optimisations CUDA ---
|
|
57
|
+
# Accélération des convolutions et matmul
|
|
58
|
+
torch.backends.cudnn.benchmark = True
|
|
59
|
+
torch.backends.cudnn.enabled = True
|
|
60
|
+
torch.backends.cuda.matmul.allow_tf32 = True
|
|
61
|
+
torch.backends.cudnn.allow_tf32 = True
|
|
62
|
+
|
|
63
|
+
# Paramètres autograd
|
|
64
|
+
torch.autograd.set_detect_anomaly(False)
|
|
65
|
+
torch.autograd.profiler.profile(enabled=False)
|
|
66
|
+
torch.use_deterministic_algorithms(False)
|
|
67
|
+
|
|
68
|
+
torch._inductor.config.max_autotune = "max"
|
|
69
|
+
|
|
70
|
+
norm_list = {
|
|
71
|
+
"Relu": nn.ReLU(),
|
|
72
|
+
"LeakyRelu": nn.LeakyReLU(),
|
|
73
|
+
"ELU": nn.ELU(),
|
|
74
|
+
"SELU": nn.SELU(),
|
|
75
|
+
"GELU": nn.GELU(),
|
|
76
|
+
"Mish": nn.Mish(),
|
|
77
|
+
"Sigmoid": nn.Sigmoid(),
|
|
78
|
+
"Tanh": nn.Tanh(),
|
|
79
|
+
"Hardtanh": nn.Hardtanh(),
|
|
80
|
+
"Softplus": nn.Softplus(),
|
|
81
|
+
"Softsign": nn.Softsign()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
crit_list = {
|
|
85
|
+
"MSE": nn.MSELoss(),
|
|
86
|
+
"L1": nn.L1Loss(),
|
|
87
|
+
"SmoothL1": nn.SmoothL1Loss(),
|
|
88
|
+
"Huber": nn.HuberLoss(),
|
|
89
|
+
"CrossEntropy": nn.CrossEntropyLoss(),
|
|
90
|
+
"KLDiv": nn.KLDivLoss(),
|
|
91
|
+
"PoissonNLL": nn.PoissonNLLLoss(),
|
|
92
|
+
"MultiLabelSoftMargin": nn.MultiLabelSoftMarginLoss()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
def optim_list(params):
|
|
96
|
+
return {
|
|
97
|
+
"Adadelta": optim.Adadelta(params),
|
|
98
|
+
"Adafactor": optim.Adafactor(params),
|
|
99
|
+
"Adam": optim.Adam(params),
|
|
100
|
+
"AdamW": optim.AdamW(params),
|
|
101
|
+
"Adamax": optim.Adamax(params),
|
|
102
|
+
"ASGD": optim.ASGD(params),
|
|
103
|
+
"NAdam": optim.NAdam(params),
|
|
104
|
+
"RAdam": optim.RAdam(params),
|
|
105
|
+
"RMSprop": optim.RMSprop(params),
|
|
106
|
+
"Rprop": optim.Rprop(params),
|
|
107
|
+
"SGD": optim.SGD(params)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
def tensorise(obj):
|
|
111
|
+
return torch.as_tensor(obj, dtype=torch.float32, device='cpu')
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# NeuralNetworks - Multi-Layer Perceptrons avec encodage Fourier
|
|
2
|
+
# Copyright (C) 2026 Alexandre Brun
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
|
|
8
|
+
from ..Dependances import torch, nn, np
|
|
9
|
+
|
|
10
|
+
class FourierEncoding (nn.Module):
|
|
11
|
+
"""
|
|
12
|
+
Encodage de Fourier aléatoire pour enrichir la représentation des entrées.
|
|
13
|
+
|
|
14
|
+
Cette couche projette les entrées dans un espace fréquentiel à l'aide
|
|
15
|
+
d'une matrice de projection apprise, puis applique des fonctions sinus
|
|
16
|
+
et cosinus afin de capturer des variations à haute fréquence.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
nb_fourier : int
|
|
21
|
+
Nombre de composantes de Fourier.
|
|
22
|
+
input_size : int
|
|
23
|
+
Dimension des entrées.
|
|
24
|
+
sigma : float
|
|
25
|
+
Écart-type utilisé pour l'initialisation de la matrice de projection.
|
|
26
|
+
"""
|
|
27
|
+
def __init__ (self, nb_fourier, input_size, sigma):
|
|
28
|
+
super ().__init__ ()
|
|
29
|
+
self.B = nn.Parameter (torch.randn (nb_fourier, input_size) * sigma)
|
|
30
|
+
|
|
31
|
+
def forward (self, x):
|
|
32
|
+
"""
|
|
33
|
+
Applique l'encodage de Fourier aux entrées.
|
|
34
|
+
|
|
35
|
+
Parameters
|
|
36
|
+
----------
|
|
37
|
+
x : torch.Tensor
|
|
38
|
+
Tensor d'entrée de shape `(N, input_size)`.
|
|
39
|
+
|
|
40
|
+
Returns
|
|
41
|
+
-------
|
|
42
|
+
torch.Tensor
|
|
43
|
+
Tensor encodé de shape `(N, 2 * nb_fourier)`, correspondant
|
|
44
|
+
à la concaténation des cosinus et sinus.
|
|
45
|
+
"""
|
|
46
|
+
vp = 2 * np.pi * x @ self.B.T
|
|
47
|
+
return torch.cat ((torch.cos (vp), torch.sin (vp)), dim = -1)
|
|
48
|
+
|
|
49
|
+
def encode (input_size, output_size, sigmas, fourier_input_size, nb_fourier):
|
|
50
|
+
"""
|
|
51
|
+
Construit les modules d'encodage (Fourier ou identité) et la couche de fusion associée.
|
|
52
|
+
|
|
53
|
+
Si `sigmas` est `None`, aucun encodage de Fourier n'est appliqué et les
|
|
54
|
+
entrées sont transmises directement au réseau.
|
|
55
|
+
Sinon, plusieurs encodages de Fourier sont créés (un par sigma), et
|
|
56
|
+
leurs sorties sont fusionnées via une couche linéaire.
|
|
57
|
+
|
|
58
|
+
Parameters
|
|
59
|
+
----------
|
|
60
|
+
input_size : int
|
|
61
|
+
Dimension des entrées.
|
|
62
|
+
output_size : int
|
|
63
|
+
Dimension de sortie du réseau.
|
|
64
|
+
sigmas : list[float] ou None
|
|
65
|
+
Liste des paramètres sigma pour les encodages de Fourier.
|
|
66
|
+
fourier_input_size : int
|
|
67
|
+
Dimension attendue après encodage (non utilisée directement ici,
|
|
68
|
+
mais conservée pour cohérence avec l'architecture globale).
|
|
69
|
+
nb_fourier : int
|
|
70
|
+
Nombre de composantes de Fourier par encodage.
|
|
71
|
+
|
|
72
|
+
Returns
|
|
73
|
+
-------
|
|
74
|
+
encodings : torch.nn.ModuleList (scripté)
|
|
75
|
+
Liste des modules d'encodage (Fourier ou identité).
|
|
76
|
+
f : torch.nn.Module (scripté)
|
|
77
|
+
Module de fusion des encodages (identité ou couche linéaire).
|
|
78
|
+
"""
|
|
79
|
+
if sigmas is None:
|
|
80
|
+
encodings = nn.ModuleList (
|
|
81
|
+
[nn.Identity ()]
|
|
82
|
+
)
|
|
83
|
+
f = nn.Identity ()
|
|
84
|
+
else:
|
|
85
|
+
encodings = nn.ModuleList (
|
|
86
|
+
[FourierEncoding (nb_fourier, input_size, sigma) for sigma in sigmas]
|
|
87
|
+
)
|
|
88
|
+
f = nn.Linear (len (encodings) * output_size, output_size)
|
|
89
|
+
return torch.jit.script (encodings), torch.jit.script (f)
|