ecjb
ecjb

Reputation: 5449

How to plot a function and its gradient/derivative using Flux.jl

I want to plot a function and its gradient using Flux.jl and Plots.jl

using Flux.Tracker
using Plots

f(x::Float64) = 3x^2 + 2x + 1
df(x::Float64) = Tracker.gradient(f, x)[1]
d2f(x::Float64) = Tracker.gradient(df, x)[1]

plot([f], -2, 2)
plot!([df], -2, 2)

I get:

ERROR: LoadError: MethodError: no method matching Float64(::Flux.Tracker.TrackedReal{Float64})
Closest candidates are:
  Float64(::Real, ::RoundingMode) where T<:AbstractFloat at rounding.jl:194
  Float64(::T<:Number) where T<:Number at boot.jl:741
  Float64(::Int8) at float.jl:60

So I guess that the idea would be to convert Flux.Tracker.TrackedReal{Float64} into a Float64. How could I do it?

Upvotes: 4

Views: 321

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69909

You can use the following (under Flux 0.8.3):

f(x::Float64) = 3x^2 + 2x + 1
df(x::Float64) = Tracker.data(Tracker.gradient(f, x, nest=true)[1])
d2f(x::Float64) = Tracker.data(Tracker.gradient(df, x, nest=true)[1])

Upvotes: 4

Related Questions