<?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 Shahbaz Fareed on Medium]]></title>
        <description><![CDATA[Stories by Shahbaz Fareed on Medium]]></description>
        <link>https://medium.com/@shahbazfdev?source=rss-5cedd72140a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lqHITbAs-3PWaHyR</url>
            <title>Stories by Shahbaz Fareed on Medium</title>
            <link>https://medium.com/@shahbazfdev?source=rss-5cedd72140a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:56:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shahbazfdev/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[From Notebook to Ship: Deploying Offline AI with Flask, PyTorch, and SQLite]]></title>
            <link>https://medium.com/@shahbazfdev/from-notebook-to-ship-deploying-offline-ai-with-flask-pytorch-and-sqlite-14c719c3248f?source=rss-5cedd72140a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/14c719c3248f</guid>
            <category><![CDATA[digital-signal-processing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[audio-processing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shahbaz Fareed]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 18:37:45 GMT</pubDate>
            <atom:updated>2026-12-05T18:37:45.567Z</atom:updated>
            <content:encoded><![CDATA[<p>A machine learning model living in a Jupyter Notebook is useless to a sailor in the middle of the ocean. For my <a href="https://shahbazfdev.github.io/projects/identification-and-reduction-of-noise-by-mechanical_systems_onboard-ships">maritime noise reduction capstone</a> (see <a href="https://shahbazfdev.github.io/blog/ship-noise-crnn-tasnet-architecture">Part 1: 3-Stage Pipeline</a>, <a href="https://shahbazfdev.github.io/blog/crnn-audio-classification-qiandaoear22">Part 2: PyTorch CRNN</a>, and <a href="https://shahbazfdev.github.io/blog/pytorch-data-pipeline-qiandaoear22">Part 3: Data Pipeline</a>), accuracy wasn’t the only metric- <strong>usability in an offline environment</strong> was the real test.</p><blockquote><strong><em>TL;DR:</em></strong><em> Deploying deep learning onboard ships meant </em><strong><em>zero internet</em></strong><em>, </em><strong><em>CPU-only hardware (Intel i7)</em></strong><em>, and </em><strong><em>immediate local feedback</em></strong><em>. By choosing a monolithic </em><strong><em>Flask + Jinja2</em></strong><em> backend loading native PyTorch </em><em>.pth weights directly into memory and logging inference metadata to </em><strong><em>SQLite</em></strong><em>, I delivered a bare-metal signal processing station with Before/After audio playback and FFT visualization.</em></blockquote><h3>1. The Constraint: No Cloud, No GPUs</h3><p>Most modern AI tutorials assume AWS, Docker, or an NVIDIA A100. Maritime deployment imposed three hard constraints:</p><ul><li><strong>Hardware:</strong> Standard laptop CPU (Intel i7, no dedicated GPU).</li><li><strong>Connectivity:</strong> Zero internet-no external API calls.</li><li><strong>Latency:</strong> Immediate local feedback without waiting on cloud uploads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*S9dsh4Ka3K9ffbdHlHIc6w.png" /><figcaption>Cloud vs Offline</figcaption></figure><h3>2. Why Flask?</h3><p>I chose <strong>Flask (Python)</strong> for the backend because:</p><ol><li><strong>Native PyTorch Integration:</strong> Flask speaks the same language as PyTorch, allowing .pth checkpoints to be loaded directly into memory without ONNX conversion overhead.</li><li><strong>Low Overhead:</strong> As a micro-framework, Flask avoids Django’s extra footprint, leaving more RAM available for the heavy <strong>TasNet</strong> denoising models.</li><li><strong>Jinja2 Templating:</strong> Rendering HTML/CSS directly from the backend eliminated the need to maintain and bundle a separate frontend framework.</li></ol><h3>3. The Inference Engine</h3><p>When a user uploads or records noisy audio, the backend runs a multi-step pipeline:</p><ol><li><strong>Ingestion &amp; Normalization:</strong> Reads the audio stream, averages stereo channels to mono, trims silence (top_db=25), and pads clips shorter than 3 seconds.</li><li><strong>Stage 1 — YAMNet Detection:</strong> Acts as a gatekeeper to verify whether mechanical ship patterns exist.</li><li><strong>Stage 2 — CRNN Identification:</strong> Classifies the vessel into SpeedBoat, UUV, or KaiYuan using Log Mel Spectrograms.</li><li><strong>Stage 3 — TasNet Denoising &amp; FFT:</strong> Routes the audio to the class-specific TasNet model, returning base64-encoded Before/After .wav audio and FFT magnitude data.</li></ol><pre>def detect_recorded_audio(audio_file):<br>    BASE_DIR = &quot;C:/Users/shahbazfareed/Desktop/FinalSolution/models&quot;<br>    NEW_MODEL_PATH = os.path.join(BASE_DIR, &quot;task2.pth&quot;)<br><br>    TASNET_MODELS = {<br>        &quot;SpeedBoat&quot;: os.path.join(BASE_DIR, &quot;speedboat_tasnet_best_model.pth&quot;),<br>        &quot;KaiYuan&quot;: os.path.join(BASE_DIR, &quot;kaiyuan_tasnet_best_model.pth&quot;),<br>        &quot;UUV&quot;: os.path.join(BASE_DIR, &quot;uuv_tasnet_best_model.pth&quot;)<br>    }<br><br>    result = {<br>        &#39;success&#39;: False,<br>        &#39;predicted_class&#39;: &#39;Error&#39;,<br>        &#39;confidence&#39;: 0.0,<br>        &#39;total_duration&#39;: 0.0,<br>        &#39;warning&#39;: None,<br>        &#39;error&#39;: None,<br>        &#39;fft_data_original&#39;: None,<br>        &#39;processing_stage&#39;: &#39;unknown&#39;,<br>        &#39;audio_cleaned_base64&#39;: None,<br>        &#39;fft_data_cleaned&#39;: None,<br>        &#39;cleaning_method&#39;: &#39;tasnet_denoising&#39;,<br>        &#39;cleaning_attempted&#39;: False,<br>        &#39;cleaning_success&#39;: False,<br>        &#39;audio_original_base64&#39;: None,<br>    }<br><br>    try:<br>        if hasattr(audio_file, &#39;seek&#39;):<br>            audio_file.seek(0)<br><br>        file_content = io.BytesIO(audio_file.read() if hasattr(audio_file, &#39;read&#39;) else audio_file)<br>        raw_audio, sr = librosa.load(file_content, sr=TASNET_SR, mono=False)<br><br>        if raw_audio.ndim == 2:<br>            raw_audio = np.mean(raw_audio, axis=0)<br><br>        trimmed_audio, _ = librosa.effects.trim(raw_audio, top_db=25)<br>        analysis_audio = raw_audio if len(trimmed_audio) &lt; sr else trimmed_audio<br><br>        audio_duration = len(analysis_audio) / sr<br>        result[&#39;total_duration&#39;] = float(audio_duration)<br><br>        if audio_duration &lt; 3.0:<br>            padding = int(3.0 * sr) - len(analysis_audio)<br>            analysis_audio = np.pad(analysis_audio, (0, padding), &#39;constant&#39;)<br><br>        # Stage 1: YAMNet Ship Detection<br>        yamnet_detector = get_yamnet_detector()<br>        yamnet_audio = analysis_audio[:min(len(analysis_audio), int(3.0 * sr))]<br>        yamnet_result = yamnet_detector.analyze(yamnet_audio, sr)<br><br>        if not yamnet_result[&#39;success&#39;]:<br>            result[&#39;error&#39;] = &quot;YAMNet analysis failed&quot;<br>            return result<br><br>        if yamnet_result[&#39;is_ship&#39;]:<br>            result[&#39;processing_stage&#39;] = &#39;task2_ship_type&#39;<br>            reducer = MechanicalNoiseReducer(sr=sr)<br>            audio_reduced, _ = reducer.reduce_noise(analysis_audio)<br>            analysis_audio = audio_reduced if audio_reduced is not None else analysis_audio<br><br>            # Stage 2: CRNN Ship Type Identification<br>            segment = analysis_audio[:min(len(analysis_audio), int(3.0 * sr))]<br>            features = extract_logmel_spectrogram(segment, sr, duration=3.0)<br>            features_tensor = torch.FloatTensor(features).unsqueeze(0).unsqueeze(0)<br><br>            model_t2 = load_new_model(NEW_MODEL_PATH)<br>            with torch.no_grad():<br>                out_t2 = model_t2(features_tensor)<br>                prob_t2 = F.softmax(out_t2, dim=1)<br>                conf_t2, pred_t2 = torch.max(prob_t2, 1)<br><br>                ship_classes = [&quot;SpeedBoat&quot;, &quot;UUV&quot;, &quot;KaiYuan&quot;]<br>                ship_type = ship_classes[pred_t2.item()]<br>                ship_confidence = float(conf_t2.item())<br><br>            # Stage 3: TasNet Audio Cleaning<br>            if ship_type in TASNET_MODELS and os.path.exists(TASNET_MODELS[ship_type]):<br>                result[&#39;cleaning_attempted&#39;] = True<br>                audio_cleaned, fft_cleaned_data = clean_audio_with_tasnet(<br>                    audio=analysis_audio,<br>                    model_path=TASNET_MODELS[ship_type],<br>                    ship_type=ship_type,<br>                    sr=sr<br>                )<br>                if fft_cleaned_data:<br>                    freqs_cleaned, mags_cleaned = fft_cleaned_data<br>                    result[&#39;fft_data_cleaned&#39;] = {<br>                        &#39;frequencies&#39;: freqs_cleaned.tolist(),<br>                        &#39;magnitude&#39;: mags_cleaned.tolist()<br>                    }<br>                if not np.array_equal(audio_cleaned, analysis_audio):<br>                    result[&#39;cleaning_success&#39;] = True<br>                    result[&#39;cleaning_method&#39;] = f&#39;tasnet_{ship_type.lower()}&#39;<br><br>            result[&#39;success&#39;] = True<br>            result[&#39;predicted_class&#39;] = ship_type<br>            result[&#39;confidence&#39;] = yamnet_result[&#39;confidence&#39;] * ship_confidence<br>            return result<br>        else:<br>            result[&#39;success&#39;] = True<br>            result[&#39;predicted_class&#39;] = &#39;Unknown&#39;<br>            result[&#39;confidence&#39;] = 0.7<br>            result[&#39;processing_stage&#39;] = &#39;task0_not_ship&#39;<br>            result[&#39;warning&#39;] = &#39;No ship pattern detected&#39;<br>            return result<br><br>    except Exception as e:<br>        traceback.print_exc()<br>        result[&#39;error&#39;] = str(e)<br>        return result</pre><h3>4. The User Interface: An A/B Testing Dashboard</h3><p>I designed the frontend as an <strong>A/B testing tool</strong> for non-technical operators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bszPQkDiquOcr19r.png" /></figure><ul><li><strong>Before &amp; After Audio Players:</strong> Two HTML5 audio players side-by-side so the operator can play the noisy recording and immediately hear the AI-cleaned output.</li><li><strong>Spectrogram &amp; FFT Comparison:</strong> Visual confirmation of noise suppression across frequency bands.</li></ul><h3>5. Serverless Logging with SQLite</h3><p>To log inference history without installing or maintaining a separate database server, I used <strong>SQLite</strong> -a single file on disk:</p><pre>id | timestamp | original_filename | processing_time_ms | user_feedback</pre><h3>Frequently Asked Questions (FAQ)</h3><h3>Why use Flask instead of FastAPI or Dockerized microservices?</h3><p>On an offline, single-laptop deployment, Flask + Jinja2 eliminates separate frontend/backend processes and container overhead, leaving maximum RAM for PyTorch and TasNet inference.</p><h3>How does the app work without internet access?</h3><p>All model weights (.pth), audio processing ( librosa, soundfile), UI templates (Jinja2), and logging ( sqlite3) run locally on the host machine with zero external API calls.</p><h3>Why use SQLite instead of PostgreSQL?</h3><p>SQLite is serverless and stores everything in a single local file, making it ideal for offline single-node deployments where installing and managing a database daemon adds unnecessary complexity.</p><p><em>Originally published at </em><a href="https://shahbazfdev.github.io/blog/offline-ai-deployment-flask-sqlite/"><em>https://shahbazfdev.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14c719c3248f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Unsung Hero of AI: Building a Lazy-Loading PyTorch Data Pipeline for QiandaoEar22]]></title>
            <link>https://medium.com/@shahbazfdev/the-unsung-hero-of-ai-building-a-lazy-loading-pytorch-data-pipeline-for-qiandaoear22-e27518955f2a?source=rss-5cedd72140a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e27518955f2a</guid>
            <category><![CDATA[digital-signals]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[digital-signal-processing]]></category>
            <category><![CDATA[artifical-intellegence]]></category>
            <dc:creator><![CDATA[Shahbaz Fareed]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 18:30:08 GMT</pubDate>
            <atom:updated>2026-12-05T18:30:08.379Z</atom:updated>
            <content:encoded><![CDATA[<p>In deep learning, model architectures get all the glory-but <strong>the model is easy; the data is the hard part</strong>. While building my <a href="https://shahbazfdev.github.io/projects/identification-and-reduction-of-noise-by-mechanical_systems_onboard-ships">maritime noise reduction system</a> (covered in <a href="https://shahbazfdev.github.io/blog/ship-noise-crnn-tasnet-architecture">Part 1: 3-Stage Pipeline</a> and <a href="https://shahbazfdev.github.io/blog/crnn-audio-classification-qiandaoear22">Part 2: PyTorch CRNN</a>), I spent roughly 70% of my development time engineering a custom PyTorch data pipeline for the <strong>QiandaoEar22</strong> underwater acoustic dataset.</p><blockquote><strong><em>TL;DR:</em></strong><em> Loading gigabytes of raw hydrophone </em><em>.wav files into RAM causes immediate Out-of-Memory (OOM) crashes. By switching to a </em><strong><em>lazy-loading PyTorch </em></strong><strong><em>Dataset</em></strong><em> with on-the-fly Librosa Log Mel Spectrogram extraction (resampled to </em><em>52,734 Hz), </em><strong><em>inverse-frequency class weights</em></strong><em> in </em><em>CrossEntropyLoss, and </em><strong><em>synthetic SNR mixing</em></strong><em> for TasNet training, I kept RAM usage constant at </em><strong><em>~2 GB</em></strong><em> and completed </em><strong><em>14-hour, 50-epoch</em></strong><em> training runs on an </em><strong><em>NVIDIA RTX A4000</em></strong><em> without crashing.</em></blockquote><h3>1. The Challenge: QiandaoEar22 &amp; Memory Limits</h3><p>The QiandaoEar22 dataset consists of gigabytes of high-fidelity hydrophone recordings across mechanical categories ( Speedboat, UUV, Kaiyuan, and Noise-target).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*KeMZlT1AXO_7eJ6m.png" /></figure><p>Attempting to load the entire dataset into RAM on a standard Colab instance or laptop results in an immediate OOM crash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h0LKBdhyBAObQGgX.jpg" /></figure><p>When prototyping on small datasets like MNIST, eager loading works fine:</p><pre>data = []<br>for file in files:<br>    data.append(load_wav(file))</pre><p>For real-world audio, eager loading fails. Instead, I implemented <strong>Lazy Loading</strong> using PyTorch’s Dataset class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*ZmDOTiYUZo--dnJNobAVSQ.png" /><figcaption>Eager vs Lazy Loading</figcaption></figure><p>By storing only file paths in __init__ and reading .wav files inside __getitem__ only when the GPU requests a batch, RAM usage stayed constant at <strong>~2 GB</strong> regardless of dataset size.</p><h3>3. On-the-Fly Transformation: Waveform to Log Mel Spectrogram</h3><p>The <a href="https://shahbazfdev.github.io/blog/crnn-audio-classification-qiandaoear22">CRNN classifier</a> expects a 2D image-like spectrogram, while disk storage holds raw 1D waveforms. I integrated librosa directly into __getitem__:</p><ul><li><strong>Resampling (</strong><strong>52,734 Hz):</strong> Hydrophones recorded at varying sample rates, so every clip is resampled to 52,734 Hz for underwater acoustic fidelity.</li><li><strong>Mel Spectrogram (</strong><strong>n_fft=2048, </strong><strong>hop_length=512):</strong> Maps linear frequencies to the logarithmic Mel scale.</li><li><strong>Decibel Scaling (</strong><strong>librosa.power_to_db):</strong> Compresses the massive dynamic range of raw underwater audio, stabilizing gradients during backpropagation.</li></ul><h3>Custom PyTorch AudioDataset</h3><pre>class AudioDataset(Dataset):<br>    def __init__(self, file_paths, labels, config):<br>        self.file_paths = file_paths<br>        self.labels = labels<br>        self.sr = config[&#39;SAMPLE_RATE&#39;]<br>        self.n_mels = config[&#39;N_MELS&#39;]<br>        self.duration = config[&#39;DURATION&#39;]<br><br>    def __len__(self):<br>        return len(self.file_paths)<br><br>    def __getitem__(self, idx):<br>        # 1. Lazy Loading: Read disk only now<br>        file_path = self.file_paths[idx]<br><br>        # Load and pad/trim to exactly 3 seconds<br>        audio, _ = librosa.load(file_path, sr=self.sr)<br>        target_len = self.sr * self.duration<br><br>        # Zero-padding for short audio clips<br>        if len(audio) &lt; target_len:<br>            audio = np.pad(audio, (0, target_len - len(audio)))<br>        else:<br>            audio = audio[:target_len]<br><br>        # 2. Feature Extraction (On-the-Fly)<br>        mels = librosa.feature.melspectrogram(<br>            y=audio,<br>            sr=self.sr,<br>            n_mels=self.n_mels<br>        )<br>        log_mels = librosa.power_to_db(mels, ref=np.max)<br><br>        # 3. Tensor Conversion<br>        # Output shape: (1, 128, 130) -&gt; Channels First for PyTorch<br>        feature = torch.tensor(log_mels, dtype=torch.float32).unsqueeze(0)<br>        label = torch.tensor(self.labels[idx], dtype=torch.long)<br><br>        return feature, label</pre><h3>4. Solving Class Imbalance Without Oversampling</h3><p>Real-world acoustic data is heavily skewed toward <strong>Background Noise</strong> compared to specific targets like <strong>UUV</strong> or <strong>Speedboat</strong>. Without intervention, a model can achieve 80% accuracy simply by predicting background noise every time.</p><p>Instead of duplicating files via oversampling, I computed <strong>inverse-frequency class weights</strong> and passed them directly into nn.CrossEntropyLoss:</p><pre># Penalize the model MORE for missing a rare class (e.g., UUV)<br>class_weights = compute_class_weight(&#39;balanced&#39;, classes=np.unique(y), y=y)<br>weights_tensor = torch.tensor(class_weights, dtype=torch.float32).to(device)<br><br>criterion = nn.CrossEntropyLoss(weight=weights_tensor)</pre><p>This forced the optimizer to pay proportional attention to rare ship classes rather than memorizing the majority class distribution.</p><h3>5. Synthetic Data Generation for TasNet (The 14-Hour Problem)</h3><p>For Stage 3 (noise reduction with TasNet), I had noisy ship recordings from QiandaoEar22-but no matching “clean” ground-truth version of that exact ocean environment.</p><p>To solve this, I engineered a <strong>synthetic training pipeline</strong> that mathematically mixes clean audio sources (human speech) with QiandaoEar22 ship noise at varying <strong>Signal-to-Noise Ratios (SNRs)</strong>:</p><ul><li><strong>Goal:</strong> Train TasNet to treat ship mechanical noise as interference and isolate the clean target signal.</li><li><strong>Compute Cost:</strong> Processing terabytes of augmented audio required <strong>14 hours per model for 50 epochs</strong> on an <strong>NVIDIA RTX A4000</strong>.</li></ul><p>Without the lazy-loading AudioDataset keeping RAM flat at ~2 GB, those 14-hour training runs would have crashed from memory exhaustion long before convergence.</p><h3>Frequently Asked Questions (FAQ)</h3><p>Precomputing works if disk space is abundant and hyperparameters ( n_mels, n_fft, sr) are frozen. On-the-fly lazy loading in __getitem__ kept RAM constant at ~2 GB while allowing rapid experimentation with spectrogram parameters without regenerating gigabytes of cached files.</p><h3>Why use class weights in CrossEntropyLoss instead of oversampling?</h3><p>Oversampling duplicates minority-class audio clips, which increases epoch time and risks overfitting to repeated samples. Inverse-frequency class weights penalize misclassifications of rare classes like UUV directly in the loss function with zero extra memory overhead.</p><h3>How does synthetic SNR mixing help train TasNet?</h3><p>Because real underwater recordings lack isolated “clean” ground-truth pairs, mixing clean reference signals with QiandaoEar22 ship noise at controlled SNRs creates exact input/target pairs for supervised time-domain audio separation.</p><p><em>Originally published at </em><a href="https://shahbazfdev.github.io/blog/pytorch-data-pipeline-qiandaoear22/"><em>https://shahbazfdev.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e27518955f2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Stage 2: Building a PyTorch CRNN for Maritime Audio Classification]]></title>
            <link>https://medium.com/@shahbazfdev/deep-dive-into-stage-2-building-a-pytorch-crnn-for-maritime-audio-classification-f71034add80b?source=rss-5cedd72140a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f71034add80b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[digital-signal-processing]]></category>
            <category><![CDATA[audio-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shahbaz Fareed]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 18:10:37 GMT</pubDate>
            <atom:updated>2026-12-05T18:10:37.570Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR:</strong> To classify shipboard mechanical noise on the <strong>QiandaoEar22</strong> dataset, we built a hybrid <strong>Convolutional Recurrent Neural Network (CRNN)</strong> in PyTorch-combining 4 CNN blocks for spatial Log-Mel Spectrogram feature extraction with a 2-layer <strong>Bidirectional GRU</strong> for temporal modeling-achieving <strong>~81% test accuracy</strong> with early stopping and ReduceLROnPlateau.</p><p>In my <a href="https://shahbazfdev.github.io/blog/ship-noise-crnn-tasnet-architecture">previous post</a>, I shared the results of my end-to-end maritime noise reduction pipeline achieving <strong>81% classification accuracy</strong> and <strong>60% noise reduction</strong>.</p><p>Today, I want to peel back the layers of <strong>Stage 2: The Identification Module</strong>.</p><p>When dealing with audio data, a common debate is: <em>Should we use Convolutional Neural Networks (CNNs) or Recurrent Neural Networks (RNNs)?</em></p><p>For my project, I chose neither. Instead, I built a hybrid: a <strong>Convolutional Recurrent Neural Network (CRNN)</strong>. Here is the technical breakdown of why this architecture was the perfect fit for the <strong>QiandaoEar22</strong> dataset and how I implemented it using <strong>PyTorch</strong>.</p><h3>1. The Data: Treating Sound as an Image</h3><p>Before feeding audio into a neural network, it needs to be transformed. Raw waveforms are dense and noisy.</p><p>I utilized <strong>Librosa</strong> to convert the 3-second .wav files into <strong>Log Mel Spectrograms</strong>.</p><ul><li><strong>Why Log Mel?</strong> It mimics human hearing perception (logarithmic scale) and effectively converts the audio problem into an “image” problem.</li><li><strong>The Shape:</strong> Unlike TensorFlow, PyTorch uses the <strong>“Channels First”</strong> convention. This resulted in input tensors of shape (1, 128, 130), representing (Channels, Freq, Time).</li></ul><h3>2. The Architecture: Best of Both Worlds</h3><p>The core challenge with ship noise is that it has both <strong>spatial features</strong> (specific frequency patterns of an engine) and <strong>temporal features</strong> (the rhythmic “chug-chug” of a piston over time).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*spEctvjc4xuz3XWD2j6YcQ.png" /></figure><h3>Part A: The Feature Extractor (CNN)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9OBHpliIq9uhvDr2.png" /></figure><p>I defined a class inheriting from nn.Module utilizing four convolutional blocks ( 32, 64, 128, and 256 filters) with BatchNorm2d and nn.MaxPool2d.</p><ul><li><strong>What it does:</strong> This section acts as a “feature extractor,” scanning the spectrogram to identify the unique spectral signatures of a <strong>Speedboat</strong> versus a <strong>UUV</strong>.</li><li><strong>Code Insight:</strong> I used padding=1 to preserve spatial dimensions and nn.ReLU() for non-linearity.</li></ul><h3>Part B: The Temporal Learner (RNN)</h3><p>After flattening the CNN output (permuting dimensions to put <strong>Time</strong> first), I fed the feature maps into a <strong>Bidirectional GRU</strong> (Gated Recurrent Unit).</p><ul><li><strong>Why GRU over LSTM?</strong> GRUs are computationally lighter than LSTMs with similar performance-critical for an offline deployment on a ship.</li><li><strong>Why Bidirectional?</strong> It allows the network to learn from the audio context in both directions (past and future), capturing the full rhythmic cycle of the mechanical noise.</li></ul><pre>class CRNN(nn.Module):<br>    &quot;&quot;&quot;<br>    Convolutional Recurrent Neural Network for audio classification<br>    Improved with better feature extraction<br>    &quot;&quot;&quot;<br><br>    def __init__(self, input_channels=1, num_classes=3, hidden_size=128):<br>        super(CRNN, self).__init__()<br><br>        # Enhanced CNN Feature Extractor (4 convolutional blocks with batch norm)<br>        self.conv1 = nn.Conv2d(input_channels, 32, kernel_size=3, padding=1)<br>        self.bn1 = nn.BatchNorm2d(32)<br>        self.conv2 = nn.Conv2d(32, 32, kernel_size=3, padding=1)<br>        self.bn2 = nn.BatchNorm2d(32)<br>        self.pool1 = nn.MaxPool2d(kernel_size=2)<br><br>        self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1)<br>        self.bn3 = nn.BatchNorm2d(64)<br>        self.conv4 = nn.Conv2d(64, 64, kernel_size=3, padding=1)<br>        self.bn4 = nn.BatchNorm2d(64)<br>        self.pool2 = nn.MaxPool2d(kernel_size=2)<br><br>        self.conv5 = nn.Conv2d(64, 128, kernel_size=3, padding=1)<br>        self.bn5 = nn.BatchNorm2d(128)<br>        self.conv6 = nn.Conv2d(128, 128, kernel_size=3, padding=1)<br>        self.bn6 = nn.BatchNorm2d(128)<br>        self.pool3 = nn.MaxPool2d(kernel_size=(2, 2))<br><br>        self.conv7 = nn.Conv2d(128, 256, kernel_size=3, padding=1)<br>        self.bn7 = nn.BatchNorm2d(256)<br>        self.conv8 = nn.Conv2d(256, 256, kernel_size=3, padding=1)<br>        self.bn8 = nn.BatchNorm2d(256)<br>        self.pool4 = nn.MaxPool2d(kernel_size=(2, 2))<br><br>        self.dropout = nn.Dropout(0.5)<br><br>        # Calculate CNN output size dynamically<br>        self.cnn_output_size = self._calculate_cnn_output_size()<br><br>        # Bidirectional GRU for temporal modeling<br>        self.rnn = nn.GRU(<br>            input_size=self.cnn_output_size,<br>            hidden_size=hidden_size,<br>            num_layers=2,<br>            batch_first=True,<br>            bidirectional=True,<br>            dropout=0.3<br>        )<br><br>        # Enhanced Classifier<br>        self.fc1 = nn.Linear(hidden_size * 2, 128)  # *2 for bidirectional<br>        self.bn9 = nn.BatchNorm1d(128)<br>        self.fc2 = nn.Linear(128, 64)<br>        self.bn10 = nn.BatchNorm1d(64)<br>        self.fc3 = nn.Linear(64, num_classes)<br><br>    def _calculate_cnn_output_size(self):<br>        &quot;&quot;&quot;Calculate CNN output feature size&quot;&quot;&quot;<br>        dummy_input = torch.zeros(1, 1, N_MELS, 311)  # Estimated time frames for 3s audio<br>        with torch.no_grad():<br>            x = self._cnn_forward(dummy_input, feature_only=True)<br>        return x.shape[1] * x.shape[2]  # channels * height<br><br>    def _cnn_forward(self, x, feature_only=False):<br>        &quot;&quot;&quot;Forward pass through CNN layers&quot;&quot;&quot;<br>        x = F.relu(self.bn1(self.conv1(x)))<br>        x = F.relu(self.bn2(self.conv2(x)))<br>        x = self.pool1(x)<br><br>        x = F.relu(self.bn3(self.conv3(x)))<br>        x = F.relu(self.bn4(self.conv4(x)))<br>        x = self.pool2(x)<br><br>        x = F.relu(self.bn5(self.conv5(x)))<br>        x = F.relu(self.bn6(self.conv6(x)))<br>        x = self.pool3(x)<br><br>        x = F.relu(self.bn7(self.conv7(x)))<br>        x = F.relu(self.bn8(self.conv8(x)))<br>        x = self.pool4(x)<br><br>        if feature_only:<br>            return x<br><br>        x = self.dropout(x)<br>        return x<br><br>    def forward(self, x):<br>        batch_size = x.size(0)<br><br>        # CNN forward<br>        x = self._cnn_forward(x)<br><br>        # Reshape for RNN: [batch, channels, height, time] -&gt; [batch, time, channels*height]<br>        x = x.permute(0, 3, 1, 2)  # [batch, time, channels, height]<br>        x = x.reshape(batch_size, x.size(1), -1)  # [batch, time, features]<br><br>        # RNN forward<br>        rnn_out, _ = self.rnn(x)<br><br>        # Use mean pooling over time dimension (better than last time step)<br>        rnn_out = torch.mean(rnn_out, dim=1)<br><br>        # Classifier with batch norm<br>        x = F.relu(self.bn9(self.fc1(rnn_out)))<br>        x = self.dropout(x)<br>        x = F.relu(self.bn10(self.fc2(x)))<br>        x = self.dropout(x)<br>        x = self.fc3(x)<br><br>        return x</pre><h3>3. The “Smart” Training Strategy</h3><p>In PyTorch, we don’t just call fit(); we write the training loop. This gave me granular control over the optimization process. To ensure convergence and prevent overfitting on the <strong>QiandaoEar22</strong> dataset, I implemented:</p><ul><li><strong>Custom Early Stopping:</strong> Tracked validation_loss after every epoch. If the loss didn&#39;t decrease for 5 consecutive epochs (Patience=5), I triggered a hard stop and loaded the best model state using torch.save().</li><li><strong>Adaptive Learning Rate:</strong> Utilized torch.optim.lr_scheduler.ReduceLROnPlateau.</li></ul><h3>4. The Results</h3><p>The training strategy paid off. The model achieved a <strong>Test Accuracy of ~81%</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*gx87BEadFwRTI42s.png" /></figure><p>Looking at the Confusion Matrix, the model showed distinct strength in separating <strong>“Kaiyuan”</strong> (a specific ship class) from background noise, which was the primary goal of this stage.</p><h3>Conclusion</h3><p>Building this CRNN taught me that model architecture isn’t about throwing the biggest network at a problem; it’s about understanding your data. By combining the feature extraction power of CNNs with the temporal memory of GRUs in PyTorch, I created a lightweight, highly accurate classifier suitable for real-time naval applications.</p><p>You can view the full training notebook and code on my <a href="https://github.com/shahbazfdev">GitHub</a>, or explore the <a href="https://shahbazfdev.github.io/projects/identification-and-reduction-of-noise-by-mechanical_systems_onboard-ships">project case study</a>.</p><h3>Frequently Asked Questions</h3><h3>Why use a CRNN instead of a standalone CNN or RNN for audio?</h3><p>A CNN captures spatial frequency patterns in Log Mel Spectrograms, while a Bidirectional GRU models the temporal rhythm of mechanical noise. Combining them achieves <strong>~81% test accuracy</strong> while remaining lightweight enough for offline shipboard deployment.</p><h3>Why use Bidirectional GRU instead of LSTM?</h3><p>GRUs are computationally lighter than LSTMs with comparable accuracy, and bidirectional processing lets the model learn from both past and future acoustic context across each 3-second clip.</p><h3>How was overfitting prevented on QiandaoEar22?</h3><p>We used <strong>custom early stopping</strong> ( Patience=5 on validation_loss), <strong>Dropout (0.5 / 0.3)</strong>, <strong>BatchNorm</strong>, and ReduceLROnPlateau learning-rate scheduling.</p><p><em>Originally published at </em><a href="https://shahbazfdev.github.io/blog/crnn-audio-classification-qiandaoear22/"><em>https://shahbazfdev.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f71034add80b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Deep Learning Pipeline for Maritime Noise Reduction — Shahbaz Fareed]]></title>
            <link>https://medium.com/@shahbazfdev/end-to-end-deep-learning-pipeline-for-maritime-noise-reduction-shahbaz-fareed-shahbaz-b0d4a931ec1f?source=rss-5cedd72140a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0d4a931ec1f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[audio-processing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Shahbaz Fareed]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 17:57:38 GMT</pubDate>
            <atom:updated>2026-12-05T17:58:01.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*16Pw34kBRC5L7Eyz.png" /><figcaption>Dataset Structure</figcaption></figure><p><strong>TL;DR:</strong> Using the <strong>QiandaoEar22</strong> underwater acoustic dataset, we built a 3-stage deep learning pipeline- <strong>YAMNet</strong> (detection gatekeeper) → <strong>CRNN</strong> (noise source classification) → <strong>TasNet</strong> (time-domain denoising)-that reduces shipboard mechanical noise by <strong>60%</strong>, deployed offline-first with <strong>Flask</strong> and <strong>SQLite</strong>.</p><h3>Introduction</h3><p>I am incredibly excited to share the technical breakdown of my Final Year Project: <strong>“Identification and Reduction of Noise by Mechanical Systems Onboard Ships.”</strong></p><p>Mechanical noise in maritime vessels is a critical issue; it compromises stealth, interferes with sonar, and poses significant risks to crew health. My goal was to move beyond traditional, expensive hardware solutions and build a software-defined, AI-driven system capable of real-time diagnostics and signal purification.</p><p>This article details the data engineering, model architecture, and full-stack deployment of a system designed to detect and reduce ship noise by <strong>60%</strong>.</p><h3>1. The Data: Wrangling QiandaoEar22</h3><p>Data preprocessing was a massive component of this project. I utilized the <strong>QiandaoEar22</strong> dataset, a specialized underwater acoustic collection. Since this is an audio dataset consisting of raw .wav files, ensuring data quality was paramount.</p><h3>Dataset Structure</h3><p>The dataset is highly structured and branches into specific mechanical categories:</p><p>Inside each category, data is further split into <strong>“Target”</strong> (the pure sound) and <strong>“Other”</strong> (background interference), containing the actual .wav files.</p><h3>Preprocessing Pipeline</h3><p>Each audio file in the dataset is exactly <strong>3 seconds</strong> long. I built a robust preprocessing pipeline to normalize these clips, handle variable sample rates, and convert them into <strong>Log Mel Spectrograms</strong>. This conversion was critical for allowing the downstream Convolutional Neural Networks (CNNs) to digest the audio features effectively.</p><h3>2. The Architecture: A 3-Stage Deep Learning Pipeline</h3><p>To achieve high fidelity and accuracy, I designed a pipeline that processes the preprocessed audio in three distinct phases. This multi-stage approach ensures efficient resource usage and high classification precision.</p><h3>Stage 1: Detection (The Gatekeeper)</h3><p>I utilized <strong>YAMNet</strong>, a pre-trained deep neural network, to act as the initial filter.</p><ul><li><strong>Function:</strong> YAMNet continuously scans the audio stream to determine if a target mechanical noise exists.</li><li><strong>Why:</strong> This acts as a gatekeeper, ensuring efficient processing power usage. The system only triggers the heavier downstream models when relevant noise is actually present, saving computational resources.</li></ul><h3>Stage 2: Identification (The Classifier)</h3><p>Once a noise is flagged by the detector, it is passed to a <strong>Convolutional Recurrent Neural Network (CRNN)</strong>.</p><h3>Stage 3: Reduction (The Denoiser)</h3><p>This was the most computationally intensive phase of the project. I trained three separate <strong>TasNets</strong> (Time-domain Audio Separation Networks)-one specifically dedicated to each category.</p><ul><li><strong>Training Complexity:</strong> Training these models was rigorous. Each category required <strong>50 epochs</strong> of training, taking approximately <strong>14 hours per model</strong> to converge effectively. By increasing the number of epochs, accuracy can increase to <strong>80%</strong>.</li><li><strong>The Result:</strong> The TasNets successfully removed background noise by <strong>60%</strong>, outputting a highly purified audio signal suitable for analysis.</li></ul><h3>3. Full-Stack Deployment</h3><p>To make this system accessible for naval engineers, I did not stop at the model level. I wrapped these deep learning models into a fully deployable web application.</p><ul><li><strong>Backend:</strong> Built with <strong>Flask (Python)</strong>, which handles the API requests and manages model inference in real time.</li><li><strong>Storage:</strong> Integrated <strong>SQLite</strong> to manage local logging of detection timestamps and confidence scores. This ensures offline functionality, a critical requirement for ships operating at sea with limited internet connectivity.</li></ul><h3>Conclusion &amp; Code</h3><p>Building this system bridged the gap between theoretical Deep Learning and practical software engineering. I am immensely proud of the persistence required to train these heavy models-particularly the TasNets-and the results achieved in signal purification.</p><p>I strongly believe in open-source development. You can check out the full code, the preprocessing scripts, and the model architecture on my <a href="https://github.com/shahbazfdev">GitHub</a>, or view the <a href="https://shahbazfdev.github.io/projects/identification-and-reduction-of-noise-by-mechanical_systems_onboard-ships">project case study</a>.</p><p>I am looking forward to applying this expertise in Data Science and Machine Learning roles. If you are working on similar challenges in signal processing or AI, I would love to connect.</p><h3>Frequently Asked Questions</h3><h3>What dataset was used for shipboard mechanical noise reduction?</h3><p>We used the <strong>QiandaoEar22</strong> underwater acoustic dataset, which contains 3-second .wav clips across <strong>Speedboat</strong>, <strong>UUV</strong>, <strong>Kaiyuan</strong>, and <strong>Noise-target</strong> categories, split into <em>Target</em> and <em>Other</em> interference.</p><h3>Why use YAMNet before CRNN and TasNet?</h3><p><strong>YAMNet</strong> acts as a lightweight gatekeeper that continuously scans incoming audio and only triggers the heavier <strong>CRNN</strong> and <strong>TasNet</strong> models when relevant mechanical noise is detected, saving compute.</p><h3>How much noise reduction did the TasNet models achieve?</h3><p>Training three dedicated <strong>TasNet</strong> models (50 epochs each, ~14 hours per model) reduced background mechanical noise by <strong>60%</strong>, with potential to reach <strong>80%</strong> accuracy with additional training epochs.</p><h3>How is the system deployed for ships with limited internet?</h3><p>The pipeline is wrapped in a <strong>Flask</strong> REST API backed by <strong>SQLite</strong> for local logging of detection timestamps and confidence scores, enabling reliable offline operation at sea.</p><p><em>Originally published at </em><a href="https://shahbazfdev.github.io/blog/ship-noise-crnn-tasnet-architecture/"><em>https://shahbazfdev.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0d4a931ec1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>