You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: tutorials/tutorial1/tutorial.py
+14-20Lines changed: 14 additions & 20 deletions
Original file line number
Diff line number
Diff line change
@@ -87,7 +87,7 @@ class TimeSpaceODE(SpatialProblem, TimeDependentProblem):
87
87
88
88
# ### Write the problem class
89
89
#
90
-
# Once the `Problem` class is initialized, we need to represent the differential equation in **PINA**. In order to do this, we need to load the **PINA** operators from `pina.operators` module. Again, we'll consider Equation (1) and represent it in **PINA**:
90
+
# Once the `Problem` class is initialized, we need to represent the differential equation in **PINA**. In order to do this, we need to load the **PINA** operators from `pina.operator` module. Again, we'll consider Equation (1) and represent it in **PINA**:
91
91
92
92
# In[2]:
93
93
@@ -99,7 +99,7 @@ class TimeSpaceODE(SpatialProblem, TimeDependentProblem):
# Once we have defined the problem and generated the data we can start the modelling. Here we will choose a `FeedForward` neural network available in `pina.model`, and we will train using the `PINN` solver from `pina.solver`. We highlight that this training is fairly simple, for more advanced stuff consider the tutorials in the ***Physics Informed Neural Networks*** section of ***Tutorials***. For training we use the `Trainer` class from `pina.trainer`. Here we show a very short training and some method for plotting the results. Notice that by default all relevant metrics (e.g. MSE error during training) are going to be tracked using a `lightning` logger, by default `CSVLogger`. If you want to track the metric by yourself without a logger, use `pina.callbacks.MetricTracker`.
199
+
# Once we have defined the problem and generated the data we can start the modelling. Here we will choose a `FeedForward` neural network available in `pina.model`, and we will train using the `PINN` solver from `pina.solver`. We highlight that this training is fairly simple, for more advanced stuff consider the tutorials in the ***Physics Informed Neural Networks*** section of ***Tutorials***. For training we use the `Trainer` class from `pina.trainer`. Here we show a very short training and some method for plotting the results. Notice that by default all relevant metrics (e.g. MSE error during training) are going to be tracked using a `lightning` logger, by default `CSVLogger`. If you want to track the metric by yourself without a logger, use `pina.callback.MetricTracker`.
trainer=Trainer(solver=pinn, max_epochs=1500, callbacks=[MetricTracker()], accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
222
+
trainer=Trainer(solver=pinn, max_epochs=1500, logger=TensorBoardLogger('tutorial_logs'), accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
224
223
225
224
# train
226
225
trainer.train()
227
226
228
227
229
-
# After the training we can inspect trainer logged metrics (by default **PINA** logs mean square error residual loss). The logged metrics can be accessed online using one of the `Lightinig` loggers. The final loss can be accessed by `trainer.logged_metrics`
228
+
# After the training we can inspect trainer logged metrics (by default **PINA** logs mean square error residual loss). The logged metrics can be accessed online using one of the `Lightning` loggers. The final loss can be accessed by `trainer.logged_metrics`
# After the problem, the feed-forward neural network is defined, through the class `FeedForward`. This neural network takes as input the coordinates (in this case $x$ and $y$) and provides the unkwown field of the Poisson problem. The residual of the equations are evaluated at several sampling points (which the user can manipulate using the method `CartesianDomain_pts`) and the loss minimized by the neural network is the sum of the residuals.
92
98
#
93
-
# In this tutorial, the neural network is composed by two hidden layers of 10 neurons each, and it is trained for 1000 epochs. We use the `MetricTracker` class to track the metrics during training.
99
+
# In this tutorial, the neural network is composed by two hidden layers of 10 neurons each, and it is trained for 1000 epochs with a learning rate of 0.006 and $l_2$ weight regularization set to $10^{-8}$. These parameters can be modified as desired.
94
100
95
-
# In[4]:
101
+
# In[]:
96
102
97
103
98
104
# make model + solver + trainer
@@ -102,21 +108,58 @@ def poisson_sol(self, pts):
102
108
output_dimensions=len(problem.output_variables),
103
109
input_dimensions=len(problem.input_variables)
104
110
)
111
+
kwargs= {'lr':0.006, 'weight_decay':1e-8}
105
112
pinn=PINN(problem, model)
106
-
trainer=Trainer(pinn, max_epochs=1000, callbacks=[MetricTracker()], accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
) # we train on CPU and avoid model summary at beginning of training (optional)
107
121
108
122
# train
109
123
trainer.train()
110
124
111
125
112
-
# Now the `Plotter` class is used to plot the results.
126
+
# Now we plot the results using `matplotlib`.
113
127
# The solution predicted by the neural network is plotted on the left, the exact one is represented at the center and on the right the error between the exact and the predicted solutions is showed.
plt.tricontourf( # convert to torch tensor + flatten
151
+
spatial_samples.extract("x").tensor.flatten(),
152
+
spatial_samples.extract("y").tensor.flatten(),
153
+
field.tensor.flatten(),
154
+
)
155
+
plt.colorbar(), plt.tight_layout()
156
+
116
157
158
+
# In[ ]:
117
159
118
-
#plotter = Plotter()
119
-
#plotter.plot(solver=pinn)
160
+
161
+
plt.figure(figsize=(12, 6))
162
+
plot_solution(solver=pinn)
120
163
121
164
122
165
# ## Solving the problem with extra-features PINNs
@@ -135,7 +178,7 @@ def poisson_sol(self, pts):
135
178
#
136
179
# Finally, we perform the same training as before: the problem is `Poisson`, the network is composed by the same number of neurons and optimizer parameters are equal to previous test, the only change is the new extra feature.
137
180
138
-
# In[6]:
181
+
# In[]:
139
182
140
183
141
184
classSinSin(torch.nn.Module):
@@ -171,18 +214,25 @@ def forward(self, x):
171
214
extra_features=[SinSin()])
172
215
173
216
pinn_feat=PINN(problem, model_feat)
174
-
trainer_feat=Trainer(pinn_feat, max_epochs=1000, callbacks=[MetricTracker()], accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
enable_progress_bar=False,) # we train on CPU and avoid model summary at beginning of training (optional)
175
224
176
225
trainer_feat.train()
177
226
178
227
179
228
# The predicted and exact solutions and the error between them are represented below.
180
229
# We can easily note that now our network, having almost the same condition as before, is able to reach additional order of magnitudes in accuracy.
181
230
182
-
# In[7]:
231
+
# In[]:
183
232
184
233
185
-
#plotter.plot(solver=pinn_feat)
234
+
plt.figure(figsize=(12, 6))
235
+
plot_solution(solver=pinn_feat)
186
236
187
237
188
238
# ## Solving the problem with learnable extra-features PINNs
@@ -199,7 +249,7 @@ def forward(self, x):
199
249
# where $\alpha$ and $\beta$ are the abovementioned parameters.
200
250
# Their implementation is quite trivial: by using the class `torch.nn.Parameter` we cam define all the learnable parameters we need, and they are managed by `autograd` module!
201
251
202
-
# In[8]:
252
+
# In[]:
203
253
204
254
205
255
classSinSinAB(torch.nn.Module):
@@ -219,34 +269,46 @@ def forward(self, x):
219
269
220
270
221
271
# make model + solver + trainer
222
-
model_lean=FeedForwardWithExtraFeatures(
272
+
model_learn=FeedForwardWithExtraFeatures(
223
273
input_dimensions=len(problem.input_variables) +1, #we add one as also we consider the extra feature dimension
224
274
output_dimensions=len(problem.output_variables),
225
275
func=Softplus,
226
276
layers=[10, 10],
227
277
extra_features=[SinSinAB()])
228
278
229
-
pinn_lean=PINN(problem, model_lean)
230
-
trainer_learn=Trainer(pinn_lean, max_epochs=1000, accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
enable_progress_bar=False) # we train on CPU and avoid model summary at beginning of training (optional)
231
287
232
288
# train
233
289
trainer_learn.train()
234
290
235
291
236
292
# Umh, the final loss is not appreciabily better than previous model (with static extra features), despite the usage of learnable parameters. This is mainly due to the over-parametrization of the network: there are many parameter to optimize during the training, and the model in unable to understand automatically that only the parameters of the extra feature (and not the weights/bias of the FFN) should be tuned in order to fit our problem. A longer training can be helpful, but in this case the faster way to reach machine precision for solving the Poisson problem is removing all the hidden layers in the `FeedForward`, keeping only the $\alpha$ and $\beta$ parameters of the extra feature.
237
293
238
-
# In[9]:
294
+
# In[]:
239
295
240
296
241
297
# make model + solver + trainer
242
-
model_lean=FeedForwardWithExtraFeatures(
298
+
model_learn=FeedForwardWithExtraFeatures(
243
299
layers=[],
244
300
func=Softplus,
245
301
output_dimensions=len(problem.output_variables),
246
302
input_dimensions=len(problem.input_variables)+1,
247
303
extra_features=[SinSinAB()])
248
-
pinn_learn=PINN(problem, model_lean)
249
-
trainer_learn=Trainer(pinn_learn, max_epochs=1000, callbacks=[MetricTracker()], accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
enable_progress_bar=False) # we train on CPU and avoid model summary at beginning of training (optional)
250
312
251
313
# train
252
314
trainer_learn.train()
@@ -257,20 +319,14 @@ def forward(self, x):
257
319
#
258
320
# We conclude here by showing the graphical comparison of the unknown field and the loss trend for all the test cases presented here: the standard PINN, PINN with extra features, and PINN with learnable extra features.
259
321
260
-
# In[10]:
261
-
262
-
263
-
#plotter.plot(solver=pinn_learn)
264
-
265
-
266
322
# Let us compare the training losses for the various types of training
0 commit comments