Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Recommenders team Recommenders Prepare Hparams

From Leeroopedia


Knowledge Sources
Domains News Recommendation, Hyperparameter Management
Last Updated 2026-02-10 00:00 GMT

Overview

Concrete tool for loading, merging, and validating hyperparameters for neural news recommendation models from YAML configuration files and runtime keyword arguments.

Description

The prepare_hparams function is the primary entry point for constructing a validated HParams object. It performs the following steps:

  1. If a YAML file path is provided, it loads and flattens the configuration using load_yaml and flat_config from deeprec_utils.
  2. If no YAML file is provided, it starts with an empty dictionary.
  3. All keyword arguments are merged into the configuration, overriding any YAML-sourced values.
  4. The merged configuration is validated via check_nn_config, which verifies that all required parameters for the specified model_type are present and that the data_format is correct.
  5. Type checking is performed via check_type, ensuring integer, float, string, list, and boolean parameters have the correct types.
  6. The validated configuration is passed to create_hparams, which applies hard-coded defaults and returns an HParams object.

Usage

Call prepare_hparams after downloading the MIND dataset and before initializing the NRMSModel. The returned HParams object is passed directly to the model constructor.

Code Reference

Source Location

Signature

def prepare_hparams(yaml_file=None, **kwargs) -> HParams:
    """Prepare the model hyperparameters and check that all have the correct value.

    Args:
        yaml_file (str): YAML file as configuration.
        **kwargs: Additional hyperparameters to override YAML values.

    Returns:
        HParams: Hyperparameter object.
    """

Import

from recommenders.models.newsrec.newsrec_utils import prepare_hparams

I/O Contract

Parameter Type Description
yaml_file str or None Path to YAML configuration file; None to use only kwargs
wordEmb_file str (kwarg) Path to pre-trained word embedding numpy file
wordDict_file str (kwarg) Path to word dictionary pickle file
userDict_file str (kwarg) Path to user dictionary pickle file
epochs int (kwarg) Number of training epochs
batch_size int (kwarg) Training batch size
head_num int (kwarg) Number of attention heads in multi-head self-attention
head_dim int (kwarg) Dimension of each attention head
learning_rate float (kwarg) Optimizer learning rate
npratio int (kwarg) Negative-to-positive sampling ratio
title_size int (kwarg) Maximum number of words in news title
his_size int (kwarg) Maximum number of clicked news in user history
data_format str (kwarg) Data format identifier (e.g., "news" for NRMS)
support_quick_scoring bool (kwarg) Enable fast evaluation via pre-computed embeddings
Return Type Description
hparams HParams Validated hyperparameter object with all configuration values accessible as attributes

Usage Examples

from recommenders.models.newsrec.newsrec_utils import prepare_hparams
import os

yaml_file = os.path.join(data_path, "utils", "nrms.yaml")

hparams = prepare_hparams(
    yaml_file,
    wordEmb_file=os.path.join(data_path, "utils", "embedding.npy"),
    wordDict_file=os.path.join(data_path, "utils", "word_dict.pkl"),
    userDict_file=os.path.join(data_path, "utils", "uid2index.pkl"),
    batch_size=32,
    epochs=5,
    head_num=20,
    head_dim=20,
    learning_rate=0.0001,
    npratio=4,
    title_size=30,
    his_size=50,
    data_format="news",
    support_quick_scoring=True,
)

# Access hyperparameters as attributes
print(hparams.batch_size)    # 32
print(hparams.head_num)      # 20
print(hparams.learning_rate) # 0.0001

Dependencies

  • yaml — Via recommenders.models.deeprec.deeprec_utils.load_yaml for parsing YAML configuration files
  • recommenders.models.deeprec.deeprec_utils.flat_config — Flattens nested YAML configuration into a single dictionary
  • recommenders.models.deeprec.deeprec_utils.HParams — Hyperparameter container class

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment