denizyuret / AutoGrad.jl

Julia port of the Python autograd package.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

scalar-valued function error

fatihtalu opened this issue · comments

tan(x) = begin
    y = exp(-2x)
    return (1.0 - y) ./ (1.0 + y)
end

Out: tan (generic function with 1 method)

using Knet
dtan = grad(tan)

Out: (::gradfun) (generic function with 1 method)

println(dtan(1))

Out: 0.419974341614026

println(dtan(Any[1,2]))

Out: grad requires a scalar-valued function, got [0.761594, 0.964028]

Hi,

AutoGrad can handle functions with array inputs only when the output is scalar. In your example, the output is not scalar when the input is Any[1,2].

tan(Any[1,2])
2-element Array{Float64,1}:
 0.761594
 0.964028
x = 1; println(dtan(x))
x = 2; println(dtan(x))
x = 3; println(dtan(x))

0.419974341614026
0.07065082485316446
0.009866037165440192

x = linspace(1,3,3); println(dtan(x))

grad requires a scalar-valued function, got [0.761594, 0.964028, 0.995055]

Hi Fatih,

If you want to call your dtan function for each element in the x array, you should force it with broadcasting:

x = linspace(1, 3, 3); println(dtan.(x))
[0.419974, 0.0706508, 0.00986604]

Perfect!
Thank you very much.