Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Keras

How to Export a Teachable Machine Model to a Website or Python App

By Freedom251 Team · · 11 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a website, export TensorFlow.js. Download or host the export, keep model.json, metadata.json, and every weight file together, then load them with the matching Teachable Machine helper or TensorFlow.js. Serve the page and model over HTTP(S), not by double-clicking an index.html file.

For Python, export Keras/TensorFlow when that option is available, or TensorFlow Lite for an interpreter, mobile, IoT, or Edge TPU target. In every case, copy the generated preprocessing exactly; input size, color handling, normalization, and audio or pose sampling are part of the model contract.

As an Amazon Associate I earn from qualifying purchases.

Choose the export that matches where inference will run

Teachable Machine projects can be used outside the training page, but the artifact differs by project type and destination. The export panel is the source of truth for the formats available for your particular image, sound, or pose project.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Destination Export to choose What you receive Best fit
Browser or JavaScript/Node.js TensorFlow.js model.json, metadata.json, and one or more referenced weight files Web pages, browser camera or microphone experiences, JavaScript servers, and static hosting
Python application TensorFlow/Keras, when offered Usually a Keras or H5 model plus a labels file and an exporter-provided sample Python programs using Keras, OpenCV, or NumPy
Python, mobile, IoT, or edge hardware TensorFlow Lite A .tflite model and labels, with interpreter-specific input and output details Compact inference runtimes, CPU deployments, and Edge TPU workflows

Do not assume that an image export can be loaded with an audio or pose helper. Those projects have different input contracts and libraries. Open the export tab for the trained project, select the format shown there, and use the generated README or code snippet as the implementation reference.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Exporting a model for a website with TensorFlow.js

1. Train and verify the project

Train the image, sound, or pose model in Teachable Machine and use its preview to check that classes are named correctly and that representative examples produce sensible predictions. Preview confidence is not a universal accuracy measurement; it is an indication for that model and those examples.

2. Select TensorFlow.js in Export Model

  1. Open the completed project.
  2. Choose Export Model.
  3. Select TensorFlow.js.
  4. Choose either Upload (shareable link) or Download.

An uploaded model gives you a hosted URL. A downloaded model gives you files that you can put in your own site or application. A hosted URL is convenient because you do not have to copy model assets into your deployment, but your application then depends on that host and on network access.

3. Preserve the complete file set

A TensorFlow.js export is not just model.json. The JSON describes the network and points to binary weight files; metadata.json contains class names and model metadata used by the Teachable Machine helper. Copy every file from the downloaded directory without renaming it, and preserve the relative directory structure. A typical local layout is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
my-site/
  index.html
  app.js
  my-model/
    model.json
    metadata.json
    group1-shard1of1.bin

The exact weight filename and number of shards vary. If model.json references two or more binary files, all of them must be present at the paths encoded in that JSON.

4. Add the runtime and the matching helper

For an image project, the official library pattern is:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@teachablemachine/image/dist/teachablemachine-image.min.js"></script>

Use the helper that matches the project type: the image helper for image classification, the pose helper for pose projects, and the audio helper for sound projects. TensorFlow.js itself can also load compatible models, but the Teachable Machine helper handles the project metadata and input preparation expected by that export.

5. Load the model asynchronously

With a downloaded image model in my-model/, the core loading and prediction pattern is:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const URL = './my-model/';
const model = await tmImage.load(
  URL + 'model.json',
  URL + 'metadata.json'
);

const prediction = await model.predict(imageElement);
console.log(prediction);

imageElement can be an image, video, or canvas element accepted by the helper. The first load is asynchronous because the browser must fetch the JSON and weight assets. Wait for that promise before starting the camera loop or submitting images.

6. Use a hosted model URL instead

For an uploaded model, set the base URL to the shareable model directory and append model.json and metadata.json in the same way. Keep the two URLs consistent: the JSON and metadata must come from the same export. If the host changes or the model is removed, the page will no longer be able to initialize.

Why opening index.html with file:// often fails

When you double-click a page, the browser usually loads it with a file:// URL. Browser security rules can block JavaScript from fetching local model files, and camera or microphone permissions are less predictable outside an HTTP(S) origin. The result may be a fetch error, a CORS-style message, a blank prediction, or a camera request that never succeeds.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Run a local HTTP server during development

Keep the terminal in the directory containing index.html and start any local static server. For example, with a Python installation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
python -m http.server 8000

Open http://localhost:8000/ in the browser, rather than the file path. Stop the server with Ctrl+C. If your application uses a different port or a subdirectory, use that exact address when testing model paths.

Deploy over HTTPS

Production pages should use HTTPS. It gives browsers a normal secure origin for camera and microphone permission prompts and lets the page fetch model assets using ordinary web requests. Verify that the deployed server sends the JSON and binary files as static assets and that the URL in your JavaScript matches the deployed directory, including capitalization.

What the website files do

  • model.json: describes the TensorFlow.js model and references its weight shards. It is not self-contained if the export includes binary weights.
  • metadata.json: stores Teachable Machine metadata such as class labels and project information used by the helper.
  • Weight files: binary data loaded according to paths in model.json. Missing or moved shards prevent model initialization.
  • Runtime script: TensorFlow.js executes the model in the browser or another JavaScript environment.
  • Project helper: converts the relevant image, audio, or pose input into the format expected by the exported model and exposes convenient prediction methods.

A common deployment mistake is uploading only model.json. Another is placing the files in a new folder without updating the base URL. Inspect the browser Network panel: successful loading should show the JSON, metadata, and every referenced weight request returning successfully.

Using a Teachable Machine export in Python

Python support depends on what the export panel offers for the project. Choose the Keras/TensorFlow route for a conventional Python model when an H5 or Keras export is provided. Choose TensorFlow Lite when you need a small interpreter, mobile or IoT deployment, or an Edge TPU workflow. The official Google Creative Lab examples include OpenCV/Keras and Edge TPU/TFLite Python patterns, but the exact input contract still comes from your own exported model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Option A: Keras or TensorFlow model

Install the libraries used by the generated example

The OpenCV/Keras pattern uses TensorFlow Keras, OpenCV, and NumPy. Install the versions appropriate for your Python environment, then keep the exported model and labels file in a known location. The export commonly contains keras_Model.h5 and labels.txt, but filenames can differ, so use the names shown in your download.

Load the model and labels

from keras.models import load_model
import cv2
import numpy as np

model = load_model('keras_Model.h5', compile=False)
labels = open('labels.txt').readlines()

compile=False is appropriate for inference when you are not resuming training. The labels file order must match the model’s output order. Do not sort or rename the lines after export.

Apply the exported preprocessing

The representative OpenCV/Keras snippet resizes a frame to 224 × 224 pixels, converts it to a float32 array, reshapes it to a batch of one, and maps pixel values with (pixel / 127.5) - 1:

frame = cv2.resize(frame, (224, 224), interpolation=cv2.INTER_AREA)
x = np.asarray(frame, dtype=np.float32).reshape(1, 224, 224, 3)
x = (x / 127.5) - 1

scores = model.predict(x)
index = int(np.argmax(scores))
print(labels[index].strip(), float(scores[0][index]))

These dimensions and scaling values describe that example; they are not universal Teachable Machine constants. A different export may require another input size, channel order, range, or audio and pose representation. Read the generated snippet or metadata and reproduce it exactly. A model can still return numbers after incorrect preprocessing, but those predictions may be meaningless.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Option B: TensorFlow Lite

A TFLite export is a .tflite graph intended for an interpreter. The standard CPU workflow and an Edge TPU workflow follow the same high-level contract: load the model and labels, allocate tensors, inspect the input shape, resize or otherwise prepare the data, invoke the interpreter, and read the output scores. Edge TPU deployments additionally require compatible Edge TPU runtime and PyCoral components; ordinary CPU inference does not require Edge TPU hardware.

Inspect the interpreter’s input contract

import numpy as np
import tensorflow as tf

interpreter = tf.lite.Interpreter(model_path='model.tflite')
interpreter.allocate_tensors()
input_info = interpreter.get_input_details()[0]
output_info = interpreter.get_output_details()[0]
print(input_info['shape'], input_info['dtype'])

Use the reported shape and data type rather than assuming 224 × 224 or float32. Quantized models may require integer input and scale or zero-point handling described in the tensor details. The generated example for an Edge TPU model similarly resizes camera frames to the interpreter’s input dimensions, invokes inference, and reads class scores with the exported labels.

Prepare, invoke, and read output

# Prepare `input_data` according to input_info, including the
# exported resize, color conversion, and normalization contract.
interpreter.set_tensor(input_info['index'], input_data)
interpreter.invoke()
scores = interpreter.get_tensor(output_info['index'])
index = int(np.argmax(scores))
labels = open('labels.txt').readlines()
print(labels[index].strip(), float(scores.reshape(-1)[index]))

The preparation step is intentionally model-specific. For images it may include RGB conversion, resizing, and normalization; for audio it may require a time-frequency representation; for pose it may require landmark coordinates or keypoint tensors. Do not reuse an image pipeline for an audio or pose export.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Preprocessing is part of the model contract

Most integration failures that look like “bad accuracy” are actually input mismatches. Before changing the model, compare your runtime with the exporter-provided example.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Image dimensions: use the expected width and height, not the camera’s native resolution.
  • Color order: confirm whether the model expects RGB or BGR. OpenCV commonly supplies BGR frames, while many web image elements are interpreted as RGB.
  • Numeric range: preserve the exact scaling, such as the example’s mapping to approximately −1 through 1. Do not add a second normalization step.
  • Batch shape: include the batch dimension and channel dimension in the order shown by the model.
  • Audio sampling: match the sample rate, windowing, duration, and feature extraction expected by the audio helper or export code.
  • Pose input: use the helper’s landmark format and coordinate conventions rather than raw camera pixels unless the export explicitly expects pixels.

Keep one known-good sample and run it through both the Teachable Machine preview and your application. Similar input conditions make discrepancies easier to diagnose than testing with an entirely new camera, room, or microphone.

Hosted model versus downloaded model

Choice Advantages Trade-offs Use it when
Hosted shareable link Minimal asset copying; the page can point directly to the exported directory. Requires network access and continued availability of the host; caching and cross-origin behavior are outside your application. You need a quick demo or a centrally managed model URL.
Downloaded files You control deployment, can self-host, and can develop without the export host. You must copy every weight shard, preserve paths, configure static serving, and update the site when the model changes. You need reproducible deployments, a private site, or offline development after assets are downloaded.

Whichever option you choose, keep the model and metadata from the same export. Mixing a newer model.json with older metadata or weight files can produce label mismatches or load failures.

Troubleshooting export and runtime failures

Symptom Likely cause Fix
“Failed to fetch” or a missing-file error The page is using file://, the server path is wrong, or a weight shard was not uploaded. Run a local HTTP server, inspect the Network panel, and copy every file referenced by model.json.
The model loads but labels are wrong metadata.json or labels.txt does not belong to the model, or label lines were reordered. Restore the files from one export and preserve their original order.
Predictions are consistently poor Input size, channel order, normalization, or sampling differs from the generated example. Compare preprocessing line by line and use the model’s reported input shape and data type.
Camera or microphone permission does not appear The page is not running in a suitable HTTP(S) origin, permission was denied, or the browser is blocking the device. Use http://localhost during development or HTTPS in production, then check the browser’s site permissions.
TensorFlow Lite throws a shape or type error The application assumed an input shape or dtype rather than reading the interpreter details. Inspect get_input_details(), prepare exactly that shape and dtype, and apply any quantization parameters required by the model.
Image code is used for sound or pose The project type has a different helper and preprocessing contract. Return to the export panel, select the matching helper, and follow that project’s generated snippet.

Validate the deployed application honestly

There is no single accuracy percentage that applies to every user-trained Teachable Machine model. Performance depends on the classes, examples, lighting or sound conditions, camera position, and the difference between training data and real inputs. Treat preview scores as model-specific rather than as a guarantee.

  1. Collect held-out examples that were not used to train the project.
  2. Make those examples resemble the actual deployment environment, including distance, background, lighting, noise, and movement.
  3. Run each example through the exported application, not only through the training preview.
  4. Record the predicted class and score, then inspect recurring confusions between classes.
  5. Improve the training examples or input pipeline when failures cluster around a particular condition.

A high score on one controlled image does not establish real-world reliability. For a safety-sensitive decision, add an application-level fallback, human confirmation, or a clear “uncertain” threshold rather than treating the largest score as truth.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical decision checklist

  • Choose TensorFlow.js for a browser or JavaScript deployment.
  • Choose Keras/TensorFlow for Python when the export panel provides an H5 or Keras artifact and you want the conventional Python API.
  • Choose TensorFlow Lite for an interpreter, mobile, IoT, or Edge TPU target.
  • Keep model.json, metadata.json, and all referenced weight files together for web exports.
  • Use the matching image, audio, or pose helper; these are not interchangeable.
  • Serve local web files over HTTP and production files over HTTPS.
  • Copy the generated preprocessing exactly, including dimensions, color order, normalization, and sampling.
  • Validate with held-out examples from the conditions in which the application will actually run.

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.

KerasMachine LearningPythonTeachable MachineTensorFlow LiteTensorFlow.jsWeb development

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.