{"record":{"id":"ad2e9d4e6a1d26eb","repo":"microsoft/qlib","slug":"model-is-not-fitted-yet-ad2e9d","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_hist.py","lineNumber":332,"sourceCode":"\n            if val_score > best_score:\n                best_score = val_score\n                stop_steps = 0\n                best_epoch = step\n                best_param = copy.deepcopy(self.HIST_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.HIST_model.load_state_dict(best_param)\n        torch.save(best_param, save_path)\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        stock2concept_matrix = np.load(self.stock2concept)\n        stock_index = np.load(self.stock_index, allow_pickle=True).item()\n        df_test = dataset.prepare(segment, col_set=\"feature\", data_key=DataHandlerLP.DK_I)\n        df_test[\"stock_index\"] = 733\n        df_test[\"stock_index\"] = df_test.index.get_level_values(\"instrument\").map(stock_index)\n        stock_index_test = df_test[\"stock_index\"].values\n        stock_index_test[np.isnan(stock_index_test)] = 733\n        stock_index_test = stock_index_test.astype(\"int\")\n        df_test = df_test.drop([\"stock_index\"], axis=1)\n        index = df_test.index\n\n        self.HIST_model.eval()\n        x_values = df_test.values\n        preds = []\n\n        # organize the data into daily batches\n        daily_index, daily_count = self.get_daily_inter(df_test, shuffle=False)","sourceCodeStart":314,"sourceCodeEnd":350,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_hist.py#L314-L350","documentation":"HISTModel.predict raises this guard when self.fitted is still False. The fitted flag is only set to True after fit() completes its training loop, so predicting before a successful fit (or after a fit that crashed mid-way) is rejected.","triggerScenarios":"Calling model.predict(dataset) on a fresh HISTModel that never ran fit(), or after fit() raised an exception before setting self.fitted = True, or using a model instance reloaded from a pickled workflow where fit was never executed.","commonSituations":"Two-stage scripts where prediction runs in a separate process/model object than training; a fit() that failed early (e.g. empty data) but the caller ignores the exception and proceeds; refactoring code that splits train and infer.","solutions":["Call model.fit(dataset) successfully before model.predict(dataset)","If the exception from fit is being swallowed, fix the control flow so predict is unreachable on failure","To reuse trained weights without refitting, restore state and set model.fitted = True after loading the saved checkpoint with load_state_dict"],"exampleFix":"# before\nmodel = HISTModel()\npreds = model.predict(dataset)  # fitted is False\n\n# after\nmodel = HISTModel()\nmodel.fit(dataset)\npreds = model.predict(dataset)","handlingStrategy":"validation","validationCode":"if not getattr(model, \"fitted\", False):\n    raise RuntimeError(\"call model.fit(dataset) before predict\")","typeGuard":"def is_fitted(model) -> bool:\n    return bool(getattr(model, \"fitted\", False))","tryCatchPattern":"try:\n    preds = model.predict(dataset)\nexcept ValueError as e:\n    if \"not fitted\" in str(e):\n        model.fit(dataset)\n        preds = model.predict(dataset)\n    else:\n        raise","preventionTips":["Check model.fitted before predict in pipeline code","Never swallow fit() exceptions; make failure abort the run"],"tags":["qlib","lifecycle","predict-before-fit","state"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}