Keras preprocessing layers make it easier to build end-to-end machine learning pipelines that handle raw text, numbers, categories, and images directly inside your model. This article walks through the available preprocessing layers, the adapt() method, and different strategies for placing preprocessing either inside the model or in the tf.data pipeline. You’ll also learn how to combine preprocessing with multi-worker training and export portable inference models, ensuring consistency, scalability, and better performance across environments.Keras preprocessing layers make it easier to build end-to-end machine learning pipelines that handle raw text, numbers, categories, and images directly inside your model. This article walks through the available preprocessing layers, the adapt() method, and different strategies for placing preprocessing either inside the model or in the tf.data pipeline. You’ll also learn how to combine preprocessing with multi-worker training and export portable inference models, ensuring consistency, scalability, and better performance across environments.

Beginner’s Guide to Keras Preprocessing Layers

2025/09/19 04:25
8 min read
For feedback or concerns regarding this content, please contact us at crypto.news@mexc.com

Content Overview

  • Keras preprocessing
  • Available preprocessing
  • Text preprocessing
  • Numerical features preprocessing
  • Categorical features preprocessing
  • Image preprocessing
  • Image data augmentation
  • The adapt() method
  • Preprocessing data before the model or inside the model
  • Benefits of doing preprocessing inside the model at inference time
  • Preprocessing during multi-worker training

\

Keras preprocessing

The Keras preprocessing layers API allows developers to build Keras-native input processing pipelines. These input processing pipelines can be used as independent preprocessing code in non-Keras workflows, combined directly with Keras models, and exported as part of a Keras SavedModel.

With Keras preprocessing layers, you can build and export models that are truly end-to-end: models that accept raw images or raw structured data as input; models that handle feature normalization or feature value indexing on their own.

Available preprocessing

Text preprocessing

  • tf.keras.layers.TextVectorization: turns raw strings into an encoded representation that can be read by an Embedding layer or Dense layer.

Numerical features preprocessing

  • tf.keras.layers.Normalization: performs feature-wise normalization of input features.
  • tf.keras.layers.Discretization: turns continuous numerical features into integer categorical features.

Categorical features preprocessing

  • tf.keras.layers.CategoryEncoding: turns integer categorical features into one-hot, multi-hot, or count dense representations.
  • tf.keras.layers.Hashing: performs categorical feature hashing, also known as the "hashing trick".
  • tf.keras.layers.StringLookup: turns string categorical values into an encoded representation that can be read by an Embedding layer or Dense layer.
  • tf.keras.layers.IntegerLookup: turns integer categorical values into an encoded representation that can be read by an Embedding layer or Dense layer.

Image preprocessing

These layers are for standardizing the inputs of an image model.

  • tf.keras.layers.Resizing: resizes a batch of images to a target size.
  • tf.keras.layers.Rescaling: rescales and offsets the values of a batch of images (e.g. go from inputs in the [0, 255] range to inputs in the [0, 1] range.
  • tf.keras.layers.CenterCrop: returns a center crop of a batch of images.

Image data augmentation

These layers apply random augmentation transforms to a batch of images. They are only active during training.

  • tf.keras.layers.RandomCrop
  • tf.keras.layers.RandomFlip
  • tf.keras.layers.RandomTranslation
  • tf.keras.layers.RandomRotation
  • tf.keras.layers.RandomZoom
  • tf.keras.layers.RandomContrast

The adapt() method

Some preprocessing layers have an internal state that can be computed based on a sample of the training data. The list of stateful preprocessing layers is:

  • TextVectorization: holds a mapping between string tokens and integer indices
  • StringLookup and IntegerLookup: hold a mapping between input values and integer indices.
  • Normalization: holds the mean and standard deviation of the features.
  • Discretization: holds information about value bucket boundaries.

Crucially, these layers are non-trainable. Their state is not set during training; it must be set before training, either by initializing them from a precomputed constant, or by "adapting" them on data.

You set the state of a preprocessing layer by exposing it to training data, via the adapt() method:

\

import numpy as np import tensorflow as tf from tensorflow import keras from keras import layers  data = np.array(     [         [0.1, 0.2, 0.3],         [0.8, 0.9, 1.0],         [1.5, 1.6, 1.7],     ] ) layer = layers.Normalization() layer.adapt(data) normalized_data = layer(data)  print("Features mean: %.2f" % (normalized_data.numpy().mean())) print("Features std: %.2f" % (normalized_data.numpy().std())) 

\

Features mean: -0.00 Features std: 1.00 

The adapt() method takes either a Numpy array or a tf.data.Dataset object. In the case of StringLookup and TextVectorization, you can also pass a list of strings:

\

data = [     "ξεῖν᾽, ἦ τοι μὲν ὄνειροι ἀμήχανοι ἀκριτόμυθοι",     "γίγνοντ᾽, οὐδέ τι πάντα τελείεται ἀνθρώποισι.",     "δοιαὶ γάρ τε πύλαι ἀμενηνῶν εἰσὶν ὀνείρων:",     "αἱ μὲν γὰρ κεράεσσι τετεύχαται, αἱ δ᾽ ἐλέφαντι:",     "τῶν οἳ μέν κ᾽ ἔλθωσι διὰ πριστοῦ ἐλέφαντος,",     "οἵ ῥ᾽ ἐλεφαίρονται, ἔπε᾽ ἀκράαντα φέροντες:",     "οἱ δὲ διὰ ξεστῶν κεράων ἔλθωσι θύραζε,",     "οἵ ῥ᾽ ἔτυμα κραίνουσι, βροτῶν ὅτε κέν τις ἴδηται.", ] layer = layers.TextVectorization() layer.adapt(data) vectorized_text = layer(data) print(vectorized_text) 

\

tf.Tensor( [[37 12 25  5  9 20 21  0  0]  [51 34 27 33 29 18  0  0  0]  [49 52 30 31 19 46 10  0  0]  [ 7  5 50 43 28  7 47 17  0]  [24 35 39 40  3  6 32 16  0]  [ 4  2 15 14 22 23  0  0  0]  [36 48  6 38 42  3 45  0  0]  [ 4  2 13 41 53  8 44 26 11]], shape=(8, 9), dtype=int64) 

In addition, adaptable layers always expose an option to directly set state via constructor arguments or weight assignment. If the intended state values are known at layer construction time, or are calculated outside of the adapt() call, they can be set without relying on the layer's internal computation. For instance, if external vocabulary files for the TextVectorizationStringLookup, or IntegerLookup layers already exist, those can be loaded directly into the lookup tables by passing a path to the vocabulary file in the layer's constructor arguments.

Here's an example where you instantiate a StringLookup layer with precomputed vocabulary:

\

vocab = ["a", "b", "c", "d"] data = tf.constant([["a", "c", "d"], ["d", "z", "b"]]) layer = layers.StringLookup(vocabulary=vocab) vectorized_data = layer(data) print(vectorized_data) 

\

tf.Tensor( [[1 3 4]  [4 0 2]], shape=(2, 3), dtype=int64) 

Preprocessing data before the model or inside the model

There are two ways you could be using preprocessing layers:

Option 1: Make them part of the model, like this:

\

inputs = keras.Input(shape=input_shape) x = preprocessing_layer(inputs) outputs = rest_of_the_model(x) model = keras.Model(inputs, outputs) 

With this option, preprocessing will happen on device, synchronously with the rest of the model execution, meaning that it will benefit from GPU acceleration. If you're training on a GPU, this is the best option for the Normalization layer, and for all image preprocessing and data augmentation layers.

Option 2: apply it to your tf.data.Dataset, so as to obtain a dataset that yields batches of preprocessed data, like this:

\

dataset = dataset.map(lambda x, y: (preprocessing_layer(x), y)) 

With this option, your preprocessing will happen on a CPU, asynchronously, and will be buffered before going into the model. In addition, if you call dataset.prefetch(tf.data.AUTOTUNE) on your dataset, the preprocessing will happen efficiently in parallel with training:

\

dataset = dataset.map(lambda x, y: (preprocessing_layer(x), y)) dataset = dataset.prefetch(tf.data.AUTOTUNE) model.fit(dataset, ...) 

This is the best option for TextVectorization, and all structured data preprocessing layers. It can also be a good option if you're training on a CPU and you use image preprocessing layers.

Note that the TextVectorization layer can only be executed on a CPU, as it is mostly a dictionary lookup operation. Therefore, if you are training your model on a GPU or a TPU, you should put the TextVectorization layer in the tf.data pipeline to get the best performance.

When running on a TPU, you should always place preprocessing layers in the tf.data pipeline (with the exception of Normalization and Rescaling, which run fine on a TPU and are commonly used as the first layer in an image model).

Benefits of doing preprocessing inside the model at inference time

Even if you go with option 2, you may later want to export an inference-only end-to-end model that will include the preprocessing layers. The key benefit to doing this is that it makes your model portable and it helps reduce the training/serving skew.

When all data preprocessing is part of the model, other people can load and use your model without having to be aware of how each feature is expected to be encoded & normalized. Your inference model will be able to process raw images or raw structured data, and will not require users of the model to be aware of the details of e.g. the tokenization scheme used for text, the indexing scheme used for categorical features, whether image pixel values are normalized to [-1, +1] or to [0, 1], etc. This is especially powerful if you're exporting your model to another runtime, such as TensorFlow.js: you won't have to reimplement your preprocessing pipeline in JavaScript.

If you initially put your preprocessing layers in your tf.data pipeline, you can export an inference model that packages the preprocessing. Simply instantiate a new model that chains your preprocessing layers and your training model:

\

inputs = keras.Input(shape=input_shape) x = preprocessing_layer(inputs) outputs = training_model(x) inference_model = keras.Model(inputs, outputs) 

Preprocessing during multi-worker training

Preprocessing layers are compatible with the tf.distribute API for running training across multiple machines.

In general, preprocessing layers should be placed inside a tf.distribute.Strategy.scope() and called either inside or before the model as discussed above.

\

with strategy.scope():     inputs = keras.Input(shape=input_shape)     preprocessing_layer = tf.keras.layers.Hashing(10)     dense_layer = tf.keras.layers.Dense(16) 

For more details, refer to the Data preprocessing section of the Distributed input tutorial.

\ \

:::info Originally published on the TensorFlow website, this article appears here under a new headline and is licensed under CC BY 4.0. Code samples shared under the Apache 2.0 License.

:::

\

Market Opportunity
Brainedge Logo
Brainedge Price(LEARN)
$0.006109
$0.006109$0.006109
-0.81%
USD
Brainedge (LEARN) Live Price Chart
Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact crypto.news@mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Ethereum koers toont zeldzaam dubbel koopsignaal en richt zich op $4.550

Ethereum koers toont zeldzaam dubbel koopsignaal en richt zich op $4.550

Connect met Like-minded Crypto Enthusiasts! Connect op Discord! Check onze Discord   Ethereum laat op de uurgrafiek twee opeenvolgende TD Sequential koopsignalen zien. Deze indicator meet uitputting in een trend en geeft vaak een signaal dat de verkoopdruk kan afnemen. Dit dubbele signaal verschijnt rond het niveau van $4.516, waar de ETH prijs kortstondig steun vindt. Dit type formatie komt zelden voor en wordt daarom extra nauwlettend gevolgd. Wat gaat de Ethereum koers hiermee doen? Ethereum koers test steun rond $4.516 De scherpe daling van de Ethereum koers vanaf de prijszone rond $4.800 bracht de ETH prijs in korte tijd naar ongeveer $4.516. Op dit niveau trad duidelijke koopactiviteit op, waardoor de neerwaartse beweging tijdelijk werd gestopt. Het dubbele signaal dat door de TD Sequential indicator is gegenereerd, viel precies samen met dit prijspunt. De TD Sequential is opgebouwd uit negen candles die een trend meetellen. Wanneer de negende candle verschijnt, kan dit duiden op een trendomslag. In dit geval verschenen zelfs twee signalen kort na elkaar, wat aangeeft dat de verkoopdruk mogelijk uitgeput is. Het feit dat dit gebeurde in een zone waar ETH kopers actief bleven, maakt het patroon extra opvallend. TD Sequential just flashed two buy signals for Ethereum $ETH! pic.twitter.com/JPO8EhiEPi — Ali (@ali_charts) September 16, 2025 Welke crypto nu kopen?Lees onze uitgebreide gids en leer welke crypto nu kopen verstandig kan zijn! Welke crypto nu kopen? Fed-voorzitter Jerome Powell heeft aangekondigd dat de rentes binnenkort zomaar eens omlaag zouden kunnen gaan, en tegelijkertijd blijft BlackRock volop crypto kopen, en dus lijkt de markt klaar om te gaan stijgen. Eén vraag komt telkens terug: welke crypto moet je nu kopen? In dit artikel bespreken we de munten die… Continue reading Ethereum koers toont zeldzaam dubbel koopsignaal en richt zich op $4.550 document.addEventListener('DOMContentLoaded', function() { var screenWidth = window.innerWidth; var excerpts = document.querySelectorAll('.lees-ook-description'); excerpts.forEach(function(description) { var excerpt = description.getAttribute('data-description'); var wordLimit = screenWidth wordLimit) { var trimmedDescription = excerpt.split(' ').slice(0, wordLimit).join(' ') + '...'; description.textContent = trimmedDescription; } }); }); Technische indicatoren schetsen herstelkans voor ETH Naast de dubbele koopsignalen verstrekken ook andere indicatoren belangrijke aanwijzingen. Tijdens de daling van de ETH koers waren grote rode candles zichtbaar, maar na de test van $4.516 stabiliseerde de Ethereum koers. Dit wijst op een mogelijke verschuiving in het evenwicht tussen de bears en bulls. Als deze opwaartse beweging doorzet, liggen de eerste weerstanden rond $4.550. Daarboven wacht een sterkere zone rond $4.650. Deze niveaus zijn in eerdere Ethereum sessies al meerdere keren getest. Een doorbraak zou ruimte openen richting de all-time high van ETH rond $4.953. Wanneer de prijs toch opnieuw onder $4.516 zakt, liggen er zones rond $4.500 en $4.450 waar grotere kooporders worden verwacht. Deze niveaus kunnen als een vangnet fungeren, mocht de druk opnieuw toenemen. Marktdynamiek bevestigt technische indicatoren De huidige situatie volgt op een bredere correctie in de cryptomarkt. Verschillende vooraanstaande crypto tokens zagen scherpe koersdalingen, waarna traders op zoek gingen naar signalen voor een mogelijke ommekeer. Dat juist Ethereum nu een dubbel TD Sequential signaal toont, versterkt de interesse in dit scenario. Fundamenteel blijft Ethereum sterk. Het aantal ETH tokens dat via staking is vastgezet, blijft groeien. Dat verkleint de vrije circulatie en vermindert verkoopdruk. Tegelijk blijft het netwerk intensief gebruikt voor DeFi, NFT’s en stablecoins. Deze activiteiten zorgen voor een stabiele vraag naar ETH, ook wanneer de prijs tijdelijk onder druk staat. Fundamentele drijfveren achter de Ethereum koers De Ethereum koers wordt echter niet alleen bepaald door candles en patronen, maar ook door bredere factoren. Een stijgend percentage van de totale ETH supply staat vast in staking contracten. Hierdoor neemt de liquiditeit op exchanges af. Dit kan prijsschommelingen versterken wanneer er plotseling meer koopdruk ontstaat. Daarnaast is Ethereum nog steeds het grootste smart contract platform. Nieuwe standaarden zoals ERC-8004 en ontwikkelingen rond layer-2 oplossingen houden de activiteit hoog. Deze technologische vooruitgang kan de waardepropositie ondersteunen en zo indirect bijdragen aan een ETH prijsherstel. Het belang van de korte termijn dynamiek De komende handelsdagen zullen duidelijk maken of de bulls genoeg kracht hebben om door de weerstandszone rond $4.550 te breken. Voor de bears ligt de focus juist op het verdedigen van de prijsregio rond $4.516. De whales, die met grote handelsorders opereren, kunnen hierin een beslissende rol spelen. Het dubbele TD Sequential signaal blijft hoe dan ook een zeldzame gebeurtenis. Voor cryptoanalisten vormt het een objectief aanknopingspunt om de kracht van de huidige Ethereum trend te toetsen. Vooruitblik op de ETH koers Ethereum liet twee opeenvolgende TD Sequential signalen zien op de uurgrafiek, iets wat zelden voorkomt. Deze formatie viel samen met steun rond $4.516, waar de bulls actief werden. Als de Ethereum koers boven dit niveau blijft, kan er ruimte ontstaan richting $4.550 en mogelijk $4.650. Zakt de prijs toch opnieuw onder $4.516, dan komen $4.500 en $4.450 in beeld als nieuwe steunzones. De combinatie van zeldzame indicatoren en een sterke fundamentele basis maakt Ethereum interessant voor zowel technische als fundamentele analyses. Of de bulls het momentum echt kunnen overnemen, zal blijken zodra de Ethereum koers de eerstvolgende weerstanden opnieuw test. Koop je crypto via Best Wallet Best wallet is een topklasse crypto wallet waarmee je anoniem crypto kan kopen. Met meer dan 60 chains gesupport kan je al je main crypto coins aanschaffen via Best Wallet. Best wallet - betrouwbare en anonieme wallet Best wallet - betrouwbare en anonieme wallet Meer dan 60 chains beschikbaar voor alle crypto Vroege toegang tot nieuwe projecten Hoge staking belongingen Lage transactiekosten Best wallet review Koop nu via Best Wallet Let op: cryptocurrency is een zeer volatiele en ongereguleerde investering. Doe je eigen onderzoek. Het bericht Ethereum koers toont zeldzaam dubbel koopsignaal en richt zich op $4.550 is geschreven door Dirk van Haaster en verscheen als eerst op Bitcoinmagazine.nl.
Share
Coinstats2025/09/17 23:31
Fed Day Dry Powder: Cryptoquant Analyst Tracks $7.6B Stablecoin Pile on Exchanges

Fed Day Dry Powder: Cryptoquant Analyst Tracks $7.6B Stablecoin Pile on Exchanges

The post Fed Day Dry Powder: Cryptoquant Analyst Tracks $7.6B Stablecoin Pile on Exchanges appeared on BitcoinEthereumNews.com. With the Federal Reserve meeting today, onchain flows are telegraphing that crypto traders are topping off exchanges and leaning long ahead of a widely expected 25-basis-point cut. Pre-Fed Positioning Stablecoins are doing the heavy lifting. Cryptoquant data shows $7.6 billion in fresh USDT and USDC (ERC-20) deposits heading to trading venues ahead of the decision. […] Source: https://news.bitcoin.com/fed-day-dry-powder-cryptoquant-analyst-tracks-7-6b-stablecoin-pile-on-exchanges/
Share
BitcoinEthereumNews2025/09/18 01:36
Michael Saylor’s Bitcoin Treasury Strategy Has Finally Hit Its Breaking Point

Michael Saylor’s Bitcoin Treasury Strategy Has Finally Hit Its Breaking Point

Bitcoin (CRYPTO:BTC) transformed from a niche digital asset into a mainstream investment over the past decade, and few people did more to accelerate that shift
Share
247 Wall St.2026/06/28 20:17

Newbies:Deposit $100, Get $1,000

Newbies:Deposit $100, Get $1,000Newbies:Deposit $100, Get $1,000

Plus Up to a $50 Referral Bonus