{"record":{"id":"8b243cf46caa0f3d","repo":"microsoft/qlib","slug":"model-is-not-fitted-yet-8b243c","errorCode":null,"errorMessage":"model is not fitted yet!","messagePattern":"model is not fitted yet!","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_lstm.py","lineNumber":264,"sourceCode":"                stop_steps = 0\n                best_epoch = step\n                best_param = copy.deepcopy(self.lstm_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.lstm_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: DatasetH, segment: Union[Text, slice] = \"test\"):\n        if not self.fitted:\n            raise ValueError(\"model is not fitted yet!\")\n\n        x_test = dataset.prepare(segment, col_set=\"feature\", data_key=DataHandlerLP.DK_I)\n        index = x_test.index\n        self.lstm_model.eval()\n        x_values = x_test.values\n        sample_num = x_values.shape[0]\n        preds = []\n\n        for begin in range(sample_num)[:: self.batch_size]:\n            if sample_num - begin < self.batch_size:\n                end = sample_num\n            else:\n                end = begin + self.batch_size\n            x_batch = torch.from_numpy(x_values[begin:end]).float().to(self.device)\n            with torch.no_grad():\n                pred = self.lstm_model(x_batch).detach().cpu().numpy()\n            preds.append(pred)\n","sourceCodeStart":246,"sourceCodeEnd":282,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_lstm.py#L246-L282","documentation":"LSTMModel.predict() guards on self.fitted, which is set True only after fit() completes (including early-stop checkpoint restore). Predicting before a successful fit raises ValueError('model is not fitted yet!') and nothing is read from the dataset.","triggerScenarios":"model.predict(dataset) on an LSTMModel instance that never ran fit(), or whose fit() aborted (empty data, runtime error, manual interrupt) before the final self.fitted = True assignment.","commonSituations":"Backtest/risk records run after a silently failed training task; loading a pickled unfitted model; notebook cells executed out of order.","solutions":["Fit first: model.fit(dataset, evals_result), then predict(dataset).","If fit failed, address that exception first; the fitted flag will not flip on partial runs.","Warm-starting from a checkpoint: model.lstm_model.load_state_dict(torch.load(save_path)); model.fitted = True; then predict."],"exampleFix":"# before\nmodel = LSTMModel(...)\npred = model.predict(dataset)  # ValueError: model is not fitted yet!\n\n# after\nmodel = LSTMModel(...)\nmodel.fit(dataset, evals_result)\npred = model.predict(dataset)","handlingStrategy":"validation","validationCode":"if not model.fitted:\n    raise RuntimeError(\"LSTMModel not fitted; call fit() first\")\npred = model.predict(dataset)","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, evals_result)\n        model.predict(dataset)\n    else:\n        raise","preventionTips":["Gate predict on model.fitted in scripts and notebooks.","After checkpoint restore, set model.fitted = True manually.","Ensure fit() exceptions halt the pipeline before predict runs."],"tags":["pytorch","qlib","model-lifecycle","lstm","validation"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}