microsoft/qlib · error · ValueError
model is not fitted yet!
Error message
model is not fitted yet!
What it means
Raised by GRUModel.predict when called before fit() completed. The `fitted` flag is set True only at the end of a successful fit; predict checks it first because the GRU weights are otherwise randomly initialized and predictions would be meaningless.
Source
Thrown at qlib/contrib/model/pytorch_gru.py:294
self.logger.info("early stop")
break
self.logger.info("best score: %.6lf @ %d" % (best_score, best_epoch))
self.gru_model.load_state_dict(best_param)
torch.save(best_param, save_path)
# Logging
rec = R.get_recorder()
for k, v_l in evals_result.items():
for i, v in enumerate(v_l):
rec.log_metrics(step=i, **{k: v})
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.gru_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.gru_model(x_batch).detach().cpu().numpy()View on GitHub (pinned to 79633dd950)
Solutions
- Call fit() to completion before predict().
- Persist the trained state (torch save_path) and reload the weights, then set model.fitted = True before predict.
- Wrap fit in code that aborts the pipeline on failure so predict is never reached unfitted.
Example fix
# before model = GRUModel(**params) model.predict(dataset) # ValueError # after model = GRUModel(**params) model.fit(dataset) model.predict(dataset)
Defensive patterns
Strategy: validation
Validate before calling
assert model.fitted, "fit the model or load a checkpoint before predict"
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)
model.predict(dataset)
else:
raise Prevention
- Check model.fitted before every predict call in inference scripts.
- Persist and reload checkpoints rather than re-instantiating models for prediction.
When it happens
Trigger: model.predict(dataset) on a fresh GRUModel; predict after a fit() that raised earlier (so fitted stayed False); using a new model instance in an inference-only script.
Common situations: Two-stage workflows (train script, then predict script) that re-instantiate the model instead of restoring it; exception swallowing in a training loop letting the code proceed to backtest.
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/62adf267835c94e4.
Report an issue: GitHub.