Fit the Prophet model. This sets self.params to contain the fitted model parameters. It is a dictionary parameter names as keys and the following items: k (Mx1 array): M posterior samples of the initial slope. m (Mx1 array): The initial intercept.
(self, df, **kwargs)
| 1189 | ) |
| 1190 | |
| 1191 | def fit(self, df, **kwargs): |
| 1192 | """Fit the Prophet model. |
| 1193 | |
| 1194 | This sets self.params to contain the fitted model parameters. It is a |
| 1195 | dictionary parameter names as keys and the following items: |
| 1196 | k (Mx1 array): M posterior samples of the initial slope. |
| 1197 | m (Mx1 array): The initial intercept. |
| 1198 | delta (MxN array): The slope change at each of N changepoints. |
| 1199 | beta (MxK matrix): Coefficients for K seasonality features. |
| 1200 | sigma_obs (Mx1 array): Noise level. |
| 1201 | Note that M=1 if MAP estimation. |
| 1202 | |
| 1203 | Parameters |
| 1204 | ---------- |
| 1205 | df: pd.DataFrame containing the history. Must have columns ds (date |
| 1206 | type) and y, the time series. If self.growth is 'logistic', then |
| 1207 | df must also have a column cap that specifies the capacity at |
| 1208 | each ds. |
| 1209 | kwargs: Additional arguments passed to the optimizing or sampling |
| 1210 | functions in Stan. |
| 1211 | |
| 1212 | Returns |
| 1213 | ------- |
| 1214 | The fitted Prophet object. |
| 1215 | """ |
| 1216 | if self.history is not None: |
| 1217 | raise Exception('Prophet object can only be fit once. ' |
| 1218 | 'Instantiate a new object.') |
| 1219 | |
| 1220 | model_inputs = self.preprocess(df, **kwargs) |
| 1221 | initial_params = self.calculate_initial_params(model_inputs.K) |
| 1222 | |
| 1223 | dat = dataclasses.asdict(model_inputs) |
| 1224 | stan_init = dataclasses.asdict(initial_params) |
| 1225 | |
| 1226 | if self.history['y'].min() == self.history['y'].max() and \ |
| 1227 | (self.growth == 'linear' or self.growth == 'flat'): |
| 1228 | self.params = stan_init |
| 1229 | self.params['sigma_obs'] = 1e-9 |
| 1230 | for par in self.params: |
| 1231 | self.params[par] = np.array([self.params[par]]) |
| 1232 | elif self.mcmc_samples > 0: |
| 1233 | self.params = self.stan_backend.sampling(stan_init, dat, self.mcmc_samples, **kwargs) |
| 1234 | else: |
| 1235 | self.params = self.stan_backend.fit(stan_init, dat, **kwargs) |
| 1236 | |
| 1237 | self.stan_fit = self.stan_backend.stan_fit |
| 1238 | # If no changepoints were requested, replace delta with 0s |
| 1239 | if len(self.changepoints) == 0: |
| 1240 | # Fold delta into the base rate k |
| 1241 | self.params['k'] = ( |
| 1242 | self.params['k'] + self.params['delta'].reshape(-1) |
| 1243 | ) |
| 1244 | self.params['delta'] = (np.zeros(self.params['delta'].shape) |
| 1245 | .reshape((-1, 1))) |
| 1246 | |
| 1247 | return self |
| 1248 |