iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
The Keras tutorial “Pneumonia Classification on TPU” is a teaching example. It trains a convolutional neural network to label chest X-ray images as NORMAL or PNEUMONIA, and it uses TensorFlow’s TPU distribution strategy to do the training. Read its held-out test result before its validation result: test accuracy was 0.7901, well below the roughly 95% validation accuracy the tutorial discusses. The example demonstrates a workflow. It does not show that the model is clinically validated or ready to guide diagnosis.
What the example sets out to teach
The tutorial walks through a complete image-classification pipeline: reading TFRecord files, turning images into fixed-size tensors, handling class imbalance, building a CNN, training on a TPU, and measuring precision and recall alongside accuracy. It is written for Python and machine-learning learners who want a concrete example of TPU acceleration with a Keras image classifier. The tutorial was created on 2020-07-28 and last modified on 2024-02-12, so check the page for any later changes before you rely on specific code details. The official page is at keras.io/examples/vision/xray_classification_with_tpus/.
| # | Preview | Product | Price | |
|---|---|---|---|---|
| 1 |
|
Coral Dev Board | $149.99 | Buy on Amazon |
| 2 |
|
G650-06076-01 Coral Accelerator Edge TPU M.2 E-Key Slot | $257.30 | Buy on Amazon |
| 3 |
|
Firgi TPU Cutting Board Set of 2 11" x 16" with Handle Juice Groove - Flexible Cutting Mats for... | $33.99 | Buy on Amazon |
| 4 |
|
Coral Dev Board Mini | $188.83 | Buy on Amazon |
| 5 |
|
Blue Ginkgo TPU Cutting Boards, Set of 3, Made in Korea | $29.99 | Buy on Amazon |
Setting up a TPU runtime
The tutorial must be run in Google Colab with a TPU runtime selected. The steps are:
- Open the notebook in Colab.
- Choose Runtime > Change runtime type.
- Set Hardware accelerator to TPU and save.
- Run the setup cell first. It connects to the TPU and creates the distribution strategy used by every later cell.
The setup code tries to connect to a TPU and creates a TensorFlow TPUStrategy. If no TPU is found, it falls back to the default strategy. The notebook then still runs, but on whatever hardware Colab provides, so training times will not match the TPU behavior the tutorial describes. If your timings look like a CPU or GPU run, confirm the runtime type before you debug anything else.
#1 Best Overall
- A development board to quickly prototype on-device ML products. Scale from prototype to production with a removable system-on-module (som)
- Performs high-speed ML inferencing: the on-board edge TPU Coprocessor is capable of performing 4 trillion operations (tera-operations) per second (tops), using 0.5 watts for each tops (2 tops per watt). For example, it can execute state-of-the-art mobile vision models such as mobilenet V2 AT 400 FPS, in a power efficient manner
- Provides a complete system: a Single-board computer with SoC plus ML plus wireless connectivity, all on the board running a derivative of Debian Linux We call Mendel, so you can run your favorite Linux tools with this board
- Supports tensorflow Lite: no need to build models from the ground up. Tensorflow Lite models can be compiled to run on the edge TPE
- Supports automl vision edge: easily build and deploy Fast, high-accuracy custom image Classification models to your device with automl vision edge
Reading the data: TFRecords, labels, and image tensors
The data comes from Google Cloud TFRecord paths for the train and test splits of the ChestXRay2017 dataset. The example reads two kinds of records and zips them together: the image records and the path records. The class label is taken from the directory name in the path record, so a path containing NORMAL maps to 0 and a path containing PNEUMONIA maps to 1.
Each image is decoded as a JPEG with three channels and resized to 180 × 180, giving a 180 × 180 × 3 tensor. The shuffled training dataset is then split: 4,200 examples are used for training, and the remaining training examples form the validation set. The test split is loaded separately and is used only for the final held-out evaluation.
The tutorial does not say whether the split is made at the patient level. If you adapt this pipeline to your own data, check how your records are grouped before you trust validation numbers.
Class imbalance and class weights
The training data is uneven, and the tutorial treats that as a modelling problem to correct rather than something to ignore. The counts and weights it uses are:
Rank #2
- Wide Compatibility: Fully compatible with making it easy to integrate into your existing projects
- Rich Interfaces: Providing flexible connectivity for sensors, displays, and motors
- Stable Communication: For stable signal transmission in smart home and IoT applications
- Beginner-Friendly Resources: Comes with a comprehensive user manualand step-by-step tutorials,Technical support and driver downloads are available to help you get started quickly
| Class | Label | Training images (tutorial’s training data) | Class weight shown in the tutorial |
|---|---|---|---|
| NORMAL | 0 | 1,349 | 1.94 |
| PNEUMONIA | 1 | 3,883 | 0.67 |
These counts describe this tutorial’s training data. They are not population statistics. The weights are consistent with weighting each class inversely to its count, so the rarer NORMAL class contributes more to the loss per image. Class weighting changes how errors are penalized during training; it does not add new images.
Model architecture and training setup
The CNN follows a common pattern for small image classifiers:
- Input scaling: pixel values are rescaled from 0–255 to 0–1.
- Feature blocks: convolution and separable-convolution blocks, each followed by max pooling and batch normalization.
- Regularization: dropout.
- Classifier head: the features are flattened, passed through dense layers, and end in a single sigmoid unit that outputs the probability of PNEUMONIA.
The model is compiled with the Adam optimizer, an exponential learning-rate decay schedule, and binary cross-entropy loss. It reports binary accuracy, precision, and recall. Training uses a model checkpoint and early stopping, so the saved model is not necessarily the one from the final epoch.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsThe batch size is set to 25 times the number of TPU replicas. Scaling the batch with the replica count keeps the work per core roughly constant as the strategy grows.
Rank #3
- Premium Korean-Made TPU Cutting Board Crafted from high-density TPU in Korea - Set of 2 includes Blue and Gray 11" x 16" boards to separate meat and vegetables - Non-porous design for long-lasting use
- Easy Grip Handle for Convenient Use Built-in handle makes it easy to lift and carry the board from countertop - Hang on hooks for quick drying and space-saving storage - Perfect for busy kitchens where convenience matters
- Juice Groove Keeps Countertops Clean Deep juice groove around the edge catches liquids from meat, fruits and vegetables - Prevents messy spills and keeps your kitchen countertop clean during food prep
- Knife-Friendly Flexible Cutting Mat High-elasticity TPU absorbs knife impact keeping your knives sharper longer - Unlike hard plastic that dulls blades or soft silicone that's unstable, TPU provides ideal firmness for safer food prep
- Non-Slip Design and Easy Clean Textured non-slip back keeps board firmly in place during chopping - Heat resistant up to 302°F and quick rinse by hand with warm water - Food grade material safe for your family
Input pipeline and caching
The tutorial caches the dataset in memory and prefetches batches. It explains the choice this way: “Please note that large image datasets should not be cached in memory. We do it here because the dataset is not very large and we want to train on TPU.” Keep that condition in mind. Caching works here because the dataset is small. For a larger image collection, read files from storage and rely on prefetching instead.
Keras’s FAQ makes a related point. It advises making sure the input pipeline reads data fast enough to keep the TPU busy. If your TPU sits idle between steps, the bottleneck is usually the input pipeline rather than the model. The general Keras documentation on loading data is at keras.io/api/data_loading/.
TPU support in Keras
This example is TensorFlow-specific. Keras’s current FAQ states: “All Keras backends (JAX, TensorFlow, PyTorch) are supported on TPU, but we recommend JAX or TensorFlow in this case.” For TensorFlow, the FAQ describes connecting through TPUClusterResolver, creating a TPUStrategy, and building the model inside strategy.scope(). The tutorial follows that pattern. The FAQ is at keras.io/getting_started/faq/.
The tutorial does not compare TensorFlow with JAX or PyTorch on TPU, and it does not measure speed against any other accelerator. Any claim that one backend or device is faster needs separate evidence.
Rank #4
- The Coral Dev Board Mini is a single-board computer that enables you to quickly prototype and deploy an embedded system with on-device ML inferencing.
- The board includes the Edge TPU coprocessor, which is a small ASIC designed by Google that accelerates TensorFlow Lite models in a power efficient manner. It's capable of performing 4 trillion operations (tera-operations) per second (tops), using 0.5 watts for each tops (2 tops per watt).
- Provides a complete system: a single-board computer with SoC + ML + wireless connectivity, all on the board running a derivative of Debian Linux we call Mendel, so you can run your favorite Linux tools with this board.
- Supports TensorFlow Lite: no need to build models from the ground up. Tensorflow Lite models can be compiled to run on the Edge TPU.
- Supports AutoML Vision Edge: easily build and deploy fast, high-accuracy custom image classification models to your device..MediaTek 8167s SoC (Quad-core Arm Cortex-A35).2 GB LPDDR3 and 8 GB eMMC memory
Results: validation versus held-out test
The tutorial reports validation accuracy of about 95%, but its displayed held-out test evaluation is different. These are the values from the tutorial’s own run:
| Metric | Validation (as discussed in the tutorial) | Held-out test (displayed output) |
|---|---|---|
| Binary accuracy | About 95% | 0.7901 |
| Precision | Not stated | 0.7524 |
| Recall | Not stated | 0.9897 |
The gap between about 95% validation accuracy and 0.7901 test accuracy is the most important number in the example. Keras’s own text says the lower test accuracy may indicate overfitting, meaning the model fit the validation data more closely than data it had never seen.
Reading precision and recall
Recall of 0.9897 means the model flagged nearly all of the pneumonia images in the test evaluation. Precision of 0.7524 means about a quarter of the images it flagged as pneumonia were actually normal. The tutorial describes this as many pneumonia images being detected alongside false positives among normal images. A model with high recall and lower precision is tuned to miss few positives at the cost of extra false alarms, and that trade-off depends on how the output is used. Accuracy alone would hide it.
Free tools Windows power users keep installed
One-click scans. No signup required.
What a single run can and cannot show
These figures come from one run with a particular random shuffle, split, and checkpoint. They are not an expected performance level for the method, and rerunning the notebook can produce different numbers. Treat them as a demonstration of how to evaluate a classifier honestly, not as a benchmark.
Best Value
- Versatile & Flexible – TPU cutting mats make everyday food prep easier. Chop vegetables, slice fruit, prepare meat, then flex the mat to funnel ingredients neatly into bowls or pans.
- Made in South Korea – Crafted from premium TPU for a durable yet flexible cutting surface. Designed to be gentler on knife edges while resisting everyday scratches and wear.
- Mess-Free Food Prep – Textured surfaces help reduce slipping, while integrated juice grooves catch liquids from fruits, vegetables, and meats to help keep countertops cleaner.
- Durable for Everyday Use – Scratch-resistant TPU is designed to handle regular meal prep, though normal cut marks may develop over time. Hand washing is recommended for best results. Top-rack dishwasher safe; air-dry only to help prevent warping.
- Space-Saving – Slim, stackable mats store easily in drawers without taking up valuable kitchen space. Portable, with hanging holes for convenient storage.
Limits of the example
The tutorial presents an image-classification exercise on one public dataset. Several questions it does not answer matter for any real use:
- Whether the train, validation, and test splits are separated by patient.
- How representative the ChestXRay2017 images are of the patients a clinic would see, including age, equipment, and imaging protocol.
- How the model would perform on images from a different hospital or scanner.
- Any regulatory, workflow, or clinical-safety requirement for a diagnostic tool.
The tutorial links to the ChestXRay2017 dataset, but this page does not summarize the dataset’s underlying paper or documentation. Consult the original dataset source before you describe its composition in your own work.
If you run this yourself
- TPU not detected: confirm the Colab runtime is set to TPU and rerun the setup cell. Without a TPU, the default strategy takes over and the TPU-specific settings have no effect.
- Test accuracy far below validation: expect this. Check the split logic and do not report the validation number alone.
- Training slows or stalls: check the input pipeline first. Confirm the dataset is cached only when it is small enough to fit in memory.
- Changing the class weights: recompute them from your own training counts instead of reusing 1.94 and 0.67.
The example shows the full path from TFRecord files to a TPU-trained Keras model and a set of evaluation metrics. Its most useful lesson is the one the tutorial itself points to: a validation score is not a test score, and precision and recall reveal what accuracy hides.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

