{"record":{"id":"098dbced400bb268","repo":"microsoft/qlib","slug":"model-is-not-fitted-yet-098dbc","errorCode":null,"errorMessage":"model is not fitted yet!","messagePattern":"model is not fitted yet!","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_gru_ts.py","lineNumber":283,"sourceCode":"                stop_steps = 0\n                best_epoch = step\n                best_param = copy.deepcopy(self.GRU_model.state_dict())\n            else:\n                stop_steps += 1\n                if stop_steps >= self.early_stop:\n                    self.logger.info(\"early stop\")\n                    break\n\n        self.logger.info(\"best score: %.6lf @ %d\" % (best_score, best_epoch))\n        self.GRU_model.load_state_dict(best_param)\n        torch.save(best_param, save_path)\n\n        if self.use_gpu:\n            torch.cuda.empty_cache()\n\n    def predict(self, dataset):\n        if not self.fitted:\n            raise ValueError(\"model is not fitted yet!\")\n\n        dl_test = dataset.prepare(\"test\", col_set=[\"feature\", \"label\"], data_key=DataHandlerLP.DK_I)\n        dl_test.config(fillna_type=\"ffill+bfill\")\n        test_loader = DataLoader(dl_test, batch_size=self.batch_size, num_workers=self.n_jobs)\n        self.GRU_model.eval()\n        preds = []\n\n        for data in test_loader:\n            feature = data[:, :, 0:-1].to(self.device)\n\n            with torch.no_grad():\n                pred = self.GRU_model(feature.float()).detach().cpu().numpy()\n\n            preds.append(pred)\n\n        return pd.Series(np.concatenate(preds), index=dl_test.get_index())\n\n","sourceCodeStart":265,"sourceCodeEnd":301,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_gru_ts.py#L265-L301","documentation":"Raised by GRUModelTS.predict when called before a completed fit(). The `fitted` flag flips True only after training, best-parameter restore, and checkpoint save; predict refuses to run otherwise because the GRU weights are random.","triggerScenarios":"Calling predict(dataset) on a newly constructed GRUModelTS, or after fit() aborted (empty data, NaN collapse, early exception) leaving fitted False.","commonSituations":"Inference scripts that re-instantiate the model rather than loading the checkpoint; workflow backtest stage running after a silent training failure.","solutions":["Complete fit() before predict().","For inference-only sessions, load the saved state dict into GRU_model and set model.fitted = True before predict.","Fail the pipeline loudly on fit errors so predict is never reached."],"exampleFix":"# before\nmodel = GRUModelTS(**params)\nmodel.predict(dataset)  # ValueError\n\n# after\nmodel = GRUModelTS(**params)\nmodel.fit(dataset)\nmodel.predict(dataset)","handlingStrategy":"validation","validationCode":"assert model.fitted, \"fit GRUModelTS (or restore its checkpoint) before predict\"","typeGuard":"def is_fitted(model) -> bool:\n    return bool(getattr(model, \"fitted\", False))","tryCatchPattern":"try:\n    model.predict(dataset)\nexcept ValueError as e:\n    if \"not fitted\" in str(e):\n        model.fit(dataset)\n        model.predict(dataset)\n    else:\n        raise","preventionTips":["Gate predict on the fitted flag.","For inference-only sessions, load the saved state dict and set model.fitted = True."],"tags":["qlib","pytorch","lifecycle","state-error"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}