microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

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.

Source

Thrown at qlib/contrib/model/pytorch_nn.py:384

                data = data.values
            data = torch.Tensor(data)
        data = data.to(self.device)
        preds = []
        self.dnn_model.eval()
        with torch.no_grad():
            batch_size = 8096
            for i in range(0, len(data), batch_size):
                x = data[i : i + batch_size]
                preds.append(self.dnn_model(x.to(self.device)).detach().reshape(-1))
        if return_cpu:
            preds = np.concatenate([pr.cpu().numpy() for pr in preds])
        else:
            preds = torch.cat(preds, axis=0)
        return preds

    def predict(self, dataset: DatasetH, segment: Union[Text, slice] = "test"):
        if not self.fitted:
            raise ValueError("model is not fitted yet!")
        x_test_pd = dataset.prepare(segment, col_set="feature", data_key=DataHandlerLP.DK_I)
        preds = self._nn_predict(x_test_pd)
        return pd.Series(preds.reshape(-1), index=x_test_pd.index)

    def save(self, filename, **kwargs):
        with save_multiple_parts_file(filename) as model_dir:
            model_path = os.path.join(model_dir, os.path.split(model_dir)[-1])
            # Save model
            torch.save(self.dnn_model.state_dict(), model_path)

    def load(self, buffer, **kwargs):
        with unpack_archive_with_buffer(buffer) as model_dir:
            # Get model name
            _model_name = os.path.splitext(list(filter(lambda x: x.startswith("model.bin"), os.listdir(model_dir)))[0])[
                0
            ]
            _model_path = os.path.join(model_dir, _model_name)
            # Load model

View on GitHub (pinned to 79633dd950)

Solutions

  1. Call model.fit(dataset) to completion before model.predict(dataset, segment).
  2. If fit() is failing, fix that first (check the earlier traceback, e.g. empty-data or device errors) — fitted only becomes True on success.
  3. 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.

Example fix

model = DNNModelPytorch(**kwargs)
model.fit(dataset)          # must complete without error
preds = model.predict(dataset, segment="test")
Defensive patterns

Strategy: validation

Validate before calling

if not getattr(model, "fitted", False):
    raise RuntimeError("DNNModelPytorch must be fitted before predict(); run fit() first")
preds = model.predict(dataset, segment="test")

Type guard

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

Try / catch

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

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


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