Skip to content

Instantly share code, notes, and snippets.

@koaning
Created March 11, 2014 12:44
Show Gist options
  • Save koaning/9484895 to your computer and use it in GitHub Desktop.
Save koaning/9484895 to your computer and use it in GitHub Desktop.
this gist contains a small script that generates data and looks for suitable linear regression parameters
# define model
y = function(x){
return (2*x + 5 + rnorm(length(x)))
}
# generate data
X = rnorm(40)
df = data.frame(X, y(X))
ggplot(df, aes(X,y.X.))+geom_point()
# define costs function
costs = function(df, a, b){
return( min(sum((df[2] - df[1]*a - b )^2),10000) )
}
# find best value
axis = seq(0,7,by=0.1)
plotty = expand.grid(a=axis, b=axis)
for(i in 1:length(plotty$a)){
plotty$error[i] = costs(df, plotty$a[i], plotty$b[i])
}
ggplot( plotty, aes(x=a,y=b)) + geom_tile(aes(fill=error))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment