0
$\begingroup$

I was trying to fit some data similar to sine, but always get weird results. So I searched and found this post.

Surprisingly, I can not reproduce the result. With below code

plot = DateListPlot[
   WeatherData["Toronto", 
    "MeanTemperature", {{2016, 1, 1}, {2019, 12, 31}, "Day"}, 
    Joined -> True]];
data = Cases[plot, Line[{x__}] -> x, Infinity];
mod = NonlinearModelFit[data, a*Sin[b*x + c] + d, {a, b, c, d}, x, 
   Method -> "NMinimize"];
Show[ListPlot[data], 
 Plot[mod[x], {x, Min[data[[All, 1]]], Max[data[[All, 1]]]}]]

What I got is

enter image description here

My Mathematica version is 12.2.0.0. What is wrong?

$\endgroup$
8
  • $\begingroup$ Look at the x-scale in the original post and your x-scale. NonlinearModelFit needs some reasonable starting values for the parameters, otherwise it sets them to 1. Instead of {a, b, c, d} write {a, {b, 10^-11}, c, d}. $\endgroup$
    – Domen
    Sep 17 at 8:35
  • $\begingroup$ @Domen Thank you for reply. But I got "NMinimize::parchange: Inappropriate parameter: InitialPoints -> {1,1/100000000000,1,1}, changed to Automatic." $\endgroup$
    – matheorem
    Sep 17 at 8:37
  • $\begingroup$ In this case drop the Method -> "NMinimize" option and use reasonable guesses for the parameters. a: (Quantile[data[[All, 2]], 0.95] - Quantile[data[[All, 2]], 0.05])/2. b: (2 \[Pi] 4)/Differences[MinMax[data[[All, 1]]]]. d: Mean[data[[All, 2]]]. Or {{a, 16}, {b, 2 10^-7}, c, {d, 10}}. Because a, c, and d are on wildly different scales than b, you'll just have to guess well to get convergence. $\endgroup$
    – JimB
    Sep 17 at 9:13
  • 1
    $\begingroup$ If one knew enough to roughly equalize the values of the parameters with a*Sin[10^(-7) b*x + c] + d, then using no initial values and Method -> "NMinimize" would work. $\endgroup$
    – JimB
    Sep 17 at 9:18
  • 2
    $\begingroup$ One more comment: this issue doesn't just pertain to Mathematica regression functions. The same thing happens with R, SAS, etc. Especially if the proposed model is based on theoretical considerations, then one should attempt to figure out reasonable starting values and modify the appearance of the model to have parameters of similar orders of magnitude to assist with the stability of the iterative procedures. $\endgroup$
    – JimB
    Sep 17 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.