microsoft/qlib · error · ValueError
model is not fitted yet!
Error message
model is not fitted yet!
What it means
ALSTMTSModel.predict() first checks the self.fitted flag, which is set to True only after fit() completes its training loop. Calling predict() on a model whose fit() never ran (or raised before finishing) raises ValueError immediately, before any data is prepared. This guard prevents running an untrained, randomly-initialized network on test data.
Source
Thrown at qlib/contrib/model/pytorch_alstm_ts.py:289
stop_steps = 0
best_epoch = step
best_param = copy.deepcopy(self.ALSTM_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.ALSTM_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!")
dl_test = dataset.prepare(segment, 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.ALSTM_model.eval()
preds = []
for data in test_loader:
feature = data[:, :, 0:-1].to(self.device)
with torch.no_grad():
pred = self.ALSTM_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
- Call fit(dataset) successfully before predict(dataset).
- If fit() raised earlier, fix that error and rerun fit; fitted only becomes True at the end of a clean fit().
- If you meant to restore a trained model, reload its parameters and set model.fitted = True manually before predict().
Example fix
# before model = ALSTMTSModel(d_feat=6) model.predict(dataset) # ValueError # after model = ALSTMTSModel(d_feat=6) model.fit(dataset) model.predict(dataset)
Defensive patterns
Strategy: validation
Validate before calling
if not getattr(model, 'fitted', False):
raise RuntimeError('ALSTMTSModel is not fitted; call fit() before predict()') Type guard
def is_fitted(m) -> bool:
return bool(getattr(m, 'fitted', False)) Try / catch
try:
pred = model.predict(dataset)
except ValueError as e:
if 'not fitted' in str(e):
model.fit(dataset)
pred = model.predict(dataset)
else:
raise Prevention
- Treat a failed fit() as 'model unusable': check model.fitted before predict in pipeline code.
- Do not swallow exceptions from fit(); a half-trained model never sets fitted=True.
- When restoring saved models in a new process, reload weights and set fitted=True explicitly.
When it happens
Trigger: Instantiating ALSTMTSModel and calling predict(dataset) directly; calling predict() after a fit() that raised (empty data, bad metric, CUDA OOM) so fitted was never set; re-creating the model object in a new process without restoring a fitted state.
Common situations: Notebook workflows where the fit cell errored but later cells keep running; checkpoint-reload scripts that build a fresh model and forget to load weights or refit; an exception during fit() being swallowed by a bare try/except so the caller believes training succeeded.
Related errors
- model is not fitted yet!
- model is not fitted yet!
- model is not fitted yet!
- model is not fitted yet!
- model is not fitted yet!
AI-assisted analysis of microsoft/qlib@79633dd950 (2026-08-15).
Data as JSON: /api/errors/71ff803d59c1dad0.
Report an issue: GitHub.