microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

Thrown by TCNModel.predict when the model's internal `fitted` flag is False. The flag is only set to True at the end of a successful fit() run, so this error means the TCN model state was never trained (or training crashed before completion) and there are no learned weights to predict with.

Source

Thrown at qlib/contrib/model/pytorch_tcn.py:274

                stop_steps = 0
                best_epoch = step
                best_param = copy.deepcopy(self.tcn_model.state_dict())
            else:
                stop_steps += 1
                if stop_steps >= self.early_stop:
                    self.logger.info("early stop")
                    break

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

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

    def predict(self, dataset: DatasetH, segment: Union[Text, slice] = "test"):
        if not self.fitted:
            raise ValueError("model is not fitted yet!")

        x_test = dataset.prepare(segment, col_set="feature", data_key=DataHandlerLP.DK_I)
        index = x_test.index
        self.tcn_model.eval()
        x_values = x_test.values
        sample_num = x_values.shape[0]
        preds = []

        for begin in range(sample_num)[:: self.batch_size]:
            if sample_num - begin < self.batch_size:
                end = sample_num
            else:
                end = begin + self.batch_size

            x_batch = torch.from_numpy(x_values[begin:end]).float().to(self.device)

            with torch.no_grad():
                pred = self.tcn_model(x_batch).detach().cpu().numpy()

View on GitHub (pinned to 79633dd950)

Solutions

  1. Call model.fit(dataset, evals_result) to completion before model.predict(dataset).
  2. If fit() appeared to run, inspect the traceback for an earlier failure — an aborted fit never sets fitted=True; fix that root cause and retrain.
  3. If the model was trained in a previous process, restore weights explicitly (e.g. torch.load of the saved state dict + set fitted=True) or persist the fitted object with pickle/joblib and load that instead.

Example fix

# before
model = TCNModel(**model_kwargs)
preds = model.predict(dataset)  # ValueError

# after
model = TCNModel(**model_kwargs)
model.fit(dataset, evals_result)
preds = model.predict(dataset)
Defensive patterns

Strategy: validation

Validate before calling

if not getattr(model, "fitted", False):
    raise RuntimeError("TCNModel must be fitted before predict — call model.fit(dataset) first")

Type guard

def is_fitted_tcn(model) -> bool:
    return getattr(model, "fitted", False) and getattr(model, "tcn_model", None) is not None

Try / catch

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

Prevention

When it happens

Trigger: Creating TCNModel and calling predict(dataset) without calling fit(dataset) first; or calling predict after a fit() that raised partway through (early crash, empty data, or an interrupt), leaving fitted=False.

Common situations: Notebook workflows where the fit cell fails (e.g. CUDA OOM, empty dataset) but later cells still run; loading a model object from a pickle without re-fitting; re-running a partial script after an exception.

Related errors


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