microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

Thrown by TCNTSModel.predict when its `fitted` flag is False. The flag flips to True only after a fully successful fit() (including best-weight reload and checkpoint save), so prediction is blocked until the time-series TCN has actually been trained in this object's lifetime.

Source

Thrown at qlib/contrib/model/pytorch_tcn_ts.py:268

                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):
        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)
        dl_test.config(fillna_type="ffill+bfill")
        test_loader = DataLoader(dl_test, batch_size=self.batch_size, num_workers=self.n_jobs)
        self.TCN_model.eval()
        preds = []

        for data in test_loader:
            feature = data[:, :, 0:-1].to(self.device)

            with torch.no_grad():
                pred = self.TCN_model(feature.float()).detach().cpu().numpy()

            preds.append(pred)

        return pd.Series(np.concatenate(preds), index=dl_test.get_index())

View on GitHub (pinned to 79633dd950)

Solutions

  1. Run fit(ds, valid) to completion before predict(ds).
  2. Wrap fit/predict sequencing so predict is skipped when fit raises; fix the underlying fit failure.
  3. To reuse trained weights across processes, load the saved state dict into the model AND set model.fitted = True explicitly.

Example fix

# before
model = TCNTSModel(**kwargs)
model.predict(dataset)  # ValueError

# after
model = TCNTSModel(**kwargs)
model.fit(dataset, valid)
model.predict(dataset)
Defensive patterns

Strategy: validation

Validate before calling

if not getattr(model, "fitted", False):
    raise RuntimeError("TCNTSModel not fitted — run fit(ds, valid) before predict(ds)")

Type guard

def tcnts_ready(model) -> bool:
    return getattr(model, "fitted", False) and hasattr(model, "TCCN_model" if False else "TCN_model")

Try / catch

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

Prevention

When it happens

Trigger: Calling model.predict(dataset) on a TCNTSModel whose fit() was never invoked or raised before completion (e.g. during a failed retrain loop triggered by lowest_valid_performance).

Common situations: Long benchmark scripts where fit silently fails on one seed and the driver still calls predict; interactive sessions re-running only the predict cell; unpickling a model object saved before fit finished.

Related errors


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