Created
April 23, 2013 03:52
-
-
Save theanti9/5440743 to your computer and use it in GitHub Desktop.
Create fit lines for data plots in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Linear func for varying theta0 and theta1 | |
h <- function(x, h0, h1){ | |
return (h0 + h1*x) | |
} | |
# Cost function for fitting data | |
J <- function(h0, h1, m, d) { | |
y = seq() | |
for (i in seq(m)) { | |
y[i] = (h(d[i,1], h0, h1) - d[i,2])^2 | |
} | |
return ((1/(2*m))*sum(y)) | |
} | |
# Minimize given a range ra, samplesize m and data 2 col matrix d | |
minimize <- function(ra, m, d) { | |
cur = 1000000000000000 | |
fi = 0 | |
fj = 0 | |
for (i in ra) { | |
for (j in ra) { | |
curj = J(i, j, m, d) | |
if (curj < cur) { | |
cur = curj | |
fi = i | |
fj = j | |
} | |
} | |
} | |
# Return the lowest cost and the theta0/theta1 pair that created it | |
return (c(cur, fi, fj)) | |
} | |
# Generate Y values for a sequence using H and the | |
# Returned/minimized theta0 and theta1 of minimize | |
genline <- function(min, max, theta0, theta1) { | |
y = seq(max-min) | |
for (i in seq(from=min, to=max)) y[i-min+1] = h(i, theta0, theta1) | |
return (y) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment