<?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 Hamdi Boukamcha on Medium]]></title>
        <description><![CDATA[Stories by Hamdi Boukamcha on Medium]]></description>
        <link>https://medium.com/@boukamchahamdi?source=rss-26cbe30d49bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9u4_pETU7oimOGXsc0qM0w.jpeg</url>
            <title>Stories by Hamdi Boukamcha on Medium</title>
            <link>https://medium.com/@boukamchahamdi?source=rss-26cbe30d49bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:03:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@boukamchahamdi/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[Startups and AI: What the Numbers Really Say in 2026!]]></title>
            <link>https://medium.com/@boukamchahamdi/startups-and-ai-what-the-numbers-really-say-in-2026-49c3a7e954ab?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/49c3a7e954ab</guid>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[bussiness]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 10:20:54 GMT</pubDate>
            <atom:updated>2026-08-30T10:20:54.620Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvSdVwV7vit7jn7ZKfVfBA.png" /></figure><p>For three years, since the AI wave began, I have been following this trend and watching its real impact on businesses. Not the promises, not the big announcements: the numbers. What AI really changes in the life of companies, month after month.</p><p>What I saw does not look like the story told by the excited people. And it does not look like the story told by the doubters either.</p><p>Before, building software needed a team, months of work, and a lot of money. It was a wall: only a few people could try.</p><p>AI broke that wall. Today, you describe what you want, and the AI writes the code. At Y Combinator, the most famous startup incubator in the world, one startup out of four chosen in early 2025 had code written 95% by AI.</p><h3>What is going very well</h3><p>The ones who succeed, succeed much faster. According to Stripe, which handles the payments of thousands of companies, AI startups reach their first million dollars of revenue in 11.5 months — four months faster than the generation before them. And with very few people: Lovable reached 200 million dollars of revenue with 45 employees.</p><h3>What is going badly</h3><p>The problem is that everybody has the same tool. If it is easy for you, it is easy for everyone, at the same time. Thousands of almost identical products appear. The customer is lost in all this choice: he tries, he hesitates, then he gives up.</p><p>And during this time, customers do not get much. MIT studied 300 AI projects inside companies: 95% of them produced no measurable financial result. The technology is not the problem. The problem is that the tool never really enters the daily work of the teams.</p><p>The worst danger comes from above. If your product is simple, OpenAI or Google adds it for free in an update, and your company has no reason to exist anymore. A Google manager said it in February 2026: putting a very thin layer of your own ideas on top of their models is not enough anymore.</p><h3>And what about the companies that close?</h3><p>Everywhere you will read that “80% or 90% of AI startups are going to close.” That number is false. People say it comes from big analyst firms, but those firms never published it. Blogs simply copy each other.</p><p>Here is what is really measured: Gartner expects that more than 40% of company AI projects will be cancelled before 2027 — but those are projects, not startups. And at Carta, which follows the real closures, these closures doubled at the seed stage between 2023 and 2024 — except that the companies that die are seven years old on average. They were born before AI.</p><p>Nobody knows their failure rate. The story is being written while we read it. So let’s follow it together, and we will see who was right.</p><p><strong>Sources:</strong> Stripe, “Indexing the AI economy” · MIT Project NANDA, “The GenAI Divide”, 2025 · Gartner, June 2025 · Carta · TechCrunch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49c3a7e954ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RF-DETR C++ TENSORRT: Real-Time End-to-End Object Detection]]></title>
            <link>https://medium.com/@boukamchahamdi/rf-detr-c-tensorrt-real-time-end-to-end-object-detection-7eec852e68a7?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eec852e68a7</guid>
            <category><![CDATA[rf-detc]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[tensorrt]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 17:27:35 GMT</pubDate>
            <atom:updated>2025-04-09T17:27:35.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*FiNAOrhJl0XrnH7P2eUiww.jpeg" /></figure><p>In the ever-evolving field of computer vision, achieving real-time object detection with high accuracy is paramount. Enter <strong>RF-DETR C++ TENSORRT</strong> — a robust, production-ready solution designed to harness the power of NVIDIA TensorRT and CUDA for high-speed, efficient object detection. This project leverages the RF-DETR model architecture and provides an end-to-end pipeline that transforms raw image data into actionable detection results with minimal latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fh6s9YD5KmJNXCUaM2u_PA.gif" /><figcaption>RF-DETR C++ Ouput</figcaption></figure><h3>Overview</h3><p>RF-DETR C++ TENSORRT is a cutting-edge implementation built in C++ that optimizes the RF-DETR model using NVIDIA’s TensorRT. By converting pre-trained ONNX models into highly efficient TensorRT engines, the project delivers rapid inference, making it an ideal choice for applications such as autonomous driving, real-time surveillance, and robotics.</p><p>Key aspects include:</p><ul><li><strong>Optimized Model Conversion:</strong> Seamlessly converting RF-DETR ONNX models into TensorRT engines</li><li><strong>CUDA-Accelerated Preprocessing:</strong> Leveraging CUDA to prepare image data swiftly for inference.</li><li><strong>Lean C++ Implementation:</strong> A robust codebase that emphasizes performance and modularity.</li></ul><h3>How It Works</h3><p>RF-DETR C++ TENSORRT is engineered for performance from initialization to inference. Here’s a closer look at its core components:</p><h3>1. TensorRT Engine Initialization</h3><p>The journey begins with initializing the TensorRT engine:</p><ul><li><strong>Engine Deserialization:</strong> The system loads a serialized TensorRT engine file (typically a .trt file), rebuilding the optimized model for runtime execution.</li><li><strong>Execution Context Setup:</strong> An execution context is created to prepare the engine for efficient, asynchronous inference.</li><li><strong>Resource Allocation:</strong> GPU memory is allocated for both input and output buffers, ensuring that data flows seamlessly through the engine during inference.</li></ul><p>This setup phase is critical, as it minimizes overhead and maximizes throughput during real-time operations.</p><h3>2. Image Preprocessing and Postprocessing</h3><p>To ensure the model receives data in the correct format, RF-DETR employs both preprocessing and postprocessing techniques:</p><p><strong>Preprocessing Steps:</strong></p><ul><li><strong>Resizing:</strong> Input images are resized to match the expected input dimensions of the RF-DETR model.</li><li><strong>Normalization:</strong> Images are normalized using predefined mean and standard deviation values, replicating the conditions used during model training.</li><li><strong>CUDA Integration:</strong> The preprocessing leverages CUDA to accelerate these tasks, reducing CPU bottlenecks and ensuring quick data preparation.</li></ul><p><strong>Postprocessing Steps:</strong></p><ul><li><strong>Output Decoding:</strong> Raw outputs from the TensorRT engine (comprising bounding boxes, class scores, and confidence levels) are decoded.</li><li><strong>Result Formatting:</strong> The results are formatted into a user-friendly representation, ready for visualization or further analysis.</li></ul><h3>3. Real-Time Inference Pipeline</h3><p>The inference pipeline is designed for speed and efficiency:</p><ol><li><strong>Data Transfer:</strong> Preprocessed images are asynchronously transferred from CPU to GPU memory.</li><li><strong>Inference Execution:</strong> The TensorRT execution context performs the forward pass, utilizing the parallel processing power of NVIDIA GPUs.</li><li><strong>Output Retrieval:</strong> The detection results are asynchronously copied back to the host for final processing.</li><li><strong>Postprocessing:</strong> The raw results are converted into structured detection outputs, such as bounding boxes with class labels and confidence scores.</li></ol><p>This pipeline ensures that the system can handle both static images and continuous video streams in real time.</p><h3>4. Comprehensive Demo and Integration</h3><p>The repository’s main.cpp provides a comprehensive demo, illustrating how to integrate RF-DETR C++ TENSORRT into your projects. Highlights include:</p><ul><li><strong>Versatile Input Handling:</strong> Support for both single-image and video stream inference.</li><li><strong>Robust Error Handling:</strong> Extensive checks during initialization and runtime ensure stability, even under high-load conditions.</li><li><strong>Performance Metrics:</strong> The demo measures processing times, providing insights into the efficiency of the pipeline.</li></ul><h3>Project Structure and Build Process</h3><p>The repository is organized to facilitate both development and deployment:</p><pre>RF_DETR-TensorRT/<br>├── CMakeLists.txt          // Build configuration for C++ and CUDA<br>├── include/                // Header files for core functionalities<br>├── src/<br>│   ├── main.cpp            // Entry point for demo applications<br>│   ├── RF_DETR.cpp         // Implementation of the RF-DETR model integration<br>│   └── preprocess.cu       // CUDA routines for image preprocessing<br>├── assets/                 // Sample images and resources<br>└── build/                  // Directory for compiled binaries</pre><h3>Prerequisites</h3><p>Before building the project, ensure that your environment meets the following requirements:</p><ul><li><strong>C++17 Compiler:</strong> Modern C++ features are used throughout the code.</li><li><strong>CUDA Toolkit:</strong> Required for GPU acceleration.</li><li><strong>NVIDIA TensorRT:</strong> Install the correct version and configure the paths in CMakeLists.txt.</li><li><strong>OpenCV:</strong> For handling image I/O and processing.</li><li><strong>Compatible NVIDIA GPU:</strong> Ensure your GPU meets the necessary compute capabilities.</li></ul><h3>Build Instructions</h3><p>To compile the project:</p><ol><li><strong>Clone the Repository:</strong></li></ol><pre>git clone https://github.com/hamdiboukamcha/RF-DETR-CPP-TENSORRT.git<br>cd RF-DETR-CPP-TENSORRT</pre><p><strong>Configure and Build:</strong></p><pre>mkdir build &amp;&amp; cd build<br>cmake ..<br>make -j$(nproc)</pre><p>Make sure to update the OpenCV and TensorRT paths in the CMakeLists.txt file to match your system configuration.</p><h3>Running the Application</h3><p>Once the project is successfully built, you can run the application to perform object detection:</p><pre>./rf_detr_app --engine rf_detr.engine --input image.jpg --output results.json</pre><p>This command runs the inference pipeline on a provided image, outputting the detection results in a JSON format. Adjust the command-line parameters as needed to suit your application, whether processing a single image or a video stream.</p><h3>Conclusion</h3><p>RF-DETR C++ TENSORRT is a powerful, high-performance solution for real-time object detection. By seamlessly integrating the RF-DETR model with NVIDIA’s TensorRT and CUDA, the project achieves a remarkable balance between speed and accuracy. Its efficient C++ implementation, comprehensive pipeline, and flexible integration make it an ideal choice for a wide array of computer vision applications.</p><p>👉 For advanced inquiries, feel free to contact me on LinkedIn : <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eec852e68a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YOLOv12 C++ TensorRT]]></title>
            <link>https://medium.com/@boukamchahamdi/yolov12-c-tensorrt-5aa51c518aca?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aa51c518aca</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[yolov12]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 11:44:20 GMT</pubDate>
            <atom:updated>2025-02-22T11:44:20.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*iUQEgMfr-4JagfMepLeVGg.png" /></figure><p>YOLOv12 (You Only Look Once, version 12) is an advanced deep-learning model for real-time object detection. To achieve high-speed inference, integrating YOLOv12 with NVIDIA’s <strong>TensorRT</strong> is an optimal choice. TensorRT optimizes deep learning models for low-latency execution on NVIDIA GPUs, making it suitable for real-time applications like autonomous driving, security surveillance, and robotics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ytDUtEV6XvJSChmCOj26DQ.jpeg" /></figure><h3>Features</h3><ul><li><strong>ONNX to TensorRT Conversion</strong>: Convert ONNX models into TensorRT engine files for optimized inference.</li><li><strong>Efficient Video &amp; Image Inference</strong>: Run detection on images and videos efficiently.</li><li><strong>CUDA Preprocessing</strong>: Faster preprocessing using CUDA kernels.</li><li><strong>Support for Batch Processing</strong>: Handle multiple images per inference batch.</li><li><strong>Low Latency &amp; High Throughput</strong>: Optimized for real-time applications.</li></ul><h3>Project Structure</h3><pre>Yolo-V12-cpp-TensorRT/<br>├── CMakeLists.txt          # Build configuration<br>├── src/<br>│   ├── main.cpp            # Main program<br>│   ├── YOLOv12.cpp         # YOLOv12 TensorRT implementation<br>│   ├── preprocess.cu       # CUDA preprocessing functions<br>├── include/                # Header files<br>├── assets/                 # Benchmark results &amp; example outputs<br>├── build/                  # Compiled binaries</pre><h3>Required Dependencies</h3><ul><li><strong>NVIDIA GPU</strong> (Compute Capability 7.5 or higher recommended)</li><li><strong>CUDA Toolkit</strong> (v11.7 or later)</li><li><strong>TensorRT</strong> (v8.6.1.6)</li><li><strong>OpenCV</strong> (v4.10.0)</li><li><strong>CMake</strong> (v3.18 or later)</li></ul><h4>Installation Steps :</h4><p>1- Clone the repository:</p><pre>git clone https://github.com/hamdiboukamcha/Yolo-V12-cpp-TensorRT.git<br>cd Yolo-V12-cpp-TensorRT</pre><p>2- Update TensorRT and OpenCV paths in CMakeLists.txt:</p><pre>set(TENSORRT_PATH &quot;F:/Program Files/TensorRT-8.6.1.6&quot;)</pre><p>3- Build the project:</p><pre>mkdir build<br>cd build<br>cmake ..<br>make -j$(nproc)</pre><h3>Using the Project</h3><h4>Converting YOLOv12 Model to ONNX</h4><p>To export a YOLOv12 model to ONNX format:</p><pre>from ultralytics import YOLO<br>model = YOLO(&quot;yolo12s.pt&quot;)<br>export_path = model.export(format=&quot;onnx&quot;)</pre><h4>Converting ONNX Model to TensorRT</h4><p>To convert an ONNX model to a TensorRT engine:</p><pre>./YOLOv12TRT convert path_to_model.onnx path_to_engine.engine</pre><h4>Running Inference on a Video</h4><pre>./YOLOv12TRT infer_video path_to_video.mp4 path_to_engine.engine</pre><h4>Running Inference on an Image</h4><pre>./YOLOv12TRT infer_image path_to_image.jpg path_to_engine.engine</pre><h3>How It Works</h3><h4>1. Model Conversion (ONNX -&gt; TensorRT)</h4><ul><li>The YOLOv12 class reads the ONNX model</li><li>The TensorRT engine is built and serialized for future inference.</li></ul><h4>2. Preprocessing (CUDA Accelerated)</h4><ul><li>Images are resized and normalized using CUDA kernels.</li><li>This speeds up data preparation before inference.</li></ul><h4>3. Inference</h4><ul><li>The TensorRT engine runs forward propagation on the model.</li><li>Predictions are extracted from the output tensor.</li></ul><h4>4. Postprocessing</h4><ul><li>Bounding boxes, class labels, and confidence scores are extracted.</li><li>Non-Maximum Suppression (NMS) filters redundant detections.</li><li>Results are drawn on the input images.</li></ul><h3>Running the Application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*17LGyN--PTg2PPDzLc1Xww.gif" /></figure><h3>Troubleshooting</h3><h4>Issue: Cannot find nvinfer.lib</h4><ul><li>Ensure TensorRT is installed and paths are correctly set in CMakeLists.txt.</li></ul><h4>Issue: CUDA Error: Out of Memory</h4><ul><li>Reduce batch size or lower the input image resolution.</li><li>Run inference on a GPU with higher memory capacity.</li></ul><h4>Issue: Linker Errors</h4><ul><li>Verify OpenCV, CUDA, and TensorRT are properly linked.</li><li>Ensure paths are set correctly in CMake configuration.</li></ul><h3>Conclusion</h3><p>Integrating YOLOv12 with TensorRT in C++ offers a highly efficient object detection pipeline for real-time applications. By leveraging CUDA acceleration and TensorRT optimization, this project achieves remarkable inference speeds on NVIDIA GPUs.</p><p>👉 For advanced inquiries, feel free to contact me on LinkedIn : <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aa51c518aca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BiRefNet C++ TENSORRT (Dichotomous Image Segmentation)]]></title>
            <link>https://medium.com/@boukamchahamdi/birefnet-c-tensorrt-dichotomous-image-segmentation-108ee0fb7be8?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/108ee0fb7be8</guid>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[birefnet]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 16:14:46 GMT</pubDate>
            <atom:updated>2025-02-16T16:14:46.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*NTlflBeXC9gWQ0yoVmFb-A.jpeg" /></figure><p>In today’s fast-paced world of computer vision, achieving real-time high-resolution segmentation is crucial for applications ranging from robotics and autonomous vehicles to medical imaging. Meet <strong>BiRefNet C++ TENSORRT (Dichotomous Image Segmentation)</strong> — a high-performance, production-ready solution that leverages the power of TensorRT and CUDA to deliver state-of-the-art dichotomous (binary) image segmentation.</p><h3>Overview</h3><p>BiRefNet is a C++ implementation of the Bilateral Reference Network (BiRefNet), designed and optimized for dichotomous segmentation. The project harnesses the efficiency of NVIDIA’s TensorRT for accelerated inference and CUDA for seamless GPU integration. With a focus on real-time performance and high-resolution outputs, this project ensures that even the most demanding segmentation tasks are handled with speed and accuracy.</p><p>The GitHub repository is structured as follows:</p><pre>BiRefNet/<br>├── include<br>│   └── birefnet.h      // Defines the BiRefNet class and key methods<br>├── src<br>│   └── birefnet.cpp    // Implements the core functionality including preprocessing, inference, and postprocessing<br>├── CMakeLists.txt      // Build configuration for C++ and CUDA using CMake<br>└── main.cpp            // Demonstrates how to integrate and use BiRefNet in both image and video applications</pre><h3>How It Works</h3><p>BiRefNet is designed with both modularity and performance in mind. Here’s a deeper look into its inner workings:</p><h3>1. TensorRT Engine Initialization</h3><p>At the heart of the project is the initialization of the TensorRT engine. The class constructor in birefnet.h loads a serialized TensorRT engine file (typically with a .trt extension) and sets up the runtime environment. This involves:</p><ul><li><strong>Deserializing the engine:</strong> Reading the binary file and reconstructing the engine.</li><li><strong>Creating an execution context:</strong> Preparing the engine to run inference.</li><li><strong>Resource allocation:</strong> Allocating GPU memory for input and output buffers and setting up a CUDA stream for asynchronous operations.</li></ul><p>This design ensures that the heavy lifting is done during initialization, allowing for fast inference during runtime.</p><h3>2. Image Preprocessing and Postprocessing</h3><p><strong>Preprocessing:</strong><br>Before inference, input images are preprocessed to match the engine’s requirements. This includes:</p><ul><li><strong>Resizing:</strong> The image is resized to the expected input dimensions (e.g., 1024×1024) while maintaining aspect ratio.</li><li><strong>Normalization:</strong> Each pixel value is normalized using pre-defined mean and standard deviation values. This step is crucial for ensuring that the network receives data in the same format as during training.</li></ul><p><strong>Postprocessing:</strong><br>After inference, the raw output — typically a floating-point array — is converted into a usable segmentation map:</p><ul><li><strong>Resizing back:</strong> The output is resized to match the original image dimensions.</li><li><strong>Conversion to 8-bit format:</strong> The floating-point segmentation map is scaled and converted to an 8-bit grayscale image, which is then transformed into a 3-channel BGR image for visualization or further processing.</li></ul><h3>3. Real-Time Inference Pipeline</h3><p>BiRefNet’s predict method encapsulates the entire inference pipeline:</p><ol><li><strong>Data Transfer:</strong> Preprocessed image data is copied asynchronously from host (CPU) memory to device (GPU) memory.</li><li><strong>Inference Execution:</strong> The TensorRT execution context runs the forward pass on the GPU, utilizing efficient memory management and parallel processing.</li><li><strong>Output Retrieval:</strong> The processed output is transferred back to the host, synchronized to ensure data integrity.</li><li><strong>Postprocessing:</strong> The raw output is converted into a final segmentation map that can be saved, displayed, or further analyzed.</li></ol><p>This streamlined process makes BiRefNet ideal for real-time applications, whether processing individual images or streaming video frames.</p><h3>4. Comprehensive Demo and Integration</h3><p>The main.cpp file in the repository demonstrates how to integrate BiRefNet into your own projects. Key highlights include:</p><ul><li><strong>Versatile Input Handling:</strong> The demo supports both single image and video processing. For video, the code processes each frame individually, measures processing time, and writes the output to a new video file.</li><li><strong>Error Handling and Resource Management:</strong> From validating input paths to ensuring CUDA streams are synchronized, the code is designed to robustly handle potential errors during inference.</li></ul><h3>How to Use BiRefNet</h3><p>Getting started with BiRefNet is straightforward:</p><h3>Prerequisites</h3><ul><li><strong>C++17 Compiler:</strong> Ensure your development environment supports C++17.</li><li><strong>CUDA Toolkit:</strong> Required for GPU acceleration.</li><li><strong>TensorRT:</strong> Install TensorRT and set the correct path in CMakeLists.txt.</li><li><strong>OpenCV:</strong> Used for image processing and handling I/O operations.</li></ul><h3>Build Instructions</h3><p><strong>Clone the Repository:</strong></p><pre>git clone https://github.com/hamdiboukamcha/BiRefNet-Cpp-TensorRT.git<br> cd BiRefNet-Cpp-TensorRT<br> mkdir build &amp;&amp; cd build<br> cmake ..<br> make -j$(nproc)</pre><p>Prepare Your Engine<strong>:</strong></p><pre>Convert your model to ONNX, then build a TensorRT engine (e.g., using trtexec or a custom builder).<br>trtexec --onnx=birefnet_model.onnx --saveEngine=BiRefNet-tiny.engine --fp16</pre><h3>Running the Application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*_M-_FAoCz9YogffT79NRYQ.jpeg" /></figure><h3>Conclusion</h3><p>BiRefNet C++ TENSORRT (Dichotomous Image Segmentation) is a robust, high-performance solution for real-time image segmentation. With its efficient use of TensorRT and CUDA, comprehensive error handling, and easy integration, it is perfectly suited for modern computer vision challenges.</p><p>👉 For advanced inquiries, feel free to contact me on LinkedIn : <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=108ee0fb7be8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing SAM Using TensorRT in C++]]></title>
            <link>https://medium.com/@boukamchahamdi/implementing-sam-using-tensorrt-in-c-e7b59641e103?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b59641e103</guid>
            <category><![CDATA[segment-anything-model]]></category>
            <category><![CDATA[segment-anything]]></category>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[sam]]></category>
            <category><![CDATA[segmentation]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 10:23:06 GMT</pubDate>
            <atom:updated>2024-11-02T10:23:06.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*6462BB7a35-6FDqI3AQoMA.png" /><figcaption>Implementing SAM Using TensorRT in C++</figcaption></figure><p>The project titled <strong>SPEED-SAM-C++-TENSORRT</strong> is a high-performance implementation of the Segment Anything Model (SAM) using NVIDIA’s TensorRT for efficient inference and CUDA for optimized GPU utilization. Below is a detailed breakdown of how the implementation works, how to compile it, and key components.</p><h3>Project Structure and Overview</h3><p>The directory structure of the project is as follows:</p><pre>SPEED-SAM-CPP-TENSORRT/<br>├── include<br>│   ├── config.h          # Model configuration and macros<br>│   ├── cuda_utils.h      # CUDA utility macros<br>│   ├── engineTRT.h       # TensorRT engine management<br>│   ├── logging.h         # Logging utilities<br>│   ├── macros.h          # API export/import macros<br>│   ├── speedSam.h        # SpeedSam class definition<br>│   └── utils.h           # Utility functions for image handling<br>├── src<br>│   ├── engineTRT.cpp     # Implementation of the TensorRT engine<br>│   ├── main.cpp          # Main entry point<br>│   └── speedSam.cpp      # Implementation of the SpeedSam class<br>└── CMakeLists.txt        # CMake configuration</pre><p>The project is designed for fast image segmentation tasks and can segment images based on selected points or bounding boxes. It uses TensorRT to build optimized inference engines from ONNX models, allowing for efficient deep learning inference on NVIDIA GPUs.</p><h3>Key Components Explained</h3><p><strong>Building TensorRT Engines</strong>:</p><ul><li>The EngineTRT::build() method parses the ONNX model and constructs the TensorRT engine. If dynamic shape support is required (for varying input sizes), optimization profiles are configured.</li><li>The EngineTRT::saveEngine() function allows saving the serialized engine to a file, facilitating quick loading in future sessions.</li></ul><p><strong>Image Segmentation Process</strong>:</p><ul><li>The SpeedSam class orchestrates the segmentation process. First, the image is encoded using a pre-trained encoder model. Next, the decoder model generates masks based on input points or bounding boxes.</li><li>Two main segmentation methods are provided:</li><li><strong>Point-Based Segmentation (</strong><strong>segmentWithPoint)</strong>: Users click on the image to specify points for segmentation.</li><li><strong>Bounding Box Segmentation (</strong><strong>segmentBbox)</strong>: Users draw a bounding box to define the region for segmentation.</li></ul><p><strong>Memory Optimization</strong>:</p><ul><li>The implementation uses CUDA streams to overlap data transfer and computation, reducing latency.</li><li>FP16 precision is employed where possible to accelerate inference without significantly sacrificing accuracy.</li></ul><h3>Compilation and Setup</h3><p><strong>Prerequisites</strong>:</p><ul><li><strong>CUDA</strong>: NVIDIA’s parallel computing platform.</li><li><strong>TensorRT</strong>: A library for high-performance deep learning inference.</li><li><strong>OpenCV</strong>: For image processing.</li><li><strong>C++17</strong>: Required for compilation.</li></ul><p><strong>Steps to Compile</strong>:</p><p>Clone the repository and navigate to the project directory:</p><pre>git clone https://github.com/hamdiboukamcha/SPEED-SAM-C-TENSORRT.git<br>cd SPEED-SAM-CPP-TENSORRT</pre><p>Create a build directory and compile using CMake:</p><pre>mkdir build &amp;&amp; cd build<br>cmake ..<br>make -j$(nproc)</pre><p><strong>Note</strong>: Update CMakeLists.txt with the correct paths for TensorRT and OpenCV if necessary.</p><h3>Running the Application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*FQITpuiaWEmTNzd5iV5r7A.jpeg" /></figure><p><strong>Point-Based Segmentation</strong>:</p><ul><li>The program displays an image and waits for the user to select a point. Once a point is selected, the model segments the image based on the specified location and overlays the mask</li></ul><p><strong>Bounding Box Segmentation</strong>:</p><ul><li>The user can draw a bounding box around the desired region. The model then segments the image within the defined area and displays the result.</li></ul><p><strong>Output</strong>:</p><ul><li>The segmented images are saved to the specified output paths, and performance metrics like inference time are logged.</li></ul><h3>Performance and Optimization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*w-fIYIMX6mmf5aBJVtNF6w.jpeg" /><figcaption>SAM Infernce Time</figcaption></figure><ul><li><strong>Inference Speed</strong>: The image encoder and mask decoder achieve fast inference times, with the entire pipeline completing in around 12 ms.</li><li><strong>Memory Management</strong>: Efficient use of GPU memory and CUDA streams minimizes latency and maximizes throughput.</li><li><strong>Precision Settings</strong>: The option to use FP16 precision allows for a trade-off between speed and accuracy.</li></ul><h3>Conclusion</h3><p>The <strong>SPEED-SAM-C++-TENSORRT</strong> project demonstrates a well-optimized implementation of the Segment Anything Model using TensorRT and CUDA. By leveraging NVIDIA’s powerful libraries, the project achieves real-time segmentation performance, making it suitable for applications that require fast and accurate image analysis. The flexible code structure and comprehensive logging also make it a valuable resource for developers working with deep learning inference on GPUs.</p><p>👉 For advanced inquiries, feel free to contact me on LinkedIn : <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b59641e103" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YOLO v11 C++ TensorRT Project]]></title>
            <link>https://medium.com/@boukamchahamdi/yolo-v11-c-tensorrt-project-d6aa2533ec44?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6aa2533ec44</guid>
            <category><![CDATA[yolov11]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[yolo]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 12:08:47 GMT</pubDate>
            <atom:updated>2024-10-14T12:08:47.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*0PbnkNiKP4LETouc.png" /></figure><p>The YOLOv11 C++ TensorRT Project is a high-performance object detection solution implemented in C++ and optimized using NVIDIA TensorRT. This project leverages the YOLOv11 model to deliver fast and accurate object detection, utilizing TensorRT to maximize inference efficiency and performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*aoxR-zx9ZkgE7DbR.gif" /></figure><h3>Key Features:</h3><ul><li>Model Conversion: Convert ONNX models to TensorRT engine files to accelerate inference.</li><li>Inference on Videos: Efficiently perform object detection on video files.</li><li>Inference on Images: Execute object detection on individual images.</li><li>High Efficiency: Optimized for real-time object detection using NVIDIA GPUs.</li><li>Preprocessing with CUDA: CUDA-enabled preprocessing for faster input handling.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*ooWJHztTdsXAt2S2.jpeg" /></figure><h3>📂 Project Structure</h3><pre>YOLOv11-TensorRT/<br>├── CMakeLists.txt          # Build configuration for the project<br>├── include/                # Header files<br>├── src/<br>│   ├── main.cpp            # Main entry point for the application<br>│   ├── yolov11.cpp         # YOLOv11 implementation<br>│   └── preprocess.cu       # CUDA preprocessing code<br>├── assets/                 # Images and benchmarks for README<br>└── build/                  # Compiled binaries</pre><h3>🛠️ Setup</h3><p><strong>Prerequisites</strong></p><ul><li>CMake (version 3.18 or higher)</li><li>TensorRT (V8.6.1.6: For optimized inference with YOLOv11.)</li><li>CUDA Toolkit (V11.7: For GPU acceleration)</li><li>OpenCV (V4.10.0: For image and video processing)</li><li>NVIDIA GPU (with compute capability 7.5 or higher)</li></ul><p><strong>Installation</strong></p><ol><li>Clone the repository:</li></ol><pre>git clone https://github.com/hamdiboukamcha/Yolo-V11-cpp-TensorRT.git<br>cd YOLOv11-TensorRT</pre><p>2. Update the TensorRT and OpenCV paths in CMakeLists.txt:</p><pre>set(TENSORRT_PATH &quot;F:/Program Files/TensorRT-8.6.1.6&quot;)  # Adjust this to your path</pre><p>3 . Build the project:</p><pre>mkdir build<br>cd build<br>cmake ..<br>make -j$(nproc)</pre><h3>🚀 Usage</h3><h3>Convert Yolov11 To ONNX Model</h3><pre>from ultralytics import YOLO<br>Load the YOLO model<br>model = YOLO(&quot;yolo11s.pt&quot;)<br>#Export the model to ONNX format<br>export_path = model.export(format=&quot;onnx&quot;)</pre><h3>Convert ONNX Model to TensorRT Engine</h3><p>To convert an ONNX model to a TensorRT engine file, use the following command:</p><pre>./YOLOv11TRT convert path_to_your_model.onnx path_to_your_engine.engine.</pre><p><strong>path_to_your_model.onnx:</strong> Path to the ONNX model file.</p><p><strong>path_to_your_engine.engine:</strong> Path where the TensorRT engine file will be saved.</p><h3>Run Inference on Video</h3><p>To run inference on a video, use the following command:</p><pre>./YOLOv11TRT infer_video path_to_your_video.mp4 path_to_your_engine.engine</pre><p><strong>path_to_your_video.mp4:</strong> Path to the input video file.</p><p><strong>path_to_your_engine.engine:</strong> Path to the TensorRT engine file.</p><h3>Run Inference on Video</h3><p>Run Inference on Image To run inference on an image, use the following command:</p><pre>./YOLOv11TRT infer_image path_to_your_image.jpg path_to_your_engine.engine</pre><p><strong>path_to_your_image.jpg:</strong> Path to the input image file.</p><p><strong>path_to_your_engine.engine:</strong> Path to the TensorRT engine file.</p><h3>⚙️ Configuration</h3><p><strong>CMake Configuration</strong></p><p>In the CMakeLists.txt, update the paths for TensorRT and OpenCV if they are installed in non-default locations:</p><p>Set the path to TensorRT installation</p><pre>#Define the path to TensorRT installation<br>set(TENSORRT_PATH &quot;F:/Program Files/TensorRT-8.6.1.6&quot;)  # Update this to the actual path for TensorRT</pre><p>Ensure that the path points to the directory where TensorRT is installed.</p><h3>Troubleshooting</h3><p>Cannot find nvinfer.lib: Ensure that TensorRT is correctly installed and that nvinfer.lib is in the specified path. Update CMakeLists.txt to include the correct path to TensorRT libraries.</p><p>Linker Errors: Verify that all dependencies (OpenCV, CUDA, TensorRT) are correctly installed and that their paths are correctly set in CMakeLists.txt.</p><p>Run-time Errors: Ensure that your system has the correct CUDA drivers and that TensorRT runtime libraries are accessible. Add TensorRT’s bin directory to your system PATH.</p><p>👉 For advanced inquiries, feel free to contact me on LinkedIn : <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6aa2533ec44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autofeat: Automating Feature Engineering with Python]]></title>
            <link>https://medium.com/@boukamchahamdi/autofeat-automating-feature-engineering-with-python-f22ec23265a9?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f22ec23265a9</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[autofeat]]></category>
            <category><![CDATA[auto-feature-engineering]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 16:43:02 GMT</pubDate>
            <atom:updated>2024-10-10T16:43:02.977Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comprehensive Guide to Autofeat: Automating Feature Engineering with Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*SzB7Ka4km8q8d9t_eadIPw.png" /><figcaption>Feature Engineering — Auto Feature Engineering Python Libraries.</figcaption></figure><p>Feature engineering is one of the most important steps in the machine learning pipeline. It involves transforming raw data into meaningful input features for models, which can significantly improve the model’s accuracy. However, feature engineering can be tedious and requires domain expertise. Autofeat helps alleviate this by automating the entire process.</p><p>This guide will walk you through the key features of Autofeat and provide step-by-step instructions with code examples.</p><h3>1. Introduction to Autofeat</h3><p>Autofeat is a Python library designed for automated feature engineering. It automates the creation, transformation, and selection of features, particularly for linear models, to improve model accuracy while maintaining interpretability.</p><p>Autofeat performs two main tasks:</p><ol><li><strong>Feature Generation</strong>: Automatically creates non-linear features from the original data.</li><li><strong>Feature Selection</strong>: Chooses the most relevant features using L1-regularized linear models, which makes the process more efficient by selecting features that contribute most to predictive performance.</li></ol><h3>2. Installation</h3><p>To get started with Autofeat, you first need to install the library. You can install it directly using pip:</p><pre>pip install autofeat  </pre><p>Autofeat has dependencies on common data science libraries like scikit-learn, numpy, pandas, sympy, pint, and numba, which will be automatically installed during the setup.</p><h3>3. Step-by-Step Guide with Code Example</h3><h4>Step 1: Import Necessary Libraries</h4><p>You’ll need to import Autofeat and other essential libraries to run the code. We’ll use a standard dataset for demonstration, such as the Boston Housing dataset.</p><pre>from autofeat import AutoFeatRegressor<br>from sklearn.datasets import load_boston<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error</pre><h4>Step 2: Load and Prepare the Dataset</h4><p>We’ll load the Boston Housing dataset, which is commonly used for regression tasks. The dataset contains various features like crime rate, average number of rooms per dwelling, etc.</p><pre># Load the dataset<br>data = load_boston()<br>X, y = data.data, data.target<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><h4>Step 3: Feature Generation with Autofeat</h4><p>We initialize AutoFeatRegressor, which automatically generates non-linear features. During the fitting process, Autofeat creates a large number of features by applying various mathematical transformations to the existing ones.</p><pre># Create an instance of AutoFeatRegressor<br>afreg = AutoFeatRegressor()<br><br># Fit the regressor to the training data (this generates new features)<br>X_train_transformed = afreg.fit_transform(X_train, y_train)<br><br># Apply the same transformation to the test data<br>X_test_transformed = afreg.transform(X_test)</pre><p>At this stage, Autofeat uses multiple feature transformations (e.g., polynomial, exponential, logarithmic) and generates new features based on combinations of the original ones. The library also automatically selects the most important features.</p><h4>Step 4: Train a Model Using the New Features</h4><p>With the newly generated features, you can train a regression model or any machine learning model of your choice. Below, we use a simple linear regression model:</p><pre>from sklearn.linear_model import LinearRegression<br><br># Initialize the model<br>model = LinearRegression()<br><br># Train the model on the newly generated features<br>model.fit(X_train_transformed, y_train)<br><br># Make predictions on the test set<br>y_pred = model.predict(X_test_transformed)<br><br># Evaluate the model<br>mse = mean_squared_error(y_test, y_pred)<br>print(f&quot;Mean Squared Error: {mse}&quot;)</pre><p>The mean squared error (MSE) will give you an idea of the model’s performance with the newly generated features. You can compare this with the performance of a model trained without Autofeat to see the improvement.</p><h4>Step 5: Feature Selection and Interpretability</h4><p>Autofeat also allows you to access the newly generated features. You can examine them to see which ones are important for the model’s predictions.</p><pre># Get the generated feature names<br>new_features = afreg.get_feature_names()<br>print(f&quot;New Features: {new_features}&quot;)</pre><p>This list of features helps in interpreting which transformations or feature interactions are significant. For example, you may find that combinations of features (e.g., the square of a feature or the interaction between two features) improve model accuracy​(<a href="https://ar5iv.org/abs/1901.07329">ar5iv</a>).</p><h3>4. Advanced Usage: Hyperparameter Tuning</h3><p>Autofeat allows for customization by adjusting the hyperparameters to control the complexity of the feature generation process. The key hyperparameters include:</p><ul><li><strong>feateng_steps</strong>: Number of feature engineering steps to perform.</li><li><strong>max_features</strong>: Maximum number of new features to generate.</li><li><strong>n_jobs</strong>: Number of CPU cores to use for parallel computation.</li></ul><p>Here’s how you can specify these parameters:</p><pre>afreg = AutoFeatRegressor(feateng_steps=2, max_features=1000, n_jobs=-1)<br>X_train_transformed = afreg.fit_transform(X_train, y_train)</pre><p>By tuning these parameters, you can optimize performance based on the complexity of your dataset and computational power​.</p><h3>5. Best Practices and Tips</h3><ul><li><strong>Start Small</strong>: Begin with default hyperparameters, then gradually increase the complexity if needed.</li><li><strong>Cross-Validation</strong>: Always use cross-validation to prevent overfitting, especially when generating many features.</li><li><strong>Interpretability</strong>: Ensure that the generated features align with your domain knowledge. Autofeat makes the process interpretable, so validate the features before using them in decision-making models.</li></ul><h3>6. Conclusion</h3><p>Autofeat simplifies the feature engineering process, making it more accessible to practitioners without extensive domain expertise. By automating the generation of non-linear features and providing powerful feature selection methods, Autofeat enables you to improve the performance of linear models without sacrificing interpretability. Whether you’re working with regression or classification problems, Autofeat can streamline your workflow and allow you to focus on other aspects of model development​</p><p>👉 Linkedin : <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f22ec23265a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Confidence: The Role of Platt Scaling in Logistic Regression]]></title>
            <link>https://medium.com/@boukamchahamdi/importance-of-platt-scaling-in-calibrating-confidence-rates-ad692c7c186f?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad692c7c186f</guid>
            <category><![CDATA[platt-scaling]]></category>
            <category><![CDATA[model-calibration]]></category>
            <category><![CDATA[probability-calibration]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 17:12:09 GMT</pubDate>
            <atom:updated>2024-08-18T17:46:37.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In machine learning, especially for classification tasks, it’s crucial to have both accurate predictions and well-calibrated confidence estimates. Calibration ensures that predicted probabilities align with actual outcomes. For example, a 70% predicted probability should mean the event happens 70% of the time. Poor calibration can lead to poor decisions, particularly in critical areas like medicine or finance.</p><p>Platt Scaling is a post-processing technique that adjusts a model’s confidence scores to better reflect true probabilities. This article highlights the importance of Platt Scaling and demonstrates its use with a Logistic Regression model in Python, showing how calibration can improve model performance.</p><h3>Why Calibration Matters</h3><p>Understanding the need for calibration is key. Many models, such as Logistic Regression, SVMs, and Neural Networks, provide probability estimates, but these are often not well-calibrated. Miscalibration can lead to overconfidence or underconfidence, affecting decisions made based on the model’s predictions.</p><h3>Introduction to Platt Scaling</h3><p>Platt Scaling is a method specifically designed to calibrate the probability estimates of classifiers, particularly Support Vector Machines (SVMs), but it can be applied to any probabilistic model. It works by fitting a logistic regression model to the output scores (usually the decision function) of the original classifier. The goal is to transform these scores into well-calibrated probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QKPEUuai3KyqhTAMXvcOgA.gif" /><figcaption>Platt Scaling</figcaption></figure><p>Given a score<strong> “s”</strong> from the original model, Platt Scaling models the probability as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*600V2DxIqybu-XP_1pT3Pw.png" /></figure><p>where “<strong>A</strong>” and “<strong>B</strong>” are parameters learned from the data.</p><h3>Practical Example: Logistic Regression with Platt Scaling</h3><p>Let’s walk through a practical example of using Platt Scaling to calibrate the confidence rates of a Logistic Regression model.</p><h4>Step 1: Setting Up the Environment</h4><p>First, we’ll set up the necessary libraries and generate a synthetic dataset.</p><h3>Practical Example: Logistic Regression with Platt Scaling</h3><p>Let’s walk through a practical example of using Platt Scaling to calibrate the confidence rates of a Logistic Regression model.</p><h4>Step 1: Setting Up the Environment</h4><p>First, we’ll set up the necessary libraries and generate a synthetic dataset.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import make_classification<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.calibration import calibration_curve, CalibratedClassifierCV<br>from sklearn.metrics import brier_score_loss, log_loss<br><br># Generate synthetic dataset<br>X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, random_state=42)<br><br># Split the data into training and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)</pre><h4>Step 2: Training the Logistic Regression Model</h4><p>Next, we will train a Logistic Regression model on the training data.</p><pre># Train a Logistic Regression model<br>log_reg = LogisticRegression()<br>log_reg.fit(X_train, y_train)<br><br># Predict probabilities on the test set<br>y_prob = log_reg.predict_proba(X_test)[:, 1]</pre><h4>Step 3: Evaluating Calibration Before Platt Scaling</h4><p>Before applying Platt Scaling, let’s evaluate the calibration of the Logistic Regression model by plotting a calibration curve.</p><pre># Plot the calibration curve<br>prob_true, prob_pred = calibration_curve(y_test, y_prob, n_bins=10)<br><br>plt.figure(figsize=(10, 7))<br>plt.plot(prob_pred, prob_true, marker=&#39;o&#39;, label=&#39;Logistic Regression&#39;)<br>plt.plot([0, 1], [0, 1], linestyle=&#39;--&#39;, label=&#39;Perfectly Calibrated&#39;)<br>plt.xlabel(&#39;Predicted Probability&#39;)<br>plt.ylabel(&#39;True Probability&#39;)<br>plt.title(&#39;Calibration Curve Before Platt Scaling&#39;)<br>plt.legend()<br>plt.show()</pre><p>In the plot, if the predicted probabilities are perfectly calibrated, the curve should lie on the diagonal line (y=x). Any deviation from this line indicates miscalibration.</p><h4>Step 4: Applying Platt Scaling</h4><p>Now, let’s apply Platt Scaling using the CalibratedClassifierCV class from sklearn. This class implements Platt Scaling for various base classifiers, including Logistic Regression.</p><pre># Apply Platt Scaling<br>calibrated_clf = CalibratedClassifierCV(base_estimator=log_reg, method=&#39;sigmoid&#39;, cv=&#39;prefit&#39;)<br>calibrated_clf.fit(X_train, y_train)<br><br># Predict probabilities after Platt Scaling<br>y_prob_calibrated = calibrated_clf.predict_proba(X_test)[:, 1]</pre><h4>Step 5: Evaluating Calibration After Platt Scaling</h4><p>After applying Platt Scaling, we’ll plot the calibration curve again to see the improvement.</p><pre># Plot the calibration curve after Platt Scaling<br>prob_true_calibrated, prob_pred_calibrated = calibration_curve(y_test, y_prob_calibrated, n_bins=10)<br><br>plt.figure(figsize=(10, 7))<br>plt.plot(prob_pred_calibrated, prob_true_calibrated, marker=&#39;o&#39;, label=&#39;Platt Scaled Logistic Regression&#39;)<br>plt.plot([0, 1], [0, 1], linestyle=&#39;--&#39;, label=&#39;Perfectly Calibrated&#39;)<br>plt.xlabel(&#39;Predicted Probability&#39;)<br>plt.ylabel(&#39;True Probability&#39;)<br>plt.title(&#39;Calibration Curve After Platt Scaling&#39;)<br>plt.legend()<br>plt.show()</pre><h4>Step 6: Interpreting the Results</h4><p>By comparing the calibration curves before and after Platt Scaling, we can observe how the calibration has improved.</p><ul><li><strong>Before Platt Scaling</strong>: The calibration curve might deviate significantly from the diagonal, indicating that the predicted probabilities are either overconfident or underconfident.</li><li><strong>After Platt Scaling</strong>: The calibration curve should be closer to the diagonal line, indicating better alignment between predicted probabilities and actual outcomes.</li></ul><p>Additionally, we can evaluate the model using metrics like the Brier score loss and log loss before and after Platt Scaling to quantify the improvement.</p><pre># Calculate Brier score and log loss before and after calibration<br>brier_before = brier_score_loss(y_test, y_prob)<br>brier_after = brier_score_loss(y_test, y_prob_calibrated)<br><br>log_loss_before = log_loss(y_test, y_prob)<br>log_loss_after = log_loss(y_test, y_prob_calibrated)<br><br>print(f&quot;Brier score before Platt Scaling: {brier_before:.4f}&quot;)<br>print(f&quot;Brier score after Platt Scaling: {brier_after:.4f}&quot;)<br><br>print(f&quot;Log loss before Platt Scaling: {log_loss_before:.4f}&quot;)<br>print(f&quot;Log loss after Platt Scaling: {log_loss_after:.4f}&quot;)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*h6DRXorVnnlpHDbLXB-hlw.png" /><figcaption>Example : Platt Scaling Calibration</figcaption></figure><h3>Conclusion</h3><p>Platt Scaling is an effective technique for improving the calibration of probability estimates in classification models. By applying it to a Logistic Regression model, we were able to enhance the alignment between predicted probabilities and actual outcomes, leading to more reliable confidence estimates. In practical applications, this can be crucial for making informed decisions, especially when dealing with uncertain or risky situations.</p><p>👉 <strong>Linkedin </strong>: <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad692c7c186f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning a ResNet18 Model with Optuna: Hyperparameter Optimization]]></title>
            <link>https://medium.com/@boukamchahamdi/fine-tuning-a-resnet18-model-with-optuna-hyperparameter-optimization-2e3eab0bcca7?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e3eab0bcca7</guid>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[model-tuning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[resnet]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 11:56:43 GMT</pubDate>
            <atom:updated>2024-08-12T11:56:43.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eJJDYv_ZF9ysJbJLOczTaQ.png" /></figure><p>Deep learning models are powerful tools, but achieving optimal performance requires careful tuning of hyperparameters. This task can be both time-consuming and computationally expensive. Thankfully, tools like Optuna make the process of hyperparameter optimization much more manageable.</p><p>In this article, we’ll walk through a practical example of fine-tuning a ResNet18 model on the CIFAR-10 dataset using Optuna to optimize the hyperparameters. By the end of this tutorial, you’ll have a solid understanding of how to apply Optuna to your own deep learning projects.</p><h3>Why Hyperparameter Optimization Matters</h3><p>Hyperparameters play a crucial role in the performance of machine learning models. These include the learning rate, batch size, momentum, weight decay, and many others. Finding the right combination of hyperparameters can significantly improve model accuracy and generalization.</p><p>Traditionally, grid search and random search have been popular methods for hyperparameter optimization. However, these methods can be inefficient, especially with large search spaces. This is where Optuna shines, offering a more efficient, automated approach to hyperparameter optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*WvZxzB8lQLBfqaLHICunjw.png" /></figure><h3>What is Optuna?</h3><p>Optuna is an open-source hyperparameter optimization framework designed to be both flexible and easy to use. It features:</p><ul><li><strong>Automatic searching</strong>: Optuna efficiently navigates the hyperparameter search space.</li><li><strong>Early stopping</strong>: It can prune unpromising trials early to save computation time.</li><li><strong>Simple integration</strong>: It can be easily integrated with existing machine learning workflows.</li></ul><h3>Step-by-Step Implementation</h3><h3>1. Setting Up the Environment</h3><p>First, ensure you have the necessary libraries installed. You can install them via pip if you haven’t already:</p><pre>pip install torch torchvision optuna  </pre><h3>2. Loading and Preprocessing the Data</h3><p>For this example, we’ll use the CIFAR-10 dataset, a popular benchmark in computer vision. It consists of 60,000 32x32 color images in 10 classes, with 6,000 images per class.</p><p>We’ll use torchvision to load and preprocess the data:</p><pre>import torch<br>import torchvision<br>import torchvision.transforms as transforms<br><br># Data preprocessing<br>transform = transforms.Compose([<br>    transforms.Resize(256),<br>    transforms.CenterCrop(224),<br>    transforms.ToTensor(),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>])<br><br>train_dataset = torchvision.datasets.CIFAR10(root=&#39;./data&#39;, train=True, download=True, transform=transform)<br>val_dataset = torchvision.datasets.CIFAR10(root=&#39;./data&#39;, train=False, download=True, transform=transform)</pre><h3>3. Defining the Model</h3><p>We’ll be using the ResNet18 architecture, which is a 18-layer deep residual network. ResNet18 is a great choice for transfer learning because of its simplicity and strong performance on a variety of tasks.</p><pre>from torchvision.models import resnet18<br>import torch.nn as nn<br><br># Load the ResNet18 model<br>model = resnet18(pretrained=True)<br><br># Replace the final fully connected layer to match the number of classes in CIFAR-10<br>in_features = model.fc.in_features<br>model.fc = nn.Linear(in_features, 10)  # CIFAR-10 has 10 classes</pre><h3>4. The Objective Function</h3><p>The core of Optuna’s optimization process is the objective function, which evaluates the model’s performance with different sets of hyperparameters. Here, we’ll define an objective function that:</p><ul><li>Loads the data.</li><li>Defines the model, optimizer, and loss function.</li><li>Trains the model.</li><li>Evaluates it on a validation set.</li><li>Returns the accuracy.</li></ul><pre>import optuna<br>import torch.optim as optim<br><br>def objective(trial):<br>    # Suggest hyperparameters<br>    batch_size = trial.suggest_int(&#39;batch_size&#39;, 16, 64)<br>    lr = trial.suggest_loguniform(&#39;lr&#39;, 1e-5, 1e-1)<br>    momentum = trial.suggest_uniform(&#39;momentum&#39;, 0.8, 0.99)<br>    weight_decay = trial.suggest_loguniform(&#39;weight_decay&#39;, 1e-5, 1e-1)<br><br>    # DataLoader<br>    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)<br>    val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, shuffle=False)<br><br>    # Model<br>    model = resnet18(pretrained=True)<br>    model.fc = nn.Linear(in_features, 10)  # CIFAR-10 has 10 classes<br>    device = torch.device(&#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br>    model.to(device)<br><br>    # Loss function and optimizer<br>    criterion = nn.CrossEntropyLoss()<br>    optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay)<br><br>    # Training loop<br>    model.train()<br>    for epoch in range(10):  # Adjust number of epochs as needed<br>        running_loss = 0.0<br>        for inputs, labels in train_loader:<br>            inputs, labels = inputs.to(device), labels.to(device)<br>            optimizer.zero_grad()<br>            outputs = model(inputs)<br>            loss = criterion(outputs, labels)<br>            loss.backward()<br>            optimizer.step()<br>            running_loss += loss.item()<br><br>    # Validation loop<br>    model.eval()<br>    correct = 0<br>    total = 0<br>    with torch.no_grad():<br>        for inputs, labels in val_loader:<br>            inputs, labels = inputs.to(device), labels.to(device)<br>            outputs = model(inputs)<br>            _, predicted = torch.max(outputs.data, 1)<br>            total += labels.size(0)<br>            correct += (predicted == labels).sum().item()<br><br>    accuracy = correct / total<br>    return accuracy</pre><h3>5. Running the Optimization</h3><p>With the objective function defined, we can now create an Optuna study to find the best hyperparameters. Here’s how you can do it:</p><pre># Create an Optuna study<br>study = optuna.create_study(direction=&#39;maximize&#39;)<br>study.optimize(objective, n_trials=50)<br><br># Display the best hyperparameters and accuracy<br>print(&quot;Best hyperparameters:&quot;, study.best_params)<br>print(&quot;Best accuracy:&quot;, study.best_value)</pre><h3>6. Analyzing the Results</h3><p>After running the optimization, Optuna provides a set of hyperparameters that yield the best validation accuracy. This process involves:</p><ul><li><strong>Hyperparameter suggestions</strong>: Optuna tries different combinations of hyperparameters within the specified ranges.</li><li><strong>Optimization direction</strong>: We aim to maximize validation accuracy.</li><li><strong>Pruning</strong>: Optuna can terminate trials early if they are not promising, saving computational resources.</li></ul><p>The best hyperparameters and accuracy are then displayed:</p><pre>Best hyperparameters: {&#39;batch_size&#39;: 32, &#39;lr&#39;: 0.00123, &#39;momentum&#39;: 0.95, &#39;weight_decay&#39;: 0.0001}<br>Best accuracy: 0.85</pre><p>(Note: The above values are hypothetical and will vary based on the dataset and number of trials.)</p><h3>7. Conclusion</h3><p>Fine-tuning a model with optimal hyperparameters can be the key to unlocking better performance. Optuna provides an efficient, automated way to explore the hyperparameter space, making the process more accessible and less time-consuming.</p><p>In this tutorial, we fine-tuned a ResNet18 model on the CIFAR-10 dataset using Optuna. By defining a robust objective function and leveraging Optuna’s powerful optimization features, we identified a set of hyperparameters that improved the model’s accuracy.</p><p>This approach can be adapted to other models and datasets, allowing you to focus more on building and deploying models rather than getting bogged down in the trial-and-error of manual hyperparameter tuning.</p><p>👉 Linkedin : <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e3eab0bcca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YOLOv10 C++ TensorRT Project]]></title>
            <link>https://medium.com/@boukamchahamdi/yolov10-c-tensorrt-project-27f66c163de1?source=rss-26cbe30d49bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/27f66c163de1</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolo-object-detection]]></category>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[yolov10]]></category>
            <dc:creator><![CDATA[Hamdi Boukamcha]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 16:09:01 GMT</pubDate>
            <atom:updated>2024-07-28T08:21:57.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>YOLO v10 C++ TensorRT Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*1M7msID5SJKxENDdt1DCCQ.png" /></figure><h3>Overview</h3><p>The YOLO v10 C++ TensorRT Project is a high-performance object detection solution designed to deliver fast and accurate results. By leveraging the powerful YOLO v10 model and optimizing it with NVIDIA TensorRT, this project provides an efficient and scalable method for real-time object detection tasks. Implemented in C++, the project supports various functionalities including model conversion, and inference on both images and videos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sf2pMIMSmlO2HXlXgE8lg.jpeg" /></figure><h3>Project Structure</h3><pre>YOLOv10-TensorRT/<br>├── include/<br>│   └── YOLOv10.hpp<br>├── src/<br>│   ├── main.cpp<br>│   └── YOLOv10.cpp<br>├── CMakeLists.txt<br>└── README.md</pre><h3>Dependencies</h3><ul><li><strong>OpenCV V4.10.0</strong>: For image and video processing.</li><li><strong>CUDA V11.7</strong>: For GPU acceleration.</li><li><strong>TensorRT V8.6.1.6</strong>: For optimized inference with YOLOv10.</li><li><strong>cuDNN V9.2.1</strong>: For accelerating deep learning training and inference on NVIDIA GPUs.</li></ul><h3>Installation</h3><h3>1. Install Dependencies</h3><ul><li><strong>OpenCV</strong>: Follow the instructions on the <a href="https://opencv.org/">OpenCV official website</a> to install OpenCV.</li><li><strong>CUDA &amp; cuDNN</strong>: Install CUDA &amp; cuDNN from the <a href="https://developer.nvidia.com/">NVIDIA website</a>.</li><li><strong>TensorRT</strong>: Download and install TensorRT from the <a href="https://developer.nvidia.com/tensorrt">NVIDIA Developer website</a>.</li></ul><h3>2. Clone the Repository</h3><pre>git clone https://github.com/hamdiboukamcha/Yolo-V10-cpp-TensorRT.git<br>cd Yolo-V10-cpp-TensorRT<br>mkdir build<br>cd build<br>cmake ..<br>cmake --build .</pre><h3>Usage</h3><h3>Convert ONNX Model to TensorRT Engine</h3><p>To convert an ONNX model to a TensorRT engine file, use the following command:</p><pre>./YOLOv10Project convert path_to_your_model.onnx path_to_your_engine.engine</pre><ul><li>path_to_your_model.onnx: Path to the ONNX model file.</li><li>path_to_your_engine.engine: Path where the TensorRT engine file will be saved.</li></ul><h3>Run Inference on Video</h3><p>To run inference on a video, use the following command:</p><pre>./YOLOv10Project infer_video path_to_your_video.mp4 path_to_your_engine.engine</pre><ul><li>path_to_your_video.mp4: Path to the input video file.</li><li>path_to_your_engine.engine: Path to the TensorRT engine file.</li></ul><h3>Run Inference on Image</h3><p>To run inference on an image, use the following command:</p><pre>./YOLOv10Project infer_image path_to_your_image.jpg path_to_your_engine.engine</pre><ul><li>path_to_your_image.jpg: Path to the input image file.</li><li>path_to_your_engine.engine: Path to the TensorRT engine file.</li></ul><h3>Configuration</h3><h3>CMake Configuration</h3><p>In the CMakeLists.txt, update the paths for TensorRT and OpenCV if they are installed in non-default locations:</p><pre>set(TENSORRT_PATH &quot;path/to/TensorRT&quot;)  # Update this to the actual path</pre><p>👉Repo: <a href="https://github.com/hamdiboukamcha/Yolo-V10-cpp-TensorRT/">https://github.com/hamdiboukamcha/Yolo-V10-cpp-TensorRT/</a></p><p>👉 Linkedin : <a href="https://www.linkedin.com/in/hamdi-boukamcha-437830146/">Hamdi Boukamcha</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27f66c163de1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>