|
| 1 | +''' |
| 2 | +# Curve fitting in 1D with Fourier features |
| 3 | +
|
| 4 | +Here, a 1D curve fitting example is explored. Imagine, a synthetic data |
| 5 | +generated from \\\( \sin(x) \\\) over the range of \\\( [0, 2\pi] \\\). |
| 6 | +
|
| 7 | +To train a neural network model on this curve, you should first define a `Variable`. |
| 8 | +
|
| 9 | +A neural network with three layers, each containing 10 neurons, and with `tanh` activation function is then generated |
| 10 | +using the `Functional` class. |
| 11 | +
|
| 12 | +The target is imposed on the output using the `Data` class from `Constraint`, and passed to the `SciModel` to form a |
| 13 | +SciANN model. |
| 14 | +''' |
| 15 | + |
| 16 | +import numpy as np |
| 17 | +from sciann import Variable, Functional, SciModel, Parameter |
| 18 | +from sciann.constraints import Data, MinMax |
| 19 | +from sciann.utils.math import diff |
| 20 | +import sciann as sn |
| 21 | + |
| 22 | +sn.set_random_seed(1234) |
| 23 | +# Synthetic data generated from sin function over [0, 2pi] |
| 24 | +x_true = np.linspace(0, np.pi*2, 10000) |
| 25 | +y_true = np.sin(x_true) |
| 26 | + |
| 27 | +# The network inputs should be defined with Variable. |
| 28 | +x = Variable('x', dtype='float64') |
| 29 | +xf = sn.fourier(x, 10) |
| 30 | + |
| 31 | +# Each network is defined by Functional. |
| 32 | +y1 = sn.Field('y1', 10) |
| 33 | +y2 = sn.Field('y2', 10) |
| 34 | +y1, y2 = sn.Functional([y1,y2], xf, [10, 10, 10], 'tanh', output_activation='tanh') |
| 35 | + |
| 36 | +y = sn.Functional('y', [xf*y1, xf*y2]) |
| 37 | + |
| 38 | +d = Parameter(10.0, inputs=x, name='d') |
| 39 | + |
| 40 | +# Define the target (output) of your model. |
| 41 | +c1 = Data(y) |
| 42 | + |
| 43 | +L = d*diff(y, x, order=2) + y |
| 44 | + |
| 45 | +# The model is formed with input `x` and condition `c1`. |
| 46 | +model = SciModel(x, [c1, sn.PDE(L)]) |
| 47 | + |
| 48 | +# Tra: .train runs the optimization and finds the parameters. |
| 49 | +history = model.train( |
| 50 | + x_true, |
| 51 | + [y_true, 'zeros'], |
| 52 | + batch_size=32, |
| 53 | + epochs=100, |
| 54 | + adaptive_weights={"method": "NTK", "freq": 10}, |
| 55 | + log_parameters=[d] |
| 56 | +) |
| 57 | + |
| 58 | +# used to evaluate the model after the training. |
| 59 | +y_pred = y.eval(model, x_true) |
| 60 | +d_pred = d.eval(model, x_true) |
| 61 | + |
0 commit comments