Skip to content

Util

read_tf_record

read_tf_record(
    path: Path,
    *,
    compressed: bool = True,
    process: Optional[
        Callable[[Example], Optional[Example]]
    ] = None,
    verbose: bool = False,
    threads: int = 20
) -> Data

Reads a TensorFlow Records data and return a dict of numpy arrays.

This method can be used to read TFRecord before applying YDF on it.

Warning: Reading examples in python is very slow. Consider providing paths to YDF directly (e.g. model.predict("record:" + path)) instead (~20x faster).

Usage example:

import ydf

# Load a dataset
ds = ydf.util.read_tf_record(path="/path/to/tfrecord")

# Apply some pre-processing
ds["my_label"] = np.log(ds["my_label"])

# Train a model
ydf.RandomForestLearner(label="my_label",
  task=ydf.Task.REGRESSION).train(ds)

This method requires for all the TF Examples to have the same features and for all the features to have the same type and number of values. If your TF Record encode missing values by skipping features, you can use the process argument to add missing values manually:

import math

def process(example: tf.train.Example):
  # Add missing values for categorical features.
  for key in ["feature_1", "feature_2]:
    if key not in example.features.feature:
      example.features.feature[key].bytes_list.value.append(b"")

  # Add missing values for numerical features.
  for key in ["feature_3", "feature_4]:
    if key not in example.features.feature:
      example.features.feature[key].float_list.value.append(math.nan)

  return example

read_ds = tf_example.read_tf_recordio(path, process=process)

Parameters:

  • path (Path) –

    Path or list of paths to TFRecord files. Supports sharded paths.

  • compressed (bool, default: True ) –

    Whether the TFRecord is compressed.

  • process (Optional[Callable[[Example], Optional[Example]]], default: None ) –

    Optional function to process each TF Example. Can be used to filter out some features or to fix some example values (e.g., to ensure all the example have consistent feature values).

  • verbose (bool, default: False ) –

    If True, print status of the dataset reading.

  • threads (int, default: 20 ) –

    Number of reading threads.

Returns:

  • Data –

    A dict of numpy arrays.

write_tf_record

write_tf_record(
    data: Data,
    *,
    path: Path,
    compressed: bool = True,
    process: Optional[Callable[[Example], Example]] = None,
    verbose: bool = False,
    threads: int = 20
) -> None

Writes a dict of numpy arrays into a TensorFlow Record.

This method can be used to prepare TFRecord for distributed training.

Usage example:

import ydf
import numpy as np

# Generate a dataset
dataset = {
    "f1": np.array([1, 2, 3]),
    "f2": np.array([1.1, 2.2, 3.3])}

# Write the dataset
ydf.util.write_tf_recordio(dataset, path="/path/to/tfrecord")

Parameters:

  • data (Data) –

    A dict of numpy arrays. Support sharded paths.

  • path (Path) –

    Path or list of paths to TFRecord files.

  • compressed (bool, default: True ) –

    Whether the TFRecord is compressed.

  • process (Optional[Callable[[Example], Example]], default: None ) –

    Optional function to process each TF Example.

  • verbose (bool, default: False ) –

    If True, print status of the dataset writing.

  • threads (int, default: 20 ) –

    Number of writing threads.

get_vertex_ai_cluster_spec

get_vertex_ai_cluster_spec(
    cluster_spec: Union[str, None] = None,
) -> VertexAIClusterSpec

Parses the Vertex AI cluster specification.

The cluster specification is a JSON string describing the nodes of the cluster. This specification is typically provided by Vertex AI as an environment variable.

Usage example:

In a train.py file runing in a Docker in Vertex AI.

# Gather the manager and workers configuration.
cluster_config = get_vertex_ai_cluster_spec()
print("cluster_config:", cluster_config)

if cluster_config.is_worker:
  # This machine is running a worker.
  ydf.start_worker(cluster_config.port)
  return

print("Train model with distribution")
learner = ydf.DistributedGradientBoostedTreesLearner(
    label=...,
    working_dir=...,
    workers=cluster_config.workers,
    resume_training=True,
)
model = learner.train(args.train_ds)

Parameters:

  • cluster_spec (Union[str, None], default: None ) –

    Cluster specification as a JSON string. If None, the CLUSTER_SPEC environment variable is used instead.

Returns:

VertexAIClusterSpec dataclass

VertexAIClusterSpec(
    workers: List[str], is_worker: bool, port: int
)

Description of the cluster for Vertex AI.

Attributes:

  • workers (List[str]) –

    List of IP addresses of the worker nodes.

  • is_worker (bool) –

    True if the current node is a worker node. False if it is the manager.

  • port (int) –

    Port number to use for communication between nodes.

is_worker instance-attribute

is_worker: bool

port instance-attribute

port: int

workers instance-attribute

workers: List[str]

LogBook

LogBook(
    directory: str,
    print_num_experiments: bool = True,
    mode: Mode = SQLITE,
    default_keys: Optional[ExperimentKey] = None,
)

A utility to key track of ML experiments.

Usage example:

# Build a log book. The pointed location might already contain results.
# Multiple log books can possibly use the same location at the same time
# (e.g. in different processes).
lb = LogBook(path="~/experiment")

# Create an experiment identifier.
key = {"param1": 1, "param2": "abc"}

# Check that the experiment does not already exist. In practice, you might
# simply want to skip already existing experiments.
assert not lb.exist(key)

# Create some fake results.
result = {"obs1": 2, "obs2": [1,2,3], "obs3": {"a":1} }

# Record the experiment results.
lb.new(key, result)

# Show at all the recorded experiments in a table.
lb.to_dataframe()
id  date  param1  param2  obs1  obs2     obs3
0   ***   1       abc     2     [1,2,3]  {"a":1}

# The keys of the identifier or the results do not have to be consistant.
# For example, we can record a new experiment with a new "param3" key.
lb.new({"param1": 1, "param2": "abc", "param3": 5}, result)
lb.to_dataframe()
id  date  param1  param2  params3   obs1  obs2     obs3
0   ***   1       abc     NA        2     [1,2,3]  {"a":1}
1   ***   1       abc     5         2     [1,2,3]  {"a":1}

# In the case the new key already implicitely existing (e.g. you forget to
# record it), you can specify key default values in the log book
# constructor. This way, displays and experiment queries remain consistant
# between your old and new experiments.
#
# Create a new log book with a default experiment key value.
lb = LogBook(path="~/experiment", default_keys={"param3":-1})
lb.to_dataframe()
id  date  param1  param2  params3   obs1  obs2     obs3
0   ***   1       abc     -1        2     [1,2,3]  {"a":1}
1   ***   1       abc     5         2     [1,2,3]  {"a":1}

# You can query subset of experiments. For example, the next line only show
# the experiment with param1=1.
lb.to_dataframe({"param1":1})

# Pandas's plot method makes it easy to plot results. For example, the
# following line plot the "obs3" for the experiments with param1=1.
lb.to_dataframe({"param1":1})["obs3"].plot()

Attributes: directory: Path to the directory containing the experiment data. print_num_experiments: If true, print the number of experiments when initializing the LogBook. mode: Backend used to store the experiment values. Only SQLITE is supported. default_keys: Dictionary of default keys for new experiments.

Initialize the log book in a directory.

add

add(key: ExperimentKey, result: ExperimentResult) -> None

Creates a new experiment.

Fails if the experiment exist already.

Parameters:

  • key (ExperimentKey) –

    Key of the experiment. A dictionary containing scalar values (float, str, int, bool) or composed objects (list, dict, set, tuple). Cannot contain the keys "id" or "timestamp".

  • result (ExperimentResult) –

    Result of the experiment. A dictionary containing scalar values (float, str, int, bool) or composed objects (list, dict, set, tuple).

count_key

count_key(key: ExperimentKey) -> int

Counts the number of occurrences of a given key.

exist

exist(key: ExperimentKey) -> bool

Tests if an existing exist.

keys

keys() -> List[ExperimentKey]

Lists the keys of all the recorded experiments.

num_experiments

num_experiments() -> int

Number of recoded experiments.

to_dataframe

to_dataframe(
    key_filter: Optional[ExperimentKey] = None,
) -> Any

Creates a Pandas Dataframe with all the experiments.

Parameters:

  • key_filter (Optional[ExperimentKey], default: None ) –

    If set, only return experiments with a key containing (i.e., super-set) "key_filter".

Returns:

  • Any –

    A dataframe with the experiments.

Raises:

  • ImportError –

    If Pandas is not installed.