NeuralNetworks 0.1.12__py3-none-any.whl → 0.2.2__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.
- NeuralNetworks/Dependances/__init__.py +75 -0
- NeuralNetworks/Dependances/matplot.py +25 -0
- NeuralNetworks/Dependances/pytorch.py +111 -0
- NeuralNetworks/MLP/FourierFeatures.py +89 -0
- NeuralNetworks/MLP/Layers.py +31 -0
- NeuralNetworks/MLP/__init__.py +99 -0
- NeuralNetworks/MLP/inference.py +26 -0
- NeuralNetworks/Trainer/__init__.py +51 -0
- NeuralNetworks/Trainer/dynamic_learning_rate.py +79 -0
- NeuralNetworks/Trainer/sample_data.py +19 -0
- NeuralNetworks/Trainer/train.py +75 -0
- NeuralNetworks/UI/Learnings.py +45 -0
- NeuralNetworks/UI/Losses.py +45 -0
- NeuralNetworks/UI/__init__.py +9 -0
- NeuralNetworks/__init__.py +11 -116
- NeuralNetworks/tools/AirfRANS.py +36 -0
- NeuralNetworks/tools/MNIST.py +118 -0
- NeuralNetworks/tools/VKI-LS59.py +7 -0
- NeuralNetworks/tools/image.py +249 -0
- neuralnetworks-0.2.2.dist-info/METADATA +194 -0
- neuralnetworks-0.2.2.dist-info/RECORD +24 -0
- NeuralNetworks/Dependances.py +0 -319
- NeuralNetworks/Image.py +0 -105
- NeuralNetworks/MLP.py +0 -591
- NeuralNetworks/Plot.py +0 -324
- neuralnetworks-0.1.12.dist-info/METADATA +0 -187
- neuralnetworks-0.1.12.dist-info/RECORD +0 -10
- {neuralnetworks-0.1.12.dist-info → neuralnetworks-0.2.2.dist-info}/WHEEL +0 -0
- {neuralnetworks-0.1.12.dist-info → neuralnetworks-0.2.2.dist-info}/licenses/LICENSE +0 -0
- {neuralnetworks-0.1.12.dist-info → neuralnetworks-0.2.2.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: NeuralNetworks
|
|
3
|
+
Version: 0.2.2
|
|
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, l'entraînement et la visualisation de Multi-Layer Perceptrons (MLP)
|
|
34
|
+
avec encodage optionnel Fourier, gestion automatique des pertes, compilation Torch et outils
|
|
35
|
+
de traitement d'images pour l'apprentissage sur des images RGB.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Contenu principal
|
|
40
|
+
|
|
41
|
+
### Classes
|
|
42
|
+
|
|
43
|
+
#### `MLP`
|
|
44
|
+
|
|
45
|
+
Multi-Layer Perceptron (MLP) avec encodage optionnel Fourier (RFF),
|
|
46
|
+
suivi automatique des pertes, visualisation et compilation PyTorch.
|
|
47
|
+
|
|
48
|
+
Cette classe fournit :
|
|
49
|
+
|
|
50
|
+
- Un MLP entièrement configurable (dimensions, normalisation, activation)
|
|
51
|
+
- Option d'encodage Fourier (Random Fourier Features) sur les entrées
|
|
52
|
+
- Méthodes pour entraîner le réseau avec mini-batchs et AMP (Automatic Mixed Precision)
|
|
53
|
+
- Visualisation de l'architecture via visualtorch
|
|
54
|
+
- Suivi et affichage de la perte d'entraînement
|
|
55
|
+
- Accès aux poids, biais et nombre de paramètres
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
##### Parameters
|
|
60
|
+
|
|
61
|
+
| Parameter | Type | Optional | Description |
|
|
62
|
+
|----------------------|---------------|----------|-----------------------------------------------------------------------------------------------|
|
|
63
|
+
| `input_size` | int | Yes | Taille des données en entrée au réseau. Default: `1` |
|
|
64
|
+
| `output_size` | int | Yes | Taille des données en sortie au réseau. Default: `1` |
|
|
65
|
+
| `hidden_layers` | list[int] | Yes | Dimensions successives des couches intermédiaires du réseau. Default: `[1]` |
|
|
66
|
+
| `sigmas` | list[float] | Yes | Liste de sigma pour encodages RFF. Si None : passthrough. Default: `None` |
|
|
67
|
+
| `fourier_input_size` | int | Yes | WIP. Default: `2` |
|
|
68
|
+
| `nb_fourier` | int | Yes | Nombre de fréquences utilisées pour les Fourier Features. Default: `8` |
|
|
69
|
+
| `norm` | str | Yes | Type de normalisation / activation pour les couches cachées (ex: `"Relu"`). Default: `"Relu"` |
|
|
70
|
+
| `name` | str | Yes | Nom du réseau pour identification ou affichage. Default: `"Net"` |
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
##### Attributes
|
|
75
|
+
|
|
76
|
+
- `losses : list[float]` — Historique des pertes cumulées lors de l'entraînement
|
|
77
|
+
- `learnings : list[float]` — Historique des taux d'apprentissage utilisées lors de l'entraînement
|
|
78
|
+
- `model : nn.Sequential` — MLP complet construit dynamiquement
|
|
79
|
+
- `name : str` — Nom du réseau
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
#### `Trainer`
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
##### Parameters
|
|
88
|
+
|
|
89
|
+
| Parameter | Type | Optional | Description |
|
|
90
|
+
|--------------|-----------------|----------|-----------------------------------------------------------------------------------------------------------------|
|
|
91
|
+
| `*nets` | *MLP | No | Réseaux pour lesquels le trainer va entrainer. |
|
|
92
|
+
| `inputs` | np.array(float) | No | Données en entrée au réseau. |
|
|
93
|
+
| `outputs` | np.array(float) | No | Données en sortie au réseau. |
|
|
94
|
+
| `test_size` | float | Yes | Proportion des données à utiliser pendant l'entrainement. Si None : utilise toutes les données. Default: `None` |
|
|
95
|
+
| `optim` | str | Yes | Nom de l’optimiseur à utiliser (doit exister dans `optims()`). Default: `"Adam"` |
|
|
96
|
+
| `init_lr` | float | Yes | Taux d’apprentissage initial pour l’optimiseur. Default: `1e-3` |
|
|
97
|
+
| `crit` | str | Yes | Fonction de perte à utiliser (doit exister dans `crits()`). Default: `"MSE"` |
|
|
98
|
+
| `batch_size` | float | Yes | Taille des minibatchs. Default: `1024` |
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
##### `Trainer.train`
|
|
103
|
+
|
|
104
|
+
Lancement d'un entrainement avec le trainer définit
|
|
105
|
+
|
|
106
|
+
| Parameter | Type | Optional | Description |
|
|
107
|
+
|-----------------|---------|----------|-----------------------------------------|
|
|
108
|
+
| `num_epochs` | int | Yes | Nombres d'itérations à effectuer. |
|
|
109
|
+
| `activate_tqdm` | boolean | Yes | Utilisation d'une barre de progression. |
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
### Dictionnaires
|
|
114
|
+
|
|
115
|
+
#### `norms()`
|
|
116
|
+
|
|
117
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
118
|
+
|---------------------|--------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
|
|
119
|
+
| **"ReLU"** | [`nn.ReLU()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.ReLU.html) | Fonction d'activation ReLU classique (Rectified Linear Unit). |
|
|
120
|
+
| **"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`). |
|
|
121
|
+
| **"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. |
|
|
122
|
+
| **"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. |
|
|
123
|
+
| **"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. |
|
|
124
|
+
| **"Mish"** | [`nn.Mish()`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Mish.html) | ReLU différentiable en tout points avec passage négatif. |
|
|
125
|
+
| **"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. |
|
|
126
|
+
| **"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. |
|
|
127
|
+
| **"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]. |
|
|
128
|
+
| **"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. |
|
|
129
|
+
| **"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]. |
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
#### `crits()`
|
|
134
|
+
|
|
135
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
136
|
+
|--------------------------------|-------------------------------------|----------------------------------------------------------------------------------------------------------------------------|
|
|
137
|
+
| **"MSE"** | [`nn.MSELoss`](https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html) | Mean Squared Error Loss, utilisée pour les régressions. |
|
|
138
|
+
| **"L1"** | `nn.L1Loss()` | L1 Loss (erreur absolue), souvent utilisée pour la régularisation. |
|
|
139
|
+
| **"SmoothL1"** | `nn.SmoothL1Loss()` | Smooth L1 Loss, une combinaison de L1 et de MSE, moins sensible aux outliers. |
|
|
140
|
+
| **"Huber"** | `nn.HuberLoss()` | Fonction de perte Huber, une version lissée de L1 et MSE, moins affectée par les grands écarts. |
|
|
141
|
+
| **"CrossEntropy"** | `nn.CrossEntropyLoss()` | Perte de Cross-Entropy, utilisée pour les problèmes de classification multi-classes. |
|
|
142
|
+
| **"KLDiv"** | `nn.KLDivLoss()` | Perte de divergence de Kullback-Leibler, souvent utilisée pour des modèles probabilistes. |
|
|
143
|
+
| **"PoissonNLL"** | `nn.PoissonNLLLoss()` | Perte de log-vraisemblance pour une distribution de Poisson, utilisée pour la modélisation de comptages. |
|
|
144
|
+
| **"MultiLabelSoftMargin"** | `nn.MultiLabelSoftMarginLoss()` | Perte utilisée pour les problèmes de classification multi-étiquettes. |
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
#### `optims()`
|
|
149
|
+
|
|
150
|
+
| **Valeurs** | **Module PyTorch** | **Description** |
|
|
151
|
+
|---------------------|--------------------------------------|------------------------------------------------------------------------------------------------------------------------------------|
|
|
152
|
+
| **"Adadelta"** | `optim.Adadelta()` | Optimiseur Adadelta, basé sur les gradients adaptatifs, sans nécessité de réglage du taux d'apprentissage. |
|
|
153
|
+
| **"Adafactor"** | `optim.Adafactor()` | Optimiseur Adafactor, variant d'Adam avec une mise à jour plus efficace de la mémoire pour de grands modèles. |
|
|
154
|
+
| **"Adam"** | `optim.Adam()` | Optimiseur Adam, utilisant un gradient stochastique adaptatif avec des moyennes mobiles des gradients et des carrés des gradients. |
|
|
155
|
+
| **"AdamW"** | `optim.AdamW()` | Optimiseur Adam avec une régularisation L2 (weight decay) distincte, plus efficace que `Adam` avec `weight_decay`. |
|
|
156
|
+
| **"Adamax"** | `optim.Adamax()` | Version d'Adam utilisant une norme infinie pour les gradients, plus stable pour certaines configurations. |
|
|
157
|
+
| **"ASGD"** | `optim.ASGD()` | Optimiseur ASGD (Averaged Stochastic Gradient Descent), utilisé pour de grandes données avec une moyenne des gradients. |
|
|
158
|
+
| **"NAdam"** | `optim.NAdam()` | Optimiseur NAdam, une version améliorée d'Adam avec une adaptation des moments de second ordre. |
|
|
159
|
+
| **"RAdam"** | `optim.RAdam()` | Optimiseur RAdam, une version robuste de l'Adam qui ajuste dynamiquement les moments pour stabiliser l'entraînement. |
|
|
160
|
+
| **"RMSprop"** | `optim.RMSprop()` | Optimiseur RMSprop, utilisant une moyenne mobile des carrés des gradients pour réduire les oscillations. |
|
|
161
|
+
| **"Rprop"** | `optim.Rprop()` | Optimiseur Rprop, basé sur les mises à jour des poids indépendantes des gradients. |
|
|
162
|
+
| **"SGD"** | `optim.SGD()` | Descente de gradient stochastique classique, souvent utilisée avec un taux d'apprentissage constant ou ajusté. |
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
### `device`
|
|
167
|
+
|
|
168
|
+
variable principale d'allocation des performances
|
|
169
|
+
|
|
170
|
+
#### **Apple Silicon (macOS)**
|
|
171
|
+
- 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.
|
|
172
|
+
- 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).
|
|
173
|
+
|
|
174
|
+
#### **Windows**
|
|
175
|
+
- 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**.
|
|
176
|
+
|
|
177
|
+
#### **Linux**
|
|
178
|
+
- Si le système d'exploitation est Linux, plusieurs vérifications sont effectuées :
|
|
179
|
+
1. **CUDA** (NVIDIA) : Si `torch.cuda.is_available()` renvoie `True`, le périphérique sera défini sur **CUDA**.
|
|
180
|
+
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).
|
|
181
|
+
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**.
|
|
182
|
+
|
|
183
|
+
#### **Système non reconnu**
|
|
184
|
+
- Si aucune des conditions ci-dessus n'est remplie, la fonction retourne **CPU** comme périphérique par défaut.
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
### Paramètres matplotlib et PyTorch
|
|
189
|
+
|
|
190
|
+
- Style global pour fond transparent et texte gris
|
|
191
|
+
- Optimisations CUDA activées pour TF32, matmul et convolutions
|
|
192
|
+
- Autograd configuré pour privilégier les performances
|
|
193
|
+
|
|
194
|
+
---
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
NeuralNetworks/__init__.py,sha256=AWRytyL2O4sZQetW9JB1XqmWtJMK1X9b50Z7WMLD1nY,798
|
|
2
|
+
NeuralNetworks/Dependances/__init__.py,sha256=qEpDbSD8cCq-E5XVisNUVf3kZOYopDnQWToyRefPgKE,1227
|
|
3
|
+
NeuralNetworks/Dependances/matplot.py,sha256=elS8u6DZHYP-8mHEpYNOw3jDzhCAWTld9tm3OAD46zw,957
|
|
4
|
+
NeuralNetworks/Dependances/pytorch.py,sha256=RQlSV3-8uHAoEgK0FBae7O4Mdug7h_MY--sN1fK59qw,3329
|
|
5
|
+
NeuralNetworks/MLP/FourierFeatures.py,sha256=klgRM1HK09oA2NRMDxQMjJJ-WoUd5hV1ip5hHe9rHjI,3250
|
|
6
|
+
NeuralNetworks/MLP/Layers.py,sha256=WAksXsiMxaClyYTxPhlyQbwwj9qTtXs3EWCO1RqjUHY,945
|
|
7
|
+
NeuralNetworks/MLP/__init__.py,sha256=cEW_M5lZPiuozlItNIAYGhJ_NauwUnhGurcY4r_gh-A,3067
|
|
8
|
+
NeuralNetworks/MLP/inference.py,sha256=9aL7pUx1LTVvrc6UYHX049UjODTgHY6cweFcp2gequQ,853
|
|
9
|
+
NeuralNetworks/Trainer/__init__.py,sha256=v0qKqx9XkYWkuouNNy0jTHQ_cZqYhFj98qrwSXlDXy0,1711
|
|
10
|
+
NeuralNetworks/Trainer/dynamic_learning_rate.py,sha256=1JAD-k0cjdL_71zGeeCUFOa61H4PzFITDjZ2nK0TzXU,2340
|
|
11
|
+
NeuralNetworks/Trainer/sample_data.py,sha256=7waC9colb7DXU4yKMcgcCnPG3Guv-isipcgVHJPPCNE,673
|
|
12
|
+
NeuralNetworks/Trainer/train.py,sha256=NAbHFKg4hl96OXq_i63lcRYwrPHiuKu7ihexakhpgDY,3182
|
|
13
|
+
NeuralNetworks/UI/Learnings.py,sha256=4TBR5pcjyoBeL7eikNKM6xn25jnqL-mWT7hbrt9q-Gw,1418
|
|
14
|
+
NeuralNetworks/UI/Losses.py,sha256=Tu5xuDiutR9a4xcZKpyWN_tzSDu3_fImEf8FbAEehio,1378
|
|
15
|
+
NeuralNetworks/UI/__init__.py,sha256=L96xwQZJ-HoqqOGxaheosiDKHR3mRopuXkif--rO1J4,409
|
|
16
|
+
NeuralNetworks/tools/AirfRANS.py,sha256=UaCT3cuMz4_SPtgk9a7ZGB12l8dnDHjoAkD2ovLrAWk,1412
|
|
17
|
+
NeuralNetworks/tools/MNIST.py,sha256=1lcB-dmlvpcxvQmjjHW2d5wR84uWB5rzYP6VC6CMoN4,4333
|
|
18
|
+
NeuralNetworks/tools/VKI-LS59.py,sha256=OZqrJvR5QDcPEtuL7H0UoxpFwkjmWmOmfVWoV1d8fIs,354
|
|
19
|
+
NeuralNetworks/tools/image.py,sha256=dtohmcOtGJ0rK3uXxy9O2zhhTE_DZDoZKmUSnBNkv0Q,8952
|
|
20
|
+
neuralnetworks-0.2.2.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
|
|
21
|
+
neuralnetworks-0.2.2.dist-info/METADATA,sha256=x5PCHM2idxDoVvJBqOfH21bzNZbhwwojuPPEuStgQb0,15176
|
|
22
|
+
neuralnetworks-0.2.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
23
|
+
neuralnetworks-0.2.2.dist-info/top_level.txt,sha256=h18nmC1BX7avyAAwKh0OQWezxgXmOpmVtbFq-8Mcbms,15
|
|
24
|
+
neuralnetworks-0.2.2.dist-info/RECORD,,
|
NeuralNetworks/Dependances.py
DELETED
|
@@ -1,319 +0,0 @@
|
|
|
1
|
-
# NeuralNetworksBeta - Multi-Layer Perceptrons avec encodage Fourier
|
|
2
|
-
# Copyright (C) 2025 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 numpy as np
|
|
9
|
-
import torch
|
|
10
|
-
import torch.optim as optim
|
|
11
|
-
import torch.nn as nn
|
|
12
|
-
import torch.quantization as tq
|
|
13
|
-
from torch.amp import autocast, GradScaler
|
|
14
|
-
from torch.utils.data import TensorDataset, DataLoader
|
|
15
|
-
|
|
16
|
-
import visualtorch
|
|
17
|
-
|
|
18
|
-
from torchmetrics.image import PeakSignalNoiseRatio as PSNR
|
|
19
|
-
from torchvision.transforms import ToTensor, Resize, Compose
|
|
20
|
-
|
|
21
|
-
from PIL import Image
|
|
22
|
-
|
|
23
|
-
import matplotlib.pyplot as plt
|
|
24
|
-
from matplotlib.gridspec import GridSpec
|
|
25
|
-
|
|
26
|
-
import platform
|
|
27
|
-
import copy
|
|
28
|
-
import math
|
|
29
|
-
import subprocess
|
|
30
|
-
import requests
|
|
31
|
-
from io import BytesIO
|
|
32
|
-
import rff
|
|
33
|
-
from tqdm import tqdm
|
|
34
|
-
|
|
35
|
-
from IPython.display import display, clear_output
|
|
36
|
-
|
|
37
|
-
torch.cuda.empty_cache()
|
|
38
|
-
|
|
39
|
-
# --- Device global ---
|
|
40
|
-
# Utilise GPU si disponible, sinon CPU
|
|
41
|
-
|
|
42
|
-
def get_best_device():
|
|
43
|
-
"""
|
|
44
|
-
Détermine automatiquement le meilleur backend PyTorch disponible selon l'OS
|
|
45
|
-
et les GPU présents sur la machine.
|
|
46
|
-
|
|
47
|
-
La priorité dépend du système :
|
|
48
|
-
|
|
49
|
-
macOS (Apple Silicon)
|
|
50
|
-
---------------------
|
|
51
|
-
- Utilise Metal/MPS si disponible.
|
|
52
|
-
- Sinon CPU.
|
|
53
|
-
|
|
54
|
-
Windows
|
|
55
|
-
-------
|
|
56
|
-
- CUDA si une GPU Nvidia CUDA est détectée.
|
|
57
|
-
- Sinon DirectML (AMD / Intel / Nvidia sans CUDA).
|
|
58
|
-
- Sinon CPU.
|
|
59
|
-
|
|
60
|
-
Linux
|
|
61
|
-
-----
|
|
62
|
-
- CUDA (Nvidia)
|
|
63
|
-
- ROCm (AMD)
|
|
64
|
-
- oneAPI / XPU (Intel GPU)
|
|
65
|
-
- Sinon CPU.
|
|
66
|
-
|
|
67
|
-
Retour
|
|
68
|
-
------
|
|
69
|
-
torch.device
|
|
70
|
-
Le device optimal pour exécuter PyTorch selon le matériel détecté.
|
|
71
|
-
|
|
72
|
-
Notes
|
|
73
|
-
-----
|
|
74
|
-
- Sur ROCm, PyTorch expose l'alias "cuda", ce qui est normal.
|
|
75
|
-
- DirectML permet un fallback GPU universel sous Windows.
|
|
76
|
-
- Cette fonction ne lance aucun test de performance, elle se base uniquement
|
|
77
|
-
sur les backends disponibles dans l'installation PyTorch.
|
|
78
|
-
"""
|
|
79
|
-
|
|
80
|
-
os_name = platform.system().lower()
|
|
81
|
-
|
|
82
|
-
# =========== APPLE SILICON (macOS) ===========
|
|
83
|
-
if os_name == "darwin":
|
|
84
|
-
if torch.backends.mps.is_available():
|
|
85
|
-
return torch.device("mps")
|
|
86
|
-
|
|
87
|
-
# =========== WINDOWS ===========
|
|
88
|
-
if os_name == "windows":
|
|
89
|
-
# 1) CUDA
|
|
90
|
-
if torch.cuda.is_available():
|
|
91
|
-
return torch.device("cuda")
|
|
92
|
-
|
|
93
|
-
# =========== LINUX ===========
|
|
94
|
-
if os_name == "linux":
|
|
95
|
-
# 1) CUDA (Nvidia)
|
|
96
|
-
if torch.cuda.is_available():
|
|
97
|
-
return torch.device("cuda")
|
|
98
|
-
# 2) ROCm (AMD)
|
|
99
|
-
elif hasattr(torch.backends, "hip") and torch.backends.hip.is_available():
|
|
100
|
-
return torch.device("cuda")
|
|
101
|
-
|
|
102
|
-
# 3) Intel oneAPI / XPU
|
|
103
|
-
elif hasattr(torch, "xpu") and torch.xpu.is_available():
|
|
104
|
-
return torch.device("xpu")
|
|
105
|
-
|
|
106
|
-
# =========== Unknown OS ===========
|
|
107
|
-
return torch.device("cpu")
|
|
108
|
-
|
|
109
|
-
device = get_best_device()
|
|
110
|
-
|
|
111
|
-
def has_gcc():
|
|
112
|
-
"""Return True if GCC is installed and callable."""
|
|
113
|
-
try:
|
|
114
|
-
r = subprocess.run(
|
|
115
|
-
["gcc", "--version"],
|
|
116
|
-
stdout=subprocess.DEVNULL,
|
|
117
|
-
stderr=subprocess.DEVNULL
|
|
118
|
-
)
|
|
119
|
-
return r.returncode == 0
|
|
120
|
-
except FileNotFoundError:
|
|
121
|
-
return False
|
|
122
|
-
|
|
123
|
-
# --- Paramètres graphiques globaux ---
|
|
124
|
-
# Fond transparent et couleur gris uniforme
|
|
125
|
-
plt.rcParams['figure.facecolor'] = (0,0,0,0)
|
|
126
|
-
plt.rcParams['axes.facecolor'] = (0,0,0,0)
|
|
127
|
-
grey_color = "#888888"
|
|
128
|
-
|
|
129
|
-
# Style général du texte et axes
|
|
130
|
-
plt.rcParams['text.color'] = grey_color
|
|
131
|
-
plt.rcParams['axes.labelcolor'] = grey_color
|
|
132
|
-
plt.rcParams['xtick.color'] = grey_color
|
|
133
|
-
plt.rcParams['ytick.color'] = grey_color
|
|
134
|
-
plt.rcParams['axes.edgecolor'] = grey_color
|
|
135
|
-
plt.rcParams['axes.titlecolor'] = grey_color
|
|
136
|
-
|
|
137
|
-
# Activation de la grille globale
|
|
138
|
-
plt.rcParams['axes.grid'] = True
|
|
139
|
-
plt.rcParams['grid.color'] = grey_color
|
|
140
|
-
|
|
141
|
-
# --- Optimisations CUDA ---
|
|
142
|
-
# Accélération des convolutions et matmul
|
|
143
|
-
torch.backends.cudnn.benchmark = True # optimise selon les tailles de tenseurs
|
|
144
|
-
torch.backends.cudnn.enabled = True
|
|
145
|
-
torch.backends.cuda.matmul.allow_tf32 = True # autorise TF32 (plus rapide sur Ampere+)
|
|
146
|
-
torch.backends.cudnn.allow_tf32 = True
|
|
147
|
-
|
|
148
|
-
# Paramètres autograd
|
|
149
|
-
torch.autograd.set_detect_anomaly(False) # pas d'analyse lourde
|
|
150
|
-
torch.autograd.profiler.profile(enabled=False)
|
|
151
|
-
torch.use_deterministic_algorithms(False) # privilégie la performance à la reproductibilité stricte
|
|
152
|
-
|
|
153
|
-
torch._inductor.config.max_autotune = "max" # config max pour Torch-Inductor
|
|
154
|
-
|
|
155
|
-
# Constantes
|
|
156
|
-
pi = math.pi
|
|
157
|
-
e = math.e
|
|
158
|
-
|
|
159
|
-
# --- Liste des normalisations/activations disponibles ---
|
|
160
|
-
norm_list = {
|
|
161
|
-
"Relu": nn.ReLU(),
|
|
162
|
-
"LeakyRelu": nn.LeakyReLU(),
|
|
163
|
-
"ELU": nn.ELU(),
|
|
164
|
-
"SELU": nn.SELU(),
|
|
165
|
-
"GELU": nn.GELU(),
|
|
166
|
-
"Sigmoid": nn.Sigmoid(),
|
|
167
|
-
"Tanh": nn.Tanh(),
|
|
168
|
-
"Hardtanh": nn.Hardtanh(),
|
|
169
|
-
"Softplus": nn.Softplus(),
|
|
170
|
-
"Softsign": nn.Softsign()
|
|
171
|
-
}
|
|
172
|
-
norms = lambda: print("""
|
|
173
|
-
"Relu"
|
|
174
|
-
"LeakyRelu"
|
|
175
|
-
"ELU"
|
|
176
|
-
"SELU"
|
|
177
|
-
"GELU"
|
|
178
|
-
"Sigmoid"
|
|
179
|
-
"Tanh"
|
|
180
|
-
"Hardtanh"
|
|
181
|
-
"Softplus"
|
|
182
|
-
"Softsign"
|
|
183
|
-
"""
|
|
184
|
-
)
|
|
185
|
-
|
|
186
|
-
# --- Liste des fonctions de perte disponibles ---
|
|
187
|
-
crit_list = {
|
|
188
|
-
"MSE": nn.MSELoss(),
|
|
189
|
-
"L1": nn.L1Loss(),
|
|
190
|
-
"SmoothL1": nn.SmoothL1Loss(),
|
|
191
|
-
"Huber": nn.HuberLoss(),
|
|
192
|
-
"CrossEntropy": nn.CrossEntropyLoss(),
|
|
193
|
-
"KLDiv": nn.KLDivLoss(),
|
|
194
|
-
"PoissonNLL": nn.PoissonNLLLoss(),
|
|
195
|
-
"MultiLabelSoftMargin": nn.MultiLabelSoftMarginLoss(),
|
|
196
|
-
}
|
|
197
|
-
crits = lambda: print("""
|
|
198
|
-
"MSE"
|
|
199
|
-
"L1"
|
|
200
|
-
"SmoothL1"
|
|
201
|
-
"Huber"
|
|
202
|
-
"CrossEntropy"
|
|
203
|
-
"KLDiv"
|
|
204
|
-
"PoissonNLL"
|
|
205
|
-
"MultiLabelSoftMargin"
|
|
206
|
-
"""
|
|
207
|
-
)
|
|
208
|
-
|
|
209
|
-
# --- Création d’un dictionnaire d’optimiseurs ---
|
|
210
|
-
def optim_list(self, learning_rate):
|
|
211
|
-
"""
|
|
212
|
-
Renvoie un dictionnaire d’optimiseurs PyTorch pour le MLP donné.
|
|
213
|
-
|
|
214
|
-
Paramètres
|
|
215
|
-
----------
|
|
216
|
-
self : objet
|
|
217
|
-
Objet contenant `self.model` à optimiser.
|
|
218
|
-
learning_rate : float
|
|
219
|
-
Taux d’apprentissage à appliquer aux optimisateurs.
|
|
220
|
-
|
|
221
|
-
Retour
|
|
222
|
-
------
|
|
223
|
-
dict
|
|
224
|
-
Dictionnaire {nom_optimiseur : instance_optimiseur}.
|
|
225
|
-
"""
|
|
226
|
-
return {
|
|
227
|
-
"Adadelta": optim.Adadelta(self.model.parameters(), lr=learning_rate),
|
|
228
|
-
"Adafactor": optim.Adafactor(self.model.parameters(), lr=learning_rate),
|
|
229
|
-
"Adam": optim.Adam(self.model.parameters(), lr=learning_rate),
|
|
230
|
-
"AdamW": optim.AdamW(self.model.parameters(), lr=learning_rate),
|
|
231
|
-
"Adamax": optim.Adamax(self.model.parameters(), lr=learning_rate),
|
|
232
|
-
"ASGD": optim.ASGD(self.model.parameters(), lr=learning_rate),
|
|
233
|
-
"NAdam": optim.NAdam(self.model.parameters(), lr=learning_rate),
|
|
234
|
-
"RAdam": optim.RAdam(self.model.parameters(), lr=learning_rate),
|
|
235
|
-
"RMSprop": optim.RMSprop(self.model.parameters(), lr=learning_rate),
|
|
236
|
-
"Rprop": optim.Rprop(self.model.parameters(), lr=learning_rate),
|
|
237
|
-
"SGD": optim.SGD(self.model.parameters(), lr=learning_rate)
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
optims = lambda: print("""
|
|
241
|
-
"Adadelta"
|
|
242
|
-
"Adafactor"
|
|
243
|
-
"Adam"
|
|
244
|
-
"AdamW"
|
|
245
|
-
"Adamax"
|
|
246
|
-
"ASGD"
|
|
247
|
-
"NAdam"
|
|
248
|
-
"RAdam"
|
|
249
|
-
"RMSprop"
|
|
250
|
-
"Rprop"
|
|
251
|
-
"SGD"
|
|
252
|
-
"""
|
|
253
|
-
)
|
|
254
|
-
|
|
255
|
-
# --- Fonctions utilitaires ---
|
|
256
|
-
def rglen(list):
|
|
257
|
-
"""
|
|
258
|
-
Renvoie un range correspondant aux indices d’une liste.
|
|
259
|
-
|
|
260
|
-
Paramètres
|
|
261
|
-
----------
|
|
262
|
-
list : list-like
|
|
263
|
-
Objet dont on souhaite obtenir les indices.
|
|
264
|
-
|
|
265
|
-
Retour
|
|
266
|
-
------
|
|
267
|
-
range
|
|
268
|
-
Range Python de 0 à len(list)-1.
|
|
269
|
-
"""
|
|
270
|
-
return range(len(list))
|
|
271
|
-
|
|
272
|
-
def tensorise(obj):
|
|
273
|
-
"""
|
|
274
|
-
Convertit un objet en tenseur PyTorch float32 et l’envoie sur le device global.
|
|
275
|
-
|
|
276
|
-
Paramètres
|
|
277
|
-
----------
|
|
278
|
-
obj : array-like, list, np.ndarray, torch.Tensor
|
|
279
|
-
Objet à convertir en tenseur.
|
|
280
|
-
|
|
281
|
-
Retour
|
|
282
|
-
------
|
|
283
|
-
torch.Tensor
|
|
284
|
-
Tenseur float32 sur le device global (CPU ou GPU).
|
|
285
|
-
|
|
286
|
-
Notes
|
|
287
|
-
-----
|
|
288
|
-
- Harmonise les types pour MLP et autres traitements PyTorch.
|
|
289
|
-
- Assure que les données sont compatibles avec les opérations GPU/CPU.
|
|
290
|
-
"""
|
|
291
|
-
return torch.as_tensor(obj, dtype=torch.float32, device=device)
|
|
292
|
-
|
|
293
|
-
def fPrintDoc(obj):
|
|
294
|
-
"""
|
|
295
|
-
Crée une fonction anonyme qui affiche le docstring d'un objet.
|
|
296
|
-
|
|
297
|
-
Paramètres
|
|
298
|
-
----------
|
|
299
|
-
obj : object
|
|
300
|
-
Tout objet Python possédant un attribut `__doc__`.
|
|
301
|
-
|
|
302
|
-
Retour
|
|
303
|
-
------
|
|
304
|
-
function
|
|
305
|
-
Une fonction sans argument. Lorsqu'on l'appelle, elle affiche
|
|
306
|
-
le docstring de l'objet passé.
|
|
307
|
-
|
|
308
|
-
Exemple
|
|
309
|
-
-------
|
|
310
|
-
>>> def ma_fonction():
|
|
311
|
-
... '''Ceci est le docstring.'''
|
|
312
|
-
... pass
|
|
313
|
-
>>> print_doc = fPrintDoc(ma_fonction)
|
|
314
|
-
>>> print_doc()
|
|
315
|
-
Ceci est le docstring.
|
|
316
|
-
"""
|
|
317
|
-
return lambda: print(obj.__doc__)
|
|
318
|
-
|
|
319
|
-
torch.cuda.empty_cache()
|
NeuralNetworks/Image.py
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
# NeuralNetworksBeta - Multi-Layer Perceptrons avec encodage Fourier
|
|
2
|
-
# Copyright (C) 2025 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 *
|
|
9
|
-
|
|
10
|
-
def image_from_url(url, img_size=256):
|
|
11
|
-
"""
|
|
12
|
-
Télécharge une image depuis une URL, la redimensionne et prépare les
|
|
13
|
-
données pour l'entraînement d'un MLP pixel-wise.
|
|
14
|
-
|
|
15
|
-
Cette fonction retourne :
|
|
16
|
-
- `img_array` : image RGB sous forme de tableau NumPy (H, W, 3), pour affichage.
|
|
17
|
-
- `inputs` : coordonnées normalisées (x, y) de chaque pixel, sous forme de tenseur (H*W, 2).
|
|
18
|
-
- `outputs` : valeurs RGB cibles pour chaque pixel, sous forme de tenseur (H*W, 3).
|
|
19
|
-
|
|
20
|
-
Paramètres
|
|
21
|
-
----------
|
|
22
|
-
url : str
|
|
23
|
-
URL de l'image à télécharger.
|
|
24
|
-
img_size : int, optionnel
|
|
25
|
-
Taille finale carrée de l'image (img_size x img_size). Par défaut 256.
|
|
26
|
-
|
|
27
|
-
Retours
|
|
28
|
-
-------
|
|
29
|
-
img_array : numpy.ndarray of shape (H, W, 3)
|
|
30
|
-
Image sous forme de tableau NumPy, valeurs normalisées entre 0 et 1.
|
|
31
|
-
inputs : torch.Tensor of shape (H*W, 2)
|
|
32
|
-
Coordonnées normalisées des pixels pour l'entrée du MLP.
|
|
33
|
-
outputs : torch.Tensor of shape (H*W, 3)
|
|
34
|
-
Valeurs RGB cibles pour chaque pixel, pour la sortie du MLP.
|
|
35
|
-
|
|
36
|
-
Notes
|
|
37
|
-
-----
|
|
38
|
-
- La fonction utilise `PIL` pour le traitement de l'image et `torchvision.transforms`
|
|
39
|
-
pour la conversion en tenseur normalisé.
|
|
40
|
-
- Les coordonnées sont normalisées dans [0, 1] pour une utilisation optimale
|
|
41
|
-
avec des MLP utilisant Fourier Features ou activations standard.
|
|
42
|
-
- Les tenseurs `inputs` et `outputs` sont prêts à être envoyés sur GPU si nécessaire.
|
|
43
|
-
"""
|
|
44
|
-
|
|
45
|
-
# --- Téléchargement et ouverture de l'image ---
|
|
46
|
-
response = requests.get(url)
|
|
47
|
-
img = Image.open(BytesIO(response.content)).convert("RGB")
|
|
48
|
-
|
|
49
|
-
# --- Redimensionnement et conversion en tenseur normalisé ---
|
|
50
|
-
transform = Compose([
|
|
51
|
-
Resize((img_size, img_size)),
|
|
52
|
-
ToTensor() # Donne un tenseur (3, H, W) normalisé entre 0 et 1
|
|
53
|
-
])
|
|
54
|
-
img_tensor = transform(img)
|
|
55
|
-
|
|
56
|
-
# Récupération de la hauteur et largeur
|
|
57
|
-
h, w = img_tensor.shape[1:]
|
|
58
|
-
|
|
59
|
-
# Conversion en tableau NumPy (H, W, 3) pour affichage
|
|
60
|
-
img_array = img_tensor.permute(1, 2, 0).numpy()
|
|
61
|
-
|
|
62
|
-
# --- Création d'une grille normalisée des coordonnées des pixels ---
|
|
63
|
-
x_coords = torch.linspace(0, 1, w)
|
|
64
|
-
y_coords = torch.linspace(0, 1, h)
|
|
65
|
-
x_grid, y_grid = torch.meshgrid(x_coords, y_coords, indexing="ij")
|
|
66
|
-
|
|
67
|
-
# Flatten de la grille pour former les entrées du MLP : shape (H*W, 2)
|
|
68
|
-
inputs = torch.stack([x_grid.flatten(), y_grid.flatten()], dim=-1)
|
|
69
|
-
|
|
70
|
-
# Extraction des valeurs RGB comme sorties cibles : shape (H*W, 3)
|
|
71
|
-
outputs = img_tensor.view(3, -1).permute(1, 0)
|
|
72
|
-
|
|
73
|
-
return img_array, inputs, outputs
|
|
74
|
-
image_from_url.help = fPrintDoc(image_from_url)
|
|
75
|
-
|
|
76
|
-
def reshape(img_array, array):
|
|
77
|
-
"""
|
|
78
|
-
Reshape un tenseur plat de prédiction en image (H, W, 3) en utilisant
|
|
79
|
-
les dimensions de l’image originale.
|
|
80
|
-
|
|
81
|
-
Parameters
|
|
82
|
-
----------
|
|
83
|
-
img_array : np.ndarray of shape (H, W, 3)
|
|
84
|
-
Image originale servant de référence pour récupérer la hauteur (H)
|
|
85
|
-
et la largeur (W).
|
|
86
|
-
array : tensor-like or ndarray of shape (H*W, 3)
|
|
87
|
-
Tableau plat contenant les valeurs RGB prédites pour chaque pixel.
|
|
88
|
-
|
|
89
|
-
Returns
|
|
90
|
-
-------
|
|
91
|
-
np.ndarray of shape (H, W, 3)
|
|
92
|
-
Image reconstruite à partir du tableau plat.
|
|
93
|
-
|
|
94
|
-
Notes
|
|
95
|
-
-----
|
|
96
|
-
- Cette fonction ne modifie pas les valeurs, elle fait uniquement un reshape.
|
|
97
|
-
- Utile après une prédiction de type MLP qui renvoie un tableau (N, 3).
|
|
98
|
-
"""
|
|
99
|
-
|
|
100
|
-
# Récupération de la hauteur et largeur à partir de l’image originale
|
|
101
|
-
h, w = img_array.shape[:2]
|
|
102
|
-
|
|
103
|
-
# Reconstruction en image RGB
|
|
104
|
-
return array.reshape(h, w, 3)
|
|
105
|
-
reshape.help = fPrintDoc(reshape)
|