Build with AI

How do you train an image style and speech recognition on your own machine?

Written as of · Published · Updated · By Robert Scales, with AI tools · 5 min read

Short answer

For images, train a small diffusion model, then add a low-rank adapter and show it about 30 pictures of the new style; for speech, teach a small network commands and test it on voices it has never heard. In measured tests the image style transferred fully but the correct shape fell to 56–76%, and adapting Whisper to invented names raised correct spelling from 4% to 85% while making ordinary sentences worse.

Pictures and sound seem far from text, but the ideas of this series carry over: frozen weights with a small adapter, tests on what was held out, and a separate measure for what must not change. This article has two projects, both of which ran on an Apple M5 Max (PyTorch 2.15, Transformers 5.22). The timings below include other work running on the machine, so they run high. No NVIDIA card was tested, and neither project uses real people's images or voices.

Project A: teach a small image model a new style

A diffusion model learns to predict the noise added to an image, and then creates images by removing noise step by step. Full-size image models need gigabytes. To keep this in reach, 12a_image_style.py draws its own pictures at 32 by 32 pixels: a circle or a square, in style A (soft blue blobs on a pale ground) or style B (orange-and-black hatching on dark). It builds a network of 597,571 parameters, told which shape to draw.

The base model trains on 4,000 images of style A only. Then it meets 30 images of style B, through an adapter on its convolution layers:

class LoRAConv(nn.Module):
    """A frozen convolution plus a small trainable correction."""
    def __init__(self, conv, rank=4):
        super().__init__()
        self.conv = conv
        for p in conv.parameters():
            p.requires_grad_(False)
        self.down = nn.Conv2d(conv.in_channels, rank, conv.kernel_size, conv.stride, conv.padding, bias=False)
        self.up = nn.Conv2d(rank, conv.out_channels, 1, bias=False)
        nn.init.normal_(self.down.weight, std=0.02)
        nn.init.zeros_(self.up.weight)     # starts as "no change at all"

    def forward(self, x):
        return self.conv(x) + self.up(self.down(x))

This applies the LoRA idea to images. Zeroing up means the adapted model starts out identical to the base.

How do you grade a picture without a person looking at 200 of them? The script trains two small judges: one names the style, the other names the shape. Checked on real drawings, the style judge scored 100% on both styles, and the shape judge 100% and 99.7%. Then it asks for a mix of shapes, and judges 200 samples per model.

Starting pointTrainable parametersTraining timeSamples in style BRight shape
Base model, no adapter380 s0%100%
Adapter, rank 18,016 (1.3%)102 s100%56%
Adapter, rank 432,064 (5.4%)113 s100%64%
Adapter, rank 16128,256 (21.5%)127 s100%72%
Base model, all weights retrained on the 30 images597,571114 s100%76%
New model from scratch on the 30 images597,571103 s100%73%

A chance level for shape is 50%. So the style moved completely in all cases, and it was the content that suffered, which is the image version of project ten. Measuring the style alone would have reported total success.

The second finding is less flattering for adapters. On this toy problem they gave no quality advantage. A model from scratch on the same 30 pictures did as well, because the task is so simple. What an adapter certainly gives you is size: rank 4 is about 5% of the model, and it can be switched on and off. On real image models, trained on far richer data, the case for reusing them is much stronger, but this project did not test that. Tutorials for running Stable Diffusion can start you there, with its own hardware needs and licence.

Project B: teach recognition, and test on strangers

The audio comes from the macOS say command, so the script works on a Mac. Linux and Windows users would need another voice generator, which was not tested. There are 27 English voices, 12 command words such as "open" and "cancel", three speaking rates: 972 clips. Each becomes a mel spectrogram, a picture of sound energy over time, fed to a small network of 24,300 parameters. Training took about 7 seconds. This kind of task, spotting a limited set of words, is what the Speech Commands dataset was built for, and its authors argue that it needs its own data rather than sentence recordings.

How it was tested (12 words, chance 8.3%)Accuracy
Random split: same voices on both sides97.4%
6 voices never heard, 21 for training83.3%
6 voices never heard, only 3 for training53.7%

The 14-point drop between the first two rows is leakage again: a random split lets the model recognize the voice. The last row shows what to collect: more speakers, even with few clips from each. These are synthetic voices, so expect real microphones, rooms and accents to be harder.

Sentence recognition is too large a job to train from nothing here, so the second part adapts a ready model. Whisper tiny.en stumbles on names it has never heard. The script uses six invented ones, such as Zorvane and Kelmora. Only the decoder, the part that writes the words, was trained (29.6 million parameters): 300 steps, 323 seconds, from 576 clips by 12 voices. The test uses other sentences and other voices.

Test on unseen voicesBeforeAfter
Invented name written correctly (108 clips)3.7%85.2%
Word error rate on those sentences40.4%33.8%
Word error rate on ordinary sentences with no names17.6%23.5%

Word error rate counts the words substituted, added or dropped, per word spoken. The gain on names is large, and the cost is visible in the last row. The model got worse at everyday speech. One output after training read "Our partner Zorvane launched the Quillby" for "Our partner Zorvane wants a quote": the training names started appearing where they do not belong. If you only tested names, you would ship that. Before training, try Whisper's cheaper options, such as a larger model or giving it the tricky names up front.

Try it: Change TEST_V in 12b_speech.py to hold out only voices with one accent, and see whether accuracy changes. This tells you whom your data is failing.

Whose images and voices are you allowed to train on?

Nothing here used a real person's face, art or voice, and that kept the project simple. Your own project may not be so simple. This is general information, not legal advice.

MaterialQuestion to ask first
Your own photos or recordingsDo they show or capture other people? Did they agree to this use?
An artist's style, from their workCopyright in the images you copied, licence terms and plain courtesy: ask
A colleague's voiceWritten permission, stating the use, how long and how to withdraw
A public figure's voice or faceRisk of impersonation, even with no intent to deceive
Model outputs in a real person's likenessLabel them. Do not use them to deceive

A voice or face can identify a person, so treat these recordings as sensitive personal information. In Québec, biometric data has its own rules, so check with the person responsible for privacy before collecting any. Also check the base model's licence, because it follows your adapter. The clips generated here stay on your disk and are not published as a dataset.

Download the companion code for this series (zip), with every script and the recorded results.

Sources

  1. Denoising Diffusion Probabilistic Models — arXiv (Jonathan Ho, Ajay Jain, Pieter Abbeel; UC Berkeley), June 19, 2020
  2. Speech Commands: A Dataset for Limited-Vocabulary Speech Recognition — arXiv, April 9, 2018
  3. Robust Speech Recognition via Large-Scale Weak Supervision — OpenAI, September 21, 2022

From the Guide to Artificial Intelligence, by Robert Scales, published by Holistic Hybrid Inc. Share and adapt it under CC BY-NC-SA 4.0: credit the guide, link to https://guidetoartificialintelligence.com/en/learn/train-image-style-speech-recognition/, no commercial use without permission, and keep the same licence.

Get the free Guide to Artificial Intelligence

Sign up for the newsletter and receive the free guide: what changed in AI, one lesson, one prompt to try. Unsubscribe in one click.

How we handle your address

Back to top

Display

Your choices are saved in this browser only. No data is sent.

Text size
100%
Colours
Reading
More settings
Accessibility statement

Get the app

Add the guide to your home screen. It opens like an app, and the pages you have read stay available offline.

Read without a connection: download the articles

iPhone and iPad (Safari, Chrome, Edge)

  1. Tap the Share button (the square with an arrow). In Chrome and Edge, it is in the address bar or the menu.
  2. Choose “Add to Home Screen”.
  3. Tap “Add”.

Android (Chrome, Edge, Samsung Internet, Firefox)

  1. Open the browser menu (⋮ or ☰).
  2. Choose “Install app” or “Add to Home screen”.
  3. Confirm with “Install”.

Computer (Chrome, Edge)

  1. Click the install icon at the right end of the address bar, or open the browser menu (⋮ or …).
  2. In Chrome, choose “Cast, save and share”, then “Install page as app”. In Edge, choose “Apps”, then “Install this site as an app”.
  3. Click “Install”.

Mac (Safari)

  1. Open the File menu.
  2. Choose “Add to Dock”.
  3. Click “Add”.

Firefox on a computer can’t install a site as an app. Use Chrome, Edge or Safari instead.