<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Talha Bin Omar on Medium]]></title>
        <description><![CDATA[Stories by Talha Bin Omar on Medium]]></description>
        <link>https://medium.com/@talhabinomar9991?source=rss-527ae2f1938f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ol6Id9n3chZ0Aans</url>
            <title>Stories by Talha Bin Omar on Medium</title>
            <link>https://medium.com/@talhabinomar9991?source=rss-527ae2f1938f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:03:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@talhabinomar9991/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[When Clean Speech Is the Wrong Training Data for ASR…..]]></title>
            <link>https://medium.com/@talhabinomar9991/when-clean-speech-is-the-wrong-training-data-for-asr-f11328786c7c?source=rss-527ae2f1938f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11328786c7c</guid>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[openai-whisper]]></category>
            <category><![CDATA[gsm-network]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <category><![CDATA[audio-processing]]></category>
            <dc:creator><![CDATA[Talha Bin Omar]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 19:10:03 GMT</pubDate>
            <atom:updated>2026-08-22T19:10:03.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxV4aHLNESotZhwLve1O5A.png" /><figcaption>Augmentation Visualization</figcaption></figure><p><strong>Building an ASR system that survives GSM distortion, background noise, bandwidth collapse, codec damage and real production speech</strong></p><p>Most speech recognition models look impressive until the audio stops being impressive.</p><p>Give them a clean microphone recording with a reasonably close speaker and they perform exactly as expected. Put the same model behind a phone call, a cheap microphone, background chatter, compression, changing volume, packet loss and an unreliable network, and suddenly the system that looked production ready starts missing entire phrases.</p><p>I spent a long time working on exactly this problem with low quality GSM audio.</p><p>These were not simply noisy recordings. Some of the speech had already passed through enough compression, bandwidth restriction and transmission damage that listening to it yourself required effort. Training an ASR model on more clean speech helped only up to a point. The real improvement came when I changed the question.</p><p>Instead of asking:</p><blockquote><em>How do I make the model understand bad audio?</em></blockquote><p>I started asking:</p><blockquote><em>How do I make bad audio normal during training?</em></blockquote><p>That shift eventually became the foundation of the augmentation pipeline I use today.</p><p>The original problem was GSM speech, but the same pipeline turned out to be useful for a much broader class of production ASR systems. Call centers are only one example. Real applications receive speech from laptops, mobile phones, headsets, conference rooms, cheap microphones, distant speakers, moving speakers and unpredictable environments.</p><p>The common problem is distribution mismatch.</p><p>Production audio rarely looks like the audio on which we wish our models could operate.</p><p>So, I stopped protecting the training data and started systematically destroying it.</p><h3>The Problem Is Bigger Than Background Noise</h3><p>A standard strategy for ASR robustness is taking clean speech and mixing in additive noise. It’s useful, but it completely fails to reproduce the physics of a production telecom environment.</p><p>A phone call alters a signal in several concurrent, structural ways:</p><ul><li>Frequencies are clamped and narrowed.</li><li>The audio is aggressively downsampled.</li><li>Lossy speech codecs fundamentally reshape the waveform.</li><li>Network drops delete temporal information.</li><li>Packet loss concealment (PLC) duplicates nearby frames to cover gaps.</li><li>Automatic gain control (AGC) wildly swings the amplitude.</li></ul><p>The final waveform looks nothing like “clean speech plus white noise.” If your training pipeline only teaches the model to separate speech from background noise, it will still fail when the phonetic structure of the speech itself has been altered by a codec. Robust ASR requires training against the <em>entire transmission channel</em>, not just the room environment.</p><h3>The Core Idea</h3><p>This changed how I approached augmentation. I stopped thinking about individual effects and started thinking about the entire audio channel. The approach itself is conceptually simple.</p><p>Take usable speech and repeatedly transform it into speech that resembles the worst conditions expected in production.</p><p>In my current implementation, an utterance can move through a pipeline similar to this:</p><pre>Original speech<br>       ↓<br>Environmental noise<br>       ↓<br>Bandwidth restriction<br>       ↓<br>16 kHz to 8 kHz to 16 kHz conversion<br>       ↓<br>GSM codec encode and decode<br>       ↓<br>Packet loss simulation<br>       ↓<br>Automatic gain control<br>       ↓<br>Optional companding<br>       ↓<br>Whisper feature extraction</pre><p>Not every sample passes through exactly the same sequence. That is important.</p><p>The full telephony path currently runs with an 70 percent probability. The remaining samples still receive lighter augmentation such as noise and resampling, but they avoid some of the more destructive transformations. This keeps enough variation in the dataset that the model does not start assuming every recording will sound like a terrible phone call.</p><p>Another important part is that almost every transformation has randomized parameters. I do not want one telephone filter, one SNR or one exact degradation pattern. I want the model to see a range of possible channels.</p><p>That turns augmentation from a preprocessing operation into a training distribution.</p><h3>Stage 1: Real Environmental Noise</h3><p>The first stage introduces environmental interference.</p><p>For this implementation, I use the <strong>RIRS_NOISES dataset available on Hugging Face</strong>, specifically the point source noise recordings from the collection. The dataset can be found here: <a href="https://huggingface.co/datasets/EaseZh/rirs_noises">EaseZh/rirs_noises on Hugging Face</a>.</p><p>There is an important implementation detail here. In this implementation, I use the point source noise recordings as additive noise. The pipeline does not currently convolve the speech with room impulse responses, although RIR convolution can be added as a separate stage. Actual RIR convolution can be added as another stage.</p><p>Instead of choosing one fixed SNR range, I divided noise conditions into two streams.</p><p>The light stream uses an SNR between 18 and 28 dB.</p><p>The strong stream uses an SNR between 3 and 12 dB.</p><p>Only 25 percent of noise augmented samples enter the light stream. The remaining samples receive the stronger range.</p><p>That decision is intentional.</p><p>If the majority of augmented speech remains easy, the model can continue relying on acoustic conditions that disappear in production.</p><p>At the same time, making every example extremely noisy creates another problem. The model can become unnecessarily specialized around damaged audio and lose performance on normal speech.</p><p>A mixture gives the model both.</p><p>The implementation selects a noise recording, resamples it when required, repeats it if it is shorter than the speech and trims it to the exact speech duration.</p><p>The noise level is then calculated from the relative magnitude of speech and noise.</p><p>Conceptually:</p><pre>snr_ratio = 10 ** (snr_db / 20)</pre><pre>scale = snr_ratio * noise_magnitude / speech_magnitude</pre><pre>mixed = (scale * speech + noise) / (scale + 1)</pre><p>The final normalization changes the total amplitude while preserving the intended ratio between the speech and noise components.</p><p>That gives much more control than simply adding an arbitrary noise waveform at an arbitrary volume.</p><h3>Stage 2: Bandwidth Shaping</h3><p>A large part of telephone degradation comes from information being removed before the signal ever reaches the ASR model. Clean recordings contain spectral detail that many real communication channels simply do not preserve, so a model trained only on full bandwidth speech can become unnecessarily dependent on frequencies that disappear in production.</p><p>I handle this by randomly applying high pass and low pass filtering before the stronger codec transformations.</p><p>A simplified version of the configuration looks like this:</p><pre>LOW_CUTOFF_RANGE = (130.0, 260.0)<br>UPPER_CUTOFF_RANGE = (1300.0, 2100.0)</pre><pre>WIDE_CHANNEL_CHANCE = 0.15<br>WIDE_CHANNEL_LIMIT = 3400.0</pre><p>Rather than using one fixed telephone filter, I sample the usable frequency range independently for each recording:</p><pre>def apply_channel_filter(audio, sample_rate):<br>    lower_bound = random.uniform(*LOW_CUTOFF_RANGE)</pre><pre>    if random.random() &lt; WIDE_CHANNEL_CHANCE:<br>        upper_bound = WIDE_CHANNEL_LIMIT<br>    else:<br>        upper_bound = random.uniform(*UPPER_CUTOFF_RANGE)</pre><pre>    audio = highpass_filter(<br>        audio,<br>        sample_rate,<br>        lower_bound<br>    )</pre><pre>    audio = lowpass_filter(<br>        audio,<br>        sample_rate,<br>        upper_bound<br>    )</pre><pre>    return audio</pre><p>The exact values are less important than the distribution they create. Most samples are pushed through a fairly narrow channel, while a smaller percentage retain a more conventional telephone bandwidth.</p><p>I also keep a secondary path that resembles a standard voice channel more closely:</p><pre>audio = highpass_filter(audio, sample_rate, 300.0)<br>audio = lowpass_filter(audio, sample_rate, 3400.0)</pre><p>This prevents the augmentation from producing only one type of severely restricted speech.</p><p>The reason for randomizing the cutoff frequencies is simple. Real production audio rarely passes through exactly the same acoustic path every time. Different devices, codecs, network conditions and preprocessing systems all produce slightly different frequency responses.</p><p>More importantly, this transformation actually removes information.</p><p>Background noise makes useful speech harder to observe, but filtering can remove parts of the signal completely. Once those frequencies have been discarded, the encoder cannot simply recover them later.</p><p>That forces the model to recognize speech from whatever spectral evidence remains available instead of becoming dependent on the cleanest possible representation of every phoneme.</p><p>In the full augmentation chain, this happens before the 8 kHz conversion and GSM codec simulation. The signal is therefore already bandwidth limited before it goes through the more destructive stages, which produces a much more realistic training distribution than applying each transformation independently.</p><h3>Stage 3: The 8 kHz Information Bottleneck</h3><p>Whisper operates on 16 kHz audio, but keeping the entire augmentation pipeline at 16 kHz would preserve far more acoustic information than many real communication channels actually provide.</p><p>For this reason, one of the transformations I use is an explicit 16 kHz to 8 kHz to 16 kHz round trip. In the current configuration it is applied with a probability of 90 percent.</p><pre>def _maybe_resample_8k_roundtrip(self, wav):<br>    if random.random() &gt; RESAMPLE_8K_PROB:<br>        return wav</pre><pre>    wav_8k = _resample_waveform(<br>        wav,<br>        self.base_sr,<br>        8000<br>    )</pre><pre>    return _resample_waveform(<br>        wav_8k,<br>        8000,<br>        self.base_sr<br>    ).clamp(-1.0, 1.0)</pre><p>The second resampling step is only there because Whisper expects a 16 kHz input. The meaningful transformation happens when the signal is reduced to 8 kHz.</p><p>Once the waveform has been downsampled, spectral information above the new Nyquist limit has already been removed. Upsampling the signal back to 16 kHz restores the expected sample rate, but it cannot recreate the spectral information discarded during downsampling.</p><p>So although the model still receives a technically valid 16 kHz waveform, it is no longer receiving the same acoustic signal.</p><p>This is useful for training because a large amount of production speech arrives through constrained channels. Telephone systems are an obvious example, but similar information loss can also appear after repeated transcoding, communication software, low bandwidth streaming and poor recording pipelines.</p><p>The purpose of this stage is therefore not simply to imitate a lower sample rate. It introduces an actual information bottleneck before feature extraction.</p><p>By the time Whisper computes its log Mel features, the model has already lost part of the spectral detail it would normally have available in clean audio.</p><h3>Stage 4: Using a Real GSM Codec</h3><p>Bandwidth filtering and resampling can make speech resemble telephone audio, but neither reproduces the artifacts introduced by an actual speech codec.</p><p>For the heavy augmentation path, I therefore pass the waveform through a real GSM codec using SoX.</p><p>The audio is first written as a temporary waveform and encoded into GSM at 8 kHz mono:</p><pre>subprocess.run(<br>    [<br>        &quot;sox&quot;,<br>        input_path,<br>        &quot;-r&quot;, &quot;8000&quot;,<br>        &quot;-c&quot;, &quot;1&quot;,<br>        &quot;-t&quot;, &quot;gsm&quot;,<br>        gsm_path,<br>    ],<br>    check=True,<br>)</pre><p>The resulting GSM stream is then decoded back into a waveform that can continue through the training pipeline:</p><pre>subprocess.run(<br>    [<br>        &quot;sox&quot;,<br>        &quot;-t&quot;, &quot;gsm&quot;,<br>        gsm_path,<br>        &quot;-r&quot;, str(sample_rate),<br>        &quot;-c&quot;, &quot;1&quot;,<br>        &quot;-e&quot;, &quot;signed-integer&quot;,<br>        &quot;-b&quot;, &quot;16&quot;,<br>        output_path,<br>    ],<br>    check=True,<br>)</pre><p>After decoding, the waveform is loaded again and returned to the augmentation pipeline.</p><p>The distinction between this and ordinary filtering is important. A filter mostly changes which frequencies survive. A speech codec changes the representation of the signal itself and introduces structured artifacts as a consequence of encoding and reconstruction.</p><p>Those artifacts are exactly what I want the acoustic model to encounter during training.</p><p>In the complete heavy path, the codec sits after environmental noise, bandwidth shaping and the 8 kHz resampling stage:</p><pre>wav = self._maybe_noise(wav)<br>wav = self._call_matched_bandshape(wav)<br>wav = self._maybe_resample_8k_roundtrip(wav)<br>wav = gsm_codec_roundtrip_sox(wav, self.base_sr)<br>wav = packet_loss_plc(wav, self.base_sr, drop_prob)<br>wav = agc_sim(wav)</pre><p>By this point the model is no longer seeing clean speech with one artificial distortion added to it. The signal has passed through several transformations that can occur together in an actual communication pipeline.</p><p>That combination matters much more than any single augmentation in isolation.</p><p>For a different production system I would apply the same principle with whatever codecs are present in the real data path. If deployment audio is regularly encoded using a particular codec, exposing the ASR model to that codec during training is generally more useful than trying to approximate all of its effects with generic noise.</p><h3>Stage 5: Packet Loss and Simple Concealment</h3><p>Codec degradation is still relatively continuous. Real communication audio can also contain short regions where information is simply missing.</p><p>To represent that failure mode, I added a lightweight packet loss simulation after the GSM codec stage.</p><p>The waveform is divided into 20 millisecond frames:</p><pre>frame = int(0.02 * sample_rate)</pre><p>A packet loss probability is sampled independently for each training example from a range between 0 and 2 percent.</p><pre>drop_prob = random.uniform(<br>    *PACKET_LOSS_PROB_RANGE<br>)</pre><p>The waveform is then processed frame by frame:</p><pre>def packet_loss_plc(wav, sr, drop_prob):<br>    out = wav.clone()</pre><pre>    frame = int(0.02 * sr)<br>    total_samples = out.shape[-1]</pre><pre>    for i in range(0, total_samples - frame, frame):<br>        if random.random() &lt; drop_prob:<br>            if i &gt;= frame:<br>                out[:, i:i + frame] = out[:, i - frame:i]<br>            else:<br>                out[:, i:i + frame] = 0.0</pre><pre>    return out</pre><p>When a frame is selected for removal, the previous frame is copied into its position. If the first frame is affected and no previous frame exists, that region is replaced with silence.</p><p>This is intentionally a simple concealment strategy. I am not trying to build a complete RTP or telecommunications network simulator inside the data loader.</p><p>What matters for ASR training is the resulting acoustic failure.</p><p>A small segment that should contain new phonetic information may instead contain repeated information from the previous 20 milliseconds. In other cases the information disappears entirely.</p><p>That creates local discontinuities that are very different from additive noise.</p><p>With additive noise, the underlying speech is still present. With packet loss, part of the evidence available to the recognizer has actually been removed or replaced.</p><p>Training on these failures encourages the model to rely more heavily on surrounding acoustic and linguistic context rather than assuming that every frame will contain reliable information.</p><p>The probability is kept relatively low because real packet loss is usually sparse. Making large portions of every utterance disappear would create an unrealistic training distribution and could easily do more harm than good.</p><h3>Stage 6: Simulating Automatic Gain Control</h3><p>Amplitude is another part of speech data that is much less stable in production than it appears in curated datasets.</p><p>The same speaker can arrive at very different levels depending on the microphone, operating system, capture software, distance from the device and any gain processing that happens before the waveform reaches the ASR service.</p><p>Rather than applying one fixed normalization value, I simulate this variation by calculating the RMS level of each waveform and assigning it a randomly selected target level.</p><pre>def agc_sim(wav):<br>    rms = wav.pow(2).mean().sqrt().clamp(min=1e-4)</pre><pre>    target = random.uniform(<br>        0.03,<br>        0.07<br>    )</pre><pre>    gain = (target / rms).clamp(<br>        0.5,<br>        4.0<br>    )</pre><pre>    return (wav * gain).clamp(<br>        -1.0,<br>        1.0<br>    )</pre><p>The RMS is calculated as:</p><pre>RMS = sqrt(mean(x²))</pre><p>A target RMS between 0.03 and 0.07 is then sampled and the required gain becomes:</p><pre>gain = target RMS / current RMS</pre><p>I constrain that gain between 0.5 and 4.0 so the augmentation can make speech quieter or louder without allowing extreme amplification values to dominate the signal.</p><p>The final waveform is clipped back into the normal range of [-1, 1].</p><p>This stage is deliberately placed after the more destructive channel transformations. By that point the waveform may already contain environmental noise, spectral loss, codec artifacts and packet concealment. The AGC therefore acts on the damaged signal rather than on an ideal clean recording.</p><p>That is closer to what happens in real audio systems, where gain control is often one component in a much larger processing chain.</p><p>The goal here is not to teach the model one preferred volume level. It is the opposite. I want amplitude to become an unreliable feature so that the encoder cannot depend on a narrow loudness distribution being present at inference time.</p><h3>An Optional Mu Law Stage</h3><p>The pipeline also contains Mu law companding support with 256 quantization levels.</p><p>It can perform an encode and decode round trip through either torchaudio or a local implementation.</p><p>In my current configuration this stage is intentionally kept disabled because the GSM codec simulation already provides a strong codec transformation.</p><p>I still keep it in the augmentation system because different production channels may justify different combinations.</p><p>This is another principle I have found useful when building robust speech pipelines. Build the augmentation system as a configurable channel simulator, not as a single fixed recipe.</p><h3>Not Every Sample Should Be Destroyed Equally</h3><p>One of the easiest mistakes with aggressive augmentation is making every training sample equally terrible.</p><p>That sounds like the strongest possible robustness training.</p><p>In practice, it makes the training distribution unnecessarily narrow.</p><p>My full telephony augmentation chain runs with a probability of 70 percent.</p><p>When it runs, the sample can receive noise, filtering, resampling, GSM compression, packet loss and AGC. But the other branch is lighter.</p><p>The lighter branch still receives environmental noise and may pass through the 8 kHz resampling stage, but it skips the complete telephony degradation chain. This keeps the training distribution from becoming unrealistically harsh.</p><p>I found it more useful to treat audio quality as a range rather than splitting the dataset into simply clean and corrupted samples. Some recordings remain fairly easy, others lose a noticeable amount of acoustic information, and a smaller portion become severely degraded.</p><p>That variation is intentional. Production audio arrives at different quality levels depending on the device, environment, codec and network path, so the training data should reflect the same kind of spread rather than forcing every example into one fixed corruption profile.</p><h3>The Model Side of the Pipeline</h3><p>One of the less obvious problems I ran into during experimentation was what happens to the encoder when the augmentation becomes this aggressive.</p><p>With large Whisper models, simply fully fine tuning the encoder-decoder on heavily degraded speech was not giving me the behavior I wanted. Once the training distribution contained strong noise, severe bandwidth restriction, codec artifacts and other distortions, the encoder had too much freedom to adapt itself to the corrupted training distribution. In several experiments it started modelling characteristics of the degradation itself instead of preserving a clean and useful representation of speech.</p><p>That is the opposite of what I want from the encoder.</p><p>The encoder should learn how to extract speech despite the noise. It should not become specialized around the noise.</p><p>Because of this, I stopped fully fine tuning the encoder and moved to LoRA based adaptation. The original encoder weights remain frozen and only a relatively small set of low rank parameters are allowed to change. I then train those adapters with a considerably higher learning rate than I would use for normal full fine tuning.</p><p>This gives the encoder enough capacity to adapt to extremely difficult speech conditions without allowing the entire acoustic representation to drift toward the augmentation distribution.</p><p>The distinction became quite important in my experiments. Heavy augmentation and full encoder fine tuning can be a bad combination, especially with larger Whisper models. The augmentation is deliberately destructive, so giving every encoder parameter complete freedom to move can end up damaging representations that were already useful.</p><p>LoRA gives me a much more controlled adaptation path. I can teach the encoder to recover speech from these difficult conditions while preserving most of what the pretrained model already knows about speech.</p><p>The decoder is a different problem.</p><p>If the existing decoder already handles the target language well, it does not necessarily need aggressive adaptation. If I am adapting Whisper to a new language or making substantial changes to the output distribution, I can either fully fine tune the decoder or use a much heavier LoRA configuration there.</p><p>So the general strategy I ended up with is simple: <strong>be conservative with the encoder and more flexible with the decoder.</strong></p><p>The encoder needs to survive the acoustic destruction without learning the destruction itself. The decoder can then be adapted according to how much the actual language and output behavior need to change.</p><h3>Different Parts of the Model Need Different Learning Rates</h3><p>Once the encoder uses LoRA and the decoder uses full fine tuning, giving both sets of parameters exactly the same learning rate is not ideal.</p><p>So the optimizer has separate parameter groups.</p><p>The encoder LoRA parameters train at:</p><pre>1e-4</pre><p>The full decoder parameters train at:</p><pre>1e-5</pre><p>The lower rate keeps full model parameters relatively stable.</p><p>The LoRA parameters can move faster because they are the dedicated adaptation path.</p><p>Weight decay is also separated correctly so that parameters such as biases and normalization weights are not treated the same way as ordinary weight matrices.</p><p>These details are not as visually interesting as an augmentation waveform, but they matter in long production training runs.</p><h3>Whisper Details That Can Quietly Ruin Fine Tuning</h3><p>Whisper fine tuning has several implementation details that look minor but can completely change how well the model learns. I ran into a few of these during experimentation where the loss was decreasing and the training loop looked healthy, but the resulting model was clearly not learning the task properly.</p><p>One of the most important things is keeping the audio and text processing paths correct. For the Trainer, I explicitly pass Whisper’s <strong>feature extractor</strong> as the processing class rather than passing the tokenizer or treating the entire processor as if it were interchangeable.</p><pre>trainer = Seq2SeqTrainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=train_dataset,<br>    eval_dataset=eval_dataset,<br>    data_collator=data_collator,<br>    processing_class=processor.feature_extractor,<br>)</pre><p>Audio feature extraction and target tokenization are then handled separately:</p><pre>input_features = processor.feature_extractor(<br>    waveform,<br>    sampling_rate=16000,<br>).input_features[0]</pre><pre>label_ids = processor.tokenizer(<br>    transcript,<br>    add_special_tokens=True,<br>).input_ids</pre><p>This separation ended up being important in my experiments. A Whisper training pipeline can be wired incorrectly around the tokenizer and feature extractor and still run without throwing an obvious error. I have had runs where the loss moved normally but the model was barely learning. Because of that, I now explicitly keep processor.feature_extractor on the audio side and use processor.tokenizer only when constructing the decoder targets.</p><p>Language token handling is another area where I prefer to keep things simple, especially when adapting Whisper to a language it does not officially support.</p><p>I would not introduce a completely new language token unless I specifically intended to modify the tokenizer vocabulary, resize the model embeddings and properly train that new token. Adding something like a custom &lt;|new_language|&gt; token by itself does not give Whisper any useful prior knowledge about what that token represents.</p><p>For unsupported languages, one strategy that has worked better in my experiments is to reuse an existing Whisper language token from a closely related supported language rather than introducing a completely untrained language token.</p><p>For example, the tokenizer can still be configured with an existing language token while the transcript itself belongs to the unsupported language:</p><pre>processor.tokenizer.set_prefix_tokens(<br>    language=closest_supported_language,<br>    task=&quot;transcribe&quot;,<br>)</pre><pre>label_ids = processor.tokenizer(<br>    transcript,<br>    add_special_tokens=True,<br>).input_ids</pre><p>The important point is that the language token acts as part of Whisper’s conditioning. It does not define what characters or words the decoder is allowed to generate. The decoder can still learn the new language from the training targets as long as its existing tokenizer can represent the script reasonably well.</p><p>In practice, I would choose the closest supported language based on script, phonetic similarity and linguistic relationship rather than introducing an untrained token into the model. The exact choice is something I would validate experimentally, but reusing an existing language token is usually a much cleaner starting point than changing Whisper’s vocabulary unnecessarily.</p><p>Decoder token handling also needs care.</p><p>During training I disable forced decoder IDs because the tokenizer is already constructing the appropriate task and language prefix for each target.</p><pre>model.config.forced_decoder_ids = None<br>model.generation_config.forced_decoder_ids = None</pre><p>During evaluation I restore the appropriate generation prompt depending on the task. In a multitask setup this matters because transcription and translation should not silently share the same generation configuration.</p><p>The decoder start token is another easy place to make a mistake. Whisper expects &lt;|startoftranscript|&gt; as its decoder start token. That should not be replaced blindly with the tokenizer BOS token.</p><p>I therefore keep Whisper’s pretrained decoder_start_token_id unchanged and remove a duplicated start of transcript token from the labels when necessary:</p><pre>start_token = processor.tokenizer.convert_tokens_to_ids(<br>    &quot;&lt;|startoftranscript|&gt;&quot;<br>)</pre><pre>if (labels[:, 0] == start_token).all():<br>    labels = labels[:, 1:]</pre><p>Whisper inserts the decoder start token internally when shifting the labels, so keeping another copy at the beginning of every sequence would shift the target incorrectly.</p><p>I also explicitly append the EOS token when it is missing:</p><pre>eos_token = processor.tokenizer.eos_token_id</pre><pre>if not label_ids or label_ids[-1] != eos_token:<br>    label_ids.append(eos_token)</pre><p>This gives the decoder a consistent end of transcript target and helps avoid unnecessary continuation after the expected output has finished.</p><p>Finally, I remove examples whose target sequences exceed Whisper’s decoder capacity before training. It is much better to catch those samples during dataset preparation than to discover them halfway through a long training run.</p><p>None of these details change the architecture itself, but they matter a lot in practice. With Whisper, a training loop completing successfully does not automatically mean the fine tuning pipeline is configured correctly. I now verify the feature extractor path, tokenizer path, language conditioning, start token handling, EOS behavior and sequence lengths before trusting the loss curve.</p><h3>Saving Models That Can Actually Be Deployed</h3><p>PEFT based training creates another practical issue.</p><p>I do not want deployment to require keeping track of a base Whisper model, an encoder adapter and separately trained decoder state.</p><p>Each checkpoint therefore merges the encoder LoRA into the underlying encoder weights before saving.</p><p>The trainer creates a clean Whisper state dictionary, removes the LoRA specific tensors, restores the training state afterwards and writes a normal standalone Whisper model together with the processor.</p><p>The resulting checkpoint can be loaded directly through WhisperForConditionalGeneration.from_pretrained.</p><p>For experimentation, adapters are convenient.</p><p>For production, a self-contained artifact is much harder to misuse.</p><p>That is why I save the model this way at every checkpoint rather than only performing the merge as an afterthought at the end.</p><h3>From GSM Robustness to Production ASR</h3><p>Although this pipeline was originally developed around extremely degraded GSM speech, I would not consider it a GSM specific augmentation system anymore. Most production ASR systems encounter the same underlying problem in different forms: the audio reaching the model is rarely as consistent as the audio used during training.</p><p>A user may be speaking through a laptop microphone with a fan running nearby. Another recording may come from a car, a conference room, a Bluetooth headset or a mobile application that has already applied noise suppression and compression. The microphone response changes, the available bandwidth changes, the signal level changes and parts of the speech may be partially damaged before the backend receives anything.</p><p>The exact source of the degradation is different, but from the perspective of the acoustic encoder many of these conditions create the same problem. Information that was reliable during training suddenly becomes unreliable at inference time.</p><p>This is also why simply adding generic noise is not enough. Additive noise mostly interferes with an existing signal, while real audio pipelines can actually transform or remove parts of that signal. Bandwidth filtering removes spectral information. Resampling changes the available frequency content. Codecs introduce structured reconstruction artifacts. Packet loss removes short sections of temporal information and gain control changes the amplitude distribution.</p><p>Those transformations are much closer to the failures an ASR model actually encounters in production.</p><p>The objective therefore is not to make the audio as corrupted as possible. I try to make the corruption representative of real deployment conditions. Once the encoder repeatedly sees speech through different channel conditions during training, it becomes much less dependent on one clean acoustic representation.</p><p>That is the main reason the approach transfers well beyond GSM. GSM happens to be an extreme example because several forms of degradation occur at the same time, but the same training strategy can be applied to almost any ASR system where the input conditions are unpredictable.</p><h3>Adapting the Pipeline to the Deployment</h3><p>I would not copy the exact augmentation probabilities from this setup into another project. The useful part is the structure of the pipeline, not the specific numbers.</p><p>For a call center system I would keep strong bandwidth restriction, codec simulation and occasional packet loss because those are realistic parts of the input path. For meeting transcription I would reduce the emphasis on GSM style degradation and spend more of the augmentation budget on room acoustics, distant microphones, overlapping background speech and reverberation. A mobile voice application may need much more device variation, outdoor noise and codec diversity.</p><p>The augmentation distribution should be designed around what can realistically happen between the speaker and the model.</p><p>I also keep the implementation defensive because a long augmentation chain introduces many possible failure points. Noise files can be malformed, audio backends can fail on unusual samples and external tools such as SoX may not be available on every training machine. In my implementation these stages have fallback behavior so that one failed augmentation does not terminate an entire training run.</p><p>If codec simulation is unavailable, the sample can continue through the remaining transformations. If the main audio backend fails, another backend can handle much of the processing. If the complete degradation chain encounters an exception, the pipeline can fall back to a simpler noise and filtering path.</p><p>That part does not improve WER directly, but it matters once the same training pipeline is expected to run reliably across large datasets and long experiments.</p><p>The way I now design these systems is to start from the deployment path rather than from a list of popular augmentations. I first ask what can happen to the signal before it reaches the recognizer, then build training transformations around those failure modes. The closer the training distribution gets to the range of conditions the model will actually see, the less surprising production audio becomes.</p><h3>The Result I Was Actually Looking For</h3><p>My original goal was not to build an augmentation library. I wanted an ASR model that could reliably transcribe speech that looked almost unusable compared with normal benchmark audio.</p><p>After enough experimentation with GSM data, the most useful result was not simply that the model became better at GSM. It became harder to surprise acoustically.</p><p>That is the property I care about in a production recognizer.</p><p>The exact degradation will change from one application to another, but the principle remains the same. A laptop microphone beside a fan, a distant speaker in a conference room, a Bluetooth headset in a car and a damaged GSM call are all different channels through which the same underlying speech has to survive.</p><p>Additive noise perturbs a signal. A real communication channel can transform it.</p><p>We cannot manufacture linguistic diversity that does not exist in the original dataset, but we can make far better use of the acoustic data we already have. Take clean speech, expose it to realistic degradation, change that degradation continuously during training, and make difficult audio part of the model’s normal operating distribution rather than an edge case.</p><p>For me, that was the difference between an ASR model that worked on a dataset and one that could actually survive production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11328786c7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Nodes to Neurons: Building a Neural Network from Scratch in C++ with Linked Lists]]></title>
            <link>https://medium.com/@talhabinomar9991/from-nodes-to-neurons-building-a-neural-network-from-scratch-in-c-with-linked-lists-fa809738301c?source=rss-527ae2f1938f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa809738301c</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[model-training]]></category>
            <dc:creator><![CDATA[Talha Bin Omar]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 21:24:54 GMT</pubDate>
            <atom:updated>2024-11-27T04:31:36.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/0*zACRZMEA_pc1qMkM.PNG" /><figcaption>Image from GeeksforGeeks</figcaption></figure><p>How many of you have built a neural network in <strong>C++</strong>? Not many, I bet. Most developers stick to Python for its simplicity and excellent libraries like TensorFlow and PyTorch. But here’s the thing: building a neural network from scratch in <strong>C++</strong>, without relying on pre-built libraries, is an amazing learning experience.</p><p>It might seem intimidating as C++ isn’t known for its simplicity, and neural networks involve quite a bit of math. Add linked lists into the mix, and it sounds like a nightmare. But fear not! This article will guide you step by step, breaking it all down so you can understand, implement, and experiment on your own.</p><p><strong>Why C++ and Linked Lists?</strong></p><ul><li><strong>Control and Learning:</strong> Building from scratch in C++ forces you to understand every moving part of a neural network.</li><li><strong>Efficiency:</strong> C++ is fast and gives you fine-grained control over memory and computation.</li><li><strong>Simplicity in Structure:</strong> Using linked lists, we’ll implement everything in a modular and beginner-friendly way, avoiding overly complex data structures like vectors.</li></ul><p><strong>The Math Behind Neural Networks</strong></p><p>Before jumping into code, let’s understand the basic components of a neural network and the math that powers them:</p><p><strong>1. Neurons: The Building Blocks</strong></p><p>A neuron is the fundamental unit of a neural network. It processes multiple inputs and produces an output based on a weighted sum of these inputs, a bias term, and an activation function.</p><p>The <strong>mathematical representation</strong> of a neuron is:</p><p>y=Activation(Bias + W1X1 + W2X2 + …+ WnXn)</p><p>Where:</p><p>• x1, x2,….,xn : Inputs to the neuron.</p><p>• w1, w2,….., wn : Weights associated with each input.</p><p>• b : Bias term, which helps the neuron shift its activation.</p><p>• Activation: A function that determines whether the neuron “fires” or activates.</p><p>Think of weights as controlling the importance of each input, while the bias allows flexibility in decision boundaries.</p><p><strong>2. Layers: Organizing Neurons</strong></p><p>Neurons are grouped into <strong>layers</strong>, which are connected sequentially:</p><ul><li><strong>Input Layer:</strong> Takes raw data as input.</li><li><strong>Hidden Layers:</strong> Intermediate layers where computations and learning occur. These layers extract features from the input data.</li><li><strong>Output Layer:</strong> Produces the final predictions or classifications.</li></ul><p>Each layer transforms its input into a new representation using neurons, weights, and activation functions. The depth (number of layers) and width (number of neurons per layer) define the network’s architecture.</p><p>3. <strong>Activation Functions:</strong> Functions like Sigmoid and ReLU introduce non-linearity, enabling the network to learn complex patterns.</p><p>Activation functions play a crucial role in enabling neural networks to model complex patterns. Without them, the entire network would act like a simple linear function, no matter how many layers it has.</p><p>Here are the two most commonly used activation functions:</p><ul><li><strong>Sigmoid:</strong> f(x) = (1)/(1 + e^(-x))</li><li><strong>ReLU:</strong> f(x) = max(0, x)</li></ul><p>Other popular activation functions that you can explore in the future:</p><ul><li><strong>Tanh:</strong> Centers the output between -1 and 1.</li><li><strong>Leaky ReLU:</strong> A variation of ReLU that allows small gradients for negative inputs.</li></ul><p>4. <strong>Training:</strong> The goal of training a neural network is to minimize the error between the network’s predictions and the actual target values. This process involves:</p><p><strong>Forward Pass:</strong></p><p>Data flows through the network, layer by layer. The final output is compared to the target value to compute the error.</p><p><strong>Backward Pass (Backpropagation):</strong></p><p>In Backpropagation we compare the output of our model with the expected output and tune the parameters (weights and biased) of the neural network in a way that minimizes the error.</p><p>Since each parameter has different impact on the output of the model, we’ll adjust the parameters based on how much they influence on the output. But how do we know the amount of impact each parameter has. The answer is derivative.</p><p>The error is propagated backward through the network to adjust weights and biases. This is done using the <strong>chain rule of calculus</strong>, which computes the gradient of the loss function with respect to each weight and bias.</p><ul><li><strong>Gradient Descent:</strong> A method to update weights and biases to reduce the error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*MkqfaJA0ipyHtQ2Pkm4HWg.png" /></figure><p>Where</p><ul><li>w : Weight being updated.</li><li>σ: Learning rate, a small value that determines the step size</li><li>d/dw (Loss) : Gradient of the loss function with respect to the weight.</li></ul><h3>Code Deep Dive:</h3><p>Now that we’ve established the theory, it’s time to get started with the implementation. Writing a neural network from scratch in C++ can seem daunting at first, especially without high-level libraries to handle the heavy lifting. But don’t worry — this guide will break it down step-by-step. By the end, you’ll not only understand how the code works but also feel confident enough to tweak and expand it.</p><h4><strong>C++ Libraries Required:</strong></h4><pre>#include &lt;iostream&gt;<br>#include &lt;cmath&gt;<br>#include &lt;cstdlib&gt; </pre><h4><strong>1. Designing the Building Blocks</strong></h4><p>At its core, a neural network is made up of layers of neurons, and each neuron requires a way to handle weights, biases, and activations. To manage storing, accessing, updating these weights and biases, we’ll utilize Templated <strong>linked lists</strong> to create a flexible, dynamic structure.</p><p>Let’s start by implementing the <strong>linked list</strong> that will form the backbone of our neural network.</p><p><strong>The Linked List Class</strong></p><p>The <strong>LinkedList</strong> class is used to dynamically store values like weights, biases, and neuron outputs. By using <strong>templates</strong>, we ensure that the class can handle different data types, making it flexible for storing various types of network parameters (e.g., doubles for weights, ints for neuron counts).</p><ul><li><strong>Why Templates?</strong> Templates allow us to write generic code that works for any data type, enabling reusability and type safety. For example, we can store both double values (for weights) and int values (for indexing) in the same linked list structure.</li></ul><pre>template &lt;typename T&gt;<br>class LinkedList {<br>public:<br>    struct Node {<br>        T value;<br>        Node* next;<br>        Node(T val) : value(val), next(nullptr) {}<br>    };<br><br>    Node* head;<br><br>    LinkedList() : head(nullptr) {}<br><br>    void append(T value) {<br>        Node* newNode = new Node(value);<br>        if (!head) {<br>            head = newNode;<br>        } else {<br>            Node* temp = head;<br>            while (temp-&gt;next) {<br>                temp = temp-&gt;next;<br>            }<br>            temp-&gt;next = newNode;<br>        }<br>    }<br><br>    int size() const {<br>        int count = 0;<br>        Node* temp = head;<br>        while (temp) {<br>            count++;<br>            temp = temp-&gt;next;<br>        }<br>        return count;<br>    }<br><br>    T get(int index) const {<br>        Node* temp = head;<br>        int count = 0;<br>        while (temp) {<br>            if (count == index) return temp-&gt;value;<br>            temp = temp-&gt;next;<br>            count++;<br>        }<br>    }<br><br>    void update(int index, T value) {<br>        Node* temp = head;<br>        int count = 0;<br>        while (temp) {<br>            if (count == index) {<br>                temp-&gt;value = value;<br>                return;<br>            }<br>            temp = temp-&gt;next;<br>            count++;<br>        }<br>    }<br><br>    LinkedList&lt;T&gt; copy() const {<br>        LinkedList&lt;T&gt; newList;<br>        Node* temp = head;<br>        while (temp) {<br>            newList.append(temp-&gt;value);<br>            temp = temp-&gt;next;<br>        }<br>        return newList;<br>    }<br>};</pre><ol><li><strong>Structure</strong>: Each node stores a value (value) and a pointer to the next node (next).</li><li><strong>Dynamic Nature</strong>: The append method dynamically adds elements to the list. This is crucial for managing weights and neuron outputs, which vary depending on the network’s architecture.</li><li><strong>Access and Update</strong>: The get and update methods allow indexed access and modification, making it easy to work with weights and biases during training.</li></ol><h4><strong>2. Layer Class: Organizing Neurons and Weights</strong></h4><p>Each layer contains several neurons, and each neuron has weights, biases, and an activation function. The <strong>Layer class</strong> encapsulates this functionality by managing neurons, weights, biases, and activation functions. Let’s go through the code of the <strong>Layer</strong> class and break it down.</p><pre>class Layer {<br>private:<br>    LinkedList&lt;double&gt; weights;  // Store weights for each neuron<br>    LinkedList&lt;double&gt; neurons;  // Store outputs of neurons<br>    double bias;                 // Bias for the layer<br>    ActivationType activationType;  // Type of activation function <br><br>    // Activation functions<br>    double sigmoid(double x) const {<br>        return 1.0 / (1.0 + exp(-x));  // Sigmoid activation function<br>    }<br><br>    double relu(double x) const {<br>        return max(0.0, x);  // ReLU activation function<br>    }<br><br>public:<br>    // Constructor to initialize the layer with input size and number of neurons<br>    Layer(int inputSize, int neuronCount, ActivationType actType = Sigmoid)<br>        : activationType(actType), bias(((double)rand() / RAND_MAX) - 0.5) {<br>        // Initialize weights with random values between -0.5 and 0.5<br>        for (int i = 0; i &lt; neuronCount * inputSize; i++) {<br>            weights.append(((double)rand() / RAND_MAX) - 0.5);  <br>        }<br><br>        // Initializing neurons Linked List (to store outputs) with 0<br>        for (int i = 0; i &lt; neuronCount; i++) {<br>            neurons.append(0.0);<br>        }<br>    }<br><br>    // Performing a forward pass through the layer<br>    LinkedList&lt;double&gt; forward(const LinkedList&lt;double&gt;&amp; inputs) {<br>        LinkedList&lt;double&gt; outputs;  // List to store outputs of neurons<br>        int inputSize = inputs.size();  // Number of inputs<br>        int neuronCount = neurons.size();  // Number of neurons<br><br>        // Iterate through each neuron<br>        for (int n = 0; n &lt; neuronCount; n++) {<br>            double weightedSum = 0.0;<br><br>            // Calculate the weighted sum of inputs for this neuron<br>            for (int i = 0; i &lt; inputSize; i++) {<br>                weightedSum += inputs.get(i) * weights.get(n * inputSize + i);  // Weights are indexed by the neuron and input<br>            }<br><br>            weightedSum += bias;  // Add the bias to the weighted sum<br><br>            // Apply the activation function (Sigmoid or ReLU)<br>            double output;<br>            if (activationType == Sigmoid) {<br>                output = sigmoid(weightedSum);  // Sigmoid activation<br>            } else {<br>                output = relu(weightedSum);  // ReLU activation<br>            }<br><br>            neurons.update(n, output);  // Update the neuron&#39;s output<br>            outputs.append(output);  // Store the output in the list<br>        }<br><br>        return outputs;  // Return the list of outputs from the neurons<br>    }<br>};</pre><p><strong>1. Core Components of the Layer Class</strong></p><p>The Layer class has four main components:</p><ul><li><strong>Weights</strong>: A linked list that holds the connection weights between inputs and neurons. Each weight determines the importance of a specific input to a neuron and is initialized with random values between -0.5 and 0.5.</li><li><strong>Neurons</strong>: Another linked list that stores the outputs of each neuron after the activation function is applied.</li><li><strong>Bias</strong>: A single value added to the weighted sum for each neuron, helping the layer adjust its output during training.</li><li><strong>Activation Function</strong>: Determines how the output of each neuron is shaped. The class supports two activation functions:</li><li><strong>Sigmoid</strong>: Squashes the output to a range between 0 and 1.</li><li><strong>ReLU (Rectified Linear Unit)</strong>: Outputs the value directly if it’s positive, or 0 if it’s negative.</li></ul><p><strong>2. Constructing a Layer</strong></p><p>The constructor of the Layer class initializes the weights, biases, and neurons based on the number of inputs and neurons specified:</p><pre>Layer(int inputSize, int neuronCount, ActivationType actType = Sigmoid)</pre><ul><li><strong>Weights Initialization</strong>: For every connection between an input and a neuron, a weight is initialized randomly. For example, with 3 inputs and 2 neurons, 6 weights are created (3 per neuron).</li><li><strong>Neurons Initialization</strong>: The outputs for all neurons are initialized to zero. These placeholders will be updated during the forward pass.</li><li><strong>Bias Initialization</strong>: A single bias value is also initialized with a random value between -0.5 and 0.5.</li></ul><p>The choice of activation function (Sigmoid or ReLU) is stored as activationType.</p><p><strong>3. The Forward Pass: Transforming Inputs into Outputs</strong></p><p>The forward method takes a list of inputs and calculates the outputs for all neurons in the layer. Here’s how it works:</p><pre>LinkedList&lt;double&gt; forward(const LinkedList&lt;double&gt;&amp; inputs) {<br>    LinkedList&lt;double&gt; outputs;  // List to store outputs of neurons<br>    int inputSize = inputs.size();  // Number of inputs<br>    int neuronCount = neurons.size();  // Number of neurons</pre><p><strong>1. Initialize Outputs:</strong></p><p>• A new LinkedList called outputs is created to store the final results for each neuron.</p><p>• The inputSize and neuronCount are calculated to determine how to process the inputs and weights.</p><pre>    for (int n = 0; n &lt; neuronCount; n++) {<br>        double weightedSum = 0.0;</pre><p><strong>2. Process Each Neuron:</strong></p><ul><li>A loop iterates over every neuron in the layer.</li><li>For each neuron, a variable weightedSum is initialized to accumulate the weighted sum of inputs.</li></ul><pre>        for (int i = 0; i &lt; inputSize; i++) {<br>            weightedSum += inputs.get(i) * weights.get(n * inputSize + i);<br>        }<br>        weightedSum += bias;  // Add the bias to the weighted sum</pre><p><strong>3. Calculate the Weighted Sum:</strong></p><ul><li>The nested loop iterates over each input, multiplying it by its corresponding weight (weights.get(n * inputSize + i) refers to the weight connecting input i to neuron n).</li><li>These products are summed into weightedSum. Finally, the bias is added to the total.</li></ul><pre>        double output;<br>        if (activationType == Sigmoid) {<br>            output = sigmoid(weightedSum);<br>        } else {<br>            output = relu(weightedSum);<br>        }</pre><p>4. <strong>Apply Activation Function</strong>:</p><ul><li>Based on the selected activationType by the user, either the <strong>Sigmoid</strong> or <strong>ReLU</strong> function is applied to the weightedSum.</li><li>This transforms the raw weighted sum into a meaningful output for the neuron.</li></ul><pre>        neurons.update(n, output);  // Update the neuron&#39;s output<br>        outputs.append(output);    // Store the output in the list<br>    }</pre><p><strong>5. Store the Output:</strong></p><ul><li>The computed output is saved in the neurons list (for internal reference) and appended to the outputs list (to pass to the next layer or return as final output).</li></ul><h4><strong>3. NeuralNetwork Class: Putting it All Together</strong></h4><p>The <strong>NeuralNetwork</strong> class is where the magic happens. It manages the layers, performs forward propagation, and adjusts weights during training. Let’s break down the code for this class.</p><pre>class NeuralNetwork {<br>private:<br>    LinkedList&lt;Layer*&gt; layers;  // A linked list of layers in the network<br><br>public:<br>    // Constructor to initialize the network with layers<br>    NeuralNetwork(int inputSize, LinkedList&lt;Layer*&gt;&amp; layerList) {<br>        auto* temp = layerList.head;  // Pointer to the first layer in the list<br>        while (temp) {<br>            layers.append(temp-&gt;value);  // Add each layer to the network<br>            temp = temp-&gt;next;  // Move to the next layer in the list<br>        }<br>    }<br><br>    // Forward propagation through the entire network<br>    double predict(LinkedList&lt;double&gt;&amp; inputs) {<br>        LinkedList&lt;double&gt; currentInputs = inputs.copy();  // Copy the inputs to avoid modifying the original<br>        auto* temp = layers.head;  // Start from the first layer<br><br>        // Pass the inputs through each layer<br>        while (temp) {<br>            currentInputs = temp-&gt;value-&gt;forward(currentInputs);  // Get the output of the current layer<br>            temp = temp-&gt;next;  // Move to the next layer<br>        }<br><br>        return currentInputs.get(0);  // Return the final output (first neuron in the last layer)<br>    }<br><br>    // Training the network using backpropagation and gradient descent<br>    void train(LinkedList&lt;double&gt;&amp; inputs, double target, double learningRate) {<br>        double output = predict(inputs);  // Get the network&#39;s prediction<br>        double error = target - output;  // Calculate the error (difference between target and prediction)<br><br>        auto temp = layers.head;  // Pointer to the first layer in the network<br>        while (temp) {<br>            Layer* currentLayer = temp-&gt;value;  // Get the current layer<br>            LinkedList&lt;double&gt;&amp; currentWeights = currentLayer-&gt;getWeights();  // Get the weights of the current layer<br><br>            // Update weights using a simple gradient descent approach<br>            for (int i = 0; i &lt; currentWeights.size(); i++) {<br>                double gradient = error * inputs.get(i);  // Calculate the gradient for each weight<br>                double newWeight = currentWeights.get(i) + learningRate * gradient;  // Update the weight<br>                currentLayer-&gt;updateWeight(i, newWeight);  // Apply the weight update<br>            }<br><br>            // Update bias based on the error (simplified approach)<br>            double newBias = currentLayer-&gt;getBias() + learningRate * error;  // Update the bias<br>            currentLayer-&gt;updateBias(newBias);  // Apply the bias update<br><br>            temp = temp-&gt;next;  // Move to the next layer<br>        }<br>    }<br>};</pre><p>1. <strong>Class Variables</strong>:</p><ul><li>layers: A linked list that holds all the layers in the neural network.</li></ul><p>2. <strong>Constructor</strong>:</p><ul><li>Initializes the network by adding all layers from the passed layerList to the layers list in the network. This setup allows the network to have multiple layers stacked together.</li></ul><p>3. <strong>Prediction</strong>:</p><ul><li>The predict() method processes the input through all layers of the network, passing the data through each layer’s forward() function. The final output is returned from the last layer.</li></ul><p>4. <strong>Training</strong>:</p><ul><li>The train() method implements a simple <strong>gradient descent</strong> algorithm to adjust weights and biases based on the error.</li><li>It computes the error between the predicted output and the target.</li><li>Then, it updates the weights and biases using this error and a learning rate, making the network gradually improve over time.</li></ul><h4><strong>Training and Testing the Neural Network on a Simple Dataset:</strong></h4><p>Now that we’ve covered the inner workings of our neural network, it’s time to put it to use with a real-world application: training the network on a simple dataset and testing it on unseen data. In this section, we’ll explain how to train our network using a small dataset and how to test the network’s ability to generalize to new inputs.</p><p>Training Dataset:<br>X | Y | Output<br>1 | 1 | 2<br>2 | 2 | 4<br>3 | 3 | 6<br>4 | 4 | 8</p><p>Testing Dataset:<br>X | Y | Output<br>5 | 5 | 10<br>6 | 6 | 12</p><p>Let’s walk through the process step-by-step and explain each part of the code in detail.</p><p><strong>1. Defining the Layers and Neural Network</strong></p><p>In this main section of the code, we will now create the layers of the network and initialize the neural network object.</p><pre>int main() {<br>    // Create layers with specified number of neurons and activation functions<br>    Layer firstLayer(2, 2, ReLU);       // 2 inputs, 2 neurons, ReLU Activation function<br><br>    LinkedList&lt;Layer*&gt; layersList;      // Creating layerslist object to store all the layers<br>    layersList.append(&amp;firstLayer);     // Add the layer to the layers list<br><br>    // Create neural network with 2 inputs, and passing the layerslist object containing all the layers defined<br>    NeuralNetwork nn(2, layersList);</pre><p>Here, we initialize the first layer of the neural network with 2 input and 2 neurons. We’re using the <strong>ReLU</strong> activation function for this layer. The Layer class constructor takes the input size, the number of neurons, and the activation function type as arguments.</p><p><strong>Linked List of Layers</strong>: A linked list (layersList) is created to hold the layers. In our case, it’s just one layer, which is appended to the list.</p><p><strong>Neural Network Initialization</strong>: Next, we initialize the NeuralNetwork object with 2 inputs and the layersList we just created. This connects the layers to the neural network.</p><p><strong>2. Training the Neural Network</strong></p><p>Next, we define the dataset and begin training the network using <strong>gradient descent</strong>.</p><pre>    // Training data <br>    double inputs[4][2] = {{1, 1}, {2, 2}, {3, 3}, {4, 4}};<br>    double targets[4] = {2, 4, 6, 8};<br>    double learningRate = 0.1;<br>    int epochs = 10000000;<br><br>    // Train the network<br>    for (int epoch = 0; epoch &lt; epochs; epoch++) {<br>        for (int i = 0; i &lt; 4; i++) {<br>            LinkedList&lt;double&gt; inputList;<br>            inputList.append(inputs[i][0]);  // First input feature<br>            inputList.append(inputs[i][1]);  // Second input feature<br>            nn.train(inputList, targets[i], learningRate);  // Train using input-target pair<br>        }<br>    }</pre><p>The inputs array contains 4 samples, each with 2 input features. These inputs represent a simple dataset (Addition of two numbers).</p><ul><li><strong>Target Values</strong>: The targets array contains the desired outputs for the corresponding inputs. The network will try to learn these targets.</li><li><strong>Training Loop</strong>: We iterate over a set number of epochs (here, 10 million epochs, which is quite high but helps demonstrate the training process).</li></ul><p>In each epoch, we loop through all training samples. For each sample, we convert it into a LinkedList&lt;double&gt; and pass it along with the corresponding target to the train() method of the NeuralNetwork. This method adjusts the weights and biases using the error between the predicted output and the target.</p><p><strong>3. Testing the Neural Network</strong></p><p>After training, we test the neural network on the same dataset and see how well it predicts.</p><pre>    // Test the network<br>    cout &lt;&lt; &quot;\nTesting Neural Network after &quot; &lt;&lt; epochs &lt;&lt; &quot; epochs:&quot; &lt;&lt; endl;<br>    for (int i = 0; i &lt; 4; i++) {<br>        LinkedList&lt;double&gt; inputList;<br>        inputList.append(inputs[i][0]);<br>        inputList.append(inputs[i][1]);<br>        double output = nn.predict(inputList);  // Get the network&#39;s prediction<br>        cout &lt;&lt; &quot;Input: (&quot; &lt;&lt; inputs[i][0] &lt;&lt; &quot;, &quot; &lt;&lt; inputs[i][1]<br>             &lt;&lt; &quot;) -&gt; Output: &quot; &lt;&lt; output &lt;&lt; endl;<br>    }</pre><p>We print the predicted output alongside the input values to see how well the network has learned the task. Ideally, the predictions should be close to the target values we trained it on.</p><p>Results:</p><p>Testing Neural Network after 10000000 epochs:</p><p>Input: (1, 1) -&gt; Output: 2</p><p>Input: (2, 2) -&gt; Output: 4</p><p>Input: (3, 3) -&gt; Output: 6</p><p>Input: (4, 4) -&gt; Output: 8</p><p>Layer 0 Weights: 0.687966 1.31203 -0.0628082 0.0497716</p><p>Layer 0 Bias: 6.25303e-15, Activation: ReLU</p><p><strong>4. Testing on Unseen Data</strong></p><p>Finally, we test the neural network on new, unseen data to check how well it generalizes.</p><pre>    cout&lt;&lt;&quot;Testing on unseen data : &quot;&lt;&lt;endl;<br>    double input_test[2][2] = {{5, 5},{6,6}};<br>    for (int i = 0; i &lt; 2; i++) {<br>        LinkedList&lt;double&gt; inputList2;<br>        inputList2.append(input_test[i][0]);<br>        inputList2.append(input_test[i][1]);<br>        double output2 = nn.predict(inputList2);<br>        cout &lt;&lt; &quot;Input: (&quot; &lt;&lt; input_test[i][0] &lt;&lt; &quot;, &quot; &lt;&lt; input_test[i][1]<br>             &lt;&lt; &quot;) -&gt; Output: &quot; &lt;&lt; output2 &lt;&lt; endl;<br>    }<br>    return 0;<br>}</pre><p>We now create a new dataset (input_test) that wasn’t used during training. This helps us test the network’s ability to generalize to new data.</p><p><strong>Prediction on Unseen Data</strong>: We pass these unseen inputs through the network, and it makes predictions based on the learned parameters.</p><p><strong>Expected Outcome</strong>: We want to see how the network performs on new examples. If the network is working well, it should give reasonably accurate predictions for the unseen data based on the patterns it learned during training.</p><p><strong>Results:</strong></p><p>Testing on unseen data :</p><p>Input: (5, 5) -&gt; Output: 10</p><p>Input: (6, 6) -&gt; Output: 12</p><p>The results showcase the neural network’s ability to learn and generalize effectively. After training for 10,000,000 epochs, the network accurately mapped training inputs to outputs, such as (1, 1) → 2 and (4, 4) → 8, demonstrating successful parameter adjustment. More importantly, it generalized well to unseen data, predicting (5, 5) → 10 and (6, 6) → 12 with high accuracy. This indicates the model successfully captured the underlying linear relationship y = 2x and applied it beyond the training set. While effective, the high number of training epochs suggests room for optimization in convergence speed and efficiency.</p><h4>Conclusion:</h4><p>Starting with the fundamentals, we’ve demonstrated how the neural network learns to approximate desired outputs through a simple training loop, adjusting weights and biases using gradient descent. We also showed how the network can be tested both on the data it was trained on and new, unseen data, evaluating its ability to generalize.</p><p>While this example uses a simple dataset, the concepts we covered can be extended to more complex tasks and real-world applications. Whether you’re working with image data, natural language processing, or even time-series forecasting, the core principles of neural networks remain the same.</p><p>Building a neural network from scratch in C++ not only deepens your understanding of machine learning but also allows for greater flexibility and control over the model’s architecture and training process. By avoiding the abstraction layers of popular libraries like TensorFlow or PyTorch, you gain a deeper appreciation of how neural networks operate under the hood.</p><p>If you’re new to C++ or machine learning, don’t be intimidated. This project is a great starting point. Experiment with modifying the architecture, training on different datasets, or even implementing your own optimization techniques. The world of machine learning is vast, and now you have the tools to explore it from the ground up.</p><p>Complete Code: <a href="https://github.com/TBO22/Neural_Network_Implementation.git">https://github.com/TBO22/Neural_Network_Implementation.git</a></p><p>Keep experimenting, learning, and pushing the boundaries of what’s possible with machine learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa809738301c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>