Skip to content

Instantly share code, notes, and snippets.

@ololobus
Last active March 17, 2017 09:58
Show Gist options
  • Save ololobus/d28f7a27bf641c67548395de825c8701 to your computer and use it in GitHub Desktop.
Save ololobus/d28f7a27bf641c67548395de825c8701 to your computer and use it in GitHub Desktop.
Nonlinear (weighted) least-squares example in R
df <- read.csv("data.csv")
# Column as 'array'
x <- df$col1
y <- df$col2
# Random seed
# set.seed(20170227)
a_start <- 5000
b_start <- 0.5
m1 <- nls(y ~ a*(x - 0.5)^8, start=list(a=a_start), control=list(maxiter=5000))
# m2 <- nls(y ~ a*(2*(x - 0.5))^20, start=list(a=a_start), control=list(maxiter=5000))
m2 <- nls(y ~ a*(2*(x - b))^14, start=list(a=a_start, b=b_start), control=list(maxiter=5000))
y_test = 15000*(2*(x - 0.5))^20
# Fit params
m1
m2
# Get some estimation of fits
cor(y, predict(m1))
cor(y, y_test)
cor(y, predict(m2))
# Plot
plot(x, y)
# Params: lty - dash size, lwd - line width
lines(x, predict(m1), lty=2, lwd=3, col="red")
lines(x, predict(m2), lty=2, lwd=3, col="blue")
lines(x, y_test, lty=2, lwd=3, col="gray")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment