{"record":{"id":"5ce82563f98dd5e7","repo":"microsoft/qlib","slug":"model-is-not-fitted-yet-5ce825","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_nn.py","lineNumber":384,"sourceCode":"                data = data.values\n            data = torch.Tensor(data)\n        data = data.to(self.device)\n        preds = []\n        self.dnn_model.eval()\n        with torch.no_grad():\n            batch_size = 8096\n            for i in range(0, len(data), batch_size):\n                x = data[i : i + batch_size]\n                preds.append(self.dnn_model(x.to(self.device)).detach().reshape(-1))\n        if return_cpu:\n            preds = np.concatenate([pr.cpu().numpy() for pr in preds])\n        else:\n            preds = torch.cat(preds, axis=0)\n        return preds\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        x_test_pd = dataset.prepare(segment, col_set=\"feature\", data_key=DataHandlerLP.DK_I)\n        preds = self._nn_predict(x_test_pd)\n        return pd.Series(preds.reshape(-1), index=x_test_pd.index)\n\n    def save(self, filename, **kwargs):\n        with save_multiple_parts_file(filename) as model_dir:\n            model_path = os.path.join(model_dir, os.path.split(model_dir)[-1])\n            # Save model\n            torch.save(self.dnn_model.state_dict(), model_path)\n\n    def load(self, buffer, **kwargs):\n        with unpack_archive_with_buffer(buffer) as model_dir:\n            # Get model name\n            _model_name = os.path.splitext(list(filter(lambda x: x.startswith(\"model.bin\"), os.listdir(model_dir)))[0])[\n                0\n            ]\n            _model_path = os.path.join(model_dir, _model_name)\n            # Load model","sourceCodeStart":366,"sourceCodeEnd":402,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_nn.py#L366-L402","documentation":"Raised by DNNModelPytorch.predict() in qlib/contrib/model/pytorch_nn.py:384 when self.fitted is False. The fitted flag is only set to True after a successful fit() run completes; predict() refuses to prepare test data or run the DNN otherwise. It is the standard qlib Model guard against inference before training.","triggerScenarios":"Calling model.predict(dataset, segment='test') on a fresh DNNModelPytorch instance without calling fit(); calling predict after a fit() run that raised an exception partway through (fitted stays False); loading a model object from a pickle whose fit never finished.","commonSituations":"Notebook experimentation where the fit cell errored (OOM, empty dataset) but the predict cell is still run; running record/predict tasks in a qlib workflow with 'only' segments misconfigured so fit is skipped; restoring a saved session incorrectly.","solutions":["Call model.fit(dataset) to completion before model.predict(dataset, segment).","If fit() is failing, fix that first (check the earlier traceback, e.g. empty-data or device errors) — fitted only becomes True on success.","For inference-only use of a saved model, restore it via its save/load round-trip (load sets fitted state) instead of a never-fitted instance."],"exampleFix":"model = DNNModelPytorch(**kwargs)\nmodel.fit(dataset)          # must complete without error\npreds = model.predict(dataset, segment=\"test\")","handlingStrategy":"validation","validationCode":"if not getattr(model, \"fitted\", False):\n    raise RuntimeError(\"DNNModelPytorch must be fitted before predict(); run fit() first\")\npreds = model.predict(dataset, segment=\"test\")","typeGuard":"def is_fitted(model) -> bool:\n    return bool(getattr(model, \"fitted\", False))","tryCatchPattern":"try:\n    preds = model.predict(dataset, segment)\nexcept ValueError as e:\n    if \"not fitted\" in str(e):\n        model.fit(dataset)\n        preds = model.predict(dataset, segment)\n    else:\n        raise","preventionTips":["Always check model.fitted before predict() in scripts and notebooks.","Treat fit()-time exceptions as fatal: fitted stays False, so retrying predict alone cannot work.","Structure workflows so the model task runs before the record/predict task and fails loudly."],"tags":["qlib","pytorch","lifecycle","predict-before-fit"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}