This is my first attempt at fitting a non-linear model in R, so please bear with me.
Problem
I am trying to understand why nls()
is giving me this error:
Error in nlsModel(formula, mf, start, wts): singular gradient matrix at initial parameter estimates
Hypotheses
From what I've read from other questions here at SO it could either be because:
- my model is discontinuous, or
- my model is over-determined, or
- bad choice of starting parameter values
So I am calling for help on how to overcome this error. Can I change the model and still use nls()
, or do I need to use nls.lm
from the minpack.lm
package, as I have read elsewhere?
My approach
Here are some details about the model:
- the model is a discontinuous function, a kind of staircase type of function (see plot below)
- in general, the number of steps in the model can be variable yet they are fixed for a specific fitting event
MWE that shows the problem
Brief explanation of the MWE code
step_fn(x, min = 0, max = 1)
: function that returns1
within the interval (min
,max
] and0
otherwise; sorry about the name, I realize now it is not really a step function...interval_fn()
would be more appropriate I guess.staircase(x, dx, dy)
: a summation ofstep_fn()
functions.dx
is a vector of widths for the steps, i.e.max - min
, anddy
is the increment iny
for each step.staircase_formula(n = 1L)
: generates aformula
object that represents the model modeled by the functionstaircase()
(to be used with thenls()
function).- please do note that I use the
purrr
andglue
packages in the example below.
Code
step_fn <- function(x, min = 0, max = 1) {
y <- x
y[x > min & x <= max] <- 1
y[x <= min] <- 0
y[x > max] <- 0
return(y)
}
staircase <- function(x, dx, dy) {
max <- cumsum(dx)
min <- c(0, max[1:(length(dx)-1)])
step <- cumsum(dy)
purrr::reduce(purrr::pmap(list(min, max, step), ~ ..3 * step_fn(x, min = ..1, max = ..2)), `+`)
}
staircase_formula <- function(n = 1L) {
i <- seq_len(n)
dx <- sprintf("dx%d", i)
min <-
c('0', purrr::accumulate(dx[-n], .f = ~ paste(.x, .y, sep = " + ")))
max <- purrr::accumulate(dx, .f = ~ paste(.x, .y, sep = " + "))
lhs <- "y"
rhs <-
paste(glue::glue('dy{i} * step_fn(x, min = {min}, max = {max})'),
collapse = " + ")
sc_form <- as.formula(glue::glue("{lhs} ~ {rhs}"))
return(sc_form)
}
x <- seq(0, 10, by = 0.01)
y <- staircase(x, c(1,2,2,5), c(2,5,2,1)) + rnorm(length(x), mean = 0, sd = 0.2)
plot(x = x, y = y)
lines(x = x, y = staircase(x, dx = c(1,2,2,5), dy = c(2,5,2,1)), col="red")
my_data <- data.frame(x = x, y = y)
my_model <- staircase_formula(4)
params <- list(dx1 = 1, dx2 = 2, dx3 = 2, dx4 = 5,
dy1 = 2, dy2 = 5, dy3 = 2, dy4 = 1)
m <- nls(formula = my_model, start = params, data = my_data)
#> Error in nlsModel(formula, mf, start, wts): singular gradient matrix at initial parameter estimates
Any help is greatly appreciated.