Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Tensorflow Tfjs Generic Utils

From Leeroopedia


Knowledge Sources
Domains Deep_Learning, Layers_API
Last Updated 2026-02-10 06:00 GMT

Overview

The generic_utils.ts module provides general-purpose utility functions used throughout the TensorFlow.js Layers codebase. It includes Python-compatible list operations, string case conversion, Keras object serialization/deserialization, assertion helpers, type validation, array utilities, and a debounce function. This module is the TypeScript port of Keras's utils/generic_utils.py.

The most important functions are serializeKerasObject() and deserializeKerasObject(), which handle model serialization and deserialization by converting between class instances and configuration dictionaries.

Code Reference

Source Location

tfjs-layers/src/utils/generic_utils.ts (View on GitHub)

Key Signatures

// List operations
export function pyListRepeat(value: any, numValues: number): any[];
export function toList<T>(x: T | T[]): T[];
export function singletonOrArray<T>(xs: T[]): T | T[];
export function unique<T>(xs: T[]): T[];

// Assertions
export function assert(val: boolean, message?: string): void;
export function assertPositiveInteger(value: number | number[], name: string): void;

// Counting
export function count<T>(array: T[], reference: T): number;

// String conversion
export function toSnakeCase(name: string): string;
export function toCamelCase(identifier: string): string;

// Keras serialization
export function serializeKerasObject(instance: serialization.Serializable): serialization.ConfigDictValue;
export function deserializeKerasObject(
    identifier: string | serialization.ConfigDict,
    moduleObjects?: object,
    customObjects?: object,
    printableModuleName?: string,
    fastWeightInit?: boolean
): any;

// Type checking
export function checkStringTypeUnionValue(values: string[], label: string, value: string): void;
export function checkArrayTypeAndLength(x: any, expectedType: string, minLength?: number, maxLength?: number): boolean;
export function isObjectEmpty(obj: {}): boolean;

// Other utilities
export function objectListUid(objs: any | any[]): string;
export function numberCompare(a: number, b: number): number;
export function reverseNumberCompare(a: number, b: number): number;
export function stringToDType(dtype: string): DataType;
export function stringsEqual(xs: string[], ys: string[]): boolean;
export function formatAsFriendlyString(value: any): string;
export function debounce<T>(f: Function, waitMs: number, nowFunc?: Function): Function;
export function mapActivationToFusedKernel(activationName: string): fused.Activation;
export function getCartesianProductOfValues(...arrayOfValues: PossibleValues): PossibleValues;

Import

import * as generic_utils from '../utils/generic_utils';
// or specific imports:
import { deserializeKerasObject, toSnakeCase, unique } from '../utils/generic_utils';

I/O Contract

Serialization

  • serializeKerasObject: Takes a serialization.Serializable instance, returns a ConfigDictValue with className and config fields. Returns null for null/undefined input.
  • deserializeKerasObject: Takes a string identifier or config dictionary, plus module/custom object maps. Returns the reconstructed object. Supports fromConfig static method on classes or direct instantiation. Handles global custom objects and NDArray scalar conversion.

String Conversion

  • toSnakeCase: Converts camelCase to snake_case. Private names (starting with _) are prefixed with private.
  • toCamelCase: Converts snake_case to camelCase. Short or non-snake_case strings pass through unchanged.

List Utilities

  • pyListRepeat: Replicates a value or array numValues times, matching Python's [value] * n behavior.
  • unique: Returns deduplicated array preserving insertion order.
  • toList: Wraps a non-array value in an array; passes arrays through unchanged.

Activation Mapping

  • mapActivationToFusedKernel: Maps layer activation identifiers ('relu', 'linear', 'elu') to fused kernel activation names. Returns null for unsupported activations.

Usage Examples

import * as generic_utils from './utils/generic_utils';

// Serialize a Keras object
const config = generic_utils.serializeKerasObject(myLayer);
// { className: 'Dense', config: { units: 32, activation: 'relu', ... } }

// Deserialize from config
const layer = generic_utils.deserializeKerasObject(config, moduleObjects);

// Case conversion
generic_utils.toSnakeCase('batchNormalization'); // 'batch_normalization'
generic_utils.toCamelCase('batch_normalization'); // 'batchNormalization'

// List repeat (Python-style)
generic_utils.pyListRepeat([1, 2], 3); // [1, 2, 1, 2, 1, 2]
generic_utils.pyListRepeat(0, 4);      // [0, 0, 0, 0]

// Unique elements
generic_utils.unique([1, 2, 2, 3, 1]); // [1, 2, 3]

// Debounce
const debouncedFn = generic_utils.debounce(expensiveCompute, 100);

Related Pages

Page Connections

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