microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

LSTMModel.predict() guards on self.fitted, which is set True only after fit() completes (including early-stop checkpoint restore). Predicting before a successful fit raises ValueError('model is not fitted yet!') and nothing is read from the dataset.

Source

Thrown at qlib/contrib/model/pytorch_lstm.py:264

                stop_steps = 0
                best_epoch = step
                best_param = copy.deepcopy(self.lstm_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.lstm_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.lstm_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.lstm_model(x_batch).detach().cpu().numpy()
            preds.append(pred)

View on GitHub (pinned to 79633dd950)

Solutions

  1. Fit first: model.fit(dataset, evals_result), then predict(dataset).
  2. If fit failed, address that exception first; the fitted flag will not flip on partial runs.
  3. Warm-starting from a checkpoint: model.lstm_model.load_state_dict(torch.load(save_path)); model.fitted = True; then predict.

Example fix

# before
model = LSTMModel(...)
pred = model.predict(dataset)  # ValueError: model is not fitted yet!

# after
model = LSTMModel(...)
model.fit(dataset, evals_result)
pred = model.predict(dataset)
Defensive patterns

Strategy: validation

Validate before calling

if not model.fitted:
    raise RuntimeError("LSTMModel not fitted; call fit() first")
pred = model.predict(dataset)

Type guard

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

Try / catch

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

Prevention

When it happens

Trigger: model.predict(dataset) on an LSTMModel instance that never ran fit(), or whose fit() aborted (empty data, runtime error, manual interrupt) before the final self.fitted = True assignment.

Common situations: Backtest/risk records run after a silently failed training task; loading a pickled unfitted model; notebook cells executed out of order.

Related errors


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