4

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?

logankilpatrick
  • 13,148
  • 7
  • 44
  • 125
ecjb
  • 5,169
  • 12
  • 43
  • 79

1 Answers1

4

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])
Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • Many thanks for your answer @BogumilKaminski. In order to try your anwer, I should update to Flux 0.8.3 which I tried, without success (despite reinstalling and updating the package) and therefore posted another question there: https://stackoverflow.com/questions/57639110/julia-how-to-update-to-the-latest-version-of-a-package-i-e-flux – ecjb Aug 25 '19 at 14:30