|
| 1 | +program test_metrics |
| 2 | + use iso_fortran_env, only: stderr => error_unit |
| 3 | + use nf, only: dense, input, network, sgd, mse |
| 4 | + implicit none |
| 5 | + type(network) :: net |
| 6 | + logical :: ok = .true. |
| 7 | + |
| 8 | + ! Minimal 2-layer network |
| 9 | + net = network([ & |
| 10 | + input(1), & |
| 11 | + dense(1) & |
| 12 | + ]) |
| 13 | + |
| 14 | + training: block |
| 15 | + real :: x(1), y(1) |
| 16 | + real :: tolerance = 1e-3 |
| 17 | + integer :: n |
| 18 | + integer, parameter :: num_iterations = 1000 |
| 19 | + real :: quadratic_loss, mse_metric |
| 20 | + real, allocatable :: metrics(:,:) |
| 21 | + |
| 22 | + x = [0.1234567] |
| 23 | + y = [0.7654321] |
| 24 | + |
| 25 | + do n = 1, num_iterations |
| 26 | + call net % forward(x) |
| 27 | + call net % backward(y) |
| 28 | + call net % update(sgd(learning_rate=1.)) |
| 29 | + if (all(abs(net % predict(x) - y) < tolerance)) exit |
| 30 | + end do |
| 31 | + |
| 32 | + ! Returns only one metric, based on the default loss function (quadratic). |
| 33 | + metrics = net % evaluate(reshape(x, [1, 1]), reshape(y, [1, 1])) |
| 34 | + quadratic_loss = metrics(1,1) |
| 35 | + |
| 36 | + if (.not. all(shape(metrics) == [1, 1])) then |
| 37 | + write(stderr, '(a)') 'metrics array is the correct shape (1, 1).. failed' |
| 38 | + ok = .false. |
| 39 | + end if |
| 40 | + |
| 41 | + ! Returns two metrics, one from the loss function and another specified by the user. |
| 42 | + metrics = net % evaluate(reshape(x, [1, 1]), reshape(y, [1, 1]), metric=mse()) |
| 43 | + |
| 44 | + if (.not. all(shape(metrics) == [1, 2])) then |
| 45 | + write(stderr, '(a)') 'metrics array is the correct shape (1, 2).. failed' |
| 46 | + ok = .false. |
| 47 | + end if |
| 48 | + |
| 49 | + mse_metric = metrics(1,2) |
| 50 | + |
| 51 | + if (.not. all(metrics < 1e-5)) then |
| 52 | + write(stderr, '(a)') 'value for all metrics is expected.. failed' |
| 53 | + ok = .false. |
| 54 | + end if |
| 55 | + |
| 56 | + if (.not. metrics(1,1) == quadratic_loss) then |
| 57 | + write(stderr, '(a)') 'first metric should be the same as that of the loss function.. failed' |
| 58 | + ok = .false. |
| 59 | + end if |
| 60 | + |
| 61 | + end block training |
| 62 | + |
| 63 | + if (ok) then |
| 64 | + print '(a)', 'test_metrics: All tests passed.' |
| 65 | + else |
| 66 | + write(stderr, '(a)') 'test_metrics: One or more tests failed.' |
| 67 | + stop 1 |
| 68 | + end if |
| 69 | + |
| 70 | +end program test_metrics |
0 commit comments