|
| 1 | +using DiffEqFlux, OrdinaryDiffEq, Flux, CUDA |
| 2 | +CUDA.allowscalar(false) # Makes sure no slow operations are occuring |
| 3 | + |
| 4 | +# Generate Data |
| 5 | +u0 = Float32[2.0; 0.0] |
| 6 | +datasize = 30 |
| 7 | +tspan = (0.0f0, 1.5f0) |
| 8 | +tsteps = range(tspan[1], tspan[2], length = datasize) |
| 9 | +function trueODEfunc(du, u, p, t) |
| 10 | + true_A = [-0.1 2.0; -2.0 -0.1] |
| 11 | + du .= ((u.^3)'true_A)' |
| 12 | +end |
| 13 | +prob_trueode = ODEProblem(trueODEfunc, u0, tspan) |
| 14 | +# Make the data into a GPU-based array if the user has a GPU |
| 15 | +ode_data = gpu(solve(prob_trueode, Tsit5(), saveat = tsteps)) |
| 16 | + |
| 17 | + |
| 18 | +dudt2 = FastChain((x, p) -> x.^3, |
| 19 | + FastDense(2, 50, tanh), |
| 20 | + FastDense(50, 2)) |
| 21 | +u0 = Float32[2.0; 0.0] |> gpu |
| 22 | +p = initial_params(dudt2) |> gpu |
| 23 | +prob_neuralode = NeuralODE(dudt2, tspan, Tsit5(), saveat = tsteps) |
| 24 | + |
| 25 | +function predict_neuralode(p) |
| 26 | + gpu(prob_neuralode(u0,p)) |
| 27 | +end |
| 28 | +function loss_neuralode(p) |
| 29 | + pred = predict_neuralode(p) |
| 30 | + loss = sum(abs2, ode_data .- pred) |
| 31 | + return loss, pred |
| 32 | +end |
| 33 | +# Callback function to observe training |
| 34 | +list_plots = [] |
| 35 | +iter = 0 |
| 36 | +callback = function (p, l, pred; doplot = false) |
| 37 | + global list_plots, iter |
| 38 | + if iter == 0 |
| 39 | + list_plots = [] |
| 40 | + end |
| 41 | + iter += 1 |
| 42 | + display(l) |
| 43 | + # plot current prediction against data |
| 44 | + plt = scatter(tsteps, Array(ode_data[1,:]), label = "data") |
| 45 | + scatter!(plt, tsteps, Array(pred[1,:]), label = "prediction") |
| 46 | + push!(list_plots, plt) |
| 47 | + if doplot |
| 48 | + display(plot(plt)) |
| 49 | + end |
| 50 | + return false |
| 51 | +end |
| 52 | +result_neuralode = DiffEqFlux.sciml_train(loss_neuralode, p, |
| 53 | + ADAM(0.05), cb = callback, |
| 54 | + maxiters = 300) |
0 commit comments