### Install Dependencies Source: https://keras.io/examples/vision/adamatch Installs the necessary libraries for the example, including SciPy and Pillow. ```bash pip install scipy pillow ``` -------------------------------- ### Install tensorflow-datasets Source: https://keras.io/examples/vision/nnclr Install the tensorflow-datasets library, which is required for this example. ```bash !pip install tensorflow-datasets ``` -------------------------------- ### Install Dependencies Source: https://keras.io/examples/timeseries/event_classification_for_payment_card_fraud_detection Installs the necessary libraries for the example, including Keras 3 and Temporian. Ensure you have these libraries before running the code. ```bash pip install temporian keras pandas tf-nightly scikit-learn -U ``` -------------------------------- ### Install TensorFlow Addons Source: https://keras.io/examples/vision/supervised-contrastive-learning Install the TensorFlow Addons library, which is required for this example. Run this command in your terminal. ```bash pip install tensorflow-addons ``` -------------------------------- ### Setup Imports and Environment Source: https://keras.io/examples/structured_data/structured_data_classification_with_feature_space Imports necessary libraries and sets the Keras backend. Ensure TensorFlow and Pandas are installed. ```python import os os.environ["KERAS_BACKEND"] = "tensorflow" import tensorflow as tf import pandas as pd import keras from keras.utils import FeatureSpace ``` -------------------------------- ### Install NetworkX Package Source: https://keras.io/examples/graph/node2vec_movielens This command installs the networkx package, which is required for this example. Ensure you have pip installed. ```bash pip install networkx ``` -------------------------------- ### Instantiate Model, Optimizer, Loss, and Metrics Source: https://keras.io/guides/writing_a_custom_training_loop_in_torch Prepare your model, optimizer, loss function, and metrics before starting the training loop. This setup is crucial for custom training. ```python # Get a fresh model model = get_model() # Instantiate an optimizer to train the model. optimizer = keras.optimizers.Adam(learning_rate=1e-3) # Instantiate a loss function. loss_fn = keras.losses.CategoricalCrossentropy(from_logits=True) # Prepare the metrics. train_acc_metric = keras.metrics.CategoricalAccuracy() val_acc_metric = keras.metrics.CategoricalAccuracy() ``` -------------------------------- ### Setup and Model Loading Source: https://keras.io/examples/vision/integrated_gradients Imports necessary libraries, loads the Xception model pre-trained on ImageNet, and prepares an example image for analysis. ```python import numpy as np import matplotlib.pyplot as plt from scipy import ndimage from IPython.display import Image, display import tensorflow as tf import keras from keras import layers from keras.applications import xception # Size of the input image img_size = (299, 299, 3) # Load Xception model with imagenet weights model = xception.Xception(weights="imagenet") # The local path to our target image img_path = keras.utils.get_file("elephant.jpg", "https://i.imgur.com/Bvro0YD.png") display(Image(img_path)) ``` -------------------------------- ### Setup Imports and Environment Source: https://keras.io/guides/custom_train_step_in_tensorflow Imports necessary libraries and sets the Keras backend to TensorFlow. This setup is required for running the guide. ```python import os # This guide can only be run with the TF backend. os.environ["KERAS_BACKEND"] = "tensorflow" import tensorflow as tf import keras from keras import layers import numpy as np ``` -------------------------------- ### Setup Keras Environment Source: https://keras.io/examples/structured_data/structured_data_classification_from_scratch Configure the Keras backend and import necessary libraries. Ensure you have pandas and keras installed. ```python import os os.environ["KERAS_BACKEND"] = "torch" # or torch, or tensorflow import pandas as pd import keras from keras import layers ``` -------------------------------- ### Install Dependencies Source: https://keras.io/keras_hub/guides/semantic_segmentation_deeplab_v3 Install the necessary Keras Hub and Keras packages. This is a prerequisite for running the guide. ```bash !pip install -q --upgrade keras-hub !pip install -q --upgrade keras ``` -------------------------------- ### Install TensorFlow Docs Source: https://keras.io/examples/generative/conditional_gan Installs the TensorFlow Docs library, which may be required for this example. Ensure you have TensorFlow 2.5 or higher. ```bash !pip install -q git+https://github.com/tensorflow/docs ``` -------------------------------- ### Launching TensorBoard for Metric Visualization Source: https://keras.io/examples/keras_recipes/sklearn_metric_callbacks This example shows the command to launch TensorBoard, which is used to visualize metrics logged during model training. Ensure TensorBoard is installed and the log directory is correctly specified. ```bash tensorboard --logdir=logs ``` -------------------------------- ### Instantiate Metrics and Optimizer Source: https://keras.io/guides/writing_a_custom_training_loop_in_tensorflow Instantiate the model, optimizer, loss function, and metrics before starting the training loop. This setup is required for tracking performance. ```python # Get a fresh model model = get_model() # Instantiate an optimizer to train the model. optimizer = keras.optimizers.Adam(learning_rate=1e-3) # Instantiate a loss function. loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) # Prepare the metrics. train_acc_metric = keras.metrics.SparseCategoricalAccuracy() val_acc_metric = keras.metrics.SparseCategoricalAccuracy() ``` -------------------------------- ### Example: Get and Inspect Model State Tree Source: https://keras.io/api/models/model This example demonstrates how to create a simple sequential model, compile and fit it, and then retrieve its state tree. The output shows the nested structure of trainable, non-trainable, optimizer, and metrics variables. ```python model = keras.Sequential([ keras.Input(shape=(1,), name="my_input"), keras.layers.Dense(1, activation="sigmoid", name="my_dense"), ], name="my_sequential") model.compile(optimizer="adam", loss="mse", metrics=["mae"]) model.fit(np.array([[1.0]]), np.array([[1.0]])) state_tree = model.get_state_tree() ``` -------------------------------- ### Setup Keras Environment Source: https://keras.io/examples/keras_recipes/sample_size_estimate Imports necessary libraries and sets up the Keras backend and random seed for reproducibility. Ensure TensorFlow is installed. ```python import os os.environ["KERAS_BACKEND"] = "tensorflow" import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import keras from keras import layers import tensorflow_datasets as tfds # Define seed and fixed variables seed = 42 keras.utils.set_random_seed(seed) AUTO = tf.data.AUTOTUNE ``` -------------------------------- ### Import Libraries and Setup Environment Source: https://keras.io/examples/graph/node2vec_movielens Imports necessary libraries and sets up the Keras backend and random seed for reproducibility. Ensure you have all listed libraries installed. ```python import os from collections import defaultdict import math import networkx as nx import random from tqdm import tqdm from zipfile import ZipFile from urllib.request import urlretrieve import numpy as np import pandas as pd import keras from keras import ops from keras import layers import matplotlib.pyplot as plt # Set seed for reproducibility keras.utils.set_random_seed(42) os.environ["KERAS_BACKEND"] = "jax" # "jax", "torch", "tensorflow" ``` -------------------------------- ### Install Dependencies Source: https://keras.io/examples/keras_recipes/approximating_non_function_mappings Install necessary libraries including Keras, JAX, and TensorFlow Probability. This setup is required for the Mixture Density Network example. ```python !pip install -q --upgrade jax tensorflow-probability[jax] keras ``` -------------------------------- ### Setup Environment and Imports Source: https://keras.io/examples/audio/speaker_recognition_using_cnn Imports necessary libraries and sets up the Keras backend. Ensure the dataset is downloaded and unzipped to the specified directory. ```python import os os.environ["KERAS_BACKEND"] = "tensorflow" import shutil import numpy as np import tensorflow as tf import keras from pathlib import Path from IPython.display import display, Audio # Get the data from https://www.kaggle.com/kongaevans/speaker-recognition-dataset/ # and save it to ./speaker-recognition-dataset.zip # then unzip it to ./16000_pcm_speeches ``` -------------------------------- ### Instantiate and Use QwenBackbone Source: https://keras.io/keras_hub/api/models/qwen/qwen_backbone Demonstrates how to instantiate a QwenBackbone model using a preset architecture and weights, or a randomly initialized model with custom configuration. Includes example input data preparation. ```python input_data = { "token_ids": np.ones(shape=(1, 12), dtype="int32"), "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]) } # Pretrained Qwen decoder. model = keras_hub.models.QwenBackbone.from_preset("qwen2.5_0.5b_en") model(input_data) # Randomly initialized Qwen decoder with custom config. model = keras_hub.models.QwenBackbone( vocabulary_size=10, hidden_dim=512, num_layers=2, num_query_heads=32, num_key_value_heads=8, intermediate_dim=1024, layer_norm_epsilon=1e-6, dtype="float32" ) model(input_data) ``` -------------------------------- ### Install TensorFlow Addons Source: https://keras.io/examples/keras_recipes/better_knowledge_distillation Install TensorFlow Addons, a dependency for this example, using pip. ```bash !pip install -q tensorflow-addons ``` -------------------------------- ### Install imgaug Library Source: https://keras.io/examples/vision/keypoint_detection Install the imgaug library for data augmentation. This is a required dependency for the example. ```bash !pip install -q -U imgaug ``` -------------------------------- ### Install Dependencies Source: https://keras.io/examples/nlp/neural_machine_translation_with_keras_hub Installs the necessary libraries for the machine translation example, including rouge-score and keras-hub. ```bash !pip install -q --upgrade rouge-score !pip install -q --upgrade keras-hub ``` -------------------------------- ### Using LlamaBackbone with Presets and Custom Configurations Source: https://keras.io/keras_hub/api/models/llama/llama_backbone Demonstrates how to load a pretrained LlamaBackbone model using `from_preset` and how to initialize a randomly configured model. Both examples show the required input data format. ```python input_data = { "token_ids": np.ones(shape=(1, 12), dtype="int32"), "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]) } # Pretrained Llama decoder. model = keras_hub.models.LlamaBackbone.from_preset("llama2_7b_en") model(input_data) # Randomly initialized Llama decoder with custom config. model = keras_hub.models.LlamaBackbone( vocabulary_size=10, hidden_dim=512, num_layers=2, num_query_heads=32, num_key_value_heads=8, intermediate_dim=1024, layer_norm_epsilon=1e-6, dtype="float32" ) model(input_data) ``` -------------------------------- ### Reasoning-Only Thinking Example Setup Source: https://keras.io/keras_hub/guides/gemma4_multimodal_and_agentic_workflows This code sets up a prompt for a model to perform complex reasoning, such as solving math problems step-by-step, without necessarily using external tools. It defines the system prompt and the user's query. ```python PROMPT_THINKING = ( "<|turn|>system\n" "<|think|>You are a helpful math tutor.\n" "<|turn|>user\n" "A train travels 120 km in 1.5 hours. How long\n" "will it take to travel 200 km at the same speed?\n" "<|turn|>model\n" ) ``` -------------------------------- ### Install medmnist Package Source: https://keras.io/examples/vision/vivit This code installs the 'medmnist' package, which is required for the Video Vision Transformer example. It uses the '-qq' flag for a quieter installation. ```python !pip install -qq medmnist ``` -------------------------------- ### Using OPTBackbone Model Source: https://keras.io/keras_hub/api/models/opt/opt_backbone Demonstrates how to use the OPTBackbone model. Load a preset model or initialize a custom one with specific configurations. ```python input_data = { "token_ids": np.ones(shape=(1, 12), dtype="int32"), "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]) } # Pretrained OPT decoder model = keras_hub.models.OPTBackbone.from_preset("opt_125m_en") model(input_data) # Randomly initialized OPT decoder model with a custom config model = keras_hub.models.OPTBackbone( vocabulary_size=50265, num_layers=4, num_heads=4, hidden_dim=256, intermediate_dim=512, max_sequence_length=128, ) model(input_data) ``` -------------------------------- ### Install TensorFlow Similarity Source: https://keras.io/examples/vision/metric_learning_tf_similarity Install the TensorFlow Similarity library using pip. This is a prerequisite for running the example. ```bash pip -q install tensorflow_similarity ``` -------------------------------- ### Install Dependencies and Download Assets Source: https://keras.io/guides/keras_hub/stable_diffusion_3_in_keras_hub Installs necessary libraries and downloads sample images for the demonstration. Ensure you have the latest Keras and Keras-Hub installed. ```bash !pip install -Uq keras !pip install -Uq git+https://github.com/keras-team/keras-hub.git !wget -O mountain_dog.png https://raw.githubusercontent.com/keras-team/keras-io/master/guides/img/stable_diffusion_3_in_keras_hub/mountain_dog.png !wget -O mountain_dog_mask.png https://raw.githubusercontent.com/keras-team/keras-io/master/guides/img/stable_diffusion_3_in_keras_hub/mountain_dog_mask.png ``` -------------------------------- ### Setup Keras Backend and Environment Source: https://keras.io/guides/orbax_checkpoint Configure the Keras backend to JAX, set up virtual devices for distributed training, and import necessary libraries. ```python import os os.environ["KERAS_BACKEND"] = "jax" import shutil import jax import keras import numpy as np # Simulate 4 CPU devices for the distributed demo. # Remove this line if using real multi-device hardware. jax.config.update("jax_num_cpu_devices", 4) ``` -------------------------------- ### Setup for Custom Training Loop with Metrics Source: https://keras.io/guides/writing_a_custom_training_loop_in_jax Instantiate model, optimizer, loss function, and metrics for a custom training loop. This setup is required before defining training and evaluation steps. ```python # Get a fresh model model = get_model() # Instantiate an optimizer to train the model. optimizer = keras.optimizers.Adam(learning_rate=1e-3) # Instantiate a loss function. loss_fn = keras.losses.CategoricalCrossentropy(from_logits=True) # Prepare the metrics. train_acc_metric = keras.metrics.CategoricalAccuracy() val_acc_metric = keras.metrics.CategoricalAccuracy() ``` -------------------------------- ### Setup PyTorch Backend for Keras Source: https://keras.io/guides/writing_a_custom_training_loop_in_torch Configure Keras to use the PyTorch backend and import necessary libraries. This setup is required for the guide. ```python import os # This guide can only be run with the torch backend. os.environ["KERAS_BACKEND"] = "torch" import torch import keras import numpy as np ``` -------------------------------- ### Setup for Keras with JAX Backend Source: https://keras.io/guides/custom_train_step_in_jax Sets the Keras backend to JAX and imports necessary libraries. This setup is required for running the guide. ```python import os # This guide can only be run with the JAX backend. os.environ["KERAS_BACKEND"] = "jax" import jax import keras import numpy as np ``` -------------------------------- ### Get Keras Version Source: https://keras.io/api/utils/config_utils Retrieves the installed Keras version. ```python keras.version() ``` -------------------------------- ### Using ESMBackbone with Presets and Custom Configuration Source: https://keras.io/keras_hub/api/models/esm/esm_backbone Demonstrates how to load a pretrained ESM2 backbone using `from_preset` or initialize a custom, randomly-weighted ESM2 backbone. Both examples require sample input data. ```python import numpy as np input_data = { "token_ids": np.ones(shape=(1, 12), dtype="int32"), } # Pretrained ESM2 encoder. model = keras_hub.models.ESM2Backbone.from_preset('hf://facebook/esm2_t6_8M_UR50D') model(input_data) # Randomly initialized ESM2 encoder with a custom config. model = keras_hub.models.ESM2Backbone( vocabulary_size=30552, num_layers=4, num_heads=4, hidden_dim=256, intermediate_dim=512, ) model(input_data) ``` -------------------------------- ### Instantiate Qwen3_5Tokenizer from Preset Source: https://keras.io/keras_hub/api/models/qwen3_5/qwen3_5_tokenizer Demonstrates how to instantiate a Qwen3_5Tokenizer using the `from_preset` method. This method allows loading tokenizers from built-in presets, Kaggle Models, Hugging Face, or local directories. ```python Qwen3_5Tokenizer.from_preset(preset, config_file="tokenizer.json", **kwargs) ``` -------------------------------- ### Monocular Depth Estimation Example Source: https://keras.io/examples/vision/depth_estimation This snippet shows a basic example of using a pre-trained depth estimation model from KerasCV to predict depth from an image. Ensure you have KerasCV installed. ```python import numpy as np import tensorflow as tf from tensorflow import keras from keras_cv.models.depth_estimation import DepthEstimation # Load a pre-trained depth estimation model model = DepthEstimation.from_preset("depth_anything_v2_tiny_fp16", "rgb") # Load an image (replace with your image path) image_path = "path/to/your/image.jpg" img = keras.utils.load_img(image_path, target_size=(512, 512)) img_array = keras.utils.img_to_array(img) img_array = tf.expand_dims(img_array, axis=0) # Create a batch # Predict depth predicted_depth = model.predict(img_array) # The predicted_depth is a tensor containing the depth map. # You can visualize or process it further. print("Depth prediction complete.") print("Shape of predicted depth:", predicted_depth.shape) ``` -------------------------------- ### Setup Keras and Backend Source: https://keras.io/keras_hub/guides/object_detection_retinanet Configure the Keras environment by setting the backend and importing essential libraries like keras and keras_hub. ```python import os os.environ["KERAS_BACKEND"] = "jax" # or "tensorflow" or "torch" import keras import keras_hub import tensorflow as tf ``` -------------------------------- ### Example Search Output: Running Trial Source: https://keras.io/keras_tuner/guides/failed_trials This output indicates that a new trial is starting. ```text Search: Running Trial #8 ``` -------------------------------- ### Instantiate QwenCausalLMPreprocessor from Preset Source: https://keras.io/keras_hub/api/models/qwen/qwen_causal_lm_preprocessor Load the preprocessor from a preset. This is the recommended way to get started. ```python preprocessor = keras_hub.models.QwenCausalLMPreprocessor.from_preset( "qwen2.5_0.5b_en" ) ``` -------------------------------- ### Loading Preprocessors with from_preset Source: https://keras.io/keras_hub/api/base_classes/seq_2_seq_lm_preprocessor Demonstrates how to load preprocessors for different tasks using the from_preset() class method. ```python # Load a preprocessor for Gemma generation. preprocessor = keras_hub.models.CausalLMPreprocessor.from_preset( "gemma_2b_en", ) # Load a preprocessor for Bert classification. preprocessor = keras_hub.models.TextClassifierPreprocessor.from_preset( "bert_base_en", ) ``` -------------------------------- ### Instantiate BartSeq2SeqLM from preset Source: https://keras.io/keras_hub/api/models/bart/bart_seq_2_seq_lm Instantiates a BartSeq2SeqLM model from a pre-trained preset. This is the recommended way to get started with the model. ```python keras_hub.models.BartSeq2SeqLM.from_preset("bart_base_en") ``` -------------------------------- ### Using MixtralBackbone with Presets and Custom Configurations Source: https://keras.io/keras_hub/api/models/mixtral/mixtral_backbone Demonstrates how to instantiate and use the MixtralBackbone model. It shows loading a pretrained model using `from_preset` and initializing a custom model with specific hyperparameters. Both examples process sample input data. ```python input_data = { "token_ids": np.ones(shape=(1, 12), dtype="int32"), "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]), } # Pretrained Mixtral decoder. model = keras_hub.models.MixtralBackbone.from_preset("mixtral7b_base_en") model(input_data) # Randomly initialized Mixtral decoder with custom config. model = keras_hub.models.MixtralBackbone( vocabulary_size=10, hidden_dim=512, num_layers=2, num_query_heads=32, num_key_value_heads=8, intermediate_dim=1024, sliding_window=512, layer_norm_epsilon=1e-6, dtype="float32" ) model(input_data) ``` -------------------------------- ### Setup Imports and Parameters Source: https://keras.io/examples/nlp/addition_rnn Imports necessary libraries and defines parameters for the model and dataset, including training size, number of digits, and whether to reverse input sequences. ```python import keras from keras import layers import numpy as np # Parameters for the model and dataset. TRAINING_SIZE = 50000 DIGITS = 3 REVERSE = True # Maximum length of input is 'int + int' (e.g., '345+678'). Maximum length of # int is DIGITS. MAXLEN = DIGITS + 1 + DIGITS ``` -------------------------------- ### End-to-End Distributed Training Example Source: https://keras.io/guides/distributed_training_with_tensorflow A complete runnable example demonstrating single-host, multi-device synchronous training. It includes model definition, dataset preparation using `tf.data.Dataset`, strategy setup, model compilation, training, and evaluation. ```python def get_compiled_model(): # Make a simple 2-layer densely-connected neural network. inputs = keras.Input(shape=(784,)) x = keras.layers.Dense(256, activation="relu")(inputs) x = keras.layers.Dense(256, activation="relu")(x) outputs = keras.layers.Dense(10)(x) model = keras.Model(inputs, outputs) model.compile( optimizer=keras.optimizers.Adam(), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[keras.metrics.SparseCategoricalAccuracy()], ) return model def get_dataset(): batch_size = 32 num_val_samples = 10000 # Return the MNIST dataset in the form of a [`tf.data.Dataset`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset). (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # Preprocess the data (these are Numpy arrays) x_train = x_train.reshape(-1, 784).astype("float32") / 255 x_test = x_test.reshape(-1, 784).astype("float32") / 255 y_train = y_train.astype("float32") y_test = y_test.astype("float32") # Reserve num_val_samples samples for validation x_val = x_train[-num_val_samples:] y_val = y_train[-num_val_samples:] x_train = x_train[:-num_val_samples] y_train = y_train[:-num_val_samples] return ( tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(batch_size), tf.data.Dataset.from_tensor_slices((x_val, y_val)).batch(batch_size), tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(batch_size), ) # Create a MirroredStrategy. strategy = tf.distribute.MirroredStrategy() print("Number of devices: {}".format(strategy.num_replicas_in_sync)) # Open a strategy scope. with strategy.scope(): # Everything that creates variables should be under the strategy scope. # In general this is only model construction & `compile()`. model = get_compiled_model() # Train the model on all available devices. train_dataset, val_dataset, test_dataset = get_dataset() model.fit(train_dataset, epochs=2, validation_data=val_dataset) # Test the model on all available devices. model.evaluate(test_dataset) ``` -------------------------------- ### Using BertBackbone with Presets and Custom Configurations Source: https://keras.io/keras_hub/api/models/bert/bert_backbone Demonstrates how to instantiate a BertBackbone model using a preset architecture and weights, and how to create a randomly initialized model with custom parameters. Both examples show how to pass input data to the model. ```python input_data = { "token_ids": np.ones(shape=(1, 12), dtype="int32"), "segment_ids": np.array([[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0]]), "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]), } # Pretrained BERT encoder. model = keras_hub.models.BertBackbone.from_preset("bert_base_en_uncased") model(input_data) # Randomly initialized BERT encoder with a custom config. model = keras_hub.models.BertBackbone( vocabulary_size=30552, num_layers=4, num_heads=4, hidden_dim=256, intermediate_dim=512, max_sequence_length=128, ) model(input_data) ``` -------------------------------- ### Import Keras and Utilities Source: https://keras.io/examples/vision/adamatch Sets up the Keras backend and imports essential modules for the example. ```python import os os.environ["KERAS_BACKEND"] = "tensorflow" # "jax" or "torch" import keras keras.utils.set_random_seed(42) import numpy as np from keras import layers from keras import ops import scipy.io from PIL import Image ``` -------------------------------- ### Create tf.data.Dataset for Training and Evaluation Source: https://keras.io/examples/vision/nl_image_search Define a feature description for parsing TFRecord examples and a function to read and preprocess each example, including decoding and resizing images. This setup is crucial for efficiently loading and preparing data for model training. ```Python feature_description = { "caption": tf.io.FixedLenFeature([], tf.string), "raw_image": tf.io.FixedLenFeature([], tf.string), } def read_example(example): features = tf.io.parse_single_example(example, feature_description) raw_image = features.pop("raw_image") features["image"] = tf.image.resize( tf.image.decode_jpeg(raw_image, channels=3), size=(299, 299) ) return features def get_dataset(file_pattern, batch_size): return ( tf.data.TFRecordDataset(tf.data.Dataset.list_files(file_pattern)) .map( read_example, num_parallel_calls=tf.data.AUTOTUNE, deterministic=False, ) .shuffle(batch_size * 10) .prefetch(buffer_size=tf.data.AUTOTUNE) .batch(batch_size) ) ``` -------------------------------- ### Install Dependencies Source: https://keras.io/keras_hub/guides/object_detection_retinanet Install the necessary packages for running the tutorial, including keras-hub, keras, and opencv-python. ```bash !pip install -q --upgrade keras-hub !pip install -q --upgrade keras !pip install -q opencv-python ``` -------------------------------- ### Instantiate Qwen3MoeCausalLM from preset Source: https://keras.io/keras_hub/api/models/qwen3_moe/qwen3_moe_causal_lm Instantiates the Qwen3MoeCausalLM model using a preset configuration. This is the recommended way to get started with the model. ```python qwen3_moe_lm = keras_hub.models.Qwen3MoeCausalLM.from_preset( "qwen3_moe_3b_en" ) ```