Flux.jl/test/gradients.jl

34 lines
831 B
Julia
Raw Normal View History

2019-03-07 01:33:02 +00:00
using Flux, Test
2019-03-08 15:00:32 +00:00
function ngradient(f, xs::AbstractArray...)
grads = zero.(xs)
for (x, Δ) in zip(xs, grads), i in 1:length(x)
δ = sqrt(eps())
tmp = x[i]
x[i] = tmp - δ/2
y1 = f(xs...)
x[i] = tmp + δ/2
y2 = f(xs...)
x[i] = tmp
Δ[i] = (y2-y1)/δ
end
return grads
end
gradcheck(f, xs...) =
all(isapprox.(ngradient(f, xs...),
gradient(f, xs...), rtol = 1e-5, atol = 1e-5))
2017-08-23 00:43:45 +00:00
2018-02-05 18:10:02 +00:00
gradtest(f, xs::AbstractArray...) = gradcheck((xs...) -> sum(sin.(f(xs...))), xs...)
2018-08-11 09:51:07 +00:00
gradtest(f, dims...) = gradtest(f, rand.(Float64, dims)...)
2017-08-23 00:43:45 +00:00
2019-07-02 06:46:24 +00:00
@testset "Zygote" begin
2017-09-03 21:10:35 +00:00
@test gradtest(Flux.mse, rand(5,5), rand(5, 5))
2017-10-17 16:36:18 +00:00
@test gradtest(Flux.crossentropy, rand(5,5), rand(5, 5))
2017-09-03 21:10:35 +00:00
2019-03-08 15:00:32 +00:00
# @test gradtest(x -> Flux.normalise(x), rand(4,3))
# @test gradtest(x -> Flux.normalise(x, dims = 2), rand(3,4))
2019-02-08 12:43:50 +00:00
2017-09-07 03:09:32 +00:00
end