microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

Raised by DNNModelPytorch.predict when called before a successful fit(). The class tracks a boolean `fitted` flag that is set to True only after training completes (including restoring best parameters); predict refuses to run on an unfitted model because there are no learned weights to load.

Source

Thrown at qlib/contrib/model/pytorch_general_nn.py:341

                if stop_steps >= self.early_stop:
                    self.logger.info("early stop")
                    break

        self.logger.info("best score: %.6lf @ %d epoch" % (best_score, best_epoch))
        self.dnn_model.load_state_dict(best_param)
        torch.save(best_param, save_path)

        if self.use_gpu:
            torch.cuda.empty_cache()

    def predict(
        self,
        dataset: Union[DatasetH, TSDatasetH],
        batch_size=None,
        n_jobs=None,
    ):
        if not self.fitted:
            raise ValueError("model is not fitted yet!")

        dl_test = dataset.prepare("test", col_set=["feature", "label"], data_key=DataHandlerLP.DK_I)
        self.logger.info(f"Test samples: {len(dl_test)}")

        if isinstance(dataset, TSDatasetH):
            dl_test.config(fillna_type="ffill+bfill")  # process nan brought by dataloader
            index = dl_test.get_index()
        else:
            # If it is a tabular, we convert the dataframe to numpy to be indexable by DataLoader
            index = dl_test.index
            dl_test = dl_test.values

        test_loader = DataLoader(dl_test, batch_size=self.batch_size, num_workers=self.n_jobs)
        self.dnn_model.eval()
        preds = []

        for data in test_loader:
            feature, _ = self._get_fl(data)

View on GitHub (pinned to 79633dd950)

Solutions

  1. Call model.fit(dataset) successfully before predict (fitted becomes True at the end of fit).
  2. If the model was trained previously, restore it rather than creating a new object; for nn models the recommended path is to rerun fit with the same save_path / or load the state dict and set model.fitted = True manually.
  3. In R workflows, ensure the task model is fitted inside the same run before the backtest record triggers predict.

Example fix

# before
model = DNNModelPytorch(**params)
preds = model.predict(dataset)  # ValueError: not fitted

# after
model = DNNModelPytorch(**params)
model.fit(dataset)
preds = model.predict(dataset)
Defensive patterns

Strategy: validation

Validate before calling

assert model.fitted, "call model.fit(dataset) (or restore a trained checkpoint) before predict()"

Type guard

def is_fitted(model) -> bool:
    return bool(getattr(model, "fitted", False))

Try / catch

try:
    preds = model.predict(dataset)
except ValueError as e:
    if "not fitted" in str(e):
        model.fit(dataset)
        preds = model.predict(dataset)
    else:
        raise

Prevention

When it happens

Trigger: Instantiating DNNModelPytorch and calling predict(dataset) directly; or fit() raising earlier (e.g. empty data, unknown loss) so fitted was never set, then predict being called in a workflow's backtest stage; loading a fresh model object instead of restoring a persisted one.

Common situations: Workflow scripts that run predict in a separate process without re-fitting or loading the saved checkpoint; silent fit failures swallowed upstream; re-instantiating the model for inference after training in a different session.

Related errors


AI-assisted analysis of microsoft/qlib@79633dd950 (2026-08-15). Data as JSON: /api/errors/8043e04533beb85b. Report an issue: GitHub.