Skip to content

Instantly share code, notes, and snippets.

@dirmeier
Last active December 24, 2021 14:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirmeier/d9f53587e32f265d92b1039d5d9a168f to your computer and use it in GitHub Desktop.
Save dirmeier/d9f53587e32f265d92b1039d5d9a168f to your computer and use it in GitHub Desktop.
Gradient descent example in Julia.
using Gadfly
using Distributions
function df(x, y, b)
sum(- (y - x*b)' * x)
end
function gd()
rnorm = Normal()
x = rand(rnorm, 100)
y = x * 2 + rand(rnorm, 100)
b = 0.0
bold = 1.0
bvals = Float64[]
while (sum(abs(b - bold)) > 1e-10)
push!(bvals, b)
bold = b
der = df(x, y, bold)
b = b - 0.001 * der
end
plot(Guide.title("True beta: 2, est. beta: " * string(b)),
layer(x=x, y=y, Geom.point(), Theme(default_color=color("orange"))),
layer(x=x,y=x*bvals[1], Geom.line(), Theme(default_color=color("red"))),
layer(x=x,y=x*bvals[5], Geom.line(), Theme(default_color=color("red"))),
layer(x=x,y=x*b, Geom.line()))
end
Copy link

ghost commented Dec 24, 2021

Error - Undefvarerror - b not defined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment