Multi-backend deep learning framework providing a unified API for building and training neural networks across JAX, TensorFlow, PyTorch, and OpenVINO backends
—
Essential classes and functions that form the foundation of Keras, including model containers, layer base classes, input handling, and core data structures for building neural networks.
High-level model containers that organize layers into trainable neural networks with built-in training, evaluation, and prediction capabilities.
class Sequential:
"""
Linear stack of layers model.
Args:
layers (list, optional): List of layers to add to the model
name (str, optional): Name of the model
"""
def __init__(self, layers=None, name=None): ...
def add(self, layer):
"""Add a layer to the model."""
def compile(self, optimizer, loss=None, metrics=None, **kwargs):
"""Configure the model for training."""
def fit(self, x, y=None, batch_size=None, epochs=1, validation_data=None, **kwargs):
"""Train the model."""
def evaluate(self, x, y=None, batch_size=None, **kwargs):
"""Evaluate the model."""
def predict(self, x, batch_size=None, **kwargs):
"""Generate predictions."""
class Model:
"""
Functional API model for complex architectures.
Args:
inputs: Input tensor(s) or list of input tensors
outputs: Output tensor(s) or list of output tensors
name (str, optional): Name of the model
"""
def __init__(self, inputs, outputs, name=None): ...
def compile(self, optimizer, loss=None, metrics=None, **kwargs):
"""Configure the model for training."""
def fit(self, x, y=None, batch_size=None, epochs=1, validation_data=None, **kwargs):
"""Train the model."""
def evaluate(self, x, y=None, batch_size=None, **kwargs):
"""Evaluate the model."""
def predict(self, x, batch_size=None, **kwargs):
"""Generate predictions."""
def summary(self, line_length=None, positions=None, print_fn=None):
"""Print model architecture summary."""Foundation class for all neural network layers providing common functionality for parameter management, computation, and serialization.
class Layer:
"""
Base class for all neural network layers.
Args:
trainable (bool): Whether layer weights should be updated during training
name (str, optional): Name of the layer
dtype (str, optional): Data type for layer computations
"""
def __init__(self, trainable=True, name=None, dtype=None, **kwargs): ...
def call(self, inputs, training=None, mask=None):
"""Forward pass computation (must be implemented by subclasses)."""
def build(self, input_shape):
"""Build layer parameters based on input shape."""
def add_weight(self, name, shape, dtype=None, initializer='zeros',
regularizer=None, trainable=None):
"""Add a weight variable to the layer."""
def get_weights(self):
"""Get layer weights as NumPy arrays."""
def set_weights(self, weights):
"""Set layer weights from NumPy arrays."""
def get_config(self):
"""Get layer configuration for serialization."""Functions and classes for defining model inputs with proper shape and type specifications.
def Input(shape, batch_size=None, name=None, dtype=None, sparse=None):
"""
Create an input tensor for a Keras model.
Args:
shape (tuple): Shape of the input (excluding batch dimension)
batch_size (int, optional): Batch size
name (str, optional): Name of the input
dtype (str, optional): Data type
sparse (bool, optional): Whether input is sparse
Returns:
KerasTensor: Input tensor
"""
class InputSpec:
"""
Specification for layer inputs.
Args:
dtype (str, optional): Expected data type
shape (tuple, optional): Expected shape
ndim (int, optional): Expected number of dimensions
max_ndim (int, optional): Maximum number of dimensions
min_ndim (int, optional): Minimum number of dimensions
axes (dict, optional): Axes constraints
"""
def __init__(self, dtype=None, shape=None, ndim=None,
max_ndim=None, min_ndim=None, axes=None): ...Essential data structures for tensor operations and variable management in neural networks.
class KerasTensor:
"""
Symbolic tensor for building computation graphs.
Attributes:
shape (tuple): Tensor shape
dtype (str): Data type
name (str): Tensor name
"""
shape: tuple
dtype: str
name: str
class Variable:
"""
Trainable variable that persists across calls.
Args:
initializer: Initial value or initializer function
shape (tuple, optional): Variable shape
dtype (str, optional): Data type
trainable (bool): Whether variable should be trained
name (str, optional): Variable name
"""
def __init__(self, initializer, shape=None, dtype=None,
trainable=True, name=None): ...
def assign(self, value):
"""Update variable value."""
def assign_add(self, delta):
"""Add delta to variable value."""
def assign_sub(self, delta):
"""Subtract delta from variable value."""
def numpy(self):
"""Get variable value as NumPy array."""Utility functions for model construction, cloning, and serialization.
def clone_model(model, input_tensors=None):
"""
Clone a Keras model.
Args:
model: Model to clone
input_tensors (list, optional): New input tensors
Returns:
Model: Cloned model
"""
def model_from_json(json_string, custom_objects=None):
"""
Load model architecture from JSON.
Args:
json_string (str): JSON string containing model config
custom_objects (dict, optional): Custom objects for deserialization
Returns:
Model: Reconstructed model
"""import keras
from keras import layers
# Create and configure a sequential model
model = keras.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)),
layers.Dropout(0.2),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Display model architecture
model.summary()import keras
from keras import layers
# Define inputs
inputs = keras.Input(shape=(28, 28, 1))
# Build the model graph
x = layers.Conv2D(32, 3, activation='relu')(inputs)
x = layers.MaxPooling2D(2)(x)
x = layers.Conv2D(64, 3, activation='relu')(x)
x = layers.MaxPooling2D(2)(x)
x = layers.Flatten()(x)
x = layers.Dense(64, activation='relu')(x)
outputs = layers.Dense(10, activation='softmax')(x)
# Create the model
model = keras.Model(inputs=inputs, outputs=outputs)
# Compile and train
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, validation_data=(x_val, y_val))import keras
from keras import layers
class CustomDenseLayer(layers.Layer):
def __init__(self, units, activation=None, **kwargs):
super().__init__(**kwargs)
self.units = units
self.activation = keras.activations.get(activation)
def build(self, input_shape):
self.w = self.add_weight(
name='kernel',
shape=(input_shape[-1], self.units),
initializer='glorot_uniform',
trainable=True
)
self.b = self.add_weight(
name='bias',
shape=(self.units,),
initializer='zeros',
trainable=True
)
super().build(input_shape)
def call(self, inputs):
x = keras.ops.matmul(inputs, self.w) + self.b
return self.activation(x) if self.activation else x
def get_config(self):
config = super().get_config()
config.update({
'units': self.units,
'activation': keras.activations.serialize(self.activation)
})
return config
# Use the custom layer
model = keras.Sequential([
CustomDenseLayer(64, activation='relu', input_shape=(784,)),
CustomDenseLayer(10, activation='softmax')
])Install with Tessl CLI
npx tessl i tessl/pypi-keras-nightly