microsoft/qlib · error · ValueError
model is not fitted yet!
Error message
model is not fitted yet!
What it means
The TS LSTM predict() checks self.fitted at entry; the flag flips True only at the very end of a successful fit(). Predicting beforehand raises ValueError('model is not fitted yet!') — no test data is prepared and no model eval occurs.
Source
Thrown at qlib/contrib/model/pytorch_lstm_ts.py:278
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):
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.LSTM_model.eval()
preds = []
for data in test_loader:
feature = data[:, :, 0:-1].to(self.device)
with torch.no_grad():
pred = self.LSTM_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
- Complete model.fit(dataset, evals_result) first; check for the 'best score: ... @ epoch' log line as confirmation.
- Fix any prior fit failure (its exception is the root cause; fitted remains False otherwise).
- Restoring a checkpoint: model.LSTM_model.load_state_dict(torch.load(save_path)); model.fitted = True; then call predict.
Example fix
# before model = LSTMModel(...) model.predict(dataset) # ValueError: model is not fitted yet! # after model = LSTMModel(...) model.fit(dataset, evals_result) model.predict(dataset)
Defensive patterns
Strategy: validation
Validate before calling
if not model.fitted:
raise RuntimeError("TS LSTM not fitted; run fit() first")
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
- Check model.fitted before predict in all workflow code.
- For checkpoint restore: load_state_dict then set fitted = True.
- Halt pipelines when fit() fails so predict never executes.
When it happens
Trigger: model.predict(dataset) where fit() never completed: never called, interrupted, or failed on empty data / NaNs / device errors before setting fitted.
Common situations: Pipeline scripts proceeding to backtest after a training step errored; resuming a session with a fresh model object; notebook cell ordering mistakes.
Related errors
- model is not fitted yet!
- model is not fitted yet!
- model is not fitted yet!
- optimizer {} is not supported!
- unknown loss `%s`
AI-assisted analysis of microsoft/qlib@79633dd950 (2026-08-15).
Data as JSON: /api/errors/6be3867dea3192f3.
Report an issue: GitHub.