<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ TensorFlow - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ TensorFlow - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 27 May 2026 16:21:09 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/tensorflow/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build AI Apps in the Browser with TensorFlow.js and WebGPU ]]>
                </title>
                <description>
                    <![CDATA[ Most developers think of AI the same way: you send data to a server, the server thinks, you get a response back. That mental model made sense for a long time. It still makes sense for a lot of use cas ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-ai-apps-in-the-browser-with-tensorflow-js-and-webgpu/</link>
                <guid isPermaLink="false">6a1706d0badcd8afcb00415d</guid>
                
                    <category>
                        <![CDATA[ Programming Tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ WebAssembly ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #chrome_devtools ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ayantunji Timilehin ]]>
                </dc:creator>
                <pubDate>Wed, 27 May 2026 14:59:28 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/87141e6b-7529-4278-a2fa-ee8e4d9f9062.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Most developers think of AI the same way: you send data to a server, the server thinks, you get a response back. That mental model made sense for a long time. It still makes sense for a lot of use cases.</p>
<p>But there’s a quiet shift happening inside the browser environment that a lot of engineers are completely missing out on.</p>
<p>The modern browser isn’t just a glorified engine for rendering HTML and CSS anymore. It’s turning into a full-blown runtime for local intelligence. We’ve reached a point where you can ship raw machine learning models straight to a user's device and run inference completely client-side. No server trips, no API keys to protect, and once those initial assets load, zero dependency on an internet connection.</p>
<p>This is the reality of Web AI. If you're building for the web today, understanding this paradigm shift is easily one of the most valuable skills you can add to your stack.</p>
<p>In this guide, we’re going to pull back the curtain on how Web AI actually operates under the hood, break down the browser technology stack making it possible, and build a real, working image classifier using Teachable Machine and TensorFlow.js. Along the way, we’ll also set up a live benchmark so you can watch exactly how WebGL and WebGPU stack up against each other in real-time execution speeds.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, you should have:</p>
<ul>
<li><p>A working knowledge of JavaScript</p>
</li>
<li><p>Basic familiarity with HTML and how the browser works</p>
</li>
<li><p>Google Chrome installed (required for WebGPU support and Chrome's built-in AI APIs)</p>
</li>
<li><p>A code editor like VS Code with the Live Server extension installed (recommended for running the demo locally)</p>
</li>
</ul>
<p>No prior machine learning experience is required.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-what-is-web-ai">What is Web AI?</a></p>
</li>
<li><p><a href="#heading-browser-ai-vs-cloud-ai">Browser AI vs Cloud AI</a></p>
</li>
<li><p><a href="#heading-the-technology-stack">The Technology Stack</a></p>
</li>
<li><p><a href="#heading-how-to-build-ai-in-the-browser">How to Build AI in the Browser</a></p>
</li>
<li><p><a href="#heading-chromes-built-in-ai-apis">Chrome's Built-in AI APIs</a></p>
</li>
<li><p><a href="#heading-where-web-ai-is-headed">Where Web AI Is Headed</a></p>
</li>
<li><p><a href="#heading-what-you-learned">What You Learned</a></p>
</li>
<li><p><a href="#heading-resources">Resources</a></p>
</li>
</ul>
<h2 id="heading-what-is-web-ai">What is Web AI?</h2>
<p>Instead of sending data off to a distant cloud server, Web AI lets you run machine learning models directly on the user’s device inside their browser. It uses standard web tech like JavaScript, WebAssembly, and WebGPU to handle all the heavy lifting right then and there.</p>
<p>The simplest definition: <strong>intelligence that runs in the browser, without sending your data anywhere.</strong></p>
<p>Most of us already interact with on-device AI every day without realizing it. Think about unlocking an iPhone. The second you lift it, Face ID maps out roughly 30,000 infrared points, feeds that data through a neural network living on Apple's local silicon, matches it against an encrypted embedding, and opens the phone. The whole process takes milliseconds and happens entirely offline.</p>
<p>Browser-based AI works on that exact same core architecture. The only real difference is that we're building on top of shared web standards rather than native hardware APIs. When you spin up a face-tracking model using TensorFlow.js or MediaPipe in Chrome, you're running that exact same pipeline:</p>
<pre><code class="language-plaintext">Camera input → Local ML model → Local decision
</code></pre>
<p>No round trip. No server. The browser is your Neural Engine.</p>
<h2 id="heading-browser-ai-vs-cloud-ai">Browser AI vs Cloud AI</h2>
<p>There’s no right or wrong answer here. It just depends on what you’re trying to build. Both approaches have their pros and cons, so it’s just a matter of picking the tool that fits your specific use case.</p>
<table>
<thead>
<tr>
<th></th>
<th>Browser AI (Client-Side)</th>
<th>Cloud AI (Server-Side)</th>
</tr>
</thead>
<tbody><tr>
<td>Internet required</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Latency</td>
<td>Near-zero</td>
<td>Depends on network</td>
</tr>
<tr>
<td>Privacy</td>
<td>Data stays on device</td>
<td>Data leaves the device</td>
</tr>
<tr>
<td>Model size</td>
<td>Small to medium</td>
<td>As large as you need</td>
</tr>
<tr>
<td>Cost at inference time</td>
<td>Free</td>
<td>Per token or per request</td>
</tr>
</tbody></table>
<p><strong>Use browser AI when:</strong></p>
<ul>
<li><p>You need split-second speed for things like tracking gestures or detecting objects live on a webcam</p>
</li>
<li><p>The app has to work offline (whether it's a PWA or just needs to survive spotty internet)</p>
</li>
<li><p>Privacy is a hard requirement to keep sensitive data like medical inputs, biometrics, or financial information strictly local</p>
</li>
<li><p>You want to reduce or eliminate API costs on high-frequency, lightweight predictions</p>
</li>
</ul>
<p><strong>Use cloud AI when:</strong></p>
<ul>
<li><p>You need large models like GPT-4, Gemini Pro, or Stable Diffusion</p>
</li>
<li><p>You need centralized model updates, A/B testing, or user analytics</p>
</li>
<li><p>You require serious GPU or TPU compute power</p>
</li>
</ul>
<p>Most production systems actually use a mix of both. Take Google Photos: it handles face detection right on your device so it’s fast and private, but leaves the heavier categorization work for the cloud. Or think of a modern web app that might use TensorFlow.js locally to classify images instantly, but calls the Gemini API when it needs deeper language processing.</p>
<p>This hybrid setup, keeping lightweight intelligence at the edge and heavy compute in the cloud, is usually the sweet spot for most apps.</p>
<h2 id="heading-the-technology-stack">The Technology Stack</h2>
<p>Browser AI isn’t just a single tool – it’s a stacked layer of technologies. Knowing how these layers fit together makes it a lot easier to choose your setup and navigate the trade-offs.</p>
<h3 id="heading-tensors">Tensors</h3>
<p>Before jumping into any ML framework, you need to understand tensors. Not deeply, just enough of a handle on them so you don't get blindsided by tensor shape errors, because they will happen and they can be tricky to debug.</p>
<p>Think of a tensor as a multi-dimensional grid of numbers. Whether your model is processing images, audio, or text, everything gets converted into this format first. Models only speak numbers, and tensors are the containers that hold them.</p>
<pre><code class="language-plaintext">A single number       → 0D tensor (scalar):  42
A list of numbers     → 1D tensor (vector):  [0.2, 0.8, 0.5]
A table of numbers    → 2D tensor (matrix):  [[1,2,3],[4,5,6]]
An image              → 3D tensor:           shape [224, 224, 3]
A batch of images     → 4D tensor:           shape [32, 224, 224, 3]
</code></pre>
<p>Models accept inputs in specific shapes. If your tensor shape doesn't match the model's expected input, your code breaks. That's why understanding dimensions is practical, not just theoretical.</p>
<p>TensorFlow is literally named after this concept. Tensor + Flow = tensors flowing through neural networks.</p>
<p>Here's how you create tensors in TensorFlow.js:</p>
<pre><code class="language-javascript">// 1D tensor — a list of values
const scores = tf.tensor([0.1, 0.7, 0.2]);

// 3D tensor — a single image (height x width x RGB channels)
const image = tf.tensor([
  [[255, 0, 0], [0, 255, 0]],
  [[0, 0, 255], [255, 255, 0]]
]);

// 4D tensor — a batch of 32 images
const batch = tf.zeros([32, 224, 224, 3]);
</code></pre>
<h3 id="heading-tensorflowjs">TensorFlow.js</h3>
<p>TensorFlow.js is Google's JavaScript version of TensorFlow. It lets you run pre-trained models right in the browser and, if you really want to, train new ones completely client-side.</p>
<p>The most important concept in TensorFlow.js is the backend, the hardware your model actually runs on. You can switch between backends depending on what the user's device supports, and it makes a significant difference to performance.</p>
<pre><code class="language-javascript">await tf.setBackend('webgpu');  // fastest — true GPU compute
await tf.setBackend('webgl');   // very fast — GPU via graphics shaders
await tf.setBackend('wasm');    // fast — near-native CPU speed
await tf.setBackend('cpu');     // slowest — plain JavaScript on CPU

await tf.ready();
console.log('Running on:', tf.getBackend());
</code></pre>
<p>In practice, you want to try the fastest available backend and fall back gracefully if a user's browser doesn't support it:</p>
<pre><code class="language-javascript">const backends = ['webgpu', 'webgl', 'wasm', 'cpu'];

for (const backend of backends) {
  try {
    await tf.setBackend(backend);
    await tf.ready();
    console.log('Using backend:', backend);
    break;
  } catch {
    continue;
  }
}
</code></pre>
<h3 id="heading-webassembly">WebAssembly</h3>
<p>WebAssembly (WASM) basically lets code written in C++ or Rust run inside the browser at near-native speeds. When it comes to AI, this is a big deal because heavy math operations like tensor calculations, data preprocessing, and running compressed models happen way faster in WASM than they ever could in standard JavaScript.</p>
<p>Under the hood, TensorFlow.js's WASM backend is using a compiled C++ runtime. If you're running compressed models on a device's CPU, switching to the WASM backend can make your app anywhere from 2 to 10 times faster than just sticking with regular JavaScript.</p>
<pre><code class="language-javascript">await tf.setBackend('wasm');
await tf.ready();
</code></pre>
<h3 id="heading-webgl-and-webgpu">WebGL and WebGPU</h3>
<p>This is where browser AI performance gets interesting.</p>
<p><strong>WebGL</strong> was originally built for 3D graphics. But developers discovered that the parallel computation that GPUs use for rendering is exactly the kind of parallel computation neural networks need.</p>
<p>TensorFlow.js's WebGL backend encodes tensor operations as graphics shader programs and runs them on the GPU. It works well, but it's a workaround, as WebGL was never designed for this kind of work.</p>
<p><strong>WebGPU</strong> is what was actually designed for the job. It launched in Chrome back in April 2023 after six years of collaboration between Apple, Google, Mozilla, Intel, and Microsoft.</p>
<p>Instead of just handling graphics, it's a modern API built from the ground up for general-purpose computing. When it comes to running AI models, it can be 2 to 3 times faster than WebGL, which means you can actually run significantly larger models right in the browser.</p>
<p>Here's how to check for WebGPU support and use it:</p>
<pre><code class="language-javascript">if ('gpu' in navigator) {
  console.log('WebGPU is supported');
  await tf.setBackend('webgpu');
} else {
  console.warn('WebGPU not available, falling back to WebGL');
  await tf.setBackend('webgl');
}

await tf.ready();
</code></pre>
<p>To enable WebGPU in Chrome for development, go to:</p>
<pre><code class="language-plaintext">chrome://flags/#enable-unsafe-webgpu → Enable → Restart Chrome
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/66058baaeb0049c5f549a186/77964ba9-2db1-4011-b6fe-17b47f48688b.png" alt="Enable web-gpu in chrome" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>The performance progression across backends looks like this:</p>
<table>
<thead>
<tr>
<th>Backend</th>
<th>What's happening under the hood</th>
<th>Relative speed</th>
</tr>
</thead>
<tbody><tr>
<td>cpu</td>
<td>Plain JavaScript on CPU</td>
<td>Slow</td>
</tr>
<tr>
<td>wasm</td>
<td>Compiled C++ on CPU</td>
<td>Fast</td>
</tr>
<tr>
<td>webgl</td>
<td>GPU via graphics shaders</td>
<td>Very fast</td>
</tr>
<tr>
<td>webgpu</td>
<td>GPU via compute shaders</td>
<td>Fastest</td>
</tr>
</tbody></table>
<h3 id="heading-mediapipe">MediaPipe</h3>
<p>MediaPipe is Google's framework for real-time perception tasks like hand tracking, face mesh detection, pose estimation, and object detection. Think of it as plug-and-play AI for anything that involves a camera.</p>
<p>You don't build these models yourself – you just import them and use them. MediaPipe is what actually powers the background blur in Google Meet and the visual filters in YouTube. Under the hood, it runs on TensorFlow.js and WebAssembly to keep everything moving fast.</p>
<p>You can try all MediaPipe models interactively before writing any code at <a href="https://mediapipe-studio.webapps.google.com/home">MediaPipe Studio</a>.</p>
<h2 id="heading-how-to-build-ai-in-the-browser">How to Build AI in the Browser</h2>
<h3 id="heading-step-1-train-a-model-with-teachable-machine">Step 1: Train a Model with Teachable Machine</h3>
<p><a href="https://teachablemachine.withgoogle.com">Teachable Machine</a> is Google's no-code tool for building models. It lets you create custom images, audio, or pose classifiers right from your webcam without needing any machine learning experience. Once you're done, you can export them as TensorFlow.js models that are completely ready to drop straight into your app.</p>
<p>Here's how to get started:</p>
<ol>
<li><p>Go to <a href="https://teachablemachine.withgoogle.com">teachablemachine.withgoogle.com</a></p>
</li>
<li><p>Choose Image Project, standard image model.</p>
</li>
<li><p>Create two or more classes. "Thumbs Up" and "Thumbs Down" is a simple starting point</p>
</li>
<li><p>Record examples for each class using your webcam</p>
</li>
<li><p>Click <strong>Train Model</strong> — training happens entirely in your browser</p>
</li>
<li><p>Click <strong>Export Model</strong> and choose <strong>TensorFlow.js</strong></p>
</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/66058baaeb0049c5f549a186/8ec77493-cf3a-4c05-add0-3140185cc5aa.png" alt="Train with teachable machine" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>When you export, you get three files:</p>
<ul>
<li><p><code>model.json</code>: The model architecture: layers, input/output shapes, and paths to the weights</p>
</li>
<li><p><code>weights.bin</code>: The trained weights stored as binary data</p>
</li>
<li><p><code>metadata.json</code>: Class labels, input size, and inference configuration</p>
</li>
</ul>
<h4 id="heading-a-note-on-training-data-quality">A note on training data quality</h4>
<p>Teachable Machine relies on supervised learning. You give the model labeled examples, and it figures out the underlying patterns. When you're gathering your data, two things matter way more than the sheer number of pictures you take:</p>
<ul>
<li><p><strong>Balance:</strong> If one class has significantly more examples than another, the model will be biased toward it. Keep the data roughly equal across classes.</p>
<p><strong>Variety:</strong> Fifty photos from different angles, distances, and lighting conditions will easily outperform two hundred near-identical shots from the same spot. The model needs to understand the concept of a "thumbs up", not memorise one specific photo of your specific thumb.</p>
</li>
</ul>
<p>Keep in mind that the actual machine learning model is usually just a tiny fraction of your overall codebase. The vast majority of what you write is going to be standard JavaScript. At the end of the day, it's just another asset in your stack.</p>
<h3 id="heading-step-2-setting-up-and-writing-the-code">Step 2: Setting up and Writing the Code</h3>
<p>Now that you have your model files, set up your project structure like this and create an <code>index.html</code> file:</p>
<pre><code class="language-plaintext">your-project/
├── index.html
├── model.json
├── weights.bin
└── metadata.json
</code></pre>
<p>The <code>model.json</code>, <code>weights.bin</code>, and <code>metadata.json</code> files all go in the same folder as your <code>index.html</code>. The demo loads them from the same directory using <code>const URL = "./"</code>.</p>
<p>To run it locally, open the folder in VS Code or your preferred IDE and use the <strong>Live Server</strong> extension. Just right-click <code>index.html</code> and select <strong>Open with Live Server</strong>. Opening the file directly in the browser without a server will cause CORS errors when loading the model files.</p>
<h3 id="heading-step-3-load-the-model-and-run-predictions">Step 3: Load the Model and Run Predictions</h3>
<p>Paste the following in your <code>index.html</code> file. This demo loads your Teachable Machine model, starts your webcam, and runs continuous predictions in a loop:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;

&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Teachable Machine - Webcam + Backend Switch Demo&lt;/title&gt;
    &lt;style&gt;
        body {
            font-family: Arial;
            text-align: center;
            margin: 20px;
        }

        #webcam-container {
            margin-top: 20px;
        }

        #label-container {
            margin-top: 10px;
            font-size: 18px;
            font-weight: bold;
        }

        button.backend-btn {
            margin: 5px;
            padding: 8px 16px;
            font-size: 16px;
            cursor: pointer;
        }

        #status {
            margin-top: 10px;
            font-weight: bold;
            color: #0078ff;
        }

        table {
            margin: 20px auto;
            border-collapse: collapse;
            width: 80%;
            max-width: 600px;
        }

        th,
        td {
            border: 1px solid #ccc;
            padding: 10px;
        }

        th {
            background: #0078ff;
            color: white;
        }
    &lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;h2&gt;AI in the web Demo&lt;/h2&gt;

    &lt;div&gt;
        &lt;button class="backend-btn" onclick="switchBackend('cpu')"&gt;CPU&lt;/button&gt;
        &lt;button class="backend-btn" onclick="switchBackend('webgl')"&gt;WebGL&lt;/button&gt;
        &lt;button class="backend-btn" onclick="switchBackend('webgpu')"&gt;WebGPU&lt;/button&gt;
    &lt;/div&gt;

    &lt;p id="status"&gt;Click a backend to start&lt;/p&gt;

    &lt;table&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;Backend&lt;/th&gt;
                &lt;th&gt;Load Time (s)&lt;/th&gt;
                &lt;th&gt;Inference Time (ms)&lt;/th&gt;
                &lt;th&gt;Status&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody id="results"&gt;&lt;/tbody&gt;
    &lt;/table&gt;

    &lt;div id="webcam-container"&gt;&lt;/div&gt;
    &lt;div id="label-container"&gt;&lt;/div&gt;

    &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"&gt;&lt;/script&gt;
    &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-webgpu"&gt;&lt;/script&gt;
    &lt;script
        src="https://cdn.jsdelivr.net/npm/@teachablemachine/image@latest/dist/teachablemachine-image.min.js"&gt;&lt;/script&gt;

    &lt;script&gt;
        const URL = "./";
        const resultsTable = document.getElementById("results");
        const statusEl = document.getElementById("status");
        const backends = ["cpu", "webgl", "webgpu"];

        let model, webcam, maxPredictions;
        const backendResults = {};

        // Initialize webcam
        async function initWebcam() {
            if (!webcam) {
                webcam = new tmImage.Webcam(200, 200, true);
                await webcam.setup();
                await webcam.play();
                document.getElementById("webcam-container").appendChild(webcam.canvas);

                const labelContainer = document.getElementById("label-container");
                labelContainer.innerHTML = "";
                for (let i = 0; i &lt; 2; i++) labelContainer.appendChild(document.createElement("div"));
            }
        }

        async function switchBackend(backend) {
            statusEl.innerText = `Switching to ${backend.toUpperCase()}...`;

            await initWebcam();

            try {
                const startLoad = performance.now();
                await tf.setBackend(backend);
                await tf.ready();
                model = await tmImage.load(URL + "model.json", URL + "metadata.json");
                maxPredictions = model.getTotalClasses();
                const endLoad = performance.now();
                const loadTime = ((endLoad - startLoad) / 1000).toFixed(2);

                // Single inference to measure time
                const startInference = performance.now();
                await model.predict(webcam.canvas);
                const endInference = performance.now();
                const inferenceTime = (endInference - startInference).toFixed(1);

                // Store results
                backendResults[backend] = { loadTime, inferenceTime };

                updateTable();

                statusEl.innerText = `${backend.toUpperCase()} ready`;
            } catch (err) {
                console.error(`${backend} not supported:`, err);
                statusEl.innerText = `${backend.toUpperCase()} not supported`;
            }
        }


        function updateTable() {
            resultsTable.innerHTML = "";
            for (let backend of backends) {
                const row = document.createElement("tr");
                const backendCell = document.createElement("td");
                const loadCell = document.createElement("td");
                const inferenceCell = document.createElement("td");
                const statusCell = document.createElement("td");

                backendCell.textContent = backend.toUpperCase();

                if (backendResults[backend]) {
                    loadCell.textContent = backendResults[backend].loadTime;
                    inferenceCell.textContent = backendResults[backend].inferenceTime;
                    statusCell.textContent = "✓";
                } else {
                    loadCell.textContent = "-";
                    inferenceCell.textContent = "-";
                    statusCell.textContent = "-";
                }

                row.appendChild(backendCell);
                row.appendChild(loadCell);
                row.appendChild(inferenceCell);
                row.appendChild(statusCell);
                resultsTable.appendChild(row);
            }
        }

        // Continuous prediction loop
        async function loop() {
            if (webcam &amp;&amp; model) {
                webcam.update();
                const prediction = await model.predict(webcam.canvas);
                const labelContainer = document.getElementById("label-container");
                labelContainer.innerHTML = "";
                for (let i = 0; i &lt; maxPredictions; i++) {
                    const p = document.createElement("div");
                    p.textContent = `\({prediction[i].className}: \){(prediction[i].probability * 100).toFixed(1)}%`;
                    labelContainer.appendChild(p);
                }
            }
            requestAnimationFrame(loop);
        }

        loop();
    &lt;/script&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre>
<p>A few things worth understanding about what this code is doing:</p>
<p>The <code>switchBackend</code> function does more than just swap the backend. Each time you click a backend button, it records how long the model takes to load on that backend and how long a single inference takes. Those numbers go straight into the comparison table so you can see the difference without having to look at console logs.</p>
<p>The <code>loop</code> function runs continuously using <code>requestAnimationFrame</code>. Every frame, it grabs the current webcam image, passes it to the model, and updates the prediction labels on screen. This is what makes the detection feel real-time.</p>
<p>Notice that <code>initWebcam</code> only runs once. It checks if <code>webcam</code> already exists before setting up. Switching backends reloads the model but keeps the same webcam stream running.</p>
<p>Open Chrome DevTools and go to the <strong>Network tab</strong> while the demo runs. After the model files finish loading, you'll see zero outbound requests. Every prediction is happening entirely in the browser.</p>
<h3 id="heading-step-4-switch-backends-and-compare-performance">Step 4: Switch Backends and Compare Performance</h3>
<p>Once the demo is running, click each backend button one at a time: CPU, then WebGL, then WebGPU. The table updates after each switch and shows you the load time in seconds and inference time in milliseconds for each backend side by side.</p>
<p>Here's what you should expect to see:</p>
<ul>
<li><p><strong>CPU</strong> will be the slowest with everything running in plain JavaScript</p>
</li>
<li><p><strong>WebGL</strong> will be noticeably faster as the GPU is now handling the tensor operations</p>
</li>
<li><p><strong>WebGPU</strong> will be the fastest with true GPU compute and less overhead than WebGL. The exact numbers depend on your machine, but the gap between CPU and WebGPU is usually significant enough to see immediately in the table.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/66058baaeb0049c5f549a186/6332c651-9b96-45c7-95cc-0d842595ff51.png" alt="Demo with network tab" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p><strong>Note:</strong> WebGPU requires Chrome with the flag enabled. If the WebGPU button shows "not supported", go to <code>chrome://flags/#enable-unsafe-webgpu</code>, enable it, and restart Chrome.</p>
<h2 id="heading-chromes-built-in-ai-apis">Chrome's Built-in AI APIs</h2>
<p>Beyond loading your own models, Chrome is rolling out native AI capabilities that you can hook into directly through browser APIs. This means no managing bulky model files, no importing TensorFlow.js, and zero manual setup.</p>
<p>The powerhouse here is Gemini Nano, a lightweight version of Google's Gemini model built to run completely on-device inside Chrome. It handles tasks like smart replies and page summarization right in the browser without ever making a cloud call.</p>
<p>If you want to build with it, you can tap into these experimental APIs that Chrome exposes to developers:</p>
<pre><code class="language-plaintext">chrome://flags → search "Prompt API for Gemini Nano" → Enable → Restart Chrome
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/66058baaeb0049c5f549a186/c1db08aa-b5b1-4496-9553-536bbc68a442.png" alt="Gemini nano" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>These are still experimental and behind flags. But they show clearly where the platform is heading.</p>
<p>For the full prerequisites and setup guide for Chrome's built-in AI, see the <a href="https://developer.chrome.com/docs/ai/get-started">official Chrome AI getting started documentation</a>.</p>
<h2 id="heading-where-web-ai-is-headed">Where Web AI Is Headed</h2>
<p>The browser is evolving into something that doesn't really have a clean name yet. It's no longer just a document viewer, and it's not quite a native app runtime either. Instead, it's becoming an intelligent edge node – a piece of infrastructure that can perceive, process, and act all on its own, without constantly phoning home for permission.</p>
<p>A few massive shifts are already well underway:</p>
<ul>
<li><p><strong>Native AI built directly into the platform:</strong> AI capabilities are turning into standard browser APIs. Because they're cached and shared across the entire ecosystem, you won't have to re-download massive models for every single domain you visit.  </p>
<p>Browsers designed with AI as their core foundation are already popping up. OpenAI's Atlas browser is a perfect early signal of this trend. Every year, the idea of the browser acting as an intelligent agent platform rather than a simple content renderer gets more concrete.</p>
</li>
<li><p><strong>The developer shift:</strong> For developers, the immediate future is clear: a significant chunk of AI features that currently live on expensive servers will migrate straight to the client side. It won't be everything, but the lightweight, high-frequency, and privacy-sensitive tasks will absolutely make the jump.</p>
</li>
</ul>
<p>WebGPU isn't just a flashy demo technology, and browser inference is definitely not a toy. These are serious production tools, and they're only getting more capable as AI models shrink and user hardware gets more powerful.</p>
<p>If you're currently building an interactive, AI-powered feature, it's well worth pausing to ask yourself: <em>does this actually need a server?</em></p>
<p>Sometimes the answer is still yes. But more and more often, the answer is a definitive no.</p>
<h2 id="heading-what-you-learned">What You Learned</h2>
<p>In this tutorial, we covered:</p>
<ul>
<li><p>What Web AI is and how it differs from cloud-based AI</p>
</li>
<li><p>When to use browser AI versus cloud AI and how a hybrid approach works</p>
</li>
<li><p>The technology stack behind browser AI: tensors, TensorFlow.js, WebAssembly, WebGL, WebGPU, and MediaPipe</p>
</li>
<li><p>How to train a custom model with Teachable Machine and export it for the browser</p>
</li>
<li><p>How to load that model, run it against live webcam input, and manage GPU memory correctly</p>
</li>
<li><p>How to benchmark WebGL vs WebGPU inference times to measure real performance differences</p>
</li>
<li><p>How to access Chrome's built-in AI APIs including Gemini Nano</p>
</li>
</ul>
<p>If you found this useful or want to connect, you can find me on <a href="https://twitter.com/timi471">Twitter/X</a> or <a href="https://www.linkedin.com/in/ayantunji-timilehin">LinkedIn</a>.</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p><a href="https://www.tensorflow.org/js">TensorFlow.js Documentation</a></p>
</li>
<li><p><a href="https://teachablemachine.withgoogle.com">Teachable Machine</a></p>
</li>
<li><p><a href="https://mediapipe-studio.webapps.google.com/home">MediaPipe Studio</a></p>
</li>
<li><p><a href="https://developer.chrome.com/docs/web-platform/webgpu">WebGPU in Chrome</a></p>
</li>
<li><p><a href="https://developer.chrome.com/docs/ai/get-started">Chrome Built-in AI — Getting Started</a></p>
</li>
<li><p><a href="https://developer.chrome.com/docs/ai/translator-api">Chrome AI Translator API</a></p>
</li>
<li><p><a href="https://github.com/GoogleChromeLabs/web-ai-demos">Google Web AI Demos on GitHub</a></p>
</li>
<li><p><a href="https://huggingface.co/docs/transformers.js">Hugging Face Transformers.js</a></p>
</li>
<li><p><a href="https://webllm.mlc.ai">WebLLM — Run LLMs in the Browser</a></p>
</li>
<li><p><a href="https://blog.google/products/chrome/new-ai-features-for-chrome/">Chrome AI Features — Google Blog</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ PyTorch vs TensorFlow – Which is Better for Deep Learning Projects? ]]>
                </title>
                <description>
                    <![CDATA[ In this article, we'll look at two popular deep learning libraries — PyTorch and TensorFlow – and see how they compare. If you are getting started with deep learning, the available tools and frameworks will be overwhelming. Industry experts may recom... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/pytorch-vs-tensorflow-for-deep-learning-projects/</link>
                <guid isPermaLink="false">66d0361612c679876b0602e9</guid>
                
                    <category>
                        <![CDATA[ Deep Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pytorch ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Wed, 10 Jan 2024 18:46:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/pytorchvs_cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, we'll look at two popular deep learning libraries — PyTorch and TensorFlow – and see how they compare.</p>
<p>If you are getting started with deep learning, the available tools and frameworks will be overwhelming. Industry experts may recommend TensorFlow while hardcore ML engineers may prefer PyTorch.</p>
<p>Both these frameworks are powerful deep-learning tools. While TensorFlow is used in Google search and by Uber, Pytorch powers OpenAI’s ChatGPT and Tesla's autopilot.</p>
<p>Choosing between these two frameworks is a common challenge for developers. If you're in this position, in this article we’ll compare TensorFlow and PyTorch to help you make an informed choice.</p>
<h2 id="heading-understanding-pytorch-and-tensorflow">Understanding PyTorch and TensorFlow</h2>
<p>Let’s start by getting to know our contenders better.</p>
<p><a target="_blank" href="https://pytorch.org/">PyTorch</a>, created by Facebook’s AI Research lab, has gained recognition for its simplicity and user-friendliness. Pytorch can efficiently handle dynamic computational graphs.</p>
<p>A computation graph is a visual representation of mathematical operations and their relationships. It’s like a flowchart that shows how data flow through the deep learning model.  </p>
<p>Training neural networks involves a lot of computations. So computation graphs help computers organize and execute calculations efficiently when training neural networks.</p>
<p>PyTorch is easy to use, making it a favoured choice among developers and researchers alike. For people who appreciate a straightforward framework for their projects, PyTorch is a perfect choice.</p>
<p><a target="_blank" href="https://www.tensorflow.org/">TensorFlow</a>, Google’s brainchild, has robust production capabilities and support for distributed training. TensorFlow excels in scenarios where you need large-scale machine learning models in real-world applications.</p>
<p>Distributed training is a technique used in deep learning to train large and complex models. By spreading the training process across multiple machines or devices, it is useful when dealing with massive datasets.</p>
<p>Tensorflow is the go-to choice for companies that need scalability and reliability in their deep learning models.</p>
<p>So as you may be able to see, the choice between PyTorch and TensorFlow often depends on the specific needs of a project.</p>
<h2 id="heading-pytorch-vs-tensorflow-which-ones-right-for-you">PyTorch vs TensorFlow – Which One's Right for You?</h2>
<h3 id="heading-ease-of-learning-and-use">Ease of Learning and Use</h3>
<p>When you’re starting a new project, it's helpful to have an easier learning curve. It helps both in building the project as well as hiring / training engineers for your project.</p>
<p>PyTorch is simpler and has a “Pythonic” way of doing things. It's a favourite for beginners and researchers. And its dynamic computation graph means you can change things on the fly, which is great for experimentation.</p>
<p>TensorFlow offers a more structured approach. Its static computation graph requires a bit more planning ahead. TensorFlow also comes with a steep learning curve. But this can lead to more optimized and high-performance models.</p>
<p>TensorFlow 2.0 has also made strides in simplicity. It has incorporated more of PyTorch’s dynamic nature through its <a target="_blank" href="https://towardsdatascience.com/eager-execution-vs-graph-execution-which-is-better-38162ea4dbf6">Eager Execution feature</a>.</p>
<p>But when it comes to simplicity and ease of learning, PyTorch is a clear winner.</p>
<h3 id="heading-performance-and-scalability">Performance and Scalability</h3>
<p>When it comes to performance and scalability, TensorFlow shines. Its can handle large-scale, distributed training with ease. So TensorFlow is a go-to choice for production environments.</p>
<p>TensorFlow’s integrated tool, <a target="_blank" href="https://www.tensorflow.org/tensorboard">TensorBoard</a>, is also a powerful tool for visualization and debugging.</p>
<p>PyTorch is catching up, with recent updates improving its scalability.</p>
<p>PyTorch has made improvements to support distributed training and scalability. It provides tools to help you train deep learning models on multiple GPUs and even across multiple machines.</p>
<p>But TensorFlow still holds the lead in deploying large-scale models in production.</p>
<h3 id="heading-community-and-support">Community and Support</h3>
<p>The strength of a framework is also partly defined by its community. As these are open-source frameworks, there is no customer support. So you have to depend on the community for help if you get stuck while building a project using these frameworks.</p>
<p>TensorFlow, being older, has a larger community. It also has a vast array of tutorials, courses, and books.</p>
<p>PyTorch, while younger, has seen rapid growth in its community. PyTorch is a favourite, especially among researchers since it's easy to use Pytorch for experimenting with datasets.</p>
<p>Both frameworks have strong support, but TensorFlow’s maturity gives it a slight edge in this area.</p>
<h3 id="heading-flexibility-and-innovation">Flexibility and Innovation</h3>
<p>If you’re working on cutting-edge research or need more flexibility, PyTorch is your best bet. Its dynamic computation graph allows for more creative and complex model architectures.</p>
<p>As I said before, this flexibility makes PyTorch a beloved tool in the research community. Where rapid prototyping and experimentation are key, PyTorch is your best option.</p>
<p>TensorFlow has been working towards adding more flexibility. But it's a difficult battle to win since PyTorch is built for simplicity from the ground up.</p>
<h3 id="heading-industry-adoption">Industry Adoption</h3>
<p><img src="https://miro.medium.com/v2/resize:fit:1050/1*3KA-wtadTjv6H9-LLSu9fw.png" alt="Image" width="600" height="400" loading="lazy">
<em>PyTorch (blue) vs TensorFlow (red)</em></p>
<p>TensorFlow has tpyically had the upper hand, particularly in large companies and production environments. Its robustness and scalability make it a safe choice for businesses.</p>
<p>But PyTorch is quickly gaining ground. As you can see in the trends chart, PyTorch has already taken over TensorFlow as the most searched deep learning library. <a target="_blank" href="https://trends.google.com/trends/explore/TIMESERIES/1704798600?hl=en&amp;tz=-330&amp;date=today+5-y&amp;q=%2Fg%2F11gd3905v1%2C%2Fg%2F11bwp1s2k3&amp;sni=3">You can find the live chart here</a>.</p>
<p>Multiple industries are starting to adopt PyTorch for research and development due to its user-friendliness and flexibility. Pytorch has also proved its capability as a production-grade tool after the release of models like ChatGPT.</p>
<p>Here is a list of companies using TensorFlow and PyTorch.</p>
<h3 id="heading-products-using-tensorflow">Products Using Tensorflow</h3>
<ul>
<li><strong>Google Search and Recommendations</strong>: Google uses TensorFlow to enhance its search engine and recommendation systems. It helps improve search accuracy and provides personalized recommendations based on user behaviour and preferences.</li>
<li><strong>NVIDIA Deep Learning Accelerator (NVDLA)</strong>: NVDLA is a hardware accelerator for deep learning applications. It uses TensorFlow to optimize and deploy models on this hardware.</li>
<li><a target="_blank" href="https://www.uber.com/en-IN/blog/michelangelo-machine-learning-platform/"><strong>Uber’s Michelangelo</strong></a>: Uber uses TensorFlow in its Michelangelo platform for machine learning. It assists in various tasks, including ETA predictions, fraud detection, and dynamic pricing.</li>
</ul>
<h3 id="heading-products-using-pytorch">Products Using PyTorch</h3>
<ul>
<li><strong>Facebook</strong>: Since PyTorch is from Facebook, Facebook uses PyTorch for various internal AI research and applications, including content recommendations and language translation.</li>
<li><strong>Tesla Autopilot</strong>: Tesla’s Autopilot system relies on PyTorch for its deep learning components, such as object detection and navigation.</li>
<li><strong>OpenAI’s GPT Models</strong>: Many of OpenAI’s language models, including GPT-2 and GPT-3, are built using PyTorch. These models are used for a wide range of natural language processing tasks, including text generation and language translation.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Choosing between PyTorch and TensorFlow depends on your project’s needs.</p>
<p>For those who need ease of use and flexibility, PyTorch is a great choice. If you prefer scalability from the ground up, production deployment, and a mature ecosystem, TensorFlow might be the way to go.</p>
<p>Both frameworks are evolving, so keep an eye on their development. Your choice today might not be your choice tomorrow. Remember, the best tool is the one that suits your project’s needs and not the popular one.</p>
<p>Thanks for coming this far. If you want weekly machine learning tutorials delivered to your inbox, <a target="_blank" href="https://turingtalks.substack.com/"><strong>join my newsletter</strong></a>. To get in touch with me, you can <a target="_blank" href="https://www.linkedin.com/in/manishmshiva/"><strong>connect with me on LinkedIn</strong></a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Binary Classification with TensorFlow Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ Binary classification is a fundamental task in machine learning, where the goal is to categorize data into one of two classes or categories.  Binary classification is used in a wide range of applications, such as spam email detection, medical diagnos... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/binary-classification-made-simple-with-tensorflow/</link>
                <guid isPermaLink="false">66ba10937282cc17abcf0c66</guid>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Arunachalam B ]]>
                </dc:creator>
                <pubDate>Thu, 21 Sep 2023 14:21:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/Binary-Classification-Made-Simple-with-TensorFlow.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Binary classification is a fundamental task in machine learning, where the goal is to categorize data into one of two classes or categories. </p>
<p>Binary classification is used in a wide range of applications, such as spam email detection, medical diagnosis, sentiment analysis, fraud detection, and many more.</p>
<p>In this article, we'll explore binary classification using TensorFlow, one of the most popular deep learning libraries.</p>
<p>Before getting into the Binary Classification, let's discuss a little about classification problem in Machine Learning.</p>
<h2 id="heading-what-is-classification-problem">What is Classification problem?</h2>
<p>A Classification problem is a type of machine learning or statistical problem in which the goal is to assign a category or label to a set of input data based on their characteristics or features. The objective is to learn a mapping between input data and predefined classes or categories, and then use this mapping to predict the class labels of new, unseen data points.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-89.png" alt="Image" width="600" height="400" loading="lazy">
<em>Sample Multi Classification</em></p>
<p>The above diagram represents a multi-classification problem in which the data will be classified into more than two (three here) types of classes.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-90.png" alt="Image" width="600" height="400" loading="lazy">
<em>Sample Binary Classification</em></p>
<p>This diagram defines Binary Classification, where data is classified into two type of classes.</p>
<p>This simple concept is enough to understand classification problems. Let's explore this with a real-life example.</p>
<h2 id="heading-heart-attack-analytics-prediction-using-binary-classification">Heart Attack Analytics Prediction Using Binary Classification</h2>
<p>In this article, we will embark on the journey of constructing a predictive model for heart attack analysis utilizing straightforward deep learning libraries. </p>
<p>The model that we'll be building, while being a relatively simple neural network, is capable of achieving an accuracy level of approximately 80%.</p>
<p>Solving real-world problems through the lens of machine learning entails a series of essential steps:</p>
<ol>
<li>Data Collection and Analytics</li>
<li>Data preprocessing</li>
<li>Building ML Model</li>
<li>Train the Model</li>
<li>Prediction and Evaluation</li>
</ol>
<h2 id="heading-data-collection-and-analytics">Data Collection and Analytics</h2>
<p>It's worth noting that for this project, I obtained the dataset from <a target="_blank" href="https://www.kaggle.com/datasets/rashikrahmanpritom/heart-attack-analysis-prediction-dataset">Kaggle</a>, a popular platform for data science competitions and datasets. </p>
<p>I encourage you to take a closer look at its contents. Understanding the dataset is crucial as it allows you to grasp the nuances and intricacies of the data, which can help you make informed decisions throughout the machine learning pipeline.</p>
<p>This dataset is well-structured, and there's no immediate need for further analysis. However, if you are collecting the dataset on your own, you will need to perform data analytics and visualization independently to achieve better accuracy.</p>
<p>Let's put on our coding shoes. </p>
<p>Here I am using Google Colab. You can use your own machine (in which case you will need to create a <code>.ipynb</code> file) or Google Colab on your account to run the notebook. You can find my source code <a target="_blank" href="https://colab.research.google.com/drive/1-LBbym1bcTP6qF9tiENCzUVLGoY_NWMj?usp=sharing">here</a>.</p>
<p>As the first step, let's import the required libraries.</p>
<pre><code><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split
<span class="hljs-keyword">import</span> sklearn
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> keras
<span class="hljs-keyword">from</span> keras.models <span class="hljs-keyword">import</span> Sequential
<span class="hljs-keyword">from</span> keras.layers <span class="hljs-keyword">import</span> Dense
<span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
<span class="hljs-keyword">from</span> sklearn.metrics <span class="hljs-keyword">import</span> confusion_matrix,ConfusionMatrixDisplay
<span class="hljs-keyword">from</span> sklearn.preprocessing <span class="hljs-keyword">import</span> MinMaxScaler
</code></pre><p>I have the dataset in my drive and I'm reading it from my drive. You can download the same dataset <a target="_blank" href="https://www.kaggle.com/datasets/rashikrahmanpritom/heart-attack-analysis-prediction-dataset">here</a>. </p>
<p>Remember the replace the path of your file in the <code>read_csv</code> method:</p>
<pre><code>df = pd.read_csv(<span class="hljs-string">"/content/drive/MyDrive/Datasets/heart.csv"</span>)
df.head()
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-91.png" alt="Image" width="600" height="400" loading="lazy">
<em>Sample 5 record in the dataset</em></p>
<p>The dataset contains thirteen input columns (age, sex, cp, and so on) and one output column (<code>output</code>), which will contain the data as either <code>0</code> or <code>1</code>.</p>
<p>Considering the input readings, <code>0</code> in the <code>output</code> represents the person will not get heart attack, while the <code>1</code> represents the person will be affected by heart attack.</p>
<p>Let's split our input and output from the above dataset to train our model:</p>
<pre><code>target_column = <span class="hljs-string">"output"</span>
numerical_column = df.columns.drop(target_column)
output_rows = df[target_column]
df.drop(target_column,axis=<span class="hljs-number">1</span>,inplace=True)
</code></pre><p>Since our objective is to predict the likelihood of a heart attack (0 or 1), represented by the target column, we split that into a separate dataset.</p>
<h2 id="heading-data-preprocessing">Data preprocessing</h2>
<p>Data preprocessing is a crucial step in the machine learning pipeline, and binary classification is no exception. It involves the cleaning, transformation, and organization of raw data into a format that is suitable for training machine learning models.</p>
<p>A dataset will contain multiple type of data such as Numerical Data, Categorical Data, Timestamp Data, and so on. </p>
<p>But most of the Machine Learning algorithms are designed to work with numerical data. They require input data to be in a numeric format for mathematical operations, optimization, and model training.</p>
<p>In this dataset, all the columns contain numerical data, so we don't need to encode the data. We can proceed with simple normalization. </p>
<p>Remember if you have any non-numerical columns in your dataset, you may have to convert it into numerical by performing one-hot encoding or using other encoding algorithms.</p>
<p>There are lot of normalization strategies. Here I am using Min-Max Normalization:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-92.png" alt="Image" width="600" height="400" loading="lazy">
<em>Min-Max Scaling Formula</em></p>
<p>Don't worry  – we don't need to apply this formula manually. We have some machine learning libraries to do this. Here I am using MinMaxScaler from sklearn:</p>
<pre><code>scaler = MinMaxScaler()
scaler.fit(df)
t_df = scaler.transform(df)
</code></pre><p><code>scaler.fit(df)</code>  computes the mean and standard deviation (or other scaling parameters) necessary to perform the scaling operation. The <code>fit</code> method essentially learns these parameters from the data.</p>
<p><code>t_df = scaler.transform(df)</code>: After fitting the scaler, we need to transform the dataset. The transformation typically scales the features to have a mean of 0 and a standard deviation of 1 (standardization) or scales them to a specific range (for example, [0, 1] with Min-Max scaling) depending on the scaler used.</p>
<p>We have completed the preprocessing. The next crucial step is to split the dataset into training and testing sets.</p>
<p>To accomplish this, I will utilize the <code>train_test_split</code> function from <code>scikit-learn</code>.</p>
<p><code>X_train</code> and <code>X_test</code> are the variables that hold the independent variables.</p>
<p><code>y_train</code> and <code>y_test</code> are the variables that hold the dependent variable, which represents the output we are aiming to predict.</p>
<pre><code>X_train, X_test, y_train, y_test = train_test_split(t_df, output_rows, test_size=<span class="hljs-number">0.25</span>, random_state=<span class="hljs-number">0</span>)
</code></pre><pre><code>print(<span class="hljs-string">'X_train:'</span>,np.shape(X_train))
print(<span class="hljs-string">'y_train:'</span>,np.shape(y_train))
print(<span class="hljs-string">'X_test:'</span>,np.shape(X_test))
print(<span class="hljs-string">'y_test:'</span>,np.shape(y_test))
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-93.png" alt="Image" width="600" height="400" loading="lazy">
<em>Sample training and testing dataset size</em></p>
<p>We split the dataset by 75% and 25%, where 75% goes for training our model and 25% goes for testing our model.</p>
<h2 id="heading-building-ml-model">Building ML Model</h2>
<p>A machine learning model is a computational representation of a problem or a system that is designed to learn patterns, relationships, and associations from data. It serves as a mathematical and algorithmic framework capable of making predictions, classifications, or decisions based on input data. </p>
<p>In essence, a model encapsulates the knowledge extracted from data, allowing it to generalize and make informed responses to new, previously unseen data.</p>
<p>Here, I am building a simple sequential model with one input layer and one output layer. Being a simple model, I am not using any hidden layer as it might increase the complexity of the concept.</p>
<h3 id="heading-initialize-sequential-model">Initialize Sequential Model</h3>
<pre><code>basic_model = Sequential()
</code></pre><p><code>Sequential</code> is a type of model in Keras that allows you to create neural networks layer by layer in a sequential manner. Each layer is added on top of the previous one.</p>
<h3 id="heading-input-layer">Input Layer</h3>
<pre><code>basic_model.add(Dense(units=<span class="hljs-number">16</span>, activation=<span class="hljs-string">'relu'</span>, input_shape=(<span class="hljs-number">13</span>,)))
</code></pre><p><code>Dense</code> is a type of layer in Keras, representing a fully connected layer. It has 16 units, which means it has 16 neurons.</p>
<p><code>activation='relu'</code> specifies the Rectified Linear Unit (ReLU) activation function, which is commonly used in input or hidden layers of neural networks.</p>
<p><code>input_shape=(13,)</code> indicates the shape of the input data for this layer. In this case, we are using 13 input features (columns).</p>
<h3 id="heading-output-layer">Output Layer</h3>
<pre><code>basic_model.add(Dense(<span class="hljs-number">1</span>, activation=<span class="hljs-string">'sigmoid'</span>))
</code></pre><p>This line adds the output layer to the model. </p>
<p>It's a single neuron (1 unit) because this appears to be a binary classification problem, where you're predicting one of two classes (0 or 1). </p>
<p>The activation function used here is <code>'sigmoid'</code>, which is commonly used for binary classification tasks. It squashes the output to a range between 0 and 1, representing the probability of belonging to one of the classes.</p>
<h3 id="heading-optimizer">Optimizer</h3>
<pre><code>adam = keras.optimizers.Adam(learning_rate=<span class="hljs-number">0.001</span>)
</code></pre><p>This line initializes the Adam optimizer with a learning rate of 0.001. The optimizer is responsible for updating the model's weights during training to minimize the defined loss function.</p>
<h3 id="heading-compile-model">Compile Model</h3>
<pre><code>basic_model.compile(loss=<span class="hljs-string">'binary_crossentropy'</span>, optimizer=adam, metrics=[<span class="hljs-string">"accuracy"</span>])
</code></pre><p>Here, we'll compile the model.</p>
<p><code>loss='binary_crossentropy'</code> is the loss function used for binary classification. It measures the difference between the predicted and actual values and is minimized during training.</p>
<p><code>metrics=["accuracy"]</code>: During training, we want to monitor the accuracy metric, which tells you how well the model is performing in terms of correct predictions.</p>
<h3 id="heading-train-model-with-dataset">Train model with dataset</h3>
<p>Hurray, we built the model. Now it's time to train the model with our training dataset.</p>
<pre><code>basic_model.fit(X_train, y_train, epochs=<span class="hljs-number">100</span>)
</code></pre><p><code>X_train</code> represents the training data, which consists of the independent variables (features). The model will learn from these features to make predictions or classifications.</p>
<p><code>y_train</code> are the corresponding target labels or dependent variables for the training data. The model will use this information to learn the patterns and relationships between the features and the target variable.</p>
<p><code>epochs=100</code>: The <code>epochs</code> parameter specifies the number of times the model will iterate over the entire training dataset. Each pass through in the dataset is called an epoch. In this case, we have 100 epochs, meaning the model will see the entire training dataset 100 times during training.</p>
<pre><code>loss_and_metrics = basic_model.evaluate(X_test, y_test)
print(loss_and_metrics)
print(<span class="hljs-string">'Loss = '</span>,loss_and_metrics[<span class="hljs-number">0</span>])
print(<span class="hljs-string">'Accuracy = '</span>,loss_and_metrics[<span class="hljs-number">1</span>])
</code></pre><p>The <code>evaluate</code> method is used to assess how well the trained model performs on the test dataset. It computes the loss (often the same loss function used during training) and any specified metrics (for example, accuracy) for the model's predictions on the test data.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-94.png" alt="Image" width="600" height="400" loading="lazy">
<em>Sample output to find the Loss and Accuracy</em></p>
<p>Here we got around 82% accuracy.</p>
<h2 id="heading-prediction-and-evaluation">Prediction and Evaluation</h2>
<pre><code>predicted = basic_model.predict(X_test)
</code></pre><p>The <code>predict</code> method is used to generate predictions from the model based on the input data (<code>X_test</code> in this case). The output (<code>predicted</code>) will contain the model's predictions for each data point in the training dataset. </p>
<p>Since I have only minimum dataset I am using the test dataset for prediction. However, it is a  recommend practice to split a part of dataset (say 10%) to use as a validation dataset.</p>
<h3 id="heading-evaluation">Evaluation</h3>
<p>Evaluating predictions in machine learning is a crucial step to assess the performance of a model. </p>
<p>One commonly tool used for evaluating classification models is the confusion matrix. Let's explore what a confusion matrix is and how it's used for model evaluation:</p>
<p>In a binary classification problem (two classes, for example, "positive" and "negative"), a confusion matrix typically looks like this:</p>
<table><tbody><tr><td></td><td>Predicted Negative (0)</td><td>Predicted Positive (1)</td></tr><tr><td>Actual Negative (0)</td><td>True Negative</td><td>False Positive</td></tr><tr><td>Actual Positive (1)</td><td>False Negative</td><td>True Positive</td></tr></tbody></table>

<p>Here's the code to plot the confusion matrix from the predicted data of our model:</p>
<pre><code>predicted = tf.squeeze(predicted)
predicted = np.array([<span class="hljs-number">1</span> <span class="hljs-keyword">if</span> x &gt;= <span class="hljs-number">0.5</span> <span class="hljs-keyword">else</span> <span class="hljs-number">0</span> <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> predicted])
actual = np.array(y_test)
conf_mat = confusion_matrix(actual, predicted)
displ = ConfusionMatrixDisplay(confusion_matrix=conf_mat)
displ.plot()
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2023/09/image-95.png" alt="Image" width="600" height="400" loading="lazy">
<em>Confusion matrix for the predicted output</em></p>
<p>Bravo! We've made significant progress toward obtaining the required output, with approximately 84% of the data appearing to be correct. </p>
<p>It's worth noting that we can further optimize this model by leveraging a larger dataset and fine-tuning the hyper-parameters. However, for a foundational understanding, what we've accomplished so far is quite impressive.</p>
<p>Given that this dataset and the corresponding machine learning models are at a very basic level, it's important to acknowledge that real-world scenarios often involve much more complex datasets and machine learning tasks. </p>
<p>While this model may perform adequately for simple problems, it may not be suitable for tackling more intricate challenges.</p>
<p>In real-world applications, datasets can be vast and diverse, containing a multitude of features, intricate relationships, and hidden patterns. Consequently, addressing such complexities often demands a more sophisticated approach.</p>
<p>Here are some key factors to consider when working with complex datasets.</p>
<ol>
<li>Complex Data Preprocessing</li>
<li>Advanced Data Encoding</li>
<li>Understanding Data Correlation</li>
<li>Multiple Neural Network Layers</li>
<li>Feature Engineering</li>
<li>Regularization</li>
</ol>
<p>If you're already familiar with building a basic neural network, I highly recommend delving into these concepts to excel in the world of Machine Learning.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we embarked on a journey into the fascinating world of machine learning, starting with the basics. </p>
<p>We explored the fundamentals of binary classification—a fundamental machine learning task. From understanding the problem to building a simple model, we've gained insights into the foundational concepts that underpin this powerful field.</p>
<p>So, whether you're just starting or already well along the path, keep exploring, experimenting, and pushing the boundaries of what's possible with machine learning. I'll see you in another exciting article!</p>
<p>If you wish to learn more about artificial intelligence / machine learning / deep learning, subscribe to my article by visiting my <a target="_blank" href="https://5minslearn.gogosoon.com/?ref=fcc_binary_classification">site</a>, which has a consolidated list of all my articles. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Medical AI Models with TensorFlow – Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ Machine learning is transforming many industries, including healthcare. Artificial intelligence is playing a pivotal role in saving lives and improving patient outcomes. And it is easier than you may think to start applying AI models to medical imagi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/medical-ai-models-with-tensorflow-tutorial/</link>
                <guid isPermaLink="false">66b205bb125aeccef6f65cfb</guid>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Thu, 03 Aug 2023 13:20:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/medicaltf2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Machine learning is transforming many industries, including healthcare. Artificial intelligence is playing a pivotal role in saving lives and improving patient outcomes. And it is easier than you may think to start applying AI models to medical imaging.</p>
<p>We just posted a course on the freeCodeCamp.org YouTube channel that will teach you how to build and evaluate medical AI models with TensorFlow. </p>
<p>Dr. Jason Adleberg teaches this course. He is a radiologist in New York City and a skilled programmer, making him the perfect instructor to guide you through this course.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-13.png" alt="Image" width="600" height="400" loading="lazy">
<em>You will use TensorFlow to evaluate chest x-rays.</em></p>
<p>In this hands-on course, you will learn how to build and evaluate AI models using TensorFlow, one of the most popular and powerful machine learning frameworks. The course is structured into two parts, offering both theoretical knowledge and practical application.</p>
<h3 id="heading-part-1-building-and-training-tensorflow-models">Part 1: Building and Training TensorFlow Models</h3>
<p>This section starts with the basics, guiding you step-by-step to build and train a simple yet effective TensorFlow model. You will learn the fundamental concepts of TensorFlow, gain insights into model architecture, and discover various techniques to optimize model performance. Dr. Adleberg's expertise will help you grasp the essentials of medical AI model development.</p>
<h3 id="heading-part-2-evaluating-medical-ai-models">Part 2: Evaluating Medical AI Models</h3>
<p>Once you have mastered model building, you'll lean how to evaluate. In this part of the course, you'll explore key metrics like AUC (Area Under the Curve), sensitivity, and specificity. These metrics play a vital role in assessing model accuracy and reliability, particularly in clinical settings.</p>
<p>Here are the sections in the course, covering the two parts above.</p>
<ul>
<li>Getting started with Google Colab </li>
<li>Facts about Chest X-Rays </li>
<li>Defining a Problem </li>
<li>Preparing the Data </li>
<li>Training the Model </li>
<li>Running the Model </li>
<li>Evaluating Performance </li>
<li>Stats: Histogram, Sensitivity &amp; Specificity </li>
<li>Stats: AUC Curve </li>
<li>Saving our Model</li>
</ul>
<p>Watch the full course on <a target="_blank" href="https://youtu.be/8m3LvPg8EuI">the freeCodeCamp.org YouTube channel</a> (1-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8m3LvPg8EuI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-course-transcript-autogenerated">Course Transcript (autogenerated)</h3>
<p>Machine learning is being used to save lives in the medical industry.</p>
<p>In this course, you will learn how to build and evaluate AI models with TensorFlow.</p>
<p>This is a great real-world project for improving your machine learning skills.</p>
<p>Dr.</p>
<p>Jason Adelberg teaches this course.</p>
<p>He is a radiologist in New York City and also a programmer.</p>
<p>So let's start learning.</p>
<p>Hey everyone, my name is Jason.</p>
<p>I'm a doctor and computer programmer in New York City.</p>
<p>And today we're going to talk about how to build and evaluate medical AI models with TensorFlow.</p>
<p>This tutorial today will have two parts.</p>
<p>The first part is going to be building and training a really simple TensorFlow model.</p>
<p>And the second part is going to be going through the statistics, the evaluation of our model, and we'll talk about metrics like AUC, sensitivity, specificity.</p>
<p>This stuff will be really useful, especially if we're interested in deploying this in the clinical space.</p>
<p>I wanted to give a big shout out to Dr.</p>
<p>Walter Wiggins for inspiring this tutorial.</p>
<p>Here's his Twitter and here's mine.</p>
<p>And with that, let's get started.</p>
<p>All right, so today we're going to be using Google Colab.</p>
<p>Google Colab is a really cool website through which you can run different parts of Python code.</p>
<p>If you've never used it before, it's relatively easy.</p>
<p>We'll start by clicking connect up here.</p>
<p>And then basically in this tutorial, all these different blocks of code here, these are known as cells, and we can click the play button here to the left of it to get everything up and running.</p>
<p>This first cell will just be us downloading a whole bunch of things, so it's a good one to get started with.</p>
<p>All right, so today we're going to be working with chest x-rays.</p>
<p>And chest x-rays are the most common imaging study performed in hospitals, in emergency departments, in outpatient settings.</p>
<p>It's usually one of the very first things that doctors want to know about if you're not feeling well.</p>
<p>Now, there are a number of things and structures you can see on a chest x-ray, so let's just go over them real quickly.</p>
<p>Here's a normal chest x-ray.</p>
<p>You can see the lungs.</p>
<p>You can see the heart here in the middle.</p>
<p>You can see the aorta coming off of the heart and supplying blood to the rest of the body.</p>
<p>You can see a number of skeletal structures.</p>
<p>So, for example, here's your collarbone or your clavicle.</p>
<p>You can see all the ribs here on both sides.</p>
<p>You can see the vertebra here in the middle.</p>
<p>This line here is called your diaphragm.</p>
<p>It goes around like that.</p>
<p>And this separates your chest, your thorax, from your abdomen.</p>
<p>Underneath this line is your liver.</p>
<p>Your spleen is over here.</p>
<p>And this little kind of air bubble sitting in here, this is your stomach, which in this case just has a little bit of air in it.</p>
<p>And again, this is a normal chest x-ray.</p>
<p>Today, we're going to be using a pretty big data set of chest x-rays called the N-ray.</p>
<p>And this is an open source data set of a few thousand chest x-rays, which happens to have eight different labels.</p>
<p>So, here's the eight different labels available to us in this data set.</p>
<p>And these represent eight pretty commonly seen things on x-rays.</p>
<p>This is not everything that you can see that can go wrong in a chest x-ray, but this is some of the more common things in the world.</p>
<p>And let's just go through them real quickly.</p>
<p>Here we have atelectasis.</p>
<p>This is when a little piece of the lung kind of deflates a little bit.</p>
<p>So, that is up here.</p>
<p>Basically, this wedge-shaped thing up here in the right upper lobe.</p>
<p>Here we have cardiomegaly.</p>
<p>Cardiomegaly is when you have a really big heart.</p>
<p>Specifically, it's when like this length of the heart is more than 50% the length of rib-to-rib.</p>
<p>And this is a sign of heart disease.</p>
<p>Here we have a pleural effusion.</p>
<p>That's when you have something that's basically sitting right outside the lung in what's called the pleural space, which is not really supposed to be full of anything.</p>
<p>This one here, this is an infiltrate.</p>
<p>And that's when you have something sitting inside the alveoli of the lungs.</p>
<p>It's not supposed to be there.</p>
<p>There's a few different things that can do that, but most of the time this means that you have a pneumonia.</p>
<p>In this x-ray, we have a mass.</p>
<p>It's this rounded density up here in the left upper lobe apex or on top of the lung.</p>
<p>A mass is something that's more than three centimeters in diameter.</p>
<p>And with the mass, you know, again, it depends on the context, but generally we're sort of worried here about some sort of tumor.</p>
<p>This is a nodule, and a nodule is a mass that's smaller than three centimeters.</p>
<p>So this is a little bit harder to see.</p>
<p>Here's pneumonia.</p>
<p>A pneumonia is an infection inside of your alveoli.</p>
<p>Again, this is not like mutually exclusive with infiltrate.</p>
<p>And then finally, last but not least, this is a pneumothorax.</p>
<p>And you know how in this one we said you can have sometimes some fluid sitting in the plural space.</p>
<p>Well, here you have air in the plural space.</p>
<p>And this is also known as a collapsed lung.</p>
<p>I bring all this up because some of these conditions are a little bit easier to see and some are a little bit harder to see.</p>
<p>For example, you can bet that you can have some of these conditions For example, you can bet that a mass, which again is more than three centimeters, you can bet that that will be easier for us to see than a nodule.</p>
<p>And so it should be easier for a computer to see this than to see this, to see a nodule.</p>
<p>You know, basically how good our model is is going to depend partly on the technology that we're using, but partly on the data itself, generally speaking.</p>
<p>You know, if you have more data, that's better.</p>
<p>If you have a higher diversity of data, like different types of nodules, et cetera, the model will work a little bit better.</p>
<p>But the quality of the labels really matters as well.</p>
<p>So now that we've looked at the eight different findings, the e-label is available to us in our data set, let's choose one for the AI model.</p>
<p>So I'm going to choose cardiomegaly.</p>
<p>And let's take a look at the data to actually see kind of a little bit more about the different images that we have.</p>
<p>So I'm going to click here on the folder button and click here on the medical AI folder and here on the images.</p>
<p>And here's just a random one we'll open up.</p>
<p>You can see that this is an example of a chest x-ray up here.</p>
<p>Also in the data that we downloaded, so there's all the images there.</p>
<p>And then here is a giant spreadsheet of all of the images that we have available to us with all the labels on them.</p>
<p>So for example, here are, you know, 100 or so images with the labels right there in that column.</p>
<p>I'm going to grab the path for that file.</p>
<p>And then put that in here.</p>
<p>And then here's just another way that we can make sure that the python that our google collab can see everything.</p>
<p>This is showing just the first five rows which happen to be atelectasis.</p>
<p>Okay, next I'm going to look for the rows of this column where the label equals our finding.</p>
<p>And then we'll do the same thing for where the finding is no finding at all.</p>
<p>These are going to serve as negatives to us.</p>
<p>We want to make sure that we have enough images to train a model with here.</p>
<p>So for this line here, I'm just going to go ahead and make sure that we have enough examples of positive cases.</p>
<p>So this is showing us that we have 146 examples of cardiomegaly that we can use today.</p>
<p>That's pretty good.</p>
<p>Now one concept for building AI models is that you want to separate the data into a training set and a testing set.</p>
<p>Usually you do about 80% for training and 20% for testing.</p>
<p>What does that mean? So, you know, the AI model is going to get taught, is going to learn what's what from our training data set.</p>
<p>But in order to tell if it's working or not, we want to show it images that's never seen before.</p>
<p>And that's going to be our testing data set, which is the other 20% of all those images.</p>
<p>So I'm just going to manually define that right now, just like this.</p>
<p>And then I'm going to go ahead and spell out exactly the number of images that we're going to use for our training data set.</p>
<p>So I'm just going to say that that number is 80% of what we have to work with today.</p>
<p>And the same thing for our test data set.</p>
<p>Let's print those out just to make sure that they make sense.</p>
<p>And you can see that we're going to go, and as you can see, we'll use 116 positive cases for our training data set and 29 positive cases for our testing data set.</p>
<p>Here, you can see we have quite a lot, we have a lot of negative examples.</p>
<p>So our limiting factor today is going to be the number of positive cases.</p>
<p>For this example, today, we're going to do a 50-50 split where we want to have an equal number of positive and negative cases for our training and for our testing.</p>
<p>So we're just going to spell that out right here.</p>
<p>Right here, I'm just going to put together the rows that are going to go in our training data set.</p>
<p>That will look like this.</p>
<p>So right here, I'm just going to put together the rows that are going to go in our training data set.</p>
<p>And the same thing for our testing data set.</p>
<p>And the same thing for our testing data set.</p>
<p>Cool.</p>
<p>Okay, great.</p>
<p>All right, so now that we know how many images we have to work with, now we'll just move them to different folders.</p>
<p>And we'll see a few examples of the images with Python to make sure we're ready to go.</p>
<p>So now we're just going to make some directories.</p>
<p>Here is our root directory with all the images in it.</p>
<p>And then this is how I'm just choosing to make some new directories.</p>
<p>So we'll make one like this for our finding.</p>
<p>We'll make one for our test data set.</p>
<p>We'll make one for our train data set.</p>
<p>And then we're going to do the same thing, but just make negative folders instead of the positive folders too.</p>
<p>And negative just means that there's no finding at all.</p>
<p>Like that.</p>
<p>Now we're going to go ahead and just move those files over.</p>
<p>And we're going to do this basically by iterating through like the rows in our data frame that we care about.</p>
<p>So we pay a little bit of attention to exactly how many images we have to move over.</p>
<p>But here's where, for example, the training positive examples happen to be located.</p>
<p>They are like this, as it's defined in our CSV file.</p>
<p>Here's where we're going to move it to.</p>
<p>And this is, again, the way that we defined it in the code block above.</p>
<p>And then this line here, this actually does the moving.</p>
<p>We'll try it real quick just to make sure it works.</p>
<p>If it does, we can double check by clicking here.</p>
<p>We're going into images.</p>
<p>Waiting a minute.</p>
<p>Going to cardiomegaly.</p>
<p>And you can see that now we've made some test folders, some train folders, and this should be a whole bunch of the images here, right? Now I'm just going to copy and paste this.</p>
<p>And instead of doing the positives in our training data set, I'm going to do the positives in our testing data set.</p>
<p>Because our training data set is 80% of all of this, this is more or less like the 80th percent row of all of the positive things that we have.</p>
<p>And then again, we're going to move this to the testing part.</p>
<p>Just going to tweak that right there.</p>
<p>And then we're going to do the same thing for our negatives.</p>
<p>So now I'm just going to again copy and paste those lines.</p>
<p>I'm just going to change positives to negatives.</p>
<p>Positive to negative.</p>
<p>Here and here.</p>
<p>Done.</p>
<p>I'll go ahead and just copy this here.</p>
<p>Cool.</p>
<p>Now that we've moved everything over, let's just use Python to show everything directly in this notebook, just to make sure that what we're doing makes sense and is appropriate.</p>
<p>So I'm going to define two arrays.</p>
<p>And then this is something that we declared in the first blocker code when we started today.</p>
<p>But let's just like, for emphasis, describe that.</p>
<p>Right here, we're just going to show like smaller versions of the pictures that we're loading up.</p>
<p>And then we'll just show like six examples.</p>
<p>And this is the way that we're going to load it.</p>
<p>And this is the way that we're going to load it into Python itself.</p>
<p>image dot open image path dot resize image width image height image height like that positive images append.</p>
<p>And this is basically like a helper function that we declared up at the very top again.</p>
<p>Image just like that.</p>
<p>And I'll be sure that I spelled it correctly.</p>
<p>Just going to do the same thing again for the negative images.</p>
<p>So again, those are the images that have no findings at all.</p>
<p>Like that.</p>
<p>Now that we've actually loaded everything, we'll go ahead and actually just like show everything with matplotlib.</p>
<p>And so we're going to go ahead and show just six images.</p>
<p>So these will be our six images that have cardiomegaly.</p>
<p>That will go there.</p>
<p>And then we're gonna do the same thing.</p>
<p>I'm copy and pasting this for negative images.</p>
<p>So I'm just going to tweak that.</p>
<p>I'm going to tweak this.</p>
<p>And we're not using, again, like the whole point with the negative images is to show ones that have no finding at all.</p>
<p>So let's go ahead and click play.</p>
<p>Here you can see that it's showing us six examples of cardiomegaly from like the folder that it's created.</p>
<p>And to me, these all look like definite cases of cardiomegaly.</p>
<p>You can see that the heart here is for sure it's enlarged.</p>
<p>It's more than half of the chest.</p>
<p>And here these look like cases with no findings.</p>
<p>So here the heart is normal size and there's not really much else going on as well.</p>
<p>Okay, so now we have visualized our data.</p>
<p>We've moved everything around and we know that we want to build an AI model for cardiomegaly.</p>
<p>In this part, we're going to actually build the TensorFlow model.</p>
<p>Now there are lots of different ways to approach model building and we can spend an hour on this topic alone.</p>
<p>But basically here, I want to talk about two different concepts for this part.</p>
<p>So the first is called transfer learning.</p>
<p>And the second concept is called data augmentation.</p>
<p>We're going to use both of those things today.</p>
<p>All right, so this first line here, this is going to have us load our model directly through TensorFlow itself.</p>
<p>And we're just going to define the size of the image that it's going to be working with, which we kind of talked about earlier, but these are going to be kind of smaller, basically scaled down versions of our chest x-ray.</p>
<p>This three here is saying that basically it's a three channel image, so like a color image, right, like red, green, and blue.</p>
<p>Now it's true that, you know, our chest x-rays are actually just all shades of gray, but we're just going to put that in there because it's a little bit easier.</p>
<p>And then this one here, include top equals false.</p>
<p>We'll come back to this, but this is basically going to let us customize our model to do what we want to do here.</p>
<p>This should be weights plural.</p>
<p>And now we're using again the ImageNet network here.</p>
<p>But what we're basically going to do is, on top of all this, for the last layer of our model, we're going to have it spit out whether it thinks there's cardiomegaly or not.</p>
<p>So we're going to just manually define that here.</p>
<p>This is basically talking about exactly what type of output we want our model to put out.</p>
<p>So this is just getting that last layer, and here we're going to go ahead and define this by saying that we want to say either basically yes or no, positive or negative.</p>
<p>So this is the way that we can do that.</p>
<p>This is just basically some stuff to, again, help us with our big task, which is saying yes or no, cardiomegaly or not cardiomegaly.</p>
<p>I'm going to say yes or no, and then I'm going to say yes or no.</p>
<p>So this is just basically some stuff to, again, help us with our big task, which is saying yes or no, cardiomegaly or not cardiomegaly.</p>
<p>All these decisions here, we could talk about this for such a long time, but I'm going to skip over exactly some of the specifics here.</p>
<p>And if there's something to put an x in there, right.</p>
<p>Okay, as for the model, so now we have this model with a slightly customized last layer.</p>
<p>And now we're just going to basically go ahead and compile it.</p>
<p>Here we're just going to say that we're interested in the accuracy, basically, so how accurate is our model in between, saying whether something is positive or negative, and that's sort of the metric that we're going to use to help us figure out if our model is working or not.</p>
<p>Oh, and then one other thing is that we should put an equal sign right in there, and that would help us as well.</p>
<p>Okay, so now that this is all done, now we're going to go ahead and just define a bunch of things that are basically just kind of helping point our model to the right information.</p>
<p>So if you remember from earlier, all of our images are hiding out right there.</p>
<p>The directory where everything is located for the imaging for the training stuff is like this.</p>
<p>For testing, it's just about the same, but like this, change this here.</p>
<p>And then this kind of keeps going.</p>
<p>So the way we have our data structured is that we have like sub-folders in our training directory that are called positive, one called negative, which we're going to put in right here.</p>
<p>That looks like this.</p>
<p>Like this.</p>
<p>And then the same thing also exists just for our test data.</p>
<p>So I'm going to make these changes here, here, here, and there.</p>
<p>I'll click play right there.</p>
<p>Okay, so now the next concept I want to talk about is something called data augmentation.</p>
<p>So as we discussed earlier, we have a bunch of images available to us with cardiomegaly, but it's not like a ton.</p>
<p>There are some ways that we can basically kind of cleverly create more training data for ourselves, and that's called data augmentation.</p>
<p>So what we're going to use here is basically a really cool concept called an image data generator.</p>
<p>And this is basically something that's going to look at all the images that we have and kind of tweak them a little bit so that we're kind of generating like more data from the data we already have.</p>
<p>Now there's a lot of different ways that you can augment data, that you can kind of tweak data around, but these are the ones we'll just happen to use today.</p>
<p>And, you know, if you're playing around with this sort of on your own, you're welcome to, you know, kind of experiment with different ideas here.</p>
<p>So what are we doing? So first of all, we're just kind of, all these methods here basically are generating extra images that are slightly tweaked from our images.</p>
<p>So specifically, this is going to generate images that are slightly rotated one way or the other, that are slightly shifted, like stretched out, that are sheared, and that are zoomed in as well.</p>
<p>One thing that's important with data augmentation is that it's not just going to be zoomed in.</p>
<p>One thing that's important with augmentation for medical data is that, you know, there's kind of some different thoughts on this, but when it comes to flipping images, you know, a chest x-ray is never really going to be flipped around, right? Like, you know, your heart is always going to be like, you know, you're, you know, when you take a chest x-ray, like, right side up, right? Like your stomach's always going to be below your lungs.</p>
<p>So if we were to flip the data upside down, that wouldn't necessarily really be helpful for our AI model.</p>
<p>In regard to horizontal flipping, you know, I think there's not really like a consensus on this when it comes to medical imaging or specifically chest x-rays.</p>
<p>It's true that our bodies are not completely symmetrical, even though we like to pretend there are, so your heart's a little bit more on your left side.</p>
<p>There is a condition where your heart can be more on the right side, but it's not super common.</p>
<p>So I'm just going to say that we're not going to flip things horizontally so that we don't kind of confuse our model, but that's a choice that you could make if you wanted to.</p>
<p>For our test data, we definitely don't want to augment, don't want to mess with our test data at all.</p>
<p>So this is just a line where, you know, we are creating an image generator, but all that we're doing here is just like redefining the numbers that are inside of our, of each pixel, basically.</p>
<p>So this is, it's not really actually doing anything, right? This is basically saying that instead of each pixel going from like zero to 255, it's going to be between zero and one.</p>
<p>All right, let's go ahead and click there.</p>
<p>That works.</p>
<p>So that's image augmentation.</p>
<p>And now this here is something that we need to use in order to get our model to train, called a train and test generator.</p>
<p>And this is basically the way that we do it here.</p>
<p>So from directory, which we already have, target size and then we're just going to do the same thing for testing right below.</p>
<p>And then, you know, of course, we just need to kind of tweak some of these things here for this particular part.</p>
<p>We'll go ahead and just define the number of steps that we're going to use for this, which is basically because we have a batch size of one.</p>
<p>It's happens to be the same, happens to be just like all the images that we're using.</p>
<p>So, I mean, this is one way of doing it, like the way that our data is structured.</p>
<p>Like the way that our data is structured.</p>
<p>So again, train steps equals the length of that folder times two.</p>
<p>And then for testing, we're going to go ahead and say that it's like this.</p>
<p>And then we actually typed this in wrong here.</p>
<p>So let's go ahead and just fix this real quick.</p>
<p>That goes like that.</p>
<p>And then this goes like this.</p>
<p>And you can see here that when we click, so it's found 232 images for the training part and 60 images for the testing part.</p>
<p>And again, that is pretty close to 80% and 20% split.</p>
<p>All right, so we have everything set up.</p>
<p>We have our model ready to go.</p>
<p>We have our data ready to go.</p>
<p>This is the cool part.</p>
<p>Now we're finally going to run our model and let it train.</p>
<p>So in order to do that, this is the method that we're going to use.</p>
<p>We're going to use what's called model.fit.</p>
<p>We're going to point it to the train generator that we talked about earlier.</p>
<p>We're just going to mention exactly the number of steps per epoch.</p>
<p>And epoch is basically one scan through all the data.</p>
<p>So in this particular example, we're just going to ask it to look at all the pictures 20 times in order to do the training.</p>
<p>And then we're also pointing it to the validation set.</p>
<p>That's our test set, the 20% that we sectioned off that it has not seen before.</p>
<p>And when we click play, you can see that you can see that I spelled epochs wrong.</p>
<p>And then finally, it's going to actually start to do its thing.</p>
<p>Now, the way that we formatted it for this tutorial today, it shouldn't really take too long to go through all the data.</p>
<p>But this will take about a few minutes or so.</p>
<p>So we're just going to click play and then basically step back.</p>
<p>We'll come back in a few minutes.</p>
<p>All right, so we're back.</p>
<p>It's been three minutes of training, which is really not that much time at all.</p>
<p>But that's OK.</p>
<p>That's enough for us to understand some of the concepts that we're working with today.</p>
<p>So now what we're going to do is we're going to see exactly how good of a job it did over time.</p>
<p>So basically, we're just going to plot how the accuracy changed.</p>
<p>And this is basically the accuracy for the training set, which should go up over time.</p>
<p>And then this is the accuracy for the validation set, the testing data set, which is basically the accuracy for the , you know, it hasn't seen before.</p>
<p>So we hope that this goes up.</p>
<p>But, you know, this is why we had to keep it separate, because this will actually show us like if it's doing a good job or not.</p>
<p>I do the same thing for loss.</p>
<p>And basically, loss is sort of another kind of abstract way of thinking about how good a job it's doing.</p>
<p>So loss is basically, you know, you want your accuracy to be going up over time, and you want your loss to be going down over time.</p>
<p>And loss is basically sort of a mathematical way of talking about, you know, the way that the network should look and the way that the network does look as it currently is.</p>
<p>So I'm just going to plot using matplotlib, some different stuff related to the loss and related to the accuracy as it changes over time.</p>
<p>We'll do the same thing here, but for the validation data set.</p>
<p>And again, this is going to be the training and test accuracy as it changes over time.</p>
<p>I'll just put this in here like this.</p>
<p>Let's click play.</p>
<p>And this is actually pretty encouraging.</p>
<p>So, you know, as this thing ran for a few minutes, only after a few minutes, it started to figure out what was what, what was cartomegaly and what wasn't.</p>
<p>So the training data set, we expect that to go up.</p>
<p>We expect that to get more accurate over time.</p>
<p>But the testing data set we hope gets more accurate.</p>
<p>And as you can see, it did.</p>
<p>So when it first started, it had like a 50-50 chance.</p>
<p>But after just a few minutes of training, it got to be roughly 70% or so accurate.</p>
<p>And, you know, that's better than flipping a coin.</p>
<p>I'm also going to go ahead and just do the same thing for loss, which again, that's another way of thinking about how good a job our model is doing.</p>
<p>And so instead of accuracy, we're just going to plot loss.</p>
<p>And I'm just going to like change this here so that we have a slightly better idea of what's going on.</p>
<p>So here's our loss.</p>
<p>And as you can see, this goes down quite a lot over time.</p>
<p>We could still, you know, we could zoom in on this to see a little bit more, but that's kind of the basic idea here.</p>
<p>All right, so now that we've trained a model, let's see how well it does.</p>
<p>And this section will basically have two parts.</p>
<p>So first, we'll just play around with a few images to see like what the model thinks.</p>
<p>And then we'll systematically look through all of the images with statistics, thinking about things like sensitivity, specificity, and AUC, or area under the curve.</p>
<p>You know, I think that kind of what distinguishes applications of AI in medicine is attention to all these details, because I think that, you know, these metrics are really important when it comes to thinking about whether, you know, this is really something that's going to ultimately help people.</p>
<p>All right, so let's start off with just like two different helper methods.</p>
<p>This first one here is just going to be a little helper method to load up an image like this.</p>
<p>We're going to resize it to fit the size that our model requires, which looks like that.</p>
<p>And we have to do an actual parentheses here.</p>
<p>From here, it's going to load it into a numpy array.</p>
<p>This is something we have to use just again to convert it from like zero to 255.</p>
<p>That is each pixel is going to go from a value between zero to 255 to zero and one.</p>
<p>This is just making sure that the array has three different values for like red, green, and blue.</p>
<p>Even though it's true, we aren't really using that, because x-rays are like usually all hopefully all in gray.</p>
<p>Okay, and then this line here.</p>
<p>This is what's going to return.</p>
<p>So this line model.predict.</p>
<p>This is how we're going to interact with our model to actually return a value between zero and one, where zero means that the model thinks there's no finding, and one means it thinks there is a finding, which here is cardiomegaly.</p>
<p>We're going to do another helper method here, and this is sort of like a sanity check for us.</p>
<p>So what this is ultimately going to do is this is going to show us an image.</p>
<p>It's going to show us like the actual file path that's associated with it.</p>
<p>Let's go ahead and load this up here.</p>
<p>And then, because our model returns us a value between zero and one, what we're going to do is we're going to define some cutoff point, which here I'm going to say is 0.5, where if the prediction is above 0.5, then the model's going to think that it's positive, right? So in this case, the model's going to think that it has cardiomegaly.</p>
<p>And this will make a little bit more sense in a minute once we actually like use this method, but this is just basically showing us all of the different information about the image as we're doing the prediction on it.</p>
<p>So this is the way that I'm going to just access all of that information.</p>
<p>Guess, plus, score, okay.</p>
<p>And then once we're down here, this will basically just use matplotlib to go ahead and get all of that up and running.</p>
<p>Let's go ahead and click play there.</p>
<p>Let's make sure that we added all of the plus signs.</p>
<p>And again, you know, one thing that's really important is that we want to be systematic in the way that we evaluate all of our data.</p>
<p>So what we're going to do here is we're going to iterate through all of the pictures, all the images in our test set, and basically try to just systematically, like in an organized way, figure out what I thought about everything.</p>
<p>This is going to be really important when it comes to getting things like sensitivity and specificity, which I'll come back to in one second.</p>
<p>But basically what we're going to do here is we're going to go through all of the negative images, so all the images in which there is no finding.</p>
<p>It was labeled, that is, as no finding.</p>
<p>And we're just going to do predictions on every single one of them.</p>
<p>So we have this array called results array.</p>
<p>And basically what we're going to do is we're just going to create this kind of like results array with all of the information that we care about.</p>
<p>So each row in the results array is going to be the file name, like the image itself, whether or not it had a label of being positive or negative.</p>
<p>These are all the negative images here, so it's going to have a negative label.</p>
<p>The guess, so what it happened to think.</p>
<p>And then the confidence, which again is that number between 0 and 1, where we're using like a 0.5 cutoff for positive versus negative, or cardiomegaly versus not cardiomegaly.</p>
<p>That first part was looking at all the negative images.</p>
<p>And now we're going to do the same thing with all the positive images.</p>
<p>I'm just going to change this down here, because again, these are like positive labels.</p>
<p>So at this point, we'll have some array with a whole bunch of stuff in it, with a whole bunch of predictions for all of the positive and negative test images.</p>
<p>What I'm going to do here is I'm just going to sort this array on basically that last column, which is like the confidence column.</p>
<p>So basically it's going to show us in order what it really thought was cardiomegaly, and then it's going to show us what it really thought was not cardiomegaly, what was no finding at all.</p>
<p>We're going to create a data frame from all these results here.</p>
<p>And then so that we can be kind of organized, we are going to create an actual list of column names too, that would be helpful.</p>
<p>File path, file name, label, guess, confidence.</p>
<p>And then once we click this here, it's going to go through and basically just make a guess on all the different images in our test set.</p>
<p>Okay, let's scroll.</p>
<p>Again, this array that we created, or this data frame that we created, let's just take a sneak peek to make sure that this makes sense.</p>
<p>Cool.</p>
<p>And here's the first five rows, right? So here's just five images in our data set where these are the five images that our model thought had the most cardiomegaly.</p>
<p>All right, so that helper method that we did earlier, where it was like a sanity check to see if our model was actually working, let's go ahead and actually make a call to that.</p>
<p>So first, we're just going to grab a random number, like from the test set.</p>
<p>And then we're going to grab a random row from our data frame, which is like all the predictions on the test set.</p>
<p>And this is that helper method that we used earlier, right? So here's a random picture.</p>
<p>You can see that it was labeled as having cardiomegaly, and the model guessed there was cardiomegaly.</p>
<p>Here's an example where this was labeled as not having cardiomegaly.</p>
<p>I agree, I think that's a normal heart.</p>
<p>And our model also thought there was no cardiomegaly.</p>
<p>Here's an example where it was labeled as having cardiomegaly, and our model got it wrong.</p>
<p>Here's an example where the model said that there was cardiomegaly, and it was labeled also as cardiomegaly.</p>
<p>And just like checking it out, I think that's a pretty big heart, so I have to agree with that.</p>
<p>We can click this button a whole bunch of different times to see whether or not it was accurate or not.</p>
<p>We can also use some numbers, like again, sensitivity and specificity, AUC, to help us also get a better feel for if it's doing a good job or not.</p>
<p>So we'll get to that in one second, but let's just go ahead and show the entire data frame right now.</p>
<p>Or rather, let's show every fifth row in the data frame, just to get another feel for what it had.</p>
<p>So this is going to show the name of the file, whether or not it was labeled as positive or negative, whether or not it was labeled as positive or negative, and basically the confidence that it had.</p>
<p>So just looking at this really quick kind of overview, it looks like it did a pretty decent job, but some of the ones here in the middle I wasn't so sure about.</p>
<p>So in other words, you know, when it was really confident that there was cardiomegaly, it got it right.</p>
<p>When it was really confident that there was not cardiomegaly, it got it right.</p>
<p>But some of these ones in the middle, it kind of was a little bit iffy.</p>
<p>So now I want to show the same information in a histogram format, and this is good because this is going to kind of start to get us to think about some of those statistics that we mentioned earlier.</p>
<p>So this is the way that I'm going to build the histogram.</p>
<p>I'm going to grab the same thing here for the negative labels.</p>
<p>And then this is going to use the map plot lib histogram function.</p>
<p>That was kind of a mouthful there, but just some more stuff setting up this histogram chart.</p>
<p>X-axis, title, confidence, scores for different images.</p>
<p>And make a legend.</p>
<p>Okay.</p>
<p>Plot.show.</p>
<p>And here you can start to see exactly how good of a job it did.</p>
<p>We'll go ahead and just scoot this legend a little bit out of the way.</p>
<p>And this is a little bit better, right? So you can see that when the model was pretty confident, it got it right on both sides.</p>
<p>So every example close to a one, it got it right.</p>
<p>Every example close to a zero, it got it right.</p>
<p>But in the middle, it was kind of iffy.</p>
<p>Overall, this is actually pretty decent, though, in my opinion.</p>
<p>So now let's go ahead and look at a confidence score.</p>
<p>So now let's think about, you know, whether...</p>
<p>So earlier we had mentioned that, you know, again, the model was returning a value between zero and one.</p>
<p>And we were using like 50 or 0.5 as the cutoff.</p>
<p>So if it was above 0.5, we would say that it was positive, that the model thought that there was card immediately.</p>
<p>And if the model returned a number between zero and 0.5, we would think that it had no finding.</p>
<p>Let's see if maybe that was the best number for it to use.</p>
<p>So here we're going to create a helper function.</p>
<p>Called createWithCutoff that basically is going to kind of just redraw our histogram, but now we're going to talk about false negatives, false positives, true negatives, and true positives.</p>
<p>So this line here, this is saying, let's find everything where it was labeled as positive.</p>
<p>And the model thought that it was positive, or it thought that the confidence value was more than that.</p>
<p>This is going to give us an array of like exactly all of the confidence values that are above our cutoff.</p>
<p>Let's do the same thing with false positive, true negative, and false negative.</p>
<p>So for false positive, that means that the real label was actually negative, but we thought it was positive.</p>
<p>For true negative, that means that the real label was negative, and our model said that it was lower than the cutoff.</p>
<p>And I'm going to go ahead and just fix this right here before I forget.</p>
<p>And then again for false negatives, finally, that's going to mean that, you know, this was labeled as positive, but the model accidentally thought it was less than our cutoff value.</p>
<p>Here we're just going to make another histogram, but we're just going to kind of tweak it a little bit.</p>
<p>So now instead of having two different colors, we're going to have four different colors, one for each of those four categories we talked about.</p>
<p>It's going to be pretty similar otherwise.</p>
<p>And then all this stuff here is going to be basically just the same as it was last time.</p>
<p>So I won't go through basically all this again.</p>
<p>Just going to type another title in, so confidence scores for different images.</p>
<p>This line here, this is going to draw like a vertical line that helps us kind of differentiate where that cutoff value is, and I'll come back to that in a second as to why we care about that.</p>
<p>We're going to put this in the upper right.</p>
<p>All right, and now this part here is pretty important.</p>
<p>So now we're going to calculate the sensitivity.</p>
<p>So sensitivity basically is something that we use a mess and a lot to see if we should roll something in.</p>
<p>So like a screening test, generally, you want to have high sensitivity for that.</p>
<p>And the formula for sensitivity is true positives over true positives plus false negatives.</p>
<p>So another way of saying this is that something that's really sensitive has a low number of false negatives.</p>
<p>It might have a lot of false positives, so it might just think that like everything is positive, but at least we're avoiding false negatives that way.</p>
<p>And then, you know, the general scheme of things is that once we have a confirmatory test, then we want high specificity.</p>
<p>So for that, it's kind of the other way around where we want there to be basically a low false positive rate.</p>
<p>So, you know, something that's like an example of this, like if you remember, you know, in 2020, when we wanted to know more about whether someone had COVID, you could use like the screening test.</p>
<p>Sometimes that would be like the self swab test or a spit test.</p>
<p>I guess that was a thing.</p>
<p>But ultimately, the PCR test was the most specific.</p>
<p>So that was like the more confirmatory test.</p>
<p>A lot of the screening tests would have high false positives, but the PCR test, that was like a lot more accurate.</p>
<p>But the PCR test was like a little bit more specific.</p>
<p>Here, I'm just going to actually like spell it out on the thing itself.</p>
<p>All right.</p>
<p>And here, we're going to go ahead and basically say that we want a cutoff of 0.5.</p>
<p>So let's try this out.</p>
<p>Okay.</p>
<p>And as you can see, now that we've defined a cutoff of 0.5, now we can start to think about true positives, false positives, true negatives and false negatives.</p>
<p>So here you can see that if we use a confidence level of 0.5, we have a relatively low rate of false positives, but higher amount of false negatives.</p>
<p>Let's see about if we change this value to be something like that.</p>
<p>How does that change our sensitivity and specificity? Well, if we lower that, then we have higher sensitivity, but we have worse specificity.</p>
<p>And basically, the big picture here is that a lot of tests in medicine kind of struggle with this.</p>
<p>Like, you know, how do we define a cutoff value for whether or not someone has a disease? For example, if you have diabetes, you can get a test called an A1C that basically looks at the amount of sugar in your blood over time.</p>
<p>And, you know, what should the cutoff be for someone who has diabetes versus someone who doesn't have diabetes? Now, the answer to that is 6.5.</p>
<p>And a lot of testing went in to figure out what's the best value for that particular test.</p>
<p>But here we're kind of thinking about a similar thing.</p>
<p>I mean, what is the cutoff for whether or not our model thinks you have cardiomegaly or doesn't have cardiomegaly? And the kind of important concept here is that, you know, we just arbitrarily chose 0.5, but that might not actually be the very best value.</p>
<p>And a lot of issues that might not be the very best value.</p>
<p>And, you know, ultimately, if our goal is to build something that can look at a chest x-ray and diagnose a disease, we want to be totally sure that whatever cutoff value it has for saying yes or no, we want to be sure that it's the very, very best cutoff value.</p>
<p>So for this next part, we're going to talk about ROC, or receiver operator curve, which is related to AUC, or area under the curve.</p>
<p>And this concept is basically how we can kind of figure out what is the very best cutoff point for this particular test, for this particular AI model, which again is going to say yes or no.</p>
<p>So let's build a method to create an AUC curve.</p>
<p>And basically what an AUC curve is going to do is it's going to do every single possible cutoff between 0 and 1.</p>
<p>It's going to calculate the sensitivity and specificity for all those possible values and classifications.</p>
<p>And that's going to give us a lot more information through which we can then figure out what's the best cutoff value.</p>
<p>So what we're going to do here is we're going to feed this thing all of the guesses that it made earlier.</p>
<p>So we're going to have it go through each one and basically now create that AUC curve.</p>
<p>So this is basically just going through all of the guesses that it had made.</p>
<p>And we'll take it that way.</p>
<p>Alright, so now we're just going to return basically all of the numbers of true positives, false positives, true negatives, and false negatives.</p>
<p>We're going to manually calculate the sensitivity, which we talked about earlier.</p>
<p>So we'll go ahead and do it this way, like this.</p>
<p>Specificity is going to be like this.</p>
<p>Oops.</p>
<p>Alright, so this is sort of the first step.</p>
<p>And then now that we've created this function, AUC curve, sorted results.</p>
<p>Now basically from here, we're just going to create a line that basically strings together like all of these different sensitivities and specificities for all these different possible cutoff values.</p>
<p>And now that we have all these different values as well, we're going to make sure that we calculate what's called the area under the curve, which basically like numerically represents how good of a model this is.</p>
<p>Or in other words, it's basically how close is our AUC curve to being perfect.</p>
<p>So here's just some code to create a line plot.</p>
<p>Alright, there's the rest of the code there.</p>
<p>And now once we go ahead and run, you can see that our AUC curve is actually pretty good.</p>
<p>It has a pretty high area of 0.923.</p>
<p>One thing that's kind of funky about this curve, about this whole graph, is that you notice the x-axis here is kind of like backwards, like one minus specificity.</p>
<p>The reason for that is basically, you know, as sensitivity goes up, as a test becomes more sensitive, it gets less specific.</p>
<p>So as the number of false negatives goes down, the number of false positives is going to go up.</p>
<p>So here, you know, like this point on the curve up here, this test is like super sensitive, which really just means that it doesn't really have that many false negatives.</p>
<p>But you can see there's going to be a lot of false positives, so it's not going to be as specific as it could be.</p>
<p>Overall, this is a pretty good ROC.</p>
<p>And you know, given that we only trained this model for like three minutes, and we only fed it like 100 images instead of like thousands of images, this is pretty encouraging.</p>
<p>You know, if we were to redo this experiment with like a way more powerful model, with like way more images, and with a lot more training time, so three minutes, something like maybe, you know, overnight or whatever.</p>
<p>There's no reason why this ROC curve couldn't get way closer to one.</p>
<p>But again, 0.923 is already like pretty good as it is.</p>
<p>If you want to go ahead and save your model, that's pretty easy to do with the code base that we're using.</p>
<p>You can just do model.save.</p>
<p>We'll save it to the content part.</p>
<p>And we'll just go ahead and put it like this so that you can find it maybe a little bit more easily.</p>
<p>You also might want to zip all this stuff up.</p>
<p>And what's really cool about Colab is that you can do just exactly that by hitting the exclamation point when you start in Colab that allows us to do like shell shell commands.</p>
<p>So if you want to go ahead and try all this here, we'll click play.</p>
<p>And in a minute, you'll see that the model is basically saved to here and zipped up.</p>
<p>I took like two minutes or so for it to zip everything up there but anyway, just click on this icon here.</p>
<p>And then here's our model which is about a gigabyte or so big.</p>
<p>Click on those three dots, download, and then that'll save it to your computer in a minute or so.</p>
<p>Alright, well that just about wraps up this presentation.</p>
<p>If you have any questions, feel free to reach me at that Twitter account above or comment on this video below.</p>
<p>And I hope you enjoyed that and thanks for your attention.</p>
<p>Thanks for your time.  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Implement Computer Vision with Deep Learning and TensorFlow ]]>
                </title>
                <description>
                    <![CDATA[ Computer vision is being used in more and more places. From enhancing security systems to improving healthcare diagnostics, computer vision techniques are revolutionizing multiple industries.  We just published a 37-hour course on the freeCodeCamp.or... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-implement-computer-vision-with-deep-learning-and-tensorflow/</link>
                <guid isPermaLink="false">66b2032525ef0bb2c5a51748</guid>
                
                    <category>
                        <![CDATA[ Computer Vision ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 06 Jun 2023 15:08:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/compvision.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Computer vision is being used in more and more places. From enhancing security systems to improving healthcare diagnostics, computer vision techniques are revolutionizing multiple industries.</p>
<p> We just published a 37-hour course on the freeCodeCamp.org YouTube channel that will teach you about deep learning for computer vision using TensorFlow. The course was expertly created by Folefac Martins from Neuralearn.ai.</p>
<h2 id="heading-a-sneak-peek-into-the-course">A Sneak Peek into the Course</h2>
<p>This course is meticulously designed to cover a broad range of topics, starting from the basics of tensors and variables to the implementation of advanced deep learning models for complex tasks such as human emotion detection and image generation.</p>
<p>After introducing the prerequisites and discussing what learners can expect from the course, the first segment focuses on the foundational aspects of tensors and variables. You'll understand the basics, initialization and casting, indexing, and common TensorFlow functions. The topics extend to cover the intriguing concepts of ragged, sparse, and string tensors, laying the groundwork for building neural networks.</p>
<p>As you venture into the world of neural networks, you'll start by predicting car prices. This practical project involves steps from data preparation to measuring model performance, and it'll provide an understanding of linear regression models, error sanctioning, and training and optimization techniques.</p>
<p>The course then delves into convolutional neural networks (ConvNets), which are particularly useful for image data. You will use ConvNets to diagnose malaria, a task that includes data preparation, visualization, and processing, and learn how to build ConvNets with TensorFlow. Along the way, you'll explore binary cross-entropy loss, model training and evaluation, and saving and loading models on Google Drive.</p>
<p>Advanced topics in TensorFlow, such as custom loss and metrics, eager and graph modes, and custom training loops, are also thoroughly discussed. A significant portion of the course is devoted to improving model performance, evaluating classification models, and using data augmentation techniques to enhance the quality and diversity of data.</p>
<p>The course proceeds to explore modern Convolutional Neural Networks like AlexNet, VGGNet, ResNet, MobileNet, and EfficientNet, applied to a human emotions detection project. Additionally, the course illustrates the black box of these models by visualizing intermediate layers and using the Gradcam method.</p>
<p>There's a great section dedicated to Transformers in Vision, understanding and building Vision Transformers (ViTs) from scratch, and fine-tuning Huggingface ViT. This section includes practical training with the Weights and Biases tool for experiment tracking, hyperparameter tuning, dataset and model versioning, known as MLOps.</p>
<p>Finally, the course closes with important topics in model deployment, including converting TensorFlow models to Onnx format, understanding and implementing quantization, building and deploying an API with FastAPI, and load testing with Locust.</p>
<p>The course concludes with a module on object detection using the YOLO algorithm and image generation using Variational Autoencoders (VAEs) and Generative Adversarial Networks (GANs).</p>
<h2 id="heading-the-learning-experience">The Learning Experience</h2>
<p>What sets this course apart is the combination of theoretical understanding and practical applications. It is a guided journey through the intricacies of TensorFlow, deep learning, and computer vision, using real-world projects such as car price prediction, malaria diagnosis, human emotion detection, and image generation.</p>
<p>The course is perfect for anyone passionate about machine learning and AI, regardless of their current expertise level. So whether you're a complete beginner, a data scientist looking to update your skills, or an AI enthusiast, this course promises a thorough and practical understanding of computer vision and deep learning with TensorFlow.</p>
<p>Watch the full course <a target="_blank" href="https://www.youtube.com/watch?v=IA3WxTTPXqQ">on the freeCodeCamp.org YouTube channel</a> (37-hour course, with subtitles).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/IA3WxTTPXqQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use TensorFlow for Deep Learning – Basics for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ TensorFlow is a library that helps engineers build and train deep learning models. It provides all the tools we need to create neural networks. We can use TensorFlow to train simple to complex neural networks using large sets of data. TensorFlow is u... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/tensorflow-basics/</link>
                <guid isPermaLink="false">66d0362131fbfb6c3390f1f3</guid>
                
                    <category>
                        <![CDATA[ Deep Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ neural networks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tensor ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Tue, 14 Feb 2023 23:46:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/tensorflow.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>TensorFlow is a library that helps engineers build and train deep learning models. It provides all the tools we need to create neural networks.</p>
<p>We can use TensorFlow to train simple to complex neural networks using large sets of data.</p>
<p>TensorFlow is used in a variety of applications, from image and speech recognition to natural language processing and robotics. TensorFlow enables us to quickly and easily build powerful AI models with high accuracy and performance.</p>
<p>TensorFlow also works with GPUs and TPUs, which are types of computer chips built to extend TensorFlow’s capabilities. These chips make TensorFlow run faster, which is helpful when you have a lot of data to work with.</p>
<p>In this article, we will learn about tensors and how to work with tensors using TensorFlow. Let’s dive right in.</p>
<h2 id="heading-what-is-a-tensor">What is a Tensor?</h2>
<p>A simple explanation would be that a tensor is a multi-dimensional array.</p>
<p><img src="https://miro.medium.com/max/1050/1*rLcM-j8b61Xlfk81k_exKw.png" alt="Image" width="600" height="400" loading="lazy">
<em>Scalar, Vector, Matrix and Tensor</em></p>
<p>A scalar is a single number. A vector is an array of numbers. A matrix is a 2-dimensional array. A tensor is an n-dimensional array.</p>
<p>In TensorFlow, everything can be considered a tensor including a scalar. A scalar would be a tensor of dimension 0, a vector of dimension 1, and a matrix of dimension 2.</p>
<p>Now, this is useful because we are not limited to working with complex datasets in TensorFlow. TensorFlow can handle any type of data and feed it to machine learning models.</p>
<h2 id="heading-what-is-tensorflow">What is TensorFlow?</h2>
<p>TensorFlow is an open-source software library for building neural networks. Google Brain team was the one who built it and it is the most popular deep learning library in the market today.</p>
<p>You can use TensorFlow to build AI models including image and speech recognition, natural language processing, and predictive modeling.</p>
<p><img src="https://miro.medium.com/max/1050/1*mPUeOmKYoWvPcZFjMdsiUQ.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Classification neural network</em></p>
<p>TensorFlow uses a dataflow graph to represent computations. To put it simply, TensorFlow has made it easy to build complex machine learning models.</p>
<p>TensorFlow takes care of a lot of work behind the scenes which makes it useful while building and training any type of machine learning model. TensorFlow also manages the computation, including parallelization and optimization, on the user’s behalf.</p>
<h2 id="heading-tensorflow-and-keras">TensorFlow and Keras</h2>
<p><img src="https://miro.medium.com/max/1050/1*X7QA_c8KHk7nD0tywv-OVg.png" alt="Image" width="600" height="400" loading="lazy">
<em>Tensorflow and Keras</em></p>
<p>TensorFlow has a high-level API called Keras. Keras was a standalone project which is now available within the TensorFlow library. Keras makes it easy to define and train models while TensorFlow provides more control over the computation.</p>
<p>TensorFlow supports a wide range of hardware, including CPUs, GPUs, and TPUs. TPUs are Tensor processing Unites, built specifically to work with Tensors and TensorFlow.</p>
<p>We can also run TensorFlow on mobile devices and IoT devices using TensorFlow Lite. TensorFlow also has a large community of developers, and it is updated with new features and capabilities.</p>
<h2 id="heading-how-to-build-tensors-with-tensorflow">How to Build Tensors with TensorFlow</h2>
<p>Let’s start writing some code. If you don't have TensorFlow installed, you can use a <a target="_blank" href="https://colab.research.google.com/">Google colab notebook</a> to follow along.</p>
<p>Let’s start by importing TensorFlow and printing out the version.</p>
<pre><code><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
print(tf.__version__)
</code></pre><pre><code>OUTPUT:
<span class="hljs-number">2.9</span><span class="hljs-number">.2</span>
</code></pre><p>Let’s first create a scalar using tf.constant. We use tf.constant to create a new constant value. We can also use tf.variable to create a variable value. We will then print the value and also check the dimension of the scalar using the ndim property. Its dimension will be zero because it is a single value.</p>
<pre><code>scalar = tf.constant(<span class="hljs-number">7</span>)
print(scalar)
print(scalar.ndim)
</code></pre><pre><code>OUTPUT:
tf.Tensor(<span class="hljs-number">7</span>, shape=(), dtype=int32)
<span class="hljs-number">0</span>
</code></pre><p>Now let’s create a vector and print its dimensions. You can see that the dimension is 1.</p>
<pre><code>vector = tf.constant([<span class="hljs-number">10</span>,<span class="hljs-number">10</span>])
print(vector)
print(vector.ndim)
</code></pre><pre><code>OUTPUT:
tf.Tensor([<span class="hljs-number">10</span> <span class="hljs-number">10</span>], shape=(<span class="hljs-number">2</span>,), dtype=int32)
<span class="hljs-number">1</span>
</code></pre><p>Now let’s try creating a matrix and printing its dimensions.</p>
<pre><code>matrix = tf.constant([
    [<span class="hljs-number">10</span>,<span class="hljs-number">11</span>],
    [<span class="hljs-number">12</span>,<span class="hljs-number">13</span>]
])
print(matrix)
print(matrix.ndim)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">10</span> <span class="hljs-number">11</span>]
 [<span class="hljs-number">12</span> <span class="hljs-number">13</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
<span class="hljs-number">2</span>
</code></pre><p>You will see that the dimension is now 2. You can also see that the shape of the matrix is 2 by 2.</p>
<p>Shapes and dimensions are useful when working with TensorFlow because we will often change them while using these data to train neural networks.</p>
<p>We have seen that these tensors have a default datatype of int32. What if we want to create a dataset with a custom datatype?</p>
<p>tf.constant provides us with the dtype argument. Let’s create the same matrix again with float16 as the data type.</p>
<pre><code>tensor_1 = tf.constant([
    [
        [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
    ],
    [
        [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
    ],
    [
        [<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
    ]
],dtype=<span class="hljs-string">'float32'</span>)
print(tensor_1)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[[<span class="hljs-number">1.</span> <span class="hljs-number">2.</span> <span class="hljs-number">3.</span>]]

 [[<span class="hljs-number">4.</span> <span class="hljs-number">5.</span> <span class="hljs-number">6.</span>]]

 [[<span class="hljs-number">7.</span> <span class="hljs-number">8.</span> <span class="hljs-number">9.</span>]]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>), dtype=float32)
</code></pre><p>Now let’s create a tensor. We will input a 3-dimensional array to tf.constant. We will also print its dimensions.</p>
<pre><code>tensor = tf.constant([
    [
        [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
    ],
    [
        [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
    ],
    [
        [<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
    ]
])
print(tensor)
print(tensor.ndim)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[[<span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span>]]
 [[<span class="hljs-number">4</span> <span class="hljs-number">5</span> <span class="hljs-number">6</span>]]
 [[<span class="hljs-number">7</span> <span class="hljs-number">8</span> <span class="hljs-number">9</span>]]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>), dtype=int32)
<span class="hljs-number">3</span>
</code></pre><p>Now we have a tensor of dimension 3 and shape 3 by 1 by 3. This is the simplest tensor you can create. In real-world scenarios, we will be dealing with tensors of higher dimensions and bigger shapes.</p>
<p>Now let’s look at how to create a variable tensor. We won’t be using variable tensors very often compared to constant tensors, but it is good to know that we have an option.</p>
<p>We will use tf.Variable to create a variable tensor. The difference between the constant tensor and variable tensor is that you can change the data in a variable tensor, but you can’t change the values in a constant tensor. Let’s create a variable tensor and print the dimensions.</p>
<pre><code>var_tensor = tf.Variable([
    [
        [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
    ],
    [
        [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
    ],
    [
        [<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
    ]
])
print(var_tensor)
</code></pre><pre><code>OUTPUT:
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">tf.Variable</span> '<span class="hljs-attr">Variable:0</span>' <span class="hljs-attr">shape</span>=<span class="hljs-string">(3,</span> <span class="hljs-attr">1</span>, <span class="hljs-attr">3</span>) <span class="hljs-attr">dtype</span>=<span class="hljs-string">int32,</span> <span class="hljs-attr">numpy</span>=
<span class="hljs-string">array([[[1,</span> <span class="hljs-attr">2</span>, <span class="hljs-attr">3</span>]],
       [[<span class="hljs-attr">4</span>, <span class="hljs-attr">5</span>, <span class="hljs-attr">6</span>]],
       [[<span class="hljs-attr">7</span>, <span class="hljs-attr">8</span>, <span class="hljs-attr">9</span>]]], <span class="hljs-attr">dtype</span>=<span class="hljs-string">int32)</span>&gt;</span></span>
</code></pre><h1 id="heading-how-to-generate-and-load-tensors">How to Generate and Load Tensors</h1>
<p>Let’s look at how to generate tensors. In most cases, you won’t be creating tensors from scratch. You will either load a dataset, convert other datasets like NumPy arrays to tensors, or generate tensors. First, let’s look at how to generate tensors.</p>
<p>Let’s create a tensor with random values. There are two common ways you can do this: generate a normal distribution of data or a uniform distribution of data.</p>
<p><img src="https://miro.medium.com/max/1050/0*tRWkwBjuQvgi2rGG.png" alt="Image" width="600" height="400" loading="lazy">
<em>Normal distribution</em></p>
<p>The normal distribution is a bell-shaped curve that represents the distribution of data. Most of the data will be close to the average and fewer data will be away from the average. This means the probability of getting a value near the average is higher.</p>
<p><img src="https://miro.medium.com/max/1050/0*SOM1PR1htTNzuRMS.png" alt="Image" width="600" height="400" loading="lazy">
<em>Uniform distribution</em></p>
<p>The uniform distribution is a straight line that represents the distribution of data. All the values in a uniform distribution will have an equal probability of occurring within a given range.</p>
<p>Before we generate random values, you must understand what a seed is. If we use a seed value, we can regenerate the same set of data multiple times. This will be useful when we want to test our machine-learning model against the same data after we tweak its performance.</p>
<p>Let’s create two arrays of random tensors. We will first set a seed and generate the random values using that seed.</p>
<pre><code>seed = tf.random.Generator.from_seed(<span class="hljs-number">42</span>)
</code></pre><p>Now we will create a normal and uniform distribution with the shape of 3 by 2.</p>
<pre><code>normal_tensor = seed.normal(shape=(<span class="hljs-number">3</span>,<span class="hljs-number">2</span>))
print(normal_tensor)
uniform_tensor = seed.uniform(shape=(<span class="hljs-number">3</span>,<span class="hljs-number">2</span>))
print(uniform_tensor)
</code></pre><pre><code>OUTPUT:
tf.Tensor( [[<span class="hljs-number">-0.7565803</span>  <span class="hljs-number">-0.06854702</span>]  [ <span class="hljs-number">0.07595026</span> <span class="hljs-number">-1.2573844</span> ]  [<span class="hljs-number">-0.23193765</span> <span class="hljs-number">-1.8107855</span> ]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>), dtype=float32)
tf.Tensor( [[<span class="hljs-number">0.7647915</span>  <span class="hljs-number">0.03845465</span>]  [<span class="hljs-number">0.8506975</span>  <span class="hljs-number">0.20781887</span>]  [<span class="hljs-number">0.711869</span>   <span class="hljs-number">0.8843919</span> ]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>), dtype=float32)
</code></pre><p>We have two tensors created, one with a normal distribution of random numbers and the other with a uniform distribution of random numbers.</p>
<p>Next, we will create a tensor with zeros and ones. In TensorFlow, tensors filled with zeros or ones are often used as a starting point for creating other tensors. They can also be placeholders for inputs in a computational graph.</p>
<p>To create a tensor of zeroes, use the tf.zeros function with a shape as the input argument. To create a tensor with ones, we use tf.ones with the shape as input argument.</p>
<pre><code>zeros = tf.zeros(shape=(<span class="hljs-number">3</span>,<span class="hljs-number">2</span>))
print(zeros)
ones = tf.ones(shape=(<span class="hljs-number">3</span>,<span class="hljs-number">2</span>))
print(ones)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
 [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
 [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>), dtype=float32)
tf.Tensor(
[[<span class="hljs-number">1.</span> <span class="hljs-number">1.</span>]
 [<span class="hljs-number">1.</span> <span class="hljs-number">1.</span>]
 [<span class="hljs-number">1.</span> <span class="hljs-number">1.</span>]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>), dtype=float32)
</code></pre><p>Now, let’s look at converting NumPy arrays into tensors. If you don’t know <a target="_blank" href="https://numpy.org/">what NumPy is</a>, it is a Python library for numerical computing. It helps us handle large datasets and perform a variety of computations on them.</p>
<p>Let’s import NumPy and create a NumPy array using NumPy’s arrange function.</p>
<pre><code><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
numpy_arr = np.arange(<span class="hljs-number">1</span>,<span class="hljs-number">25</span>,dtype=np.int32)
</code></pre><p>Now, we can create a tensor using the tf.constant function with the NumPy array as input. TensorFlow has built-in support to handle NumPy arrays, so it is just a matter of importing a NumPy array and setting a shape.</p>
<pre><code>print(numpy_arr)
numpy_tensor = tf.constant(numpy_arr,shape=[<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>])
print(numpy_tensor)
</code></pre><pre><code>OUTPUT:
[ <span class="hljs-number">1</span>  <span class="hljs-number">2</span>  <span class="hljs-number">3</span>  <span class="hljs-number">4</span>  <span class="hljs-number">5</span>  <span class="hljs-number">6</span>  <span class="hljs-number">7</span>  <span class="hljs-number">8</span>  <span class="hljs-number">9</span> <span class="hljs-number">10</span> <span class="hljs-number">11</span> <span class="hljs-number">12</span> <span class="hljs-number">13</span> <span class="hljs-number">14</span> <span class="hljs-number">15</span> <span class="hljs-number">16</span> <span class="hljs-number">17</span> <span class="hljs-number">18</span> <span class="hljs-number">19</span> <span class="hljs-number">20</span> <span class="hljs-number">21</span> <span class="hljs-number">22</span> <span class="hljs-number">23</span> <span class="hljs-number">24</span>]
tf.Tensor(
[[[ <span class="hljs-number">1</span>  <span class="hljs-number">2</span>  <span class="hljs-number">3</span>]
  [ <span class="hljs-number">4</span>  <span class="hljs-number">5</span>  <span class="hljs-number">6</span>]
  [ <span class="hljs-number">7</span>  <span class="hljs-number">8</span>  <span class="hljs-number">9</span>]
  [<span class="hljs-number">10</span> <span class="hljs-number">11</span> <span class="hljs-number">12</span>]]
 [[<span class="hljs-number">13</span> <span class="hljs-number">14</span> <span class="hljs-number">15</span>]
  [<span class="hljs-number">16</span> <span class="hljs-number">17</span> <span class="hljs-number">18</span>]
  [<span class="hljs-number">19</span> <span class="hljs-number">20</span> <span class="hljs-number">21</span>]
  [<span class="hljs-number">22</span> <span class="hljs-number">23</span> <span class="hljs-number">24</span>]]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">3</span>), dtype=int32)
</code></pre><p>You can see both the NumPy array as well as our tensor. The original NumPy array was 1x12 but our tensor is 2x4x3. This is called re-shaping a tensor which we will often do while training deep neural networks.</p>
<h1 id="heading-basic-operations-using-tensorflow">Basic Operations using Tensorflow</h1>
<p>We have learned how tensors are created in TensorFlow. Now let’s look at some basic operations using tensors.</p>
<p>We will start by getting some information on our tensors. Let’s create a 4D tensor with 0 values with the shape 2x3x4x5.</p>
<pre><code>rank4_tensor = tf.zeros([<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>])
print(rank4_tensor)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[[[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]
  [[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]
  [[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]]
 [[[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]
  [[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]
  [[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>), dtype=float32)
</code></pre><p>We have created our rank 4 tensor. Now let's get some information about the size, shape (number of values), and the dimension of the tensor. </p>
<p>We will use tf.size function to get the size. The shape and ndim properties will give us the shape and dimensions of the tensor. </p>
<pre><code>print(<span class="hljs-string">"Size"</span>,tf.size(rank4_tensor))
print(<span class="hljs-string">"shape"</span>,rank4_tensor.shape)
print(<span class="hljs-string">"Dimension"</span>,rank4_tensor.ndim)
</code></pre><pre><code>OUTPUT: 

Size tf.Tensor(<span class="hljs-number">120</span>, shape=(), dtype=int32)
shape (<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
Dimension <span class="hljs-number">4</span>
</code></pre><p>Let’s look at some simple calculations using the tensor. I will create a new basic tensor.</p>
<pre><code>basic_tensor = tf.constant([[<span class="hljs-number">10</span>,<span class="hljs-number">11</span>],[<span class="hljs-number">12</span>,<span class="hljs-number">13</span>]])
print(basic_tensor)
</code></pre><pre><code>OUTPUT: 

tf.Tensor(
[[<span class="hljs-number">10</span> <span class="hljs-number">11</span>]
 [<span class="hljs-number">12</span> <span class="hljs-number">13</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
</code></pre><p>Let’s try some simple operations. We can add, subtract, multiply, and divide every value in a tensor using the basic operators.</p>
<pre><code>print(basic_tensor + <span class="hljs-number">10</span>)
print(basic_tensor - <span class="hljs-number">10</span>)
print(basic_tensor * <span class="hljs-number">10</span>)
print(basic_tensor / <span class="hljs-number">10</span>)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">20</span> <span class="hljs-number">21</span>]
 [<span class="hljs-number">22</span> <span class="hljs-number">23</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
tf.Tensor(
[[<span class="hljs-number">0</span> <span class="hljs-number">1</span>]
 [<span class="hljs-number">2</span> <span class="hljs-number">3</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
tf.Tensor(
[[<span class="hljs-number">100</span> <span class="hljs-number">110</span>]
 [<span class="hljs-number">120</span> <span class="hljs-number">130</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
tf.Tensor(
[[<span class="hljs-number">1.</span>  <span class="hljs-number">1.1</span>]
 [<span class="hljs-number">1.2</span> <span class="hljs-number">1.3</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=float64)
</code></pre><p>Now let’s try matrix multiplication. I will create two simple tensors tensor_011 and tensor_012.</p>
<pre><code>tensor_011 = tf.constant([[<span class="hljs-number">2</span>,<span class="hljs-number">2</span>],[<span class="hljs-number">4</span>,<span class="hljs-number">4</span>]])
tensor_012 = tf.constant([[<span class="hljs-number">2</span>,<span class="hljs-number">3</span>],[<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]])
</code></pre><p>Keep in mind that in matrix multiplication, the inner dimensions should match. For example, a (3, 5) <em> (3, 5) multiplication won’t work but (3, 5) </em> (5, 3) will work.</p>
<p>The final shape of the resulting matrix will be its outer dimension. so, a 3x5 tensor multiplied by a 5x3 tensor will give us a 5x5 tensor. We will use the tf.matmul function to perform matrix multiplication.</p>
<pre><code>print(tf.matmul(tensor_011,tensor_012))
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">12</span> <span class="hljs-number">16</span>]
 [<span class="hljs-number">24</span> <span class="hljs-number">32</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
</code></pre><p>Next, let’s look at reshaping and transposing a matrix. As we saw before, we will often use reshaping to change our matrix structure while training neural networks.</p>
<p>For example, an image pixel matrix of 28x28 will be converted into a 1-dimensional 784-pixel array for an image classification neural network.</p>
<p>To reshape, we use the tf.reshape function. To transpose, we use the tf.transpose function. If you don't know what a transpose is, it's converting rows into columns and columns into rows.</p>
<pre><code>print(tf.reshape(tensor_011,[<span class="hljs-number">4</span>,<span class="hljs-number">1</span>]))
print(tf.transpose(tensor_011))
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">2</span>]
 [<span class="hljs-number">2</span>]
 [<span class="hljs-number">4</span>]
 [<span class="hljs-number">4</span>]], shape=(<span class="hljs-number">4</span>, <span class="hljs-number">1</span>), dtype=int32)
tf.Tensor(
[[<span class="hljs-number">2</span> <span class="hljs-number">4</span>]
 [<span class="hljs-number">2</span> <span class="hljs-number">4</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
</code></pre><p>Finally, let’s look at some aggregate operations like min, max, standard deviation, square and square root.</p>
<p>To find the minimum and maximum values, we use the tf.reduce_min and tf.reduce_max functions. And to find the sum of the array, we use the tf.reduce_sum function.</p>
<pre><code>tensor_013 = tf.constant([
    [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>],
    [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>],
    [<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
],dtype=<span class="hljs-string">'float32'</span>)
print(tf.reduce_min(tensor_013))
print(tf.reduce_max(tensor_013))
print(tf.reduce_sum(tensor_013))
</code></pre><pre><code>OUTPUT:
tf.Tensor(<span class="hljs-number">1.0</span>, shape=(), dtype=float32)
tf.Tensor(<span class="hljs-number">9.0</span>, shape=(), dtype=float32)
tf.Tensor(<span class="hljs-number">45.0</span>, shape=(), dtype=float32)
</code></pre><p>Now for the standard deviation and variance, we use the tf.math.reduce_std function and tf.math.reduce_variance function.</p>
<pre><code>print(tf.math.reduce_std(tensor_013))
print(tf.math.reduce_variance(tensor_013))
</code></pre><pre><code>OUTPUT:
tf.Tensor(<span class="hljs-number">2.5819888</span>, shape=(), dtype=float32)
tf.Tensor(<span class="hljs-number">6.6666665</span>, shape=(), dtype=float32)
</code></pre><p>Let’s find the square, square root, and log of each value in a tensor.</p>
<pre><code>print(tf.sqrt(tensor_013))
print(tf.square(tensor_013))
print(tf.math.log(tensor_013))
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">1.</span>        <span class="hljs-number">1.4142135</span> <span class="hljs-number">1.7320508</span>]
 [<span class="hljs-number">2.</span>        <span class="hljs-number">2.236068</span>  <span class="hljs-number">2.4494898</span>]
 [<span class="hljs-number">2.6457512</span> <span class="hljs-number">2.828427</span>  <span class="hljs-number">3.</span>       ]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>), dtype=float32)
tf.Tensor(
[[ <span class="hljs-number">1.</span>  <span class="hljs-number">4.</span>  <span class="hljs-number">9.</span>]
 [<span class="hljs-number">16.</span> <span class="hljs-number">25.</span> <span class="hljs-number">36.</span>]
 [<span class="hljs-number">49.</span> <span class="hljs-number">64.</span> <span class="hljs-number">81.</span>]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>), dtype=float32)
tf.Tensor(
[[<span class="hljs-number">0.</span>        <span class="hljs-number">0.6931472</span> <span class="hljs-number">1.0986123</span>]
 [<span class="hljs-number">1.3862944</span> <span class="hljs-number">1.609438</span>  <span class="hljs-number">1.7917595</span>]
 [<span class="hljs-number">1.9459102</span> <span class="hljs-number">2.0794415</span> <span class="hljs-number">2.1972246</span>]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>), dtype=float32)
</code></pre><p>We have learned the basics of TensorFlow in this article. You are now equipped to work with TensorFlow and use it to model data.</p>
<p>If you want to start using this knowledge and build a project, you can check out my course on <a target="_blank" href="https://learn.manishmshiva.com/tensorflow-basics-handwriting-recognition-using-computer-vision">building a handwriting recognition neural network using TensorFlow</a>. You can also learn advanced TensorFlow concepts using the <a target="_blank" href="https://www.tensorflow.org/overview">official documentation.</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Tensorflow is a powerful library to build deep-learning models. It has all the tools we need to construct neural networks to solve problems like image classification, sentiment analysis, stock market predictions, etc. </p>
<p>With the advent of technologies like ChatGPT, learning TensorFlow will give you a head start in the current job market.</p>
<p><em>Hope you liked this article. You can learn more about me and my articles/videos at</em> <a target="_blank" href="https://www.manishmshiva.com/"><em>manishmshiva.com</em></a><em>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Validate your Machine Learning Models Using TensorFlow Model Analysis ]]>
                </title>
                <description>
                    <![CDATA[ My first deployed Machine Learning model was a failure. It was a simple Diabetes Diagnosis Model for potential diabetes mellitus patients – and quite frankly, I was beyond excited on deployment.  But the excitement soon disappeared when I received fe... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-validate-machine-learning-models-with-tensorflow-model-analysis/</link>
                <guid isPermaLink="false">66ba2dd5c346e93df556affb</guid>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Validation ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Salim Oyinlola ]]>
                </dc:creator>
                <pubDate>Wed, 05 Oct 2022 14:37:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/pexels-pixabay-159275.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>My first deployed Machine Learning model was a failure. It was a simple Diabetes Diagnosis Model for potential diabetes mellitus patients – and quite frankly, I was beyond excited on deployment. </p>
<p>But the excitement soon disappeared when I received feedback from users. Simply put, the users felt the model was bad. </p>
<p>I was saddened by this, but looking back, they were correct. The model may have performed well in terms of top-level metrics. But from the perspective of the consumer, if a machine learning model provides a poor forecast, that person's experience with the model will be bad. </p>
<p>The issue was that specific model features, or slices of data, were causing the model to perform poorly. </p>
<p>In short, before deploying any machine learning model, the onus is on machine learning engineers to assess it, make sure it satisfies strict quality standards, and acts as predicted for all pertinent slices of data.</p>
<h2 id="heading-what-is-tensorflow-model-analysis">What is TensorFlow Model Analysis?</h2>
<p>To enable Machine Learning engineers to look at the performance of their models at a deeper level, Google created <a target="_blank" href="https://www.tensorflow.org/tfx/guide/tfma">TensorFlow Model Analysis (TFMA)</a>. According to the docs, "TFMA performs its computations in a distributed manner over large amounts of data using Apache Beam."</p>
<p>TFMA, as a tool, enables you to really dig into the model's performance and understand how it varies on different slices of data. It provides support for calculating metrics that were used at training time (that is built-in metrics) as well as metrics defined after the model was saved as part of the TFMA configuration settings. </p>
<p>In this tutorial, you will analyze and evaluate results on a previously trained machine learning model. The model you will use is trained for a <a target="_blank" href="https://github.com/tensorflow/tfx/tree/master/tfx/examples/chicago_taxi_pipeline">Chicago Taxi Example</a>, which uses the <a target="_blank" href="https://data.cityofchicago.org/Transportation/Taxi-Trips/wrvz-psew">Taxi Trips dataset</a> released by the city of Chicago. You can check out the full dataset <a target="_blank" href="https://bigquery.cloud.google.com/dataset/bigquery-public-data:chicago_taxi_trips">here</a>. </p>
<p>When you are done with this tutorial, you will be able to use Apache Beam to do a full pass over the specified evaluation dataset. Also, you will not only have a more accurate calculation of metrics, but you'll be able to scale up to massive evaluation datasets, since Beam pipelines can be run using distributed processing back-ends.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>Fundamental knowledge of Apache Beam. The <a target="_blank" href="https://beam.apache.org/documentation/programming-guide/">Beam Programming Guide</a> is a great place to start.</li>
<li>Fundamental understanding of the workings of machine learning models. </li>
<li>A new Google Colab notebook to run the Python code in your Google Drive. You can set this up by following this <a target="_blank" href="https://www.freecodecamp.org/news/google-colaboratory-python-code-in-your-google-drive/">tutorial</a>.</li>
</ul>
<h2 id="heading-step-1-how-to-install-tensorflow-model-analysis-tfma">Step 1 – How to Install TensorFlow Model Analysis (TFMA)</h2>
<p>With your Google Colab notebook ready, the first thing to do is to pull in all the dependencies. This will take a while.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-23.png" alt="Image" width="600" height="400" loading="lazy">
<em>A blank (new) notebook in dark mode</em></p>
<p>Rename the file from <code>Untitled.ipynb</code> to <code>TFMA.ipynb</code>. </p>
<pre><code class="lang-python">!pip install -U pip
!pip install tensorflow-model-analysis`
</code></pre>
<p>The first line upgrades <code>pip</code> to the latest version. <code>pip</code> is the package management system used to install and manage software packages written in Python. It stands for “preferred installer program”. The second line will install TensorFlow Model Analysis, TFMA.  </p>
<p>Now, after that is done, restart the runtime before running the cells below. It is important to restart the runtime before running the cells.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-26.png" alt="Image" width="600" height="400" loading="lazy"></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sys
<span class="hljs-keyword">assert</span> sys.version_info.major==<span class="hljs-number">3</span> 
<span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
<span class="hljs-keyword">import</span> apache_beam <span class="hljs-keyword">as</span> beam
<span class="hljs-keyword">import</span> tensorflow_model_analysis <span class="hljs-keyword">as</span> tfma
</code></pre>
<p>This block of code imports the needed libraries – <code>sys</code>, <code>tensorflow</code>, <code>apache_beam</code> and <code>tensorflow_model_analysis</code>. You use the <code>assert sys.version_info.major==3</code> command to verify that the notebook is being run using Python 3. </p>
<h2 id="heading-step-2-how-to-load-the-dataset">Step 2 – How to Load the dataset</h2>
<p>You will download the <code>tar</code> file and extract it.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> io, os, tempfile
TAR_NAME = <span class="hljs-string">'saved_models-2.2'</span>
BASE_DIR = tempfile.mkdtemp()
DATA_DIR = os.path.join(BASE_DIR, TAR_NAME, <span class="hljs-string">'data'</span>)
MODELS_DIR = os.path.join(BASE_DIR, TAR_NAME, <span class="hljs-string">'models'</span>)
SCHEMA = os.path.join(BASE_DIR, TAR_NAME, <span class="hljs-string">'schema.pbtxt'</span>)
OUTPUT_DIR = os.path.join(BASE_DIR, <span class="hljs-string">'output'</span>)

!curl -O https://storage.googleapis.com/artifacts.tfx-oss-public.appspot.com/datasets/{TAR_NAME}.tar
!tar xf {TAR_NAME}.tar
!mv {TAR_NAME} {BASE_DIR}
!rm {TAR_NAME}.tar
</code></pre>
<p>The dataset downloaded is in the <code>tar</code> file format. It includes the training datasets, evaluation datasets, the data schema and the training and serving saved models along with eval saved models. You will need all of them in this tutorial.</p>
<h2 id="heading-step-3-how-to-parse-the-schema">Step 3 – How to Parse the Schema</h2>
<p>You need to parse the downloaded schema so that you can use it with TFMA. </p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
<span class="hljs-keyword">from</span> google.protobuf <span class="hljs-keyword">import</span> text_format
<span class="hljs-keyword">from</span> tensorflow.python.lib.io <span class="hljs-keyword">import</span> file_io
<span class="hljs-keyword">from</span> tensorflow_metadata.proto.v0 <span class="hljs-keyword">import</span> schema_pb2
<span class="hljs-keyword">from</span> tensorflow.core.example <span class="hljs-keyword">import</span> example_pb2

schema = schema_pb2.Schema()
contents = file_io.read_file_to_string(SCHEMA)
schema = text_format.Parse(contents, schema)
</code></pre>
<p>You will parse the schema using the <code>text_format</code> method of the <code>google.protobuf</code> library to convert the protobuf message to text format and TensorFlow's <code>schema_pb2</code>.</p>
<h2 id="heading-step-4-how-to-use-the-schema-to-create-tfrecords">Step 4 – How to Use the Schema to Create TFRecords</h2>
<p>The next course of action would be to give TFMA access to our dataset. For this, we need to create a <code>TFRecords</code> file.  We used our schema to create it, since it gives us the correct type for each feature.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> csv
datafile = os.path.join(DATA_DIR, <span class="hljs-string">'eval'</span>, <span class="hljs-string">'data.csv'</span>)
reader = csv.DictReader(open(datafile, <span class="hljs-string">'r'</span>))
examples = []
<span class="hljs-keyword">for</span> line <span class="hljs-keyword">in</span> reader:
  example = example_pb2.Example()
  <span class="hljs-keyword">for</span> feature <span class="hljs-keyword">in</span> schema.feature:
    key = feature.name
    <span class="hljs-keyword">if</span> feature.type == schema_pb2.FLOAT:
      example.features.feature[key].float_list.value[:] = (
          [float(line[key])] <span class="hljs-keyword">if</span> len(line[key]) &gt; <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> [])
    <span class="hljs-keyword">elif</span> feature.type == schema_pb2.INT:
      example.features.feature[key].int64_list.value[:] = (
          [int(line[key])] <span class="hljs-keyword">if</span> len(line[key]) &gt; <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> [])
    <span class="hljs-keyword">elif</span> feature.type == schema_pb2.BYTES:
      example.features.feature[key].bytes_list.value[:] = (
          [line[key].encode(<span class="hljs-string">'utf8'</span>)] <span class="hljs-keyword">if</span> len(line[key]) &gt; <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> [])
  <span class="hljs-comment"># Add a new column 'big_tipper' that indicates if the tip was &gt; 20% of the fare. </span>
  <span class="hljs-comment"># TODO(b/157064428): Remove after label transformation is supported for Keras.</span>
  big_tipper = float(line[<span class="hljs-string">'tips'</span>]) &gt; float(line[<span class="hljs-string">'fare'</span>]) * <span class="hljs-number">0.2</span>
  example.features.feature[<span class="hljs-string">'big_tipper'</span>].float_list.value[:] = [big_tipper]
  examples.append(example)
tfrecord_file = os.path.join(BASE_DIR, <span class="hljs-string">'train_data.rio'</span>)
<span class="hljs-keyword">with</span> tf.io.TFRecordWriter(tfrecord_file) <span class="hljs-keyword">as</span> writer:
  <span class="hljs-keyword">for</span> example <span class="hljs-keyword">in</span> examples:
    writer.write(example.SerializeToString())
!ls {tfrecord_file}
</code></pre>
<p>It is worthy of note that TFMA supports a number of different model types including TF Keras models, models based on generic TF2 signature APIs, as well TF estimator-based models. However, for this tutorial, you will configure a Keras-based model. </p>
<p>In your Keras <a target="_blank" href="https://www.tensorflow.org/tfx/model_analysis/setup">setup</a>, you will add your metrics and plots manually as part of the configuration (see the <a target="_blank" href="https://www.tensorflow.org/tfx/model_analysis/metrics">metrics</a> guide for information on the metrics and plots that are supported).</p>
<h2 id="heading-step-5-how-to-set-up-and-run-tfma-using-keras">Step 5 – How to Set Up and Run TFMA using Keras</h2>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tensorflow_model_analysis <span class="hljs-keyword">as</span> tfma
</code></pre>
<p>You'll finally call and use the instance of <code>tfma</code> that you previously imported at this point. </p>
<pre><code class="lang-python"><span class="hljs-comment"># You will setup tfma.EvalConfig settings</span>
keras_eval_config = text_format.Parse(<span class="hljs-string">"""
  ## Model information
  model_specs {
    # For keras (and serving models) we need to add a `label_key`.
    label_key: "big_tipper"
  }

  ## You will post training metric information. These will be merged with any built-in
  ## metrics from training.
  metrics_specs {
    metrics { class_name: "ExampleCount" }
    metrics { class_name: "BinaryAccuracy" }
    metrics { class_name: "BinaryCrossentropy" }
    metrics { class_name: "AUC" }
    metrics { class_name: "AUCPrecisionRecall" }
    metrics { class_name: "Precision" }
    metrics { class_name: "Recall" }
    metrics { class_name: "MeanLabel" }
    metrics { class_name: "MeanPrediction" }
    metrics { class_name: "Calibration" }
    metrics { class_name: "CalibrationPlot" }
    metrics { class_name: "ConfusionMatrixPlot" }
    # ... add additional metrics and plots ...
  }

  ## You will slice the information
  slicing_specs {}  # overall slice
  slicing_specs {
    feature_keys: ["trip_start_hour"]
  }
  slicing_specs {
    feature_keys: ["trip_start_day"]
  }
  slicing_specs {
    feature_values: {
      key: "trip_start_month"
      value: "1"
    }
  }
  slicing_specs {
    feature_keys: ["trip_start_hour", "trip_start_day"]
  }
"""</span>, tfma.EvalConfig())
</code></pre>
<p>It's also important that you create a <code>tfma.EvalSharedModel</code> that points at the Keras model.</p>
<pre><code class="lang-python">keras_model_path = os.path.join(MODELS_DIR, <span class="hljs-string">'keras'</span>, <span class="hljs-string">'2'</span>)
keras_eval_shared_model = tfma.default_eval_shared_model(
    eval_saved_model_path=keras_model_path,
    eval_config=keras_eval_config)

keras_output_path = os.path.join(OUTPUT_DIR, <span class="hljs-string">'keras'</span>)
</code></pre>
<p>And then you finally run TFMA, ending this step.</p>
<pre><code class="lang-python">keras_eval_result = tfma.run_model_analysis(
    eval_shared_model=keras_eval_shared_model,
    eval_config=keras_eval_config,
    data_location=tfrecord_file,
    output_path=keras_output_path)
</code></pre>
<p>Now that you have run the evaluation, look at the visualizations using TFMA. For the following examples, you can visualize the results from running the evaluation on the Keras model. </p>
<p>To view metrics, you will use <code>[tfma.view.render_slicing_metrics](https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/view/render_slicing_metrics)</code>. By default, the views will display the <code>Overall</code> slice. To view a particular slice, you can either use the name of the column (by setting <code>slicing_column</code>) or provide a <a target="_blank" href="https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/SlicingSpec"><code>tfma.SlicingSpec</code></a>.</p>
<h2 id="heading-step-6-how-to-visualize-the-metrics-and-plots">Step 6 – How to Visualize the Metrics and Plots</h2>
<p>At this point, it is important that you note that the columns used in the dataset are as follows: </p>
<ul>
<li><code>pickup_community_area</code></li>
<li><code>fare</code></li>
<li><code>trip_start_month</code></li>
<li><code>trip_start_hour</code></li>
<li><code>trip_start_day</code></li>
<li><code>trip_start_timestamp</code></li>
<li><code>pickup_latitude</code></li>
<li><code>pickup_longitude</code></li>
<li><code>dropoff_latitude</code></li>
<li><code>dropoff_longitude</code></li>
<li><code>trip_miles</code></li>
<li><code>pickup_census_tract</code></li>
<li><code>dropoff_census_tract</code></li>
<li><code>payment_type</code></li>
<li><code>company</code></li>
<li><code>trip_seconds</code></li>
<li><code>dropoff_community_area</code>, and </li>
<li><code>tips</code> </li>
</ul>
<p>For a first trial and as an example, you can set <code>slicing_column</code> to look at the <code>trip_start_hour</code> feature from our previous <code>slicing_specs</code>. You are then able to visualize the column. </p>
<pre><code class="lang-python">tfma.view.render_slicing_metrics(keras_eval_result, slicing_column=<span class="hljs-string">'trip_start_hour'</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-27.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-28.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On running this, you will see that the metrics visualization supports the following interactions:</p>
<ul>
<li>Click and drag to pan</li>
<li>Scroll to zoom</li>
<li>Right click to reset the view</li>
<li>Hover over the desired data point to see more details.</li>
<li>Select from four different types of views using the selections at the bottom.</li>
</ul>
<p>Note that your initial <code>tfma.EvalConfig</code> has created a whole list of <code>slicing_specs</code>, which you can visualize by updating slice information passed to <code>tfma.view.render_slicing_metrics</code>. Here you can select the <code>trip_start_day</code> slice (days of the week).</p>
<pre><code class="lang-python">tfma.view.render_slicing_metrics(keras_eval_result, slicing_column=<span class="hljs-string">'trip_start_day'</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-31.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>TFMA also supports creating feature crosses to analyze combinations of features. To test this, you will create a cross between <code>trip_start_hour</code> and <code>trip_start_day</code>.</p>
<pre><code class="lang-python">tfma.view.render_slicing_metrics(
    keras_eval_result,
    slicing_spec=tfma.SlicingSpec(
        feature_keys=[<span class="hljs-string">'trip_start_hour'</span>, <span class="hljs-string">'trip_start_day'</span>]))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-32.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, crossing the two columns creates a lot of combinations! But you will narrow down your cross to only look at <em>trips that start at 1pm</em>. Then, you will select <code>binary_accuracy</code> from the visualization as shown below.</p>
<pre><code class="lang-python">tfma.view.render_slicing_metrics(
    keras_eval_result,
    slicing_spec=tfma.SlicingSpec(
        feature_keys=[<span class="hljs-string">'trip_start_day'</span>], feature_values={<span class="hljs-string">'trip_start_hour'</span>: <span class="hljs-string">'13'</span>}))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-step-7-how-to-track-your-models-performance-over-time">Step 7 – How to Track Your Model's Performance Over Time</h2>
<p>You'll use your training dataset for training your model. It will hopefully be representative of your test dataset and the data that will be sent to your model in production.  </p>
<p>But while the data in inference requests may remain the same as your training data, in many cases it will start to change enough so that the performance of your model will change.</p>
<p>That means that you need to monitor and measure your model's performance on an ongoing basis, so that you can be aware of and react to changes.  </p>
<p>Let's look at how TFMA can help.</p>
<pre><code class="lang-python">output_paths = []
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">3</span>):
  <span class="hljs-comment"># Create a tfma.EvalSharedModel that points to our saved model.</span>
  eval_shared_model = tfma.default_eval_shared_model(
      eval_saved_model_path=os.path.join(MODELS_DIR, <span class="hljs-string">'keras'</span>, str(i)),
      eval_config=keras_eval_config)

  output_path = os.path.join(OUTPUT_DIR, <span class="hljs-string">'time_series'</span>, str(i))
  output_paths.append(output_path)

  <span class="hljs-comment"># Run TFMA</span>
  tfma.run_model_analysis(eval_shared_model=eval_shared_model,
                          eval_config=keras_eval_config,
                          data_location=tfrecord_file,
                          output_path=output_path)

  eval_results_from_disk = tfma.load_eval_results(output_paths[:<span class="hljs-number">2</span>])

tfma.view.render_time_series(eval_results_from_disk)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-35.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Using the <code>tfma</code>, you can validate and evaluate your machine learning models across different slices of data. </p>
<p>You can see from the image above that you can evaluate the <code>auc</code> (area under the curve), <code>auc_precision_recall</code>, <code>binary_accuracy</code>, <code>binary_crossentropy</code>, <code>calibration</code>, <code>example_count</code>, <code>mean_label</code>, <code>mean_prediction</code>, <code>precision</code>, and <code>recall</code> metrics of the machine learning model. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Finally, it is important that TFMA can be configured to evaluate multiple models at the same time. Typically, you do this to compare a new model against a baseline (such as the currently serving model) to determine what the performance differences in metrics (for example AUC) are relative to the baseline. </p>
<p>When thresholds are configured, TFMA will produce a <a target="_blank" href="https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/ValidationResult"><code>tfma.ValidationResult</code></a> record indicating whether the performance matches expectations.  </p>
<p>If at this point, you have questions about the difference between evaluating machine learning models using <a target="_blank" href="https://www.freecodecamp.org/news/how-to-evaluate-machine-learning-models-using-tensorboard/">TensorBoard</a> and TensorFlow Metrics Analysis (TFMA), this is a valid concern. Both are tools for providing the measurements and visualizations needed during the Machine Learning workflow. </p>
<p>But it is important to note that you use them in different stages of the development process. At a high level, you use TensorBoard to analyze the training process itself while TFMA is concerned with the deep analysis of the 'finished' trained model.</p>
<p>Thank you for reading!  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Evaluate Machine Learning Models using TensorBoard with TensorFlow ]]>
                </title>
                <description>
                    <![CDATA[ A key part of the Machine Learning pipeline is finding a model that best represents your data and will function effectively on future datasets.  By virtue of their very nature, Machine Learning models improve iteratively. There is hardly any machine ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-evaluate-machine-learning-models-using-tensorboard/</link>
                <guid isPermaLink="false">66ba2dcf0ecf2905f20d3648</guid>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Salim Oyinlola ]]>
                </dc:creator>
                <pubDate>Wed, 14 Sep 2022 18:31:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/TensorFlow_Logo_with_text.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A key part of the Machine Learning pipeline is finding a model that best represents your data and will function effectively on future datasets. </p>
<p>By virtue of their very nature, Machine Learning models improve iteratively. There is hardly any machine learning model that is trained perfectly on the first try. Usuaully, several iterations are required. </p>
<p>As you would imagine, these models have to be evaluated to make them better. In other words, a machine learning model needs to be assessed before it can be improved on. </p>
<p><a target="_blank" href="https://www.tensorflow.org/tensorboard/get_started">TensorBoard</a> was developed to give machine learning engineers a more in-depth look at the performance of their models. </p>
<h2 id="heading-what-is-tensorboard"><strong>What is TensorBoard?</strong></h2>
<p>TensorBoard's basic functionality is to deliver the metrics and visualizations you need for your Machine Learning workflow. It allows you to monitor loss and accuracy, view and assess error graphs, and perform many other tasks. </p>
<p>TensorBoard uses graph concepts to represent the data flow and model actions whilst allowing you to see the graph topologies and parameters of complex, huge models. It also has a very user-friendly and basic UI.</p>
<p>In this tutorial, you will analyze and evaluate results on a trained machine learning model. The model you will use will be trained for a <a target="_blank" href="https://www.tensorflow.org/api_docs/python/tf/keras/datasets/mnist">MNIST handwritten digits dataset</a>. It uses the MNIST (Modified National Institute of Standards and Technology) database, which contains an ample collection of handwritten digits. This dataset is commonly used for training various image processing systems.</p>
<h3 id="heading-prerequisites"><strong>Prerequisites</strong></h3>
<p>To complete this tutorial, you will need:</p>
<ol>
<li>Fundamental understanding of the workings of Machine Learning models.</li>
<li>A new Google Colab notebook to run the Python code in your Google Drive. You can set this up by following this <a target="_blank" href="https://www.freecodecamp.org/news/google-colaboratory-python-code-in-your-google-drive/">tutorial</a>.</li>
</ol>
<h2 id="heading-step-1-how-to-set-up-tensorboard"><strong>Step 1 – How to Set Up TensorBoard</strong></h2>
<p>Since TensorBoard comes automatically with TensorFlow, you don't need to install it using <code>pip</code> in this setup. Also, since TensorFlow comes pre-installed when you create a new notebook on Google Colab, TensorBoard comes pre-installed as well. So, when setting TensorBoard up, you only need to import <code>tensorflow</code> .  </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-157.png" alt="Image" width="600" height="400" loading="lazy">
<em>A blank (new) notebook in dark mode</em></p>
<ul>
<li>Load the <code>tensorboard</code> extension using the <code>%load_ext</code> magic in your notebook. </li>
<li>After doing this, import the necessary libraries (that is, <code>tensorflow</code> and <code>datetime</code>) as shown below:</li>
</ul>
<pre><code class="lang-python">%load_ext tensorboard
</code></pre>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
<span class="hljs-keyword">import</span> datetime
</code></pre>
<p>At this point, you have successfully imported an instance of <code>TensorBoard</code> and set it up. You can now get started.</p>
<h2 id="heading-step-2-how-to-create-and-train-the-model"><strong>Step 2 – How to Create and Train the Model</strong></h2>
<p>In this tutorial, you will use the MNIST dataset, which includes tiny 28 x 28-pixel handwritten single-digit greyscale images. The dataset, which is one of the pre-installed datasets offered by <code>Keras</code> is frequently used to develop Machine Learning models for digit recognition. </p>
<ul>
<li>Create an instance of the dataset and name it <code>mnist</code>.</li>
<li>Split the data into train sets and test sets. A train set is a subset of the original data that is used to train the machine learning model while a test set is the subset that is used to check the accuracy of the model. </li>
<li>Standardize all the values of your train and test sets. This implies normalizing the image to the [0,1] range.</li>
<li>Define a function that will be used to train the machine learning model on your dataset. The <code>Sequential</code> Keras model will be used. </li>
</ul>
<pre><code class="lang-python">mnist = tf.keras.datasets.mnist
</code></pre>
<pre><code class="lang-python">(x_train, y_train),(x_test, y_test) = mnist.load_data()
</code></pre>
<pre><code class="lang-python">x_train, x_test = x_train/<span class="hljs-number">255.0</span>, x_test/<span class="hljs-number">255.0</span>
</code></pre>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_model</span>():</span>
  <span class="hljs-keyword">return</span> tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(<span class="hljs-number">28</span>, <span class="hljs-number">28</span>)),
    tf.keras.layers.Dense(<span class="hljs-number">512</span>, activation=<span class="hljs-string">'relu'</span>),
    tf.keras.layers.Dropout(<span class="hljs-number">0.2</span>),
    tf.keras.layers.Dense(<span class="hljs-number">10</span>, activation=<span class="hljs-string">'softmax'</span>)
  ])
</code></pre>
<p>You will use the <code>Sequential</code> Keras model. At its core, it groups a linear stack of layers into <code>tf.keras.Model</code> whilst providing training and inference features on this model.</p>
<p>The <code>.Flatten()</code> layer flattens the input without affecting the batch size. The input shape in this example is 28 x 28 since the images from the dataset are 28×28-pixel grayscale images of handwritten single-digits. The first <code>.Dense()</code> layer is a regular densely connected NN layer. </p>
<p>The activation function used is 'relu' and the dimensionality of its output space is 512. The <code>.Dropout()</code> layer drops some of the input with the fraction of the input units dropped in this tutorial given as 0.2. </p>
<p>Finally, like the first one, the second. <code>Dense</code> layer is also your regular densely connected NN layer. The activation function we're using is 'softmax' and the dimensionality of its output space is ten.</p>
<ul>
<li>Call the defined function for the model like this: </li>
<li>With the defined function called, train the model with suitable parameters.</li>
<li>Using the <code>datatime</code> library you previously imported, place the logs in a timestamped subdirectory to allow easy selection of different training runs.</li>
</ul>
<pre><code class="lang-python">model = create_model()
</code></pre>
<pre><code class="lang-python">model.compile(optimizer=<span class="hljs-string">'adam'</span>,
              loss=<span class="hljs-string">'sparse_categorical_crossentropy'</span>,
              metrics=[<span class="hljs-string">'accuracy'</span>])
</code></pre>
<p>The logs are important because the TensorBoard will read from the logs to display the various visualizations with respect to the time at the point. </p>
<pre><code class="lang-python">log_dir = <span class="hljs-string">"logs/fit/"</span> + datetime.datetime.now().strftime(<span class="hljs-string">"%Y%m%d-%H%M%S"</span>)
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=<span class="hljs-number">1</span>)
</code></pre>
<ul>
<li>Finally, train (or fit) the machine learning model on three epochs (iterations).</li>
</ul>
<pre><code class="lang-python">model.fit(x=x_train, 
          y=y_train, 
          epochs=<span class="hljs-number">3</span>, 
          validation_data=(x_test, y_test), 
          callbacks=[tensorboard_callback])
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-158.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-step-3-how-to-evaluate-the-model"><strong>Step 3 – How to Evaluate the Model</strong></h2>
<p>To start TensorBoard within your notebook, run the code below:</p>
<pre><code class="lang-python">%tensorboard --logdir logs/fit
</code></pre>
<p>You can now view the dashboards showing the metrics for the model on tabs at the top and evaluate and improve your machine learning models accordingly.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-159.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-step-4-how-to-improve-the-model"><strong>Step 4 – How to Improve the Model</strong></h2>
<p>Since the point of evaluating your Machine Learning models is to gain better insight to improve the algorithm, it is imperative that we enhance our model. With these visuals, you can now see the in-depth performance of the model.</p>
<ul>
<li>The <code>Scalars</code> dashboard can be used to observe other scalar values such as training efficiency and learning rate. It demonstrates how the metrics and loss fluctuate with each epoch. </li>
<li>As the name implies, the <code>Graphs</code> dashboard is used to visualize your model. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-160.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Graph with the tensorboard</em></p>
<p>To improve this model, you will adjust the number of epochs from 3 to 6 and see how the model performs.</p>
<p>In general, the number of epochs is the number of iterations over the entire training dataset the machine learning model is trained on.</p>
<p>Intuitively, increasing this number almost always improves the performance of your machine learning model. To do this, you will run the code as follows:</p>
<pre><code class="lang-python">model.fit(x=x_train, 
          y=y_train, 
          epochs=<span class="hljs-number">6</span>, 
          validation_data=(x_test, y_test), 
          callbacks=[tensorboard_callback])
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-161.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>With the change we made, you can then generate another TensorBoard like this:</p>
<pre><code>%tensorboard --logdir logs/fit
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-162.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>From the newly generated visuals, you can see that there is a remarkable improvement in the model's performance.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this article, you learned how you can use TensorBoard to assess and improve your Machine Learning model's performance.</p>
<p>If at this point you have questions about the difference between TensorBoard and TensorFlow Metrics Analysis (TFMA), this is a valid concern. After all, both are tools for providing the measurements and visualizations needed during the Machine Learning workflow.</p>
<p>But it is important to note that you use each of these tools in distinct stages of the development process. At its core, TensorBoard is used to analyze the training process itself, while TFMA is concerned with the analysis of the 'finished' trained model.</p>
<p>Finally, I share my writings on <a target="_blank" href="https://twitter.com/SalimOyinlola">Twitter</a> if you enjoyed this article and want to see more.</p>
<p>Thank you for reading :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Text Classification with TensorFlow ]]>
                </title>
                <description>
                    <![CDATA[ Text classification algorithms are used in a lot of different software systems to help process text data. For example, when you get an email, the email software uses a text classification algorithm to decide whether to put it in your inbox or in your... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/text-classification-tensorflow/</link>
                <guid isPermaLink="false">66b2069639b555ffda8bfebe</guid>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Wed, 15 Jun 2022 14:01:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/classification.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Text classification algorithms are used in a lot of different software systems to help process text data. For example, when you get an email, the email software uses a text classification algorithm to decide whether to put it in your inbox or in your spam folder. It's also how discussion forums know which comments to flag as inappropriate, and how search engines index the web.</p>
<p>We just published a course on the freeCodeCamp.org YouTube channel that will teach you how to classify text using TensorFlow. </p>
<p>This course will give you an introduction to machine learning concepts and neural network implementation using TensorFlow.</p>
<p>Kylie Ying developed this course. Kylie is a current computer science grad student at MIT, working on research in the domain of machine learning and particle physics. She has a YouTube channel focused on programming tutorials and projects, and is passionate about teaching code and inspiring people to pursue STEM.</p>
<p>Kylie explains basic concepts, such as classification, regression, training/validation/test datasets, loss functions, neural networks, and model training. She then demonstrates how to implement a feedforward neural network to predict whether someone has diabetes, as well as two different neural net architectures to classify wine reviews.</p>
<p>Here are all the sections covered in this course.</p>
<ul>
<li>Introduction</li>
<li>Colab intro (importing wine dataset)</li>
<li>What is machine learning?</li>
<li>Features (inputs)</li>
<li>Outputs (predictions)</li>
<li>Anatomy of a dataset</li>
<li>Assessing performance</li>
<li>Neural nets</li>
<li>Tensorflow</li>
<li>Colab (feedforward network using diabetes dataset)</li>
<li>Recurrent neural networks</li>
<li>Colab (text classification networks using wine dataset)</li>
</ul>
<p>Watch the full course below or <a target="_blank" href="https://youtu.be/VtRLrQ3Ev-U">on the freeCodeCamp.org YouTube channel</a> (2-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/VtRLrQ3Ev-U" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Deploy a TensorFlow Model as a RESTful API Service ]]>
                </title>
                <description>
                    <![CDATA[ By Neil Ruaro If you're like I am, then you've probably watched and read a number of tutorials on creating machine learning models with TensorFlow, PyTorch, Scikit-Learn or any other framework out there.  But there is one thing that these tutorials t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/deploy-an-ml-model-using-fastapi-and-docker/</link>
                <guid isPermaLink="false">66d46040b6b7f664236cbe0c</guid>
                
                    <category>
                        <![CDATA[ deployment ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                    <category>
                        <![CDATA[ fastai,  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 07 Mar 2022 14:58:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/deploying-tensorflow-heroku-docker.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Neil Ruaro</p>
<p>If you're like I am, then you've probably watched and read a number of tutorials on creating machine learning models with TensorFlow, PyTorch, Scikit-Learn or any other framework out there. </p>
<p>But there is one thing that these tutorials tend to miss out on, and that's model deployment.</p>
<p>In this tutorial, I'll discuss on how to deploy a CNN TensorFlow model that classifies food images to Heroku using FastAPI and Docker.</p>
<h3 id="heading-tech-well-be-using">Tech We'll Be Using</h3>
<p>If you're unfamiliar, FastAPI is a Python web framework for creating fast API applications. And in my opinion, it is the easiest to learn out of all the Python web frameworks out there. </p>
<p>FastAPI also has default integration with swagger documentation and makes it easy to configure and update.</p>
<p>Docker, on the other hand, is an industry staple in software engineering, as it is one of the most popular containerization softwares out there. Docker is used for developing, deploying, and managing applications in virtualized environments called containers.</p>
<p>The main selling point of using Docker is that it solves the problem "it works on my machine, why not in yours?". Coincidentally, I actually faced this exact issue working on this very project, ultimately fixing it when I decided to use Docker.</p>
<p>Heroku, lastly, is a cloud platform where you can deploy, manage, and scale web applications. It works with back-end applications, front-end applications, or full-stack applications.</p>
<h2 id="heading-prerequisuites">Prerequisuites</h2>
<p>Before we begin, you'll first need the following:</p>
<ol>
<li>A Docker account</li>
<li>A Heroku account, and the Heroku CLI</li>
<li>A Python installation</li>
</ol>
<h2 id="heading-the-application-were-building">The Application We're Building</h2>
<p>We're going to be building a RESTful API service for a TensorFlow CNN model that classifies food images. </p>
<p>After building the API service, I'll show you how to dockerize the application, and then deploy it to Heroku.</p>
<h2 id="heading-how-to-download-the-necessities">How to Download the Necessities</h2>
<p>You'll first need to clone the GitHub repository at this <a target="_blank" href="https://github.com/eRuaro/food-vision-api">link</a>.</p>
<p><code>git clone https://github.com/eRuaro/food-vision-api.git</code></p>
<p>There are two branches in this repository – you'll use the <code>start-here</code> branch as <code>main</code> is the completed branch.</p>
<p>Once you've gotten the cloned repository, you'll need to download <a target="_blank" href="https://docs.docker.com/get-docker/">Docker</a> to your local system, and the <a target="_blank" href="https://devcenter.heroku.com/articles/heroku-cli">Heroku CLI</a> as well.</p>
<p>You must also install the following packages on pip:</p>
<ol>
<li>FastAPI</li>
<li>TensorFlow</li>
<li>Numpy</li>
<li>Uvicorn</li>
<li>Image</li>
</ol>
<p>To do so, create a <code>requirements.txt</code> file on the <code>start-here</code> branch, and put in the following. Note that you can use any other version of the listed packages below, as long as they still work together.</p>
<pre><code>fastapi==<span class="hljs-number">0.73</span><span class="hljs-number">.0</span>
numpy==<span class="hljs-number">1.19</span><span class="hljs-number">.5</span>
uvicorn==<span class="hljs-number">0.15</span><span class="hljs-number">.0</span>
image==<span class="hljs-number">1.5</span><span class="hljs-number">.33</span>
tensorflow-cpu==<span class="hljs-number">2.7</span><span class="hljs-number">.0</span>
</code></pre><p>After which you can install the packages using the command<br><code>pip install -r requirements.txt</code>.</p>
<p>Currently our <code>start-here</code> branch has the saved model file, as well as the Jupyter notebook used in creating the model. The notebook also has the code that implements our API feature. That is, it implements predicting the food class of an image based on its URL link.</p>
<h2 id="heading-brief-introduction-to-fastapi">Brief introduction to FastAPI</h2>
<p>With that in mind, let's start writing the code! In the root directory, create a <code>main.py</code> file. In that file, add the following lines of code:</p>
<pre><code><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI
<span class="hljs-keyword">from</span> fastapi.middleware.cors <span class="hljs-keyword">import</span> CORSMiddleware
<span class="hljs-keyword">from</span> uvicorn <span class="hljs-keyword">import</span> run
<span class="hljs-keyword">import</span> os

app = FastAPI()

origins = [<span class="hljs-string">"*"</span>]
methods = [<span class="hljs-string">"*"</span>]
headers = [<span class="hljs-string">"*"</span>]

app.add_middleware(
    CORSMiddleware, 
    allow_origins = origins,
    allow_credentials = True,
    allow_methods = methods,
    allow_headers = headers    
)

@app.get(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> def root():
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"message"</span>: <span class="hljs-string">"Welcome to the Food Vision API!"</span>}

<span class="hljs-keyword">if</span> __name == <span class="hljs-string">"__main__"</span>:
    port = int(os.environ.get(<span class="hljs-string">'PORT'</span>, <span class="hljs-number">5000</span>))
    run(app, host=<span class="hljs-string">"0.0.0.0"</span>, port=port)
</code></pre><p>Running the command <code>python -m uvicorn main:app --reload</code> will run the app, and will listen to changes we make on the server. </p>
<p>Alternatively, you can use <code>python main.py</code> and it will run the app on port 5000, courtesy of the last 3 lines of code. However, this won't let the app listen to changes we make, so you'll have to re-run the app every time you want to see your changes.</p>
<p>We also added the <code>CORSMiddleware</code> which essentially allows us to access the API in a different host. That is, we can extend the app further by creating a front-end interface for it. We won't cover that in this article but I put it here just in case you want to create a front-end to interact with the API as well.</p>
<p>Going to the port where the app is running, you'll get this.</p>
<pre><code>{
    <span class="hljs-string">"message"</span>: <span class="hljs-string">"Welcome to the Food Vision API!"</span>
}
</code></pre><p>The command <code>python -m uvicorn main:app --reload</code> refers to the following:</p>
<pre><code>main -&gt; The file main.py
app -&gt; The object created inside <span class="hljs-keyword">of</span> main.py <span class="hljs-keyword">with</span> the line app = FastAPI()
--reload -&gt; Make the server restart after code changes
</code></pre><p>Let's dissect the code we've written so far.</p>
<pre><code>@app.get(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> def root():
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"message"</span>: <span class="hljs-string">"Welcome to the Food Vision API!"</span>}
</code></pre><p><code>@app</code> is needed for FastAPI commands. The <code>get</code> is an HTTP method, while the <code>"/"</code> is the URL path of that specific API request. Below that we call a function that will return something. Here we just return a simple <code>json</code> message.</p>
<p>That is, we have a template for writing API endpoints with FastAPI.</p>
<pre><code>@app.http_method(<span class="hljs-string">"url_path"</span>)
<span class="hljs-keyword">async</span> def functionName():
    <span class="hljs-keyword">return</span> something
</code></pre><h2 id="heading-how-to-write-the-api-functionality">How to Write the API Functionality</h2>
<p>Let's write the main API functionality, that is, taking a food image URL from the internet, and predicting the name of that food. </p>
<p>First, let's extend the code that we wrote earlier, import all the required functions that we'll use, and load the model itself.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI
<span class="hljs-keyword">from</span> tensorflow.keras.models <span class="hljs-keyword">import</span> load_model
<span class="hljs-keyword">from</span> tensorflow.keras.utils <span class="hljs-keyword">import</span> get_file 
<span class="hljs-keyword">from</span> tensorflow.keras.utils <span class="hljs-keyword">import</span> load_img 
<span class="hljs-keyword">from</span> tensorflow.keras.utils <span class="hljs-keyword">import</span> img_to_array
<span class="hljs-keyword">from</span> tensorflow <span class="hljs-keyword">import</span> expand_dims
<span class="hljs-keyword">from</span> tensorflow.nn <span class="hljs-keyword">import</span> softmax
<span class="hljs-keyword">from</span> numpy <span class="hljs-keyword">import</span> argmax
<span class="hljs-keyword">from</span> numpy <span class="hljs-keyword">import</span> max
<span class="hljs-keyword">from</span> numpy <span class="hljs-keyword">import</span> array
<span class="hljs-keyword">from</span> json <span class="hljs-keyword">import</span> dumps
<span class="hljs-keyword">from</span> uvicorn <span class="hljs-keyword">import</span> run
<span class="hljs-keyword">import</span> os

app = FastAPI()
model_dir = <span class="hljs-string">"food-vision-model.h5"</span>
model = load_model(model_dir)

...
...
...

<span class="hljs-keyword">if</span> __name == <span class="hljs-string">"__main__"</span>:
    port = int(os.environ.get(<span class="hljs-string">'PORT'</span>, <span class="hljs-number">5000</span>))
    run(app, host=<span class="hljs-string">"0.0.0.0"</span>, port=port)
</code></pre>
<p>After loading in the model, let's add in the food classes that we have, which are based on the Food 101 dataset.</p>
<pre><code class="lang-python">class_predictions = array([
    <span class="hljs-string">'apple pie'</span>,
    <span class="hljs-string">'baby back ribs'</span>,
    <span class="hljs-string">'baklava'</span>,
    <span class="hljs-string">'beef carpaccio'</span>,
    <span class="hljs-string">'beef tartare'</span>,
    <span class="hljs-string">'beet salad'</span>,
    <span class="hljs-string">'beignets'</span>,
    <span class="hljs-string">'bibimbap'</span>,
    <span class="hljs-string">'bread pudding'</span>,
    <span class="hljs-string">'breakfast burrito'</span>,
    <span class="hljs-string">'bruschetta'</span>,
    <span class="hljs-string">'caesar salad'</span>,
    <span class="hljs-string">'cannoli'</span>,
    <span class="hljs-string">'caprese salad'</span>,
    <span class="hljs-string">'carrot cake'</span>,
    <span class="hljs-string">'ceviche'</span>,
    <span class="hljs-string">'cheesecake'</span>,
    <span class="hljs-string">'cheese plate'</span>,
    <span class="hljs-string">'chicken curry'</span>,
    <span class="hljs-string">'chicken quesadilla'</span>,
    <span class="hljs-string">'chicken wings'</span>,
    <span class="hljs-string">'chocolate cake'</span>,
    <span class="hljs-string">'chocolate mousse'</span>,
    <span class="hljs-string">'churros'</span>,
    <span class="hljs-string">'clam chowder'</span>,
    <span class="hljs-string">'club sandwich'</span>,
    <span class="hljs-string">'crab cakes'</span>,
    <span class="hljs-string">'creme brulee'</span>,
    <span class="hljs-string">'croque madame'</span>,
    <span class="hljs-string">'cup cakes'</span>,
    <span class="hljs-string">'deviled eggs'</span>,
    <span class="hljs-string">'donuts'</span>,
    <span class="hljs-string">'dumplings'</span>,
    <span class="hljs-string">'edamame'</span>,
    <span class="hljs-string">'eggs benedict'</span>,
    <span class="hljs-string">'escargots'</span>,
    <span class="hljs-string">'falafel'</span>,
    <span class="hljs-string">'filet mignon'</span>,
    <span class="hljs-string">'fish and chips'</span>,
    <span class="hljs-string">'foie gras'</span>,
    <span class="hljs-string">'french fries'</span>,
    <span class="hljs-string">'french onion soup'</span>,
    <span class="hljs-string">'french toast'</span>,
    <span class="hljs-string">'fried calamari'</span>,
    <span class="hljs-string">'fried rice'</span>,
    <span class="hljs-string">'frozen yogurt'</span>,
    <span class="hljs-string">'garlic bread'</span>,
    <span class="hljs-string">'gnocchi'</span>,
    <span class="hljs-string">'greek salad'</span>,
    <span class="hljs-string">'grilled cheese sandwich'</span>,
    <span class="hljs-string">'grilled salmon'</span>,
    <span class="hljs-string">'guacamole'</span>,
    <span class="hljs-string">'gyoza'</span>,
    <span class="hljs-string">'hamburger'</span>,
    <span class="hljs-string">'hot and sour soup'</span>,
    <span class="hljs-string">'hot dog'</span>,
    <span class="hljs-string">'huevos rancheros'</span>,
    <span class="hljs-string">'hummus'</span>,
    <span class="hljs-string">'ice cream'</span>,
    <span class="hljs-string">'lasagna'</span>,
    <span class="hljs-string">'lobster bisque'</span>,
    <span class="hljs-string">'lobster roll sandwich'</span>,
    <span class="hljs-string">'macaroni and cheese'</span>,
    <span class="hljs-string">'macarons'</span>,
    <span class="hljs-string">'miso soup'</span>,
    <span class="hljs-string">'mussels'</span>,
    <span class="hljs-string">'nachos'</span>,
    <span class="hljs-string">'omelette'</span>,
    <span class="hljs-string">'onion rings'</span>,
    <span class="hljs-string">'oysters'</span>,
    <span class="hljs-string">'pad thai'</span>,
    <span class="hljs-string">'paella'</span>,
    <span class="hljs-string">'pancakes'</span>,
    <span class="hljs-string">'panna cotta'</span>,
    <span class="hljs-string">'peking duck'</span>,
    <span class="hljs-string">'pho'</span>,
    <span class="hljs-string">'pizza'</span>,
    <span class="hljs-string">'pork chop'</span>,
    <span class="hljs-string">'poutine'</span>,
    <span class="hljs-string">'prime rib'</span>,
    <span class="hljs-string">'pulled pork sandwich'</span>,
    <span class="hljs-string">'ramen'</span>,
    <span class="hljs-string">'ravioli'</span>,
    <span class="hljs-string">'red velvet cake'</span>,
    <span class="hljs-string">'risotto'</span>,
    <span class="hljs-string">'samosa'</span>,
    <span class="hljs-string">'sashimi'</span>,
    <span class="hljs-string">'scallops'</span>,
    <span class="hljs-string">'seaweed salad'</span>,
    <span class="hljs-string">'shrimp and grits'</span>,
    <span class="hljs-string">'spaghetti bolognese'</span>,
    <span class="hljs-string">'spaghetti carbonara'</span>,
    <span class="hljs-string">'spring rolls'</span>,
    <span class="hljs-string">'steak'</span>,
    <span class="hljs-string">'strawberry shortcake'</span>,
    <span class="hljs-string">'sushi'</span>,
    <span class="hljs-string">'tacos'</span>,
    <span class="hljs-string">'takoyaki'</span>,
    <span class="hljs-string">'tiramisu'</span>,
    <span class="hljs-string">'tuna tartare'</span>,
    <span class="hljs-string">'waffles'</span>
])
</code></pre>
<p>Now that we have the food classes, let's write the main API functionality.</p>
<pre><code>@app.post(<span class="hljs-string">"/net/image/prediction/"</span>)
<span class="hljs-keyword">async</span> def get_net_image_prediction(image_link: str = <span class="hljs-string">""</span>):
    <span class="hljs-keyword">if</span> image_link == <span class="hljs-string">""</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">"message"</span>: <span class="hljs-string">"No image link provided"</span>}

    img_path = get_file(
        origin = image_link
    )
    img = load_img(
        img_path, 
        target_size = (<span class="hljs-number">224</span>, <span class="hljs-number">224</span>)
    )

    img_array = img_to_array(img)
    img_array = expand_dims(img_array, <span class="hljs-number">0</span>)

    pred = model.predict(img_array)
    score = softmax(pred[<span class="hljs-number">0</span>])

    class_prediction = class_predictions[argmax(score)]
    model_score = round(max(score) * <span class="hljs-number">100</span>, <span class="hljs-number">2</span>)

    <span class="hljs-keyword">return</span> {
        <span class="hljs-string">"model-prediction"</span>: class_prediction,
        <span class="hljs-string">"model-prediction-confidence-score"</span>: model_score
    }
</code></pre><p>Here, we make a <strong>post</strong> request to the endpoint <code>/net/image/prediction/</code> and provide the <code>image_url</code> as a query parameter. That is, the full endpoint when posting an image URL link would be <code>/net/image/prediction/image_url=image-url</code>.</p>
<p>For simplicity's sake, we give the <code>image_link</code> a default value of <code>""</code> and when there's no link passed to the endpoint, we simply return a message saying that there's no image link provided. </p>
<p><code>get_file()</code> downloads the image through the provided URL link, while <code>load_img()</code> loads the image in PIL format, and turns it into the appropriate image size that the model wants. </p>
<p><code>img_to_array()</code> converts the loaded image to a NumPy array. <code>expand_dims()</code> expands the dimensions of the array by one at the zero'th index. </p>
<p>We then use <code>model.predict()</code> to get the model prediction on the loaded image, and get the model's confidence score on said prediction using <code>softmax()</code>. I used softmax here as that's the activation function used in creating the model.</p>
<p>We finally then get the food type by using <code>argmax()</code> on the model's confidence score. We'll use that as the index that we'll use in searching through the <code>class_predictions</code> array which contains the various food classes we have. </p>
<p>Lastly, we multiply the model's confidence score by 100 so that the range of the score would be from 1 to 100.</p>
<p>We then return the model's prediction, and the model's confidence score.</p>
<h2 id="heading-why-we-need-to-use-docker-to-deploy-this-app">Why We Need to Use Docker to Deploy this App</h2>
<p>You can actually deploy this app as is on Heroku, using the usual method of defining a <code>Procfile</code>. But when I tried this method, I kept on getting a <a target="_blank" href="https://stackoverflow.com/questions/71152285/valueerror-out-of-range-float-values-are-not-json-compliant-error-on-heroku-an"><code>ValueError: Out of range float values are not JSON compliant</code></a> error. I also get this error when running the app on <em>Windows Subsystem for Linux</em> (WSL). When I run on Windows, however, the error disappears.</p>
<p>You can actually avoid this error by adding this line of code, after the initial assignment of the <code>model_score</code> variable:</p>
<pre><code>model_score = dumps(model_score.tolist())
</code></pre><p>This lets the app run on both Heroku and WSL, but it will only return these values when making the POST request.</p>
<pre><code>{
    <span class="hljs-string">"model-prediction"</span>: <span class="hljs-string">"apple pie"</span>,
    <span class="hljs-string">"model-prediction-confidence-score"</span>: <span class="hljs-literal">NaN</span>,
}
</code></pre><p>So, it works on my machine (Windows), but not on Heroku (using Procfile), nor on WSL. This is the kind of problem that Docker solves! </p>
<h2 id="heading-how-to-dockerize-the-application">How to Dockerize the Application</h2>
<p>Let's start dockerizing the application. Create a <code>Dockerfile</code> in the project's root directory and put in the following content:</p>
<pre><code>FROM python:<span class="hljs-number">3.7</span><span class="hljs-number">.3</span>-stretch

# Maintainer info
LABEL maintainer=<span class="hljs-string">"your-email-address"</span>

# Make working directories
RUN  mkdir -p  /food-vision-api
WORKDIR  /food-vision-api

# Upgrade pip <span class="hljs-keyword">with</span> no cache
RUN pip install --no-cache-dir -U pip

# Copy application requirements file to the created working directory
COPY requirements.txt .

# Install application dependencies <span class="hljs-keyword">from</span> the requirements file
RUN pip install -r requirements.txt

# Copy every file <span class="hljs-keyword">in</span> the source folder to the created working directory
COPY  . .

# Run the python application
CMD [<span class="hljs-string">"python"</span>, <span class="hljs-string">"main.py"</span>]
</code></pre><p>This pulls the Python 3.7.3 image, and installs all the necessary packages defined in the <code>requirements.txt</code> file. Then it runs the application by using the command <code>python main.py</code> as defined in the last line of the file.</p>
<p>You can then build and run the application using the following CLI commands:</p>
<pre><code>$ docker image build -t &lt;app-name&gt; .
$ docker run -p <span class="hljs-number">5000</span>:<span class="hljs-number">5000</span> -d &lt;app-name&gt;
</code></pre><p>Then you can stop the app, and free up system resources by running the following:</p>
<pre><code>$ docker container stop &lt;container-id&gt;
$ docker system prune
</code></pre><p><code>container-id</code> is returned when running the <code>docker run</code> command above. </p>
<h2 id="heading-how-to-deploy-to-heroku">How to Deploy to Heroku</h2>
<p>With the app now dockerized, we can deploy it to Heroku. I'm assuming you already have the Heroku CLI installed, and have already logged the CLI into your Heroku account. </p>
<p>Let's first create the app in Heroku through the CLI:</p>
<pre><code>$ heroku create &lt;app-name&gt;
</code></pre><p>Then we can push and release the app through the Docker container we made earlier with the following commands:</p>
<pre><code>$ heroku container:push web --app &lt;app-name&gt;
$ heroku container:release web --app &lt;app-name&gt;
</code></pre><p>After this, you can go to your Heroku dashboard and open the app. You should be greeted with the JSON message we have in the <code>"/"</code> directory of the application.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/image-7.png" alt="Image" width="600" height="400" loading="lazy">
<em>JSON message greeting on <code>"/"</code> directory</em></p>
<p>When you navigate to the <code>/docs</code> you'll be greeted with the Swagger documentation of the application. Here you can play around with the POST request we created and see if the model predictions are correct. Note that you must upload image links with the <code>jpeg</code> or <code>png</code> in its URL.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/image-8.png" alt="Image" width="600" height="400" loading="lazy">
<em>Swagger documentation of the application on <code>/docs</code></em></p>
<p>Let's try this out by using a picture of a chocolate cake, its URL link is <a target="_blank" href="https://tallypress.com/wp-content/uploads/2017/11/7-irresistible-chocolate-cakes-you-should-try-in-klang-valley.jpg">this</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/image-9.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image from tallypress.com</em></p>
<p>Paste the link to the text box in the <code>/docs</code> as so, then press <code>Execute</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/image-10.png" alt="Image" width="600" height="400" loading="lazy">
<em>Demonstration of the app</em></p>
<p>After pressing the <code>Execute</code> button, it will take a few seconds until we get the model prediction. That's because we're using <code>tensorflow-cpu</code> because we're limited with the RAM and the slug size of our application when using the free tier of Heroku. </p>
<p>After the execution is finished, you should be greeted with this response:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/image-11.png" alt="Image" width="600" height="400" loading="lazy">
<em>Response of the API after usage</em></p>
<p>As you can see, the model predicted it correctly, with a confidence score of 2.65%. This confidence score is alright as we're not dealing with model accuracy (which requires the truth value beforehand), and we're dealing with data the model hasn't seen before. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned how to deploy a TensorFlow CNN model to Heroku by serving it as a RESTful API, and by using Docker. </p>
<p>If you find this article helpful, feel free to share it on social media. Let's connect on <a target="_blank" href="https://twitter.com/neil_ruaro">Twitter</a>! You can also support me by <a target="_blank" href="https://www.buymeacoffee.com/eRuaro">buying me a coffee</a>. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn TensorFlow Lite for Edge Devices ]]>
                </title>
                <description>
                    <![CDATA[ TensorFlow Lite is an open source deep learning framework that can be used on small devices. We just published a TensorFlow Lite course on the freeCodeCamp.org YouTube channel. Bhavesh Bhatt created this course. Bhavesh has created many courses on hi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-tensorflow-lite-for-edge-devices/</link>
                <guid isPermaLink="false">66b2051f297cd6de0bd54679</guid>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 19 Oct 2021 16:58:53 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/tensoflowlite2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>TensorFlow Lite is an open source deep learning framework that can be used on small devices.</p>
<p>We just published a TensorFlow Lite course on the freeCodeCamp.org YouTube channel.</p>
<p>Bhavesh Bhatt created this course. Bhavesh has created many courses on his own channel and is a great teacher.</p>
<p>TensorFlow Lite is developed by Google and is used to train Machine Learning models on mobile, IoT (Interned of Things), and embedded devices.</p>
<p>When you use TensorFlow Lite the machine learning all happens within the device. This can avoid sending data back and forth with a server.</p>
<p>Here are the topics covered in this course:</p>
<ul>
<li>Why do we need TensorFlow Lite?</li>
<li>What is Edge Computing?</li>
<li>Why is Edge Computing gaining popularity?</li>
<li>Challenges in deploying models on Edge devices</li>
<li>What is TensorFlow Lite or TFLite?</li>
<li>TensorFlow Lite Workflow</li>
<li>Creating a TensorFlow or Keras model</li>
<li>Converting a TensorFlow or Keras model to TFLite</li>
<li>Validating the TFLite model performance</li>
<li>What is Quantization?</li>
<li>Compressing the TFLite model further</li>
<li>Compressing the TFLite model even further</li>
<li>Validating the most compressed TFLite model performance</li>
</ul>
<p>Watch the full course below or <a target="_blank" href="https://youtu.be/OJnaBhCixng">on the freeCodeCamp.org YouTube channel</a> (1-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/OJnaBhCixng" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-transcript">Transcript</h2>
<p>(autogenerated)</p>
<p>TensorFlow light allows you to do machine learning on small devices.</p>
<p>bhavesh is an experienced instructor and He will teach you all about TensorFlow light in this course.</p>
<p>Hello, everyone.</p>
<p>In this tutorial, you will learn the basics of TensorFlow light, and how TensorFlow light can help you create really efficient models that you can deploy on edge devices.</p>
<p>So without wasting any further time, let's kick start the tutorial.</p>
<p>Let us kick start today's discussion about the flight with a small story.</p>
<p>I have a friend whose name is john.</p>
<p>JOHN really likes traveling to different places.</p>
<p>One of his favorite applications is Google lense.</p>
<p>Whenever he visits a new country, he removes his cell phone takes a photograph of the monument that is in front of.</p>
<p>And Google essentially tells him which monument it is.</p>
<p>So now, just by the sheer fascination of the tool, john goes forward and creates his own neural network for detecting landmarks.</p>
<p>He goes through a rigorous process of collecting data, labeling data, cleaning data.</p>
<p>And finally he creates a machine learning model that can tell john, which monument it is.</p>
<p>So everything looks good, he is able to reach a very high accuracy score as well.</p>
<p>Now the only challenge that he has is where should he deploy the model that is created.</p>
<p>So technically, he has two options.</p>
<p>The option that he explores first is cloud computing.</p>
<p>He takes his train model, and he deploys it on Cloud.</p>
<p>He exposes the API that he is created.</p>
<p>And essentially, he creates an Android application that kind of queries the API and fetches the result once he's kind of passed in an image.</p>
<p>Now one of the major challenges that he saw when he created the solution is the network latency.</p>
<p>So the images that are captured generally by cell phones today, range anywhere between three to 10 Mb.</p>
<p>So transporting such huge files take up a lot of time in the entire process of making a prediction.</p>
<p>The second piece that adds complexity to the entire solution is the cost.</p>
<p>The neural network that john has created requires to resources, a storage resource wherein he can save the model weights, and a compute resource for making an inference, the overall project becomes a costly affair for john.</p>
<p>What does he do next, he creates an Android application.</p>
<p>And he finds a way to make an inference on Android using this huge model that he is created.</p>
<p>So john now faces a new issue.</p>
<p>The issue is the model is really huge.</p>
<p>And the cell phone is not very capable enough of storing and processing such a big model.</p>
<p>So now john, is really confused.</p>
<p>He's tried out different techniques to make this work.</p>
<p>But nothing is solving this issue.</p>
<p>Well, it is here that TF light comes into picture.</p>
<p>Before we jump and discuss about the flight, I wanted to throw some light in terms of what edge devices are.</p>
<p>So edge devices are your normal cell phones that you use.</p>
<p>So if you're planning to create some amazing TensorFlow based applications, then essentially one of the main platforms that you can utilize is your cell phones, bat or Android cell phone, or an iOS powered cell phone, anything works.</p>
<p>The other pieces of hardware devices that you can classify into edge devices or microcontrollers.</p>
<p>So there are some amazing applications that have been built using very small compute power.</p>
<p>And all of it is thanks to microcontrollers.</p>
<p>Given how recently, the variable devices that you were essentially have increased their computation power by using a more or faster CPU, you can also put your wearable devices such as your smartwatches into the edge computing bracket.</p>
<p>Now let me go forward and give you a formal definition of edge computing.</p>
<p>So edge computing is basically the practice of moving compute and storage resources closer to the location at which it is needed.</p>
<p>So that is where your edge devices would come into picture.</p>
<p>Now, if you recall it, john had two options to deploy the model.</p>
<p>The first option was to deploy the model on Cloud.</p>
<p>Now many of you would have the impression that a machine learning model running on the server using a large GPU is much more better as compared to running it on the device itself.</p>
<p>Well, the truth is edge devices have become an important platform for machine learning.</p>
<p>Why is it gaining so much of popularity that you essentially have to run your entire machine learning models on the edge devices? Well, let me share details one at a time.</p>
<p>The first and foremost reason why edge computing as a whole is gaining popularity is because of latency.</p>
<p>The use cases that require real time speed, definitely require models to run on the device.</p>
<p>For example, you might be able to reduce the inference latency of resnet 50, from 30 milliseconds to 20 milliseconds.</p>
<p>But the network latency can go up to seconds.</p>
<p>So essentially, it also depends on where your model is deployed.</p>
<p>Where are you waiting the API from.</p>
<p>So if you take into account all of these factors, then essentially deploying a model on server would not be the best possible situation when you want inferences in near real time, or exactly real time as well.</p>
<p>The second reason why creating machine learning models on edge devices is important is because of network and activity.</p>
<p>So if you go back to our earlier example, wherein john wanted to create his own version of Google lense for detecting landmarks, if he happens to visit a country where there is little to no connectivity, it is here that creating a model that sits on the device would be much more better as compared to deploying it on server, because there is this additional dependency on the network that comes into picture.</p>
<p>The third reason why it's very important for you to create machine learning models that run on edge devices, is user privacy.</p>
<p>Putting your machine learning models on the edge devices is also appealing when you are handling sensitive user data.</p>
<p>Machine learning on the cloud means that your systems might have to send user data over networks, making it susceptible to being intercepted.</p>
<p>Cloud computing also means that storing data of many users in the same place or location, which means a data breach can affect many people at once.</p>
<p>So it becomes really important to create machine learning models that can run on edge devices, which can preserve the user privacy data.</p>
<p>Let me now go forward and show you some examples of on device machine learning use cases.</p>
<p>The first one that I'm showing you right now is the feature to try out various cosmetics using AR on YouTube.</p>
<p>The entire computation piece that you're seeing here, is essentially happening on the device itself.</p>
<p>Now the second example that I want to show you is something that you might be already aware of, which is Google Translate.</p>
<p>Google Translate has a feature that allows you to capture text with your phone camera, and translate them in real time without any internet connection.</p>
<p>All of this is essentially possible using edge computing, and more specifically, TF light.</p>
<p>Now that you've seen the amazing new applications that you can create at your end as well, you might be wondering, the second alternative that john had taken initially, that is to create an entire huge TensorFlow model, and then run the inferences from the device.</p>
<p>Why did that fail? Well, to answer that question, here are some of the challenges that you might face when you create chaos or TensorFlow models, and deploy them directly onto edge devices.</p>
<p>Edge devices, not only restricted to mobile phones, but your microcontrollers as well have limited compute power.</p>
<p>Limited memory.</p>
<p>battery consumption is also a factor that you have to account for, as well as the application size.</p>
<p>If I consider a simple microcontroller is well, the processing power isn't so much that you can essentially run inferences on a three or four GB model.</p>
<p>If you consider the storage capacity of majority of the edge devices, well, then ideally, you wouldn't have a lot of storage that you can utilize for just one model.</p>
<p>So these are the challenges that john faced when he took the second approach as well.</p>
<p>So what is the solution? Well, the solution is TensorFlow light.</p>
<p>And so flow light is a production ready cross platform framework for deploying machine learning models on mobile devices and embedded systems.</p>
<p>And flow light at this point of time supports Android, iOS, and any IoT device that can run Linux.</p>
<p>So essentially, if you have any of these hardware devices handy with you Then you can quickly create a TensorFlow model, convert it to an equivalent TF light model, and start using the amazing TF light model.</p>
<p>Now, you might wonder, what exactly is the workflow to create a TF light model? Well, let's look at that as well.</p>
<p>So the workflow is fairly simple, you start by creating a TensorFlow slash karass model.</p>
<p>So in the entire process, you would have to collect data, you would have to clean data, pre processed data, then create models, iterate over multiple models, and based on the metric that you're chasing, if you are chasing for a higher accuracy score, then you would choose a model that would give you the best possible accuracy.</p>
<p>And that's about it, you have your TensorFlow model ready.</p>
<p>Now from that TensorFlow model, you convert it to a TensorFlow light model.</p>
<p>So there is a format change that happens.</p>
<p>I'll talk more about it as we go along.</p>
<p>Once you've converted your model from TensorFlow, to TensorFlow light, then you go forward and deploy the entire TF light model and run your inferences on the edge device.</p>
<p>When I mean inferences, I mean, predictions.</p>
<p>Okay.</p>
<p>Let me now explain this using a block diagram.</p>
<p>So this essentially is the workflow that I've just mentioned, you start off with your high level curiosity is create a model.</p>
<p>Once you have the model ready, then you can essentially use a TF light converter.</p>
<p>And the converter basically takes your save TensorFlow format file, and converts it into a flat buffer file.</p>
<p>I'll give you an idea in terms of what I mean by flat buffer file.</p>
<p>So let's move forward.</p>
<p>So TensorFlow lite represents your model in a flat buffer format.</p>
<p>Now flat buffer format is an efficient cross platform serialization library for c++, C sharp, go Java, kotlin, JavaScript, Python, and so on and so forth.</p>
<p>It was originally created at Google for game development and other performance critical applications.</p>
<p>But slowly, Google realized that you can use the flat buffer format in deploying models on edge devices.</p>
<p>Now you might have an obvious question, why not use our old tried and tested protocol buffers.</p>
<p>And why shift to something that is as newest flatbuffers protocol buffers just to give you context, all your kiraz models that you create all your TensorFlow models that you create are essentially protocol buffer format.</p>
<p>protocol buffers are essentially very similar to the flat buffer format that Google has created.</p>
<p>The major difference is flatbuffers do not need a parsing or an unpacking step to a secondary representation, before you can access the data.</p>
<p>And the code essentially is also larger in case of protocol buffers.</p>
<p>It is your while using TF lite, we make use a flat buffer format, and not protocol buffer format.</p>
<p>So now let's move forward.</p>
<p>So far, we've looked at various aspects of edge computing, we've looked at how deploying models on edge devices is better as compared to deploying it on Cloud.</p>
<p>We've also looked at what TensorFlow light is, and what all it can support at this point of time.</p>
<p>Now is where things would get interesting when I show you through code, how TF light can actually compress your model size without compromising on the accuracy piece.</p>
<p>So now let's go forward and witness the magic of TF light.</p>
<p>Now that we've understood the basics of TensorFlow light, and edge computing, let me show you the power of TensorFlow light using Python.</p>
<p>So for this example, I'm using Google collab.</p>
<p>For those of you who don't know, Google lab is an online environment wherein you can write Python code, you can create machine learning and deep learning models, you can also make use of deep learning models that Google gives you access to for good amount of time.</p>
<p>So this is the interface that I'll be using.</p>
<p>I'll be attaching the link to the GitHub repository in the description section of the video, feel free to access the code from there.</p>
<p>Also inside the GitHub repository.</p>
<p>I'll also give you a link that can open a Google collab notebook directly.</p>
<p>With all the groundwork done, let me now go forward and show you the magic of TensorFlow light.</p>
<p>So the process that I'll follow in this particular tutorial, is I'll create a deep learning model using TensorFlow slash Eros.</p>
<p>I will scale it down to a TF light equivalent model.</p>
<p>Once that is accomplished, I will show you the size difference between the original model as well as the compression model.</p>
<p>I will show you techniques how you can keep compressing the model even further without having to compromise on the accuracy piece.</p>
<p>With that, let me create an instance on Google collab by pressing Connect.</p>
<p>So currently, Google is allocating some space for my computations.</p>
<p>If you're planning to replicate the entire thing that I show in today's video in your local machine, then you will require some set of installations as well.</p>
<p>Given that I'm working with Google collab, all the dependencies that I require for this example are already met.</p>
<p>So now let me go through the different things that are required for this entire tutorial.</p>
<p>First things first, I require the voice module to essentially read my files.</p>
<p>Next up, I'll import NumPy as NP I will require this particular library for mathematical operations.</p>
<p>I will also require h5 p y library.</p>
<p>The h5 p vi library is a pythonic interface to the HD f5 binary data format.</p>
<p>So technically, whatever models I create in chaos, I will basically save it into the h5 format.</p>
<p>Next up, I require matplotlib.</p>
<p>This is again used for visualization.</p>
<p>I require TensorFlow, I'll import kiraz.</p>
<p>From TensorFlow.</p>
<p>These are some of the layers that will require when we come to the deep learning model creation aspect.</p>
<p>If I want to calculate how good my model is performing in terms of accuracy score, this is where SK learn dot matrix module will give me the accuracy score functionality.</p>
<p>And from the system library, I'll also require the function get size of.</p>
<p>So these are some of the things that I require in order to create a TF like model.</p>
<p>So now, let me go forward and run the cell.</p>
<p>So when I run the cell, what essentially happens is Python essentially runs that piece of code.</p>
<p>So let me now go forward and run the cell.</p>
<p>So I don't see any error.</p>
<p>That means all of our imports are in place.</p>
<p>Let me go forward and show you the TensorFlow version that I'm using for this particular tutorial.</p>
<p>I'm currently using TensorFlow 2.6 point zero.</p>
<p>If there are changes that creep up with respect to the API.</p>
<p>Feel free to refer to the TensorFlow documentation.</p>
<p>There are two functions that have created the first function name is get underscore file underscore size.</p>
<p>Essentially, I'm passing in the file location using the OAS library and specifically the function get size, I'm able to get the size of a particular file that I pass in, in byte so let me now go forward and run this cell.</p>
<p>In the previous function, that is get underscore file underscore size, the value returned would be in bytes.</p>
<p>So now rather than comprehending the values of a file size in byte, I've created a helper function called as convert underscore bytes, which essentially takes in the input size in bytes and converts it in either KB MB.</p>
<p>So this is something that I've created.</p>
<p>I've not included DBS because so this is more of an explainer video wherein I intend to create a smaller model or rather a proof of concept rather than like a huge model.</p>
<p>So that is why I have restricted my units to cavies or MDS.</p>
<p>So let me go forward and run the sale.</p>
<p>Now for this particular example, I'll be basically using a very famous data set and deep learning, Carla's fashion m&amp;s data set, so let me unhide the cell so fashion emnes data set contains 70,000 grayscale images, which belong to 10 different categories.</p>
<p>So categories would include the shirt, trouser, pullover, dress, code, sandal, shirt, sneaker bike, and ankle boot.</p>
<p>So these are the different categories that are part of this data set.</p>
<p>The entire activity is a supervised learning task, I will have a set of images, and every image will have a label associated with it.</p>
<p>And I'm trying to train a deep learning model.</p>
<p>So now let me go forward.</p>
<p>So you don't have to worry about the download pieces.</p>
<p>Well, if you have installed TensorFlow correctly, then essentially you just have to call the chaos dot data set dot fashion amnesty function, save the entire data set into a variable called as fashion underscore m nest.</p>
<p>So that is the first step that I've done here.</p>
<p>Once you've done that, then essentially what you have to do next is you have to split your data set into training and testing.</p>
<p>The way you can achieve that is ideally by calling a function called as load underscore data.</p>
<p>So this is what you have in terms of the function.</p>
<p>Once you call this function from fashion underscore m nished, the variable that you just created, you would be able to split your data into training images, training labels, st images, and test labels.</p>
<p>So that's how simple it is.</p>
<p>So let me go forward and run the cell.</p>
<p>So we've downloaded the data files, we've split our data into training and testing.</p>
<p>I've also created a variable, a list variable, called as class underscore names, which contains all the names of the classes that are part of this entire activity.</p>
<p>So let me go forward and run the cell.</p>
<p>So if you recollect, we had 70,000 samples in our data set, we've already split that entire data set into training and testing.</p>
<p>So let me go forward and show you how many images are part of the training data set.</p>
<p>So let me run this cell.</p>
<p>So the shape of my training data set is 60,000 comma 28, comma 28.</p>
<p>So I have 60,000 images.</p>
<p>Each image has a size of 28 cross 28.</p>
<p>So 28 rows, 28 columns represent each image, and I have 60,000 such images.</p>
<p>Given this is a supervised learning task, I would also require 60,000 labels.</p>
<p>So let me check if the total number of labels in my training data set are 60,000.</p>
<p>So let me run this cell.</p>
<p>So as you can clearly see, I have 60,000 labels as well.</p>
<p>Now given that, I've already mentioned that there are 10 unique classes, let me verify that as well.</p>
<p>So as you can clearly see I have class numbers ranging from zero to nine.</p>
<p>And the mapping is what I've created here, which is contained in the variable class underscore names.</p>
<p>Let's now go forward and explore that testing data set as well.</p>
<p>So let me quickly unhide this let me show you the total number of images in the testing data set.</p>
<p>So that come out to be 10,000 60,000 for training in 1000.</p>
<p>For testing, each image is again of the size 28 cross 28.</p>
<p>Similarly, if I look at test underscore labels, I'll have 10,000 samples.</p>
<p>What I intend to show you next is I want to show you a sample image.</p>
<p>So let me show that to you.</p>
<p>So this is a sample image that is part of this data set.</p>
<p>This is clearly an ankle boot.</p>
<p>The size of the image is 28 cross 28.</p>
<p>So 28 rows 28 columns is what you see here.</p>
<p>Before we go forward and train a neural network, a good practice is to scale In the intensity values of the images, which range between zero to 255, zero to one.</p>
<p>So that is what I have done in this piece of code.</p>
<p>So let me run this.</p>
<p>So now my train images will have values ranging from zero to one, and not zero to 255.</p>
<p>So far, we've downloaded the data set, we've split our data set into training and testing.</p>
<p>And we've done some sort of pre processing as well, now is the time when we'll create a simple neural network that 10 classify the entire images into one of the 10 categories that are there.</p>
<p>So in this piece of code, I'm calling the sequential class from the chaos library.</p>
<p>I'm passing in the first layer as a flattened layer.</p>
<p>Now, if you recollect, the images were 28 cross 28.</p>
<p>If I have to pass it through a layer, then I have to basically flatten it first, I am not creating a convolutional neural network given that the data set is fairly simple, I will stick to a normal deep neural network.</p>
<p>So the first layer that I add is a flattened layer, wherein I pass the input shape, which is 28, comma 28.</p>
<p>The second layer is the dense layer.</p>
<p>And the activations supplied to this dense layer is relu.</p>
<p>The final layer is again a dense layer, given that I have 10 different classes to classify between.</p>
<p>So that is what I have here.</p>
<p>So let me quickly create an instance of the model.</p>
<p>So let me run this.</p>
<p>Before we go forward and compile the model, I'll show you the structure of the model as well.</p>
<p>So I'll say model dot summary.</p>
<p>So this essentially is the model summary.</p>
<p>So for the given architecture, we have close to 100k trainable parameters.</p>
<p>Now the next step is to compile the model.</p>
<p>I'm passing in the optimizer, I am passing in this past categorical cross entropy loss.</p>
<p>Given that our classes are mutually exclusive, I'm using the sparse categorical cross entropy loss as compared to the normal categorical cross entropy loss.</p>
<p>And the matrix attend casing for his accuracy.</p>
<p>So I want to create a model that is fairly accurate.</p>
<p>So let me now go forward and run the cell.</p>
<p>So I've created an instance of the model.</p>
<p>I've also compiled the model, now is the time when I'll pass in the training images as well as the training labels to train the entire trainable parameters.</p>
<p>So let me now call the model dot fit function, wherein I'll be passing in the train images, train labels, and I kind of run the entire exercise for 10 epochs.</p>
<p>So let me run the cell.</p>
<p>So with every epoch, you can see that the accuracy is increasing.</p>
<p>So we've successfully trained our model and we've reached a training accuracy score of around 91%, which is Something that's reasonably good given that I've trained the model for only 10 epochs.</p>
<p>So let's go forward.</p>
<p>And remember one thing, the objective of the video is not to train the most accurate classifier at this point of time, but to show you the power of TF light, so that is why I've kind of stopped at 10 a box.</p>
<p>Now the next thing that I do is I create a variable called SK Ross underscore model underscore name.</p>
<p>This is something that will be used as reference, or this will be the baseline model performance that I evaluate later on with the TF light models as well.</p>
<p>So the name of this particular variable is pf underscore model, underscore fashion underscore m NIST dot h phi.</p>
<p>So let me quickly run the cell.</p>
<p>Now let me go forward and call the model dot save function and pass in the filename that I just created.</p>
<p>So let me run the cell.</p>
<p>So as soon as you run the cell, you would have a file that would be created in your Google collab session or in your local directory, which is essentially your saved model file.</p>
<p>So let me show that is well.</p>
<p>So this is our saved model file that has been created.</p>
<p>So let me quickly and I the cell again.</p>
<p>Now I'll go forward, and I'll show you the size of this particular file that we've created.</p>
<p>So let me call the two functions that I've created, that is convert underscore bytes, and get underscore file underscore size, I pass in the same file name, and I want the file size to be in MB.</p>
<p>So let me run the cell.</p>
<p>So currently, I have a model that occupies 1.2 Mb.</p>
<p>So I'll go forward and I'll create a variable called SK Ross underscore model, underscore size, and save the byte equivalent size into this particular variable.</p>
<p>So let me run the cell.</p>
<p>We know for a fact that the model is performing really well on the training data set.</p>
<p>But then essential litmus test is to check how well the model is performing on unseen data that is my testing data set.</p>
<p>So let me go forward and evaluate how good our model performances on their testing data set.</p>
<p>So I call the function model dot evaluate, I pass in the test images, test labels.</p>
<p>And I save the results into two variables called test underscore loss, and test underscore accuracy.</p>
<p>So let me quickly run the cell.</p>
<p>So as you can clearly see, the loss is at a very small value, which is around point three, seven.</p>
<p>And I've reached a testing accuracy score of around 88%.</p>
<p>So we've completed the first part, now it's time to move on to the next part that is creating a TF light equivalent of the same model.</p>
<p>So let's go forward.</p>
<p>So I start the activity by creating a variable called as TF underscore light underscore model underscore file underscore name.</p>
<p>And I pass in an equivalent name to this particular TF light model, which in our case, currently is TF underscore light underscore model.tf light.</p>
<p>So let me quickly run the cell.</p>
<p>Now the process of converting a TensorFlow model or a karass model into a TF light model, essentially requires just a couple of steps.</p>
<p>So this is what I'll highlight right now.</p>
<p>So the first step is to call tf.light.tf light converter dot from Kara's underscore model, I pass in the model that I created.</p>
<p>So if you remember the name of the model variable was essentially model so that is what I'm passing in here in the first line.</p>
<p>Once I've created an instance of the TF light converter from Eros MADI, I save the entire piece into a variable called as TF underscore light underscore converter.</p>
<p>And finally, what I do next is I call the Convert function.</p>
<p>Once the conversion happens, I want the result to be saved into a variable called as TF light underscore model.</p>
<p>So let me quickly run the cell.</p>
<p>So if you look at the output, it says that assets are written into a particular temporary file.</p>
<p>So from that temporary file, I basically have to retrieve the model weights and save it into a TF light equivalent file.</p>
<p>So that is what I've done using this piece of code.</p>
<p>I've created the first variable which is TF light underscore module underscore name.</p>
<p>And I'm passing in the initial name that I've created in the first line of this particular section.</p>
<p>I open the file name with write access, and I write this particular temporary file into this file that I've created.</p>
<p>So that's how simple it is.</p>
<p>So let me quickly run this.</p>
<p>So there is a particular output that is displayed.</p>
<p>This tells me the total number of bytes that have been returned to this particular file.</p>
<p>Now let me go forward and show you the exact size of this TF lite model in kilobytes.</p>
<p>So let me run this.</p>
<p>So the overall file size is close to 400 kilobytes.</p>
<p>So we started off with a model which was occupying around 1.2 Mb.</p>
<p>And after just running a couple of lines of code, we have brought down the file size to around 400 kb.</p>
<p>Now, let me go forward and save this file size into a variable called s TF light underscore file underscore size.</p>
<p>This is something that will make a lot of sense once we go forward.</p>
<p>So let me quickly run this L.</p>
<p>Now we've already converted a model from kiraz to tf light.</p>
<p>But one thing that we've not validated currently is how good the model is in terms of performance.</p>
<p>Is it actually good on unseen data? Or has it dropped in terms of the accuracy score.</p>
<p>So that is what I want to check next, that after compressing the model using TF light, are we losing out on accuracy or not.</p>
<p>So in this section, I'll go over how you can validate the results in terms of how good your TF light model is performing.</p>
<p>So now, let me quickly unhide the cell.</p>
<p>Now, don't get scared by looking at this piece of code, I'll help you understand what I'm trying to achieve.</p>
<p>You're now loading a model, or TensorFlow or a karass model into a TensorFlow session is fairly easy.</p>
<p>But here, what we have done is we've kind of created a TF light model.</p>
<p>If you go back to the discussion that we had, TF led models are essentially flat buffer format files and not your normal usual protocol buffer files.</p>
<p>So in order for us to actually make an inference out of TF light files on our TensorFlow or a Python session, we require something called as an interpreter.</p>
<p>So it is your that will be basically making use of tensor flows interpreter to load the TF light file, and then make inferences or predictions.</p>
<p>So let me now take you through each and every line of code.</p>
<p>So in the first line, I create an instance of the interpreter class, I pass in the TF light model name that we've just created.</p>
<p>So if you look at this particular section, you will also have a TF lite file.</p>
<p>This is what I'm passing in here.</p>
<p>Now once we've created the interpreter object, the interpreter object saves details about the model.</p>
<p>It will have details about the input that it expects the value that type of values it expects, and in terms of the output, it will tell you what the shape of the output should be.</p>
<p>In terms of the output, it will tell you the output shape as well as the output the type that is the output values, it will predict what are the values and what are the type of values.</p>
<p>So all of that is what this particular interpreter will actually have details about.</p>
<p>The details it is fetching is again from the interpreter object that we created and we passed in the TF lite file.</p>
<p>So all of the details would be captured in this particular TF lite file, which is what is read by this interpreter object.</p>
<p>And that is what we are trying to accumulate from input underscore details and output underscore details.</p>
<p>Once we have the input and output details, I also am interested in the shape of the input that is expected and that type of inputs are the variable nature of the inputs that are there.</p>
<p>So let me quickly run this cell to make more sense.</p>
<p>So if you look closely, the input shape is 128 28.</p>
<p>The input type that it expects is NumPy, float 32 the output shape is one comma 10 that is one so basically has one row and 10 columns and the output type is again NumPy float 32.</p>
<p>So this is essentially what the TF lite file contains.</p>
<p>Now if you look at this particular one, this denotes that the A flight is expecting one input at a time.</p>
<p>Now I want to check how good it is performing for 10,000 inputs.</p>
<p>That is where I'll have to reshape the input shape to a particular value, which is what I'll be achieving in this piece of code.</p>
<p>Just to reiterate, again, the input shape is 128 28.</p>
<p>So ideally, I have to pass in just one image sample.</p>
<p>And essentially, I would get a corresponding output for it.</p>
<p>But essentially, in my use case, I want to validate how good the TF light model is performing for the testing data set that I have, which essentially contains 10,000 images.</p>
<p>So if this idea is clear to you, let's go forward.</p>
<p>So now I want to validate how good my TF light model is performing on my testing data set.</p>
<p>So I call the resize underscore tensor underscore input function.</p>
<p>I pass in the details that I want to resize this particular index value, and I pass in how I have to resize it.</p>
<p>So currently, I have 10,000 samples.</p>
<p>So that is what I have entered here, that is 10,000 comma 28, comma 28.</p>
<p>Similar resize operation is what I'm doing at the output side.</p>
<p>So you can see your 10,000 comma 10, from the initial one comma 10.</p>
<p>So that is what I've done here.</p>
<p>Now, once the resize operation has happened, I want to call the allocate tensors.</p>
<p>to actually change the entire structure of the interpreter.</p>
<p>This is what it's read using the TF light file.</p>
<p>And now when I print the input details and output details, I should be able to see that the entire TF light input output values have changed.</p>
<p>So let me quickly run this piece of code.</p>
<p>So as you can clearly see, the input shape has changed from 128 28 to 10,028 28.</p>
<p>So this essentially will help me to validate how good my TF light model is performing.</p>
<p>The other thing that I want to highlight right now is s underscore images dot d type is float 64.</p>
<p>So if you look at the input shape that the model expects is NumPy dot float 32.</p>
<p>So now the only other change that I have to make in order to validate my TF light model is I have to create a new array called as test underscore images underscore NumPy.</p>
<p>Pass in the original array, and change the D type.</p>
<p>I can do it in the same area as well.</p>
<p>But I'm essentially choosing to create two different arrays.</p>
<p>So let me quickly run the cell.</p>
<p>So now if I show you the D type of test underscore images dot NumPy, it will be NumPy float 32.</p>
<p>Now that we have the entire interpreter object set up correctly for our set of inputs, that is the testing data set.</p>
<p>All I have to do right now is firstly call the set underscore tensor function, passing the test underscore images underscore NumPy array that I just created and call the invoke function.</p>
<p>What the invoke function would essentially do is pass in the inputs, get the output.</p>
<p>And once you have the output ready, you call the get underscore Insert Function, which will kind of have the output ready for you and save it into a variable called as TF slide underscore model underscore predictions.</p>
<p>So let me quickly run the cell.</p>
<p>Now the output that you see here, which is prediction results shape is 10,000 rows and 10 columns.</p>
<p>So every column would essentially contain a probability score.</p>
<p>So what I have to do next is I have to pick out the value or the index between zero to nine that has the maximum probability, which is what I've done using this function called as NP dot arg max.</p>
<p>So this will help me get numbers directly that is zero to nine rather than having 10 different columns with probability scores.</p>
<p>Now let me calculate the accuracy score.</p>
<p>And let me print it out for you.</p>
<p>So the testing accuracy of the TF light model is exactly the same that you see when you compare it with your normal karass model.</p>
<p>Now how much of space Have you saved in this entire process? says, Mel let me calculate a ratio between TF lite file size and karass model file size.</p>
<p>So overall, the TF lite model occupies close to 32% of the overall file size that my normal karass model occupies.</p>
<p>But the uniqueness is that I'm not losing out on any accuracy.</p>
<p>So this is the power of TF Lite.</p>
<p>I've been able to compress my entire model from 1.2 Mb to around 400 kb.</p>
<p>And I haven't yet compromised a bit on the accuracy pieces.</p>
<p>Well, Isn't this amazing? Well, if you think the story is ended here, hang on for a second, there is more to go.</p>
<p>So far, what we've done is I've taken a TensorFlow model.</p>
<p>And without any optimization, I've basically converted that into an equivalent TF light model.</p>
<p>Now I'll show you how you can compress your model even further.</p>
<p>without losing out on accuracy as such.</p>
<p>So now let me introduce you to a new concept called les quantization.</p>
<p>So what exactly is this term that I've just mentioned, that is quantization.</p>
<p>So for a given weight value that can be represented in float 32 or float 64 format? Wouldn't it be great if we can bring down the size of those particular values and see very little change in accuracy? Well, this essentially is the concept of quantization, I'm reducing the total number of bits for every weight value, so that the overall size of the entire array reduces.</p>
<p>Just to be more clear, if I have a neural network something like this, where this particular weight value is 5.31345, this particular weight value is 3.8958.</p>
<p>And you have the other way values is well, what if I can change these representations that occupies so many bits to something like this, there will be a small hit in the accuracy.</p>
<p>But overall, I'll be able to compress my model even further.</p>
<p>How when whatever questions you have in mind, just wait for some time.</p>
<p>If this entire idea is clear to you, let us go back to the coding section.</p>
<p>And I'll show you how you can compress your TF light model even further.</p>
<p>So by default, in the previous example, wherein we took a karass model, and we converted that to a TF light model, every weight value is essentially float 32 format.</p>
<p>Wouldn't it be great if I compress it from float 32 to float 16.</p>
<p>This is the activity that I'll be performing next.</p>
<p>So I create a variable with an MTF underscore light underscore model underscore float underscore 16 underscore file underscore name.</p>
<p>And I basically give it a TF lightning which essentially represents that the entire weights inside it would be fluid 16.</p>
<p>So that is what I have here.</p>
<p>So let me quickly run the cell.</p>
<p>If you look at the previous section in terms of how we created a TF light model, the first line of code is something that is pretty much familiar to you, you pass in your karass model, you call the TF light converter dot from kiraz model, and you save it into a variable.</p>
<p>Even the last piece of code is also something that you've already looked at.</p>
<p>What you haven't seen so far is the optimization.</p>
<p>So when you create an instance of the TF light converter, there is a flag called as optimizations.</p>
<p>So you have the optimizations flag here.</p>
<p>I set it to tf dot light dot optimizer default, so I want the default optimizations to take place.</p>
<p>And one other things that I do here.</p>
<p>So I'll speak more about the optimizations in the next section.</p>
<p>So hold on to that thought as well.</p>
<p>Now here there is one more flag called as target underscore spec, and supported underscore types.</p>
<p>Here is where I set every weight value from floor 32 to float 16.</p>
<p>So that is what I'm doing here.</p>
<p>So let me quickly run this piece of code.</p>
<p>So now I have a TF light model, wherein every weight value would be a float 64 Automat, I follow the same process again, wherein I'm fetching data from the temporary file and saving it into a TF lite model.</p>
<p>So let me run this.</p>
<p>I don't know if you've guessed it already or not.</p>
<p>This essentially is a file size in bytes for the newly converted a flight model.</p>
<p>So if I now show you the size of this newly converted TF flight model, then my size has drastically reduced from 400 kilobytes to 200 kilobytes.</p>
<p>The only thing that I changed here was I changed the individual representation of every made value that's about it.</p>
<p>Isn't this amazing, I'm able to save so much of memory, just by changing few values here and there.</p>
<p>Say again, save the file size into a variable called as TF lite underscore float underscore 16 underscore file underscore size.</p>
<p>So let me run this.</p>
<p>Now if I compare it to the original karass model, this particular model occupies 16% of the size that the original model occupied.</p>
<p>And if I compare it to the previously created version, then I can see almost 50% compression that I'm able to achieve by changing the weights from floor 32 to floor 16.</p>
<p>So this is the power of optimizations and TF light.</p>
<p>If you think this is it weird for the next section, wherein I compress the model even further.</p>
<p>I'm not showing you the accuracy piece right now you might be wondering, why isn't he showing us the accuracy has accuracy taken a toss? Well, the answer is no.</p>
<p>I show you the accuracy of an even compress model.</p>
<p>So that will give you a fair sense in terms of how much compression is changing the overall accuracy values as well.</p>
<p>Okay.</p>
<p>So now we have reached the final section wherein I will compress the model even further.</p>
<p>Okay, so here I've created a variable called as TF underscore light, underscore size, underscore current underscore model, underscore file underscore name.</p>
<p>And here I want to see what the eflite file with this particular name.</p>
<p>So I'll quickly run the cell.</p>
<p>In the previous example, I changed every weight value from floor 32, to floor 16.</p>
<p>Rather than you deciding what is good for your model, I would rather let TF light decide that for me.</p>
<p>So if you've been following along so far, then this piece of code is something that we've already covered.</p>
<p>This piece of code is also something that we've already covered.</p>
<p>This is something that is unique.</p>
<p>So here, I set the optimizations fly.</p>
<p>And here I just mentioned, optimize for size, there are different values that you can kind of go through in the documentation.</p>
<p>So based on your needs, you can kind of optimize for size, and the other optimization that are also available for TF light.</p>
<p>So I'm not specifying what type of data type I want, I just want the most optimized version wherein the size that is occupied by this particular TF light model is the most compressed version.</p>
<p>Okay, so I'll quickly run the cell.</p>
<p>So I catch all of the file that is saved into a temporary variable, I save it into this particular variable that I created.</p>
<p>And if you've guessed by now, this is the new file size in bytes.</p>
<p>If I go to the kilobyte section, then my file occupies around 100 kb.</p>
<p>So if you remember, we started from 1.4 Mb, and we have brought down the file size of a deep neural network.</p>
<p>200 kilobytes.</p>
<p>Isn't this amazing.</p>
<p>Just to give you some numbers again, if I compare this particular file size with my original file size, then my current file is almost 8% the size of my original file, that is my karass model that I created.</p>
<p>If I compare it to the previous model as well, I'm basically able to achieve 50% compression, all because of optimizing for size.</p>
<p>This essentially is a power of TF light.</p>
<p>Now I'm really happy with the compression, I have a 1.4 Mb file that I've compressed down to around 100 kb.</p>
<p>But is the accuracy still the same? Well, we'll again follow the same process, wherein I load the newly quantized model into the interpreter object.</p>
<p>I'll get details of those objects, and I'll again reshape the values and pass it testing data set entirely through the interpreter object.</p>
<p>So I'll quickly run the cell.</p>
<p>So as you can clearly see, 128 28 is the interpreter object input values that it expects, I have the output as one comma 10.</p>
<p>The input and output values that are expected are NumPy, float 32.</p>
<p>So that is all good as well.</p>
<p>Coming to the final section, I follow the same process.</p>
<p>Again, no change in the process.</p>
<p>I have a testing data set of 10,000 images, which is what I pass in here.</p>
<p>I allocate tensors, I get the details, and I'll show the details to you as well.</p>
<p>So let me quickly run this 10,028 28 128 28.</p>
<p>So we've resized the tensor input values that we are expecting to validate our testing data set.</p>
<p>You essentially don't need the step again, but as kind of copy it from the initial part.</p>
<p>So I'm running it again.</p>
<p>I pass in the values again.</p>
<p>Now I calculate the accuracy score.</p>
<p>Now is the litmus test for this highly compressed TF light model.</p>
<p>So let me quickly run the cell.</p>
<p>So the accuracy of a TF lite model that occupies almost 8% of the size of the original karass model is equivalent to the original karass model.</p>
<p>If I go up, I'm recording this video in one go.</p>
<p>So if I go up where did this value go? here the value was at 7.66%.</p>
<p>Here it is at 87.59%.</p>
<p>So this is what you can achieve using TF Lite.</p>
<p>I started off with a very simple neural network, the entire model occupied around 1.2 Mb.</p>
<p>You might also argue that 1.2 Mb is kind of small.</p>
<p>But the problem statement was fairly simple.</p>
<p>If you have like a really complex example, wherein you have to classify images into 1000 or 10,000 categories, the model size would eventually increase.</p>
<p>So the objective then becomes can we compress the model size? And the answer is yes, TF lite will help you compress the model size without having to compromise any bit on the accuracy front.</p>
<p>If you've reached this point, then I'm assuming you've seen the entire video or if randomly reached at this point, whichever way you've reached this point.</p>
<p>I hope you enjoyed today's video, I keep creating such amazing videos on data science, machine learning, and Python.</p>
<p>So feel free to check out my channel in the description section of the video as well.</p>
<p>Thank you so much for watching this video. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ TensorFlow for Computer Vision – Full Course on Python for Machine Learning ]]>
                </title>
                <description>
                    <![CDATA[ TensorFlow can do some amazing things when it comes to computer vision. We just published a full course on the freeCodeCamp.org YouTube channel that will teach you how to use TensorFlow 2 for computer vision applications. Nour Islam Mokhtari created ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-tensorflow-for-computer-vision/</link>
                <guid isPermaLink="false">66b2037127569435a9255acb</guid>
                
                    <category>
                        <![CDATA[ Computer Vision ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 05 Oct 2021 15:07:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/tf-vision.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>TensorFlow can do some amazing things when it comes to computer vision.</p>
<p>We just published a full course on the freeCodeCamp.org YouTube channel that will teach you how to use TensorFlow 2 for computer vision applications.</p>
<p>Nour Islam Mokhtari created this course. Nour is a Machine Learning Engineer and experienced teacher.</p>
<p>The course shows you how to create two computer vision projects. The first involves an image classification model with a prepared dataset. The second is a more real-world problem where you will have to clean and prepare a dataset before using it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/image-26.png" alt="Image" width="600" height="400" loading="lazy">
<em>MNIST Dataset with labels</em></p>
<p>Here are the topics covered in this course:</p>
<ul>
<li>Why learn Tensorflow</li>
<li>We will be using an IDE and not notebooks</li>
<li>Visual Studio Code (how to download and install it)</li>
<li>Miniconda - how to install it</li>
<li>Miniconda - why we need it</li>
<li>How are we going to use conda virtual environments in VS Code?</li>
<li>Installing Tensorflow 2 (CPU version)</li>
<li>Installing Tensorflow 2 (GPU version)</li>
<li>What do we want to achieve?</li>
<li>Exploring MNIST dataset</li>
<li>Tensorflow layers</li>
<li>Building a neural network the sequential way</li>
<li>Compiling the model and fitting the data</li>
<li>Building a neural network the functional way</li>
<li>Building a neural network the Model Class way</li>
<li>Things we should add</li>
<li>Restructuring our code for better readability</li>
<li>First part summary</li>
<li>What we want to achieve</li>
<li>Downloading and exploring the dataset</li>
<li>Preparing train and validation sets</li>
<li>Preparing the test set</li>
<li>Building a neural network the functional way</li>
<li>Creating data generators</li>
<li>Instantiating the generators</li>
<li>Compiling the model and fitting the data</li>
<li>Adding callbacks</li>
<li>Evaluating the model</li>
<li>Potential improvements</li>
<li>Running prediction on single images</li>
</ul>
<p>Watch the full course below or <a target="_blank" href="https://youtu.be/cPmjQ9V6Hbk">on the freeCodeCamp.org YouTube channel</a> (4.5-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/cPmjQ9V6Hbk" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Deep Learning Frameworks Compared: MxNet vs TensorFlow vs DL4j vs PyTorch ]]>
                </title>
                <description>
                    <![CDATA[ It's a great time to be a deep learning engineer. In this article, we will go through some of the popular deep learning frameworks like Tensorflow and CNTK so you can choose which one is best for your project. Deep Learning is a branch of Machine Lea... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/deep-learning-frameworks-compared-mxnet-vs-tensorflow-vs-dl4j-vs-pytorch/</link>
                <guid isPermaLink="false">66d035ba12c679876b0602d9</guid>
                
                    <category>
                        <![CDATA[ Deep Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pytorch ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Tue, 29 Sep 2020 15:22:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/09/wall-3.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>It's a great time to be a deep learning engineer. In this article, we will go through some of the popular deep learning frameworks like Tensorflow and CNTK so you can choose which one is best for your project.</p>
<p>Deep Learning is a branch of <a target="_blank" href="https://www.sas.com/en_in/insights/analytics/machine-learning.html">Machine Learning</a>. Though machine learning has various algorithms, the most powerful are neural networks. </p>
<p>Deep learning is the technique of building complex multi-layered neural networks. This helps us solve tough problems like image recognition, language translation, self-driving car technology, and more.</p>
<p>There are tons of real-world applications of deep learning from self-driving Tesla cars to AI assistants like Siri. To build these neural networks, we use different frameworks like Tensorflow, CNTK, and MxNet. </p>
<p>If you are new to deep learning, <a target="_blank" href="https://www.coursera.org/specializations/deep-learning">start here</a> for a good overview.</p>
<h1 id="heading-frameworks">Frameworks</h1>
<p>Without the right framework, constructing quality neural networks can be hard. With the right framework, you only have to worry about getting your hands on the right data. </p>
<p>That doesn’t imply that knowledge of the deep learning frameworks alone is enough to make you a successful data scientist.</p>
<p><em>You need a strong foundation of the fundamental concepts to be a successful deep learning engineer.</em> But the right framework will make your life easier.</p>
<p>Also, not all programming languages have their own machine learning / deep learning frameworks. This is because not all programming languages have the capacity to handle machine learning problems. </p>
<p>Languages like Python stand out among others due to their complex data processing capability.</p>
<p>Let's go through some of the popular deep learning frameworks in use today. Each one comes with its own set of advantages and limitations. It is important to have at least a basic understanding of these frameworks so you can choose the right one for your organization or project.</p>
<h1 id="heading-tensorflow">TensorFlow</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/tensorflow.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>TensorFlow is the most famous deep learning library around. If you are a data scientist, you probably started with Tensorflow. It is one of the most efficient open-source libraries to work with. </p>
<p>Google built TensorFlow to use as an internal deep learning tool before open-sourcing it. TensorFlow powers a lot of useful applications including Uber, Dropbox, and Airbnb.</p>
<h3 id="heading-advantages-of-tensorflow">Advantages of Tensorflow</h3>
<ul>
<li>User Friendly. Easy to learn if you are familiar with Python.</li>
<li><a target="_blank" href="https://www.tensorflow.org/tensorboard">Tensorboard</a> for monitoring and visualization. It is a great tool if you want to see your deep learning models in action.</li>
<li>Community support. Experts engineers from Google and other companies improve TensorFlow almost on a daily basis.</li>
<li>You can use TensorFlow Lite to run TensorFlow models on mobile devices.</li>
<li><a target="_blank" href="https://www.tensorflow.org/js">Tensorflow.js</a> lets you to run real-time deep learning models in the browser using JavaScript.</li>
</ul>
<h3 id="heading-limitations-of-tensorflow">Limitations of Tensorflow</h3>
<ul>
<li>TensorFlow is a bit slow compared to frameworks like MxNet and CNTK.</li>
<li>Debugging can be challenging.</li>
<li>No support for <a target="_blank" href="https://en.wikipedia.org/wiki/OpenCL">OpenCL</a>.</li>
</ul>
<h1 id="heading-apache-mxnet">Apache MXNet</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/mxnet.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>MXNet is another popular Deep Learning framework. Founded by the <a target="_blank" href="https://www.apache.org/">Apache Software Foundation</a>, MXNet supports a wide range of languages like JavaScript, Python, and C++. MXNet is also supported by Amazon Web Services to build deep learning models. </p>
<p>MXNet is a computationally efficient framework used in business as well as in academia.</p>
<h3 id="heading-advantages-of-apache-mxnet">Advantages of Apache MXNet</h3>
<ul>
<li>Efficient, scalable, and fast.</li>
<li>Supported by all major platforms.</li>
<li>Provides GPU support, along with multi-GPU mode.</li>
<li>Support for programming languages like Scala, R, Python, C++, and JavaScript.</li>
<li>Easy model serving and high-performance API.</li>
</ul>
<h3 id="heading-disadvantages-of-apache-mxnet">Disadvantages of Apache MXNet</h3>
<ul>
<li>Compared to TensorFlow, MXNet has a smaller open source community.</li>
<li>Improvements, bug fixes, and other features take longer due to a lack of major community support.</li>
<li>Despite being widely used by many organizations in the tech industry, MxNet is not as popular as Tensorflow.</li>
</ul>
<h1 id="heading-microsoft-cntk">Microsoft CNTK</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/cntk-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Large companies usually use Microsoft Cognitive Toolkit (CNTK) to build deep learning models. </p>
<p>Though created by Microsoft, CNTK is an open-source framework. It illustrates neural networks in the form of directed graphs by using a sequence of computational steps. </p>
<p>CNTK is written using C++, but it supports various languages like C#, Python, C++, and Java.</p>
<p>Microsoft’s backing is an advantage for CNTK since Windows is the preferred operating system for enterprises. CNTK is also heavily used in the Microsoft ecosystem. </p>
<p>Popular products that use CNTK are Xbox, Cortana, and Skype.</p>
<h3 id="heading-advantages-of-microsoft-cntk">Advantages of Microsoft CNTK</h3>
<ul>
<li>Offers reliable and excellent performance.</li>
<li>The scalability of CNTK has made it a popular choice in many enterprises.</li>
<li>Has numerous optimized components.</li>
<li>Easy to integrate with <a target="_blank" href="https://spark.apache.org/">Apache Spark</a>, an analytics engine for data processing.</li>
<li>Works well with Azure Cloud, both being backed by Microsoft.</li>
<li>Resource usage and management are efficient.</li>
</ul>
<h3 id="heading-disadvantages-of-microsoft-cntk">Disadvantages of Microsoft CNTK</h3>
<ul>
<li>Minimal community support compared to Tensorflow, but has a dedicated team of Microsoft engineers working full time on it.</li>
<li>Significant learning curve.</li>
</ul>
<h1 id="heading-pytorch">PyTorch</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/pytorch.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>PyTorch is another popular deep learning framework. <a target="_blank" href="https://ai.facebook.com/">Facebook developed Pytorch</a> in its AI research lab (FAIR). Pytorch has been giving tough competition to Google’s Tensorflow.</p>
<p>Pytorch supports both Python and C++ to build deep learning models. Released three years ago, it's already being used by companies like Salesforce, Facebook, and Twitter.</p>
<p>Image Recognition, Natural Language Processing, and Reinforcement Learning are some of the many areas in which PyTorch shines. It is also used in research by universities like Oxford and organizations like IBM.</p>
<p>PyTorch is also a great choice for creating computational graphs. It also supports cloud software development and offers useful features, tools, and libraries. And it works well with cloud platforms like AWS and Azure.</p>
<h3 id="heading-advantages-of-pytorch">Advantages of PyTorch</h3>
<ul>
<li>User-friendly design and structure that makes constructing deep learning models transparent.</li>
<li>Has useful debugging tools like PyCharm debugger.</li>
<li>Contains many pre-trained models and supports distributed training.</li>
</ul>
<h3 id="heading-disadvantages-of-pytorch">Disadvantages of PyTorch</h3>
<ul>
<li>Does not have interfaces for monitoring and visualization like TensorFlow.</li>
<li>Comparatively, PyTorch is a new deep learning framework and currently has less community support.</li>
</ul>
<h1 id="heading-deeplearning4j">DeepLearning4j</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/dl4j.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>DeepLearning4j is an excellent framework if your main programming language is Java. It is a commercial-grade, open-source, distributed deep-learning library. </p>
<p>Deeplearning4j supports all major types of neural network architectures like RNNs and CNNs.</p>
<p>Deeplearning4j is written for Java and Scala. It also integrates well with Hadoop and Apache Spark. Deeplearning4j also has support for GPUs, making it a great choice for Java-based deep learning solutions.</p>
<h3 id="heading-advantages-of-deeplearning4j">Advantages of DeepLearning4j</h3>
<ul>
<li>Scalable and can easily process large amounts of data.</li>
<li>Easy integration with Apache Spark.</li>
<li>Excellent community support and documentation.</li>
</ul>
<h3 id="heading-disadvantages-of-deeplearning4j">Disadvantages of DeepLearning4j</h3>
<ul>
<li>Limited to the Java programming language.</li>
<li>Relatively less popular compared to Tensorflow and PyTorch.</li>
</ul>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Each framework comes with its list of pros and cons. But choosing the right framework is crucial to the success of a project. </p>
<p>You have to consider various factors like security, scalability, and performance. For enterprise-grade solutions, reliability becomes another primary contributing factor.</p>
<p>If you are just getting started, begin with Tensorflow. If you are building a Windows-based enterprise product, choose CNTK. If you prefer Java, choose DL4J.</p>
<p>I hope this article helps you choose the right deep learning framework for your next project. If you have any questions, reach out to me.</p>
<hr>
<p><em>Loved this article?</em> <a target="_blank" href="http://tinyletter.com/manishmshiva"><strong><em>Join my Newsletter</em></strong></a> <em>and get a summary of my articles and videos every Monday.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Pass the TensorFlow Developer Certificate Exam ]]>
                </title>
                <description>
                    <![CDATA[ On March 12, this year, the TensorFlow team introduced the TensorFlow Developer Certificate Exam. Cut to June 13, and I am TensorFlow Developer Certified. ✅ So what happened in this 3-month long gap? After honoring all my business and personal commit... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-i-passed-the-certified-tensorflow-developer-exam/</link>
                <guid isPermaLink="false">66d45f414a7504b7409c3419</guid>
                
                    <category>
                        <![CDATA[ Certification ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Google ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Harshit Tyagi ]]>
                </dc:creator>
                <pubDate>Wed, 24 Jun 2020 17:08:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/Fashion-Beauty-Lifestyle-Youtube-Channel-Art--1--1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>On March 12, this year, the TensorFlow team <a target="_blank" href="https://blog.tensorflow.org/2020/03/introducing-tensorflow-developer-certificate.html">introduced the TensorFlow</a> Developer Certificate Exam.</p>
<p>Cut to June 13, and I am TensorFlow Developer Certified. ✅</p>
<p>So what happened in this 3-month long gap?</p>
<p>After honoring all my business and personal commitments, I managed to take off one month to prepare for the exam. After studying all the details of the exam, I created a learning plan to get myself exam-ready in <em>14 days.</em>*</p>
<h3 id="heading-thats-all-cool-but-what-is-tensorflow">That’s all cool – but what is TensorFlow?</h3>
<p>The gist: <a target="_blank" href="https://www.tensorflow.org/">TensorFlow</a> is an end-to-end open-source machine learning platform. It has a comprehensive ecosystem of libraries, tools, and community resources that lets ML/AI Engineers, Scientists/Analysts build and deploy ML-powered applications.</p>
<p>Google, Airbnb, DeepMind, intel, Twitter, and many others are currently powered by TensorFlow and it helps them solve a wide gamut of problems.</p>
<p>Now, I am not a certification evangelist. But since I was already using and following TensorFlow so closely as a Data Science Enthusiast it got my attention.</p>
<p>It has been an amazing learning streak and I am here to share all the nitty-gritty details of <strong>what</strong> the program is, <strong>how I</strong> did it, and <strong>how you can</strong> do it too!</p>
<h1 id="heading-what-is-this-certificate-programhttpswwwtensorfloworgcertificate-about">What is this <a target="_blank" href="https://www.tensorflow.org/certificate"><strong>certificate program</strong></a> about?</h1>
<p>The certificate is an official validation confirming your proficiency with TensorFlow with respect to solving deep learning and ML problems in the AI-driven job market.</p>
<p>If you’re someone who has got the skills to develop those Deep Neural Networks and solve problems with it, you can take the exam to differentiate yourself with the certificate.</p>
<p><em>Oh, snap! Not another Certification Program…?</em></p>
<h1 id="heading-why-should-you-take-the-exam">Why should you take the exam?</h1>
<p>Firstly, this is not like the certification where you watch a few 2–3 minute-long video lectures and take a quiz of multiple-choice questions and get yourself certified. This will require you to code and solve a class of problems that you'll need to prepare for.</p>
<p>Secondly, how many times have you thought of mastering a new library or technique, and then abandoned your plans midway? If you're anything like me, 99% of the time.</p>
<p>For me, the certification worked as the destination for my learning journey. I had some experience using TensorFlow but this came in as a challenge to work on problems that I hadn't actually solved myself.</p>
<p>Thirdly, you should keep monitoring the technology space in your field at least. So here is a trend from <a target="_blank" href="https://insights.stackoverflow.com/trends?tags=tensorflow%2Cpytorch%2Cscikit-learn">StackOverflow</a> that shows how TensorFlow is being used by a huge number of users accounting for nearly 1 out of every 100 questions on the platform:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/stack_overflow.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Lastly, I feel that Google always provides value to its users/developers. I believe the way they have structured the exam makes it worth trying, as it validates your skillsets and adds weight to your profile.</p>
<p><em>OKAY! I’m sold, can you tell me what am I supposed to do in this exam?</em></p>
<h1 id="heading-exam-walkthrough">Exam Walkthrough</h1>
<p>The exam is an online performance-based test where you are provided with questions to solve by building TensorFlow models within a dedicated PyCharm environment.</p>
<p>You can take this exam from your computer that supports the <a target="_blank" href="https://www.jetbrains.com/help/pycharm/installation-guide.html">PyCharm IDE</a> requirements. You'll need a reliable internet connection, and you can take the exam at whatever time suits you (I started mine at midnight).</p>
<p>The exam tests your ability to solve problems like Image classification from real-world images, Natural Language Processing, and time series forecasting using <strong>Tensorflow 2.x</strong>.</p>
<p>You can take up to 5 hours for the exam. If you exceed the time limit, the exam will be auto-submitted and you will only be graded for the questions for which you have submitted and tested your model.</p>
<p>You are allowed to use whatever learning resources you would normally use during your ML development work.</p>
<p><strong>Exam Cost:</strong> Each attempt costs you $100 USD.</p>
<p><em>Ah</em>-hah_! so how did you prepare for this scary long exam?_</p>
<h1 id="heading-how-i-started-preparing-for-the-exam">How I started preparing for the Exam</h1>
<p>The first thing I did was spend a good amount of time studying the exam itself. The TensorFlow team provides you with this <a target="_blank" href="https://www.tensorflow.org/site-assets/downloads/marketing/cert/TF_Certificate_Candidate_Handbook.pdf"><strong>comprehensive handbook</strong></a> that tells you every detail about the exam and what skills you should master before taking it:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727764701825/d633d75e-d949-44b4-9130-bc24c6a46a6b.gif" alt="d633d75e-d949-44b4-9130-bc24c6a46a6b" class="image--center mx-auto" width="800" height="450" loading="lazy"></p>
<p>After studying the exam, I <strong>designed a curriculum</strong> for myself to cover every skillset that is mentioned in this handbook.</p>
<p>Next, I set myself up with <strong>a schedule</strong> so that my work engagements didn't push me off track and I prioritized learning for those ~20 days.</p>
<p>And that’s all – I started preparing for the exam using this curriculum comprised of these <a target="_blank" href="https://www.notion.so/15049893501f4387893a5de0059ef8a5?v=9154c52a61494668b12802f157bce0d4">recommended and useful resources:</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727764719002/1143ab77-8ec7-4221-98a0-60e44ea24ff9.png" alt="1143ab77-8ec7-4221-98a0-60e44ea24ff9" class="image--center mx-auto" width="1281" height="788" loading="lazy"></p>
<p><em>Link to my compilation of resources:</em> <a target="_blank" href="https://www.notion.so/15049893501f4387893a5de0059ef8a5?v=9154c52a61494668b12802f157bce0d4"><em>https://www.notion.so/15049893501f4387893a5de0059ef8a5?v=9154c52a61494668b12802f157bce0d4</em></a></p>
<h1 id="heading-imp-learning-curriculum-review-of-all-the-resources-i-used-to-pass-the-exam">[Imp]: Learning Curriculum — Review of all the resources I used to pass the exam</h1>
<p>For someone new to Tensorflow or Machine learning, the handbook might portray a terrifying picture. But having a plan and setting up a schedule will get you through. Here’s the curriculum that will prepare you well for the exam.</p>
<p>The Tensorflow team again did an amazing job of suggesting the resources based on your familiarity with Machine Learning. On top of that, I had been following a few books and playlists that helped me a great deal to cement the fundamentals in my brain and helped me go beyond the exam requirements themselves.</p>
<p>I have also reviewed all these resources that I used with a scoring scale of <strong>5</strong>, based off the following qualities:</p>
<ul>
<li><p>Usefulness — to pass the exam</p>
</li>
<li><p>Learning Value — might not have a direct effect on the exam results but will help you build a strong foundation and work on more complex problems.</p>
</li>
</ul>
<p>Here’s the list of resources along with the time and cost that each will incur:</p>
<h3 id="heading-1-courseras-tensorflow-in-practice-specializationhttpswwwcourseraorgspecializationstensorflow-in-practice">1. <a target="_blank" href="https://www.coursera.org/specializations/tensorflow-in-practice">Coursera’s TensorFlow in Practice Specialization</a></h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-12.15.16-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Usefulness: 5/5 —</strong> This is absolutely needed to score well (or even pass) on the exam. It will help you cover every skill mentioned on the skills checklist in the Handbook. This is the recommended course on the <a target="_blank" href="https://www.tensorflow.org/certificate">Certification home page</a>.</p>
<p>If you carefully study the skills checklist and then compare it with the course outline, you’ll be able to figure out the direct mapping of each skill. It looks like either the course was created with the certification exam in mind or vice versa.</p>
<p>The entire specialization contains 4 courses:</p>
<ul>
<li><p>Introduction to Machine Learning and Deep Learning.</p>
</li>
<li><p>Convolutional Neural Networks in TensorFlow</p>
</li>
<li><p>Natural Language Processing in TensorFlow</p>
</li>
<li><p>Sequence, Time series, and Prediction</p>
</li>
</ul>
<p><strong>Learning Value: 4/5 —</strong> The course itself depends on other resources to help you get an in-depth understanding of the fundamental concepts and topics that it uses. This is more of a Hands-On course.</p>
<p><strong>Time:</strong> It should take you 4–8 weeks depending on the amount of time you dedicate. I had prior experience with Image classification problems, and it took me 14 days to watch the entire specialization series and practice all the exercises they provide.</p>
<p><strong>Cost:</strong> This comes at a cost of $59 per month after a 7-day free trial. Totally worth it if you have to pay. The other resources provide a free alternative.</p>
<h3 id="heading-2-youtube-playlists-on-machine-learning-foundation-by-laurence-moroneyhttpswwwyoutubecomplaylistlistplou2xlyxmsii9mzq-xxug4l2o04jbrklv">2. <a target="_blank" href="https://www.youtube.com/playlist?list=PLOU2XLYxmsII9mzQ-Xxug4l2o04JBrkLV">YouTube Playlists on Machine Learning Foundation by Laurence Moroney</a></h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-1.08.17-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Usefulness: 4/5 —</strong> This is an alternative to the starting 2 courses in the TensorFlow specialization on the <a target="_blank" href="https://www.youtube.com/channel/UC_x5XG1OV2P6uZZ5FSM9Ttw?sub_confirmation=1">Google Developers YouTube channel.</a></p>
<p>There is a dedicated <a target="_blank" href="https://www.youtube.com/playlist?list=PLQY2H8rRoyvzDbLUZkbudP-MFQZwNmU4S">NLP zero to hero playlist</a> by the same author — Laurence Moroney.</p>
<p><strong>Learning Value: 3/5</strong> —Same as above but relies on other videos and resources in case you’re a beginner in Machine Learning.</p>
<p><strong>Time:</strong> 1-2 weeks per playlist if you’re dedicating like 3–4 hours daily to your preparation.</p>
<p><strong>Cost: Free</strong></p>
<h3 id="heading-3-hands-on-machine-learning-with-scikit-learn-keras-and-tensorflow-2nd-editionhttpslearningoreillycomlibraryviewhands-on-machine-learning9781492032632">3. <a target="_blank" href="https://learning.oreilly.com/library/view/hands-on-machine-learning/9781492032632/">Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition</a></h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-1.19.06-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Usefulness: 3/5</strong> — The score is because of its <strong>relevance to the exam</strong>. For beginners, this will be a foundational resource to understanding Machine Learning and then gradually diving into the depths of Deep Learning, TensorFlow, Computer Vision, CNNs, RNNs, and much more.</p>
<p><strong>Following are the</strong> most u<strong>seful chapters from the book:</strong></p>
<ul>
<li><p>Chapter 10 — Introduction to Artificial Neural Networks with Keras</p>
</li>
<li><p>Chapter 11 — Training Deep Neural Networks</p>
</li>
<li><p>Chapter 12 — Custom Models and Training with TensorFlow</p>
</li>
<li><p>Chapter 13 — Loading and Preprocessing Data with TensorFlow</p>
</li>
<li><p>Chapter 14 — Deep Computer Vision Using Convolutional Neural Networks</p>
</li>
<li><p>Chapter 15 — Processing Sequences Using RNNs and CNNs</p>
</li>
<li><p>Chapter 16 — Natural Language Processing with RNNs and Attention</p>
</li>
</ul>
<p>I have been reading this book since before the exam and the author Aurelion has created a gem of a book for aspiring Data Scientists, ML/AI engineers.</p>
<p>It elucidates the foundational concepts, explains the mathematics behind each algorithm, and then explains the hands-on code to solve problems along with the best practices, covering everything. A MUST-read for all Machine Learning aspirants.</p>
<p><strong>Learning Value: 5/5 —</strong> This is by far the best book to get started with Machine Learning.</p>
<p><strong>Time: 3–4 Months —</strong> I would recommend that you read each chapter slowly and then practice the exercise given at the end of each chapter.</p>
<p><strong>Cost:</strong> If you can afford it, I’d recommend getting an <a target="_blank" href="https://learning.oreilly.com/register/"><strong>O’Reilly Media</strong></a> subscription for <strong>$50</strong> a month where you not only get this book but all the publications and video/live lectures. Alternatively, you can buy the paperback on Amazon for the price it is available in your region (around $60).</p>
<p>I am an <a target="_blank" href="https://www.oreilly.com/pub/au/7782">O’Reilly Instructor</a>, so I have the resources available in my portal.</p>
<h3 id="heading-4-other-useful-youtube-playlists">4. Other Useful YouTube Playlists</h3>
<p>These are a few playlists that I went over to get a good grip over each of the required concepts:</p>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/playlist?list=PLtBw6njQRU-rwp5__7C0oIVt26ZgjG9NI"><strong>MIT 6.S191: Introduction to Deep Learning:</strong></a><br>  <strong>Usefulness 3/5 —</strong> It will help you get familiar with Deep learning and developing neural networks using TensorFlow. You should cover the first 3 videos in the playlist — Intro to DL, Recurrent Neural Network and Convolutional Neural Networks.<br>  <strong>Learning Value 4/5</strong> — Gives you a good refresher on the basics and I used it as a good video to watch when I was just in the mood to watch and not actually do much hands-on.<br>  <strong>Cost:</strong> Free<br>  <strong>Time:</strong> 3 hours</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/playlist?list=PLkDaE6sCZn6Gl29AoE31iwdVwSG-KnDzF"><strong>Convolutional Neural Networks by Andrew NG</strong></a><br>  Just like the above playlist but with Andrew NG’s method of explaining Deep learning. I watched this series last year, very helpful.<br>  I watched the videos that Laurence recommended in his course.<br>  <strong>Usefulness: 3/5 —</strong> More on the basics.<br>  <strong>Learning Value: 4/5</strong><br>  <strong>Time:</strong> 8–10 hours to understand the concepts in each video.</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/playlist?list=PLkDaE6sCZn6F6wUI9tvS_Gw1vaFAx6rd6"><strong>Sequence Models</strong></a> <strong>by Andrew NG</strong><br>  <strong>Usefulness: 3/5 —</strong> More on the basics.<br>  <strong>Learning Value: 4/5</strong><br>  <strong>Time:</strong> 8–10 hours to understand concepts in each video.</p>
</li>
</ul>
<h3 id="heading-5-pycharm-tutorial-serieshttpswwwjetbrainscompycharmlearning-center-and-environment-set-up-guidelineshttpswwwtensorfloworgsite-assetsdownloadsmarketingcertsettinguptfdevelopercertificateexampdfauthuser4">5. <a target="_blank" href="https://www.jetbrains.com/pycharm/learning-center/">PyCharm Tutorial Series</a> and <a target="_blank" href="https://www.tensorflow.org/site-assets/downloads/marketing/cert/Setting_Up_TF_Developer_Certificate_Exam.pdf?authuser=4">Environment Set up guidelines</a></h3>
<p>In case you have never worked in an IDE before, getting familiar with the exam environment is highly recommended.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-1.58.49-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Usefulness: 5/5</strong> (required) — This is a getting started series for PyCharm <strong>beginners</strong> that’ll help you get up to speed with how to use PyCharm efficiently.</p>
<p><strong>Learning Value: NA</strong></p>
<p>Make sure you read the environment set up guidelines to take the <a target="_blank" href="https://www.tensorflow.org/site-assets/downloads/marketing/cert/Setting_Up_TF_Developer_Certificate_Exam.pdf?authuser=4">TensorFlow Developer Certificate exam</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-2.03.19-PM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_[https://www.tensorflow.org/site-assets/downloads/marketing/cert/Setting_Up_TF_Developer_Certificate_Exam.pdf?authuser=4](https://www.tensorflow.org/site-assets/downloads/marketing/cert/Setting_Up_TF_Developer_Certificate_Exam.pdf?authuser=4" class="by cv lk ll lm ln" target="<em>blank" rel="noopener nofollow" style="box-sizing: inherit; color: inherit; text-decoration: none; -webkit-tap-highlight-color: transparent; background-repeat: repeat-x; background-image: url("data:image/svg+xml;utf8,&lt;svg preserveAspectRatio="none" viewBox="0 0 1 1" xmlns="http://www.w3.org/2000/svg"&gt;&lt;line x1="0" y1="0" x2="1" y2="1" stroke="rgba(41, 41, 41, 1)" /&gt;"); background-size: 1px 1px; background-position: 0px calc(1em + 1px);)</em></p>
<p>Follow the instructions mentioned in the PDF because the certification team can’t be held responsible for your negligence.</p>
<p><em>Whoa! That is a long list of resources, how did you manage to study?</em></p>
<h1 id="heading-my-schedule-for-preparation">My Schedule for Preparation</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/ezgif.com-video-to-gif--3-.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>By the end of April, I was sure to check this off my list. I’d take it up just like any other project and was determined to see it through.</p>
<p>So, I used to plan every night what I was about to do the next morning. The pink-colored time slots are blocked for studying for the course. These 3–4 hours in the morning were my most productive where I could grasp the most.</p>
<p>I had a fairly consistent routine throughout the 2 weeks and I raised the intensity when I got close to exam day with more than 5–6 hours of practice each day.</p>
<p><em>Ok, so w_hat</em> was <em>your process of studying?</em>_</p>
<h1 id="heading-how-i-studied">How I studied</h1>
<p>I used to first watch the lessons of each week, then practice the code in the colab provided following the video lessons.</p>
<p>At the end of each week, I would complete the assignment designed by Laurence in his course.<br><strong>NOTE: I used to write the entire code myself rather than just completing the placeholder code.</strong></p>
<p>I would also revisit the chapters in the Hands-on ML book later at night before sleeping or at the end of my time slot just to make everything crystal clear. Then I would learn about the next steps that were beyond the exam curriculum.</p>
<p>TL;DR: <strong>WATCH. CODE. PRACTICE. READ. REPEAT.</strong></p>
<h1 id="heading-all-prepared-to-take-the-exam-whats-next">All prepared to take the Exam — What’s next?</h1>
<p>If you think that you have covered all the skills mentioned in the Handbook and feel like you’re ready to take the exam, that's great.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-3.22.42-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now you're ready to purchase your exam. It's served by a third party platform called TrueAbility. You are required to submit your government issued ID (passport would work) for authentication.</p>
<p>Pay $100 for the exam. You are now good to go, you can start the exam as and when you feel ready.</p>
<p>They provide you detailed instructions on how to set up your PyCharm for the exam. Here’s what I recommend doing before starting your exam:</p>
<ul>
<li><p>Make sure that you have a good reliable internet connection.</p>
</li>
<li><p>Make sure that you have gone through the PyCharm beginner tutorial if you’re new to the IDE.</p>
</li>
<li><p>I tested my PyCharm by running a few TensorFlow <a target="_blank" href="https://www.tensorflow.org/tutorials/images/classification?authuser=4">tutorials</a>. They worked fine and I was ready to install the exam plugin to get started.</p>
</li>
<li><p>I read the exam instructions thoroughly before hitting the start exam button. It will be provided to you after signing up for the exam.</p>
</li>
</ul>
<p>HIT the Start Exam button!</p>
<h1 id="heading-during-the-exam">During the Exam</h1>
<p>Your exam environment will be created and you’ll be directed to the questions you'll have to solve. I won’t be sharing the details of the exam as that’d be unethical.</p>
<p>In my experience, it all went smoothly, and I was fairly confident I'd complete the exam after looking at the questions. And sure enough I completed the exam <strong>within 3 hours.</strong></p>
<h2 id="heading-tips-and-tricks">Tips and Tricks</h2>
<ul>
<li><p>Make sure you practice a few exercises on PyCharm 1–2 days before the exam rather than just working on Colab notebooks.</p>
</li>
<li><p>For the models that took time on my local machine, I trained them on Google Colab and then uploaded the trained model in the project folder.</p>
</li>
<li><p>Keep working on other questions while your model is training; I had 3 models under training — 1 on my machine and 2 on Google colab and I was working on the 4th while I was trying to tune the hyperparameters.</p>
</li>
<li><p>If you have enough time, keep trying to get the best results for each model.</p>
</li>
</ul>
<h1 id="heading-post-exam-rituals">Post-Exam Rituals</h1>
<p>When you're finished, hit the Submit and End Exam button. When I was done, I received an email from TrueAbility congratulating me on passing the exam:</p>
<p><img src="https://miro.medium.com/max/60/1*3RGLSZTKIFi8EgOYkCqRoQ.png?q=20" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-6.03.44-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>There is no detailed analysis or report on how you did on the exam. They simply mention whether or not you’ve passed the exam.</p>
<p>After passing the exam, you are requested to join the <a target="_blank" href="https://developers.google.com/certification/directory/tensorflow">TensorFlow Certificate</a> Network that tells you the Certificate holders in different regions:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-3.41.40-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-where-is-the-certificate">Where is the Certificate?</h2>
<p>It takes a week or so to actually get your hands onto the certificate. I got mine 3 days after the exam.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-16-at-11.45.06-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>My Certificate</em></p>
<p>Once you received your certificate, you can flash that badge on your social media profiles and mark it as an achievement in your resume.</p>
<h1 id="heading-exam-faqs">Exam FAQs</h1>
<h3 id="heading-is-it-really-that-important-to-take-the-exam-cant-i-just-work-on-an-equivalent-project-based-on-each-section">Is it really that important to take the exam, can’t I just work on an equivalent project based on each section?</h3>
<p>I’d say you can definitely do that and in fact, that is probably the better approach when you’re developing a new skill.</p>
<p>But the Exam helps you get recognized and, since it is coming from Google, it is nice to have. It's not a be-all-end-all solution to learning Deep learning or TensorFlow.</p>
<h3 id="heading-i-want-to-start-from-scratch-what-resources-should-i-be-looking-at">I want to start from scratch, what resources should I be looking at?</h3>
<p>Learn by doing things. Many blogs talk about learning deep mathematics first but you’ll soon loose interest using that approach.</p>
<p>Start by learning programming (Python or any other language) and then gradually dive into Machine Learning. You can also look at this <a target="_blank" href="https://www.coursera.org/learn/ai-for-everyone?utm_source=gg&amp;utm_medium=sem&amp;utm_content=08-AIforEveryone-IN&amp;campaignid=6499977756&amp;adgroupid=76330509045&amp;device=c&amp;keyword=artificial%20intelligence%20deep%20learning&amp;matchtype=b&amp;network=g&amp;devicemodel=&amp;adpostion=&amp;creativeid=382100381191&amp;hide_mobile_promo&amp;gclid=Cj0KCQjwuJz3BRDTARIsAMg-HxV5tfB76c0JYtqj1dGU3Oa9IFBkvWjr-yydlUYtXj5mODRUhBQ8TyMaAlkcEALw_wcB">course by Andrew NG.</a></p>
<h3 id="heading-i-always-need-a-mentor-or-someone-to-push-me-to-do-things-and-solve-my-doubts-and-problems-can-you-propose-a-solution">I always need a mentor or someone to push me to do things and solve my doubts and problems, can you propose a solution?</h3>
<p>A mentor does indeed help in many cases. If you’re someone who wants someone to help you with theses details apart from these resources, you can look at <a target="_blank" href="https://www.codementor.io/?partner=harshittyagi">Codementor</a> where you’ll find ML and AI experts who can help you resolve all your queries.</p>
<h3 id="heading-this-is-a-little-expensive-for-me-is-there-a-free-or-less-expensive-approach">This is a little expensive for me, is there a free or less expensive approach?</h3>
<p>Yes, the Tensorflow team is offering a few stipends to people who might have some trouble affording the exam. Visit <a target="_blank" href="https://www.tensorflow.org/site-assets/downloads/marketing/cert/TF_Education_Stipend.pdf">this link for more details</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screenshot-2020-06-15-at-4.25.22-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If your question is not addressed here, feel free to respond to this post and I’ll get back to you. :)</p>
<h1 id="heading-whats-next">What’s next?</h1>
<p>Just like with any other skill, start building things and working on real-world projects. Start looking into open-source projects like TensorFlow. Apply for jobs with this badge and share your story with others.</p>
<p>I’m working on a complete Deep Learning Foundation series that’ll be useful for ML/DL aspirants. You can watch me teach on to <a target="_blank" href="https://www.youtube.com/c/DataSciencewithHarshit?sub_confirmation=1">my Youtube channel</a> in the meanwhile.</p>
<p>Here is a video based on this blog where you can watch me share my journey:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/yapSsspJzAw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>I’ll be rolling out a complete series on TensorFlow soon. Subscribe to my channel for interesting data science content.</p>
<h1 id="heading-data-science-with-harshithttpswwwyoutubecomcdatasciencewithharshitsubconfirmation1"><a target="_blank" href="https://www.youtube.com/c/DataSciencewithHarshit?sub_confirmation=1">Data Science with Harshit</a></h1>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/-pVOoKrBtL8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>With this channel, I am planning to roll out a couple of <a target="_blank" href="https://towardsdatascience.com/hitchhikers-guide-to-learning-data-science-2cc3d963b1a2?source=---------8------------------">series covering the entire data science space</a>. Here is why you should be subscribing to the <a target="_blank" href="https://www.youtube.com/channel/UCH-xwLTKQaABNs2QmGxK2bQ">channel</a>:</p>
<ul>
<li><p>These series would cover all the required/demanded quality tutorials on each of the topics and subtopics like <a target="_blank" href="https://towardsdatascience.com/python-fundamentals-for-data-science-6c7f9901e1c8?source=---------5------------------">Python fundamentals for Data Science</a>.</p>
</li>
<li><p>Explained <a target="_blank" href="https://towardsdatascience.com/practical-reasons-to-learn-mathematics-for-data-science-1f6caec161ea?source=---------9------------------">Mathematics and derivations</a> of why we do what we do in ML and Deep Learning.</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=a2pkZCleJwM&amp;t=2s">Podcasts with Data Scientists and Engineers</a> at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies.</p>
</li>
<li><p><a target="_blank" href="https://towardsdatascience.com/building-covid-19-analysis-dashboard-using-python-and-voila-ee091f65dcbb?source=---------2------------------">Projects and instructions</a> to implement the topics learned so far.</p>
</li>
</ul>
<p>If this tutorial was helpful, you should check out my data science and machine learning courses on <a target="_blank" href="https://www.wiplane.com/">Wiplane Academy</a>. They are comprehensive yet compact and helps you build a solid foundation of work to showcase.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn how to use TensorFlow 2.0 for machine learning in this MASSIVE free course ]]>
                </title>
                <description>
                    <![CDATA[ TensorFlow is one of the most popular machine learning platforms—and it's completely open source. With TensorFlow 2.0, it has never been easier to build and deploy machine learning models. We have released a 7-hour TensorFlow 2.0 course on the freeCo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/massive-tensorflow-2-0-free-course/</link>
                <guid isPermaLink="false">66b2059a297cd6de0bd54684</guid>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 03 Mar 2020 15:47:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/03/tensorflow7-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>TensorFlow is one of the most popular machine learning platforms—and it's completely open source. With TensorFlow 2.0, it has never been easier to build and deploy machine learning models.</p>
<p>We have released a 7-hour TensorFlow 2.0 course on the freeCodeCamp.org YouTube channel. The course is designed for Python programmers looking to enhance their knowledge and skills in machine learning and artificial intelligence.  </p>
<p>Not only will this course teach you how to use TensorFlow, it will also give you a great overview of machine learning and artificial intelligence.</p>
<p>The creator of this course is Tim Ruscica, who is known for his popular “Tech With Tim” YouTube channel. Throughout eight modules, Tim covers the fundamental concepts and methods in machine learning and artificial intelligence like:</p>
<ul>
<li>core learning algorithms, </li>
<li>deep learning with neural networks, </li>
<li>computer vision with convolutional neural networks, </li>
<li>natural language processing with recurrent neural networks, </li>
<li>and reinforcement learning. </li>
</ul>
<p>To go along with the video portion of this course, there are six information-packed Jupyter notebook files. These files contain extensive notes, instructions, and diagrams. They also include all the code used in the course so you can easily try out the code yourself. And you can access the files on Google Colaboratory, allowing you to run all the code in your browser.</p>
<p>After completing this course you will have a thorough knowledge of the core techniques in machine learning and AI and have the skills necessary to apply these techniques to your own datasets.    </p>
<p>Here is a break-down of each module.</p>
<h3 id="heading-module-1-machine-learning-fundamentals">Module 1: Machine Learning Fundamentals</h3>
<p>The first module covers the difference between artificial intelligence, neural networks, and machine learning. The machine learning fundamentals laid out in this module will provide the foundation for the rest of the course.</p>
<h3 id="heading-module-2-introduction-to-tensorflow">Module 2: Introduction to TensorFlow</h3>
<p>This module provides a general introduction to TensorFlow. You will learn what a Tensor is and learn about shapes and data representation. You will also learn how TensorFlow works on a lower level. </p>
<p>While you can create machine learning models without knowing how everything works, a more in-depth understanding makes it easier to tweak models and get the best results.</p>
<h3 id="heading-module-3-core-learning-algorithms">Module 3: Core Learning Algorithms</h3>
<p>You will learn four of the fundamental machine learning algorithms. Each of the algorithms will be applied to unique problems and datasets.</p>
<p>The algorithms covered are:</p>
<ul>
<li>Linear regression</li>
<li>Classification</li>
<li>Clustering</li>
<li>Hidden Markov models</li>
</ul>
<h3 id="heading-module-4-neural-networks-with-tensorflow">Module 4: Neural Networks with TensorFlow</h3>
<p>In this module you will learn how neural networks work and the math behind them. You will learn about gradient descent, backpropagation, and how information flows through a neural network.</p>
<p>In the second part of the module you will see how to create a neural network with Karas to classify articles of clothing.</p>
<h3 id="heading-module-5-deep-computer-vision-convolutional-neural-networks">Module 5: Deep Computer Vision - Convolutional Neural Networks</h3>
<p>This module will teach how to use a convolutional neural network to perform image classification and object detection/recognition.</p>
<p>You will learn about the following concepts:</p>
<ul>
<li>Image data</li>
<li>Convolutional layers</li>
<li>Pooling layers</li>
<li>CNN architectures</li>
</ul>
<h3 id="heading-module-6-natural-language-processing-with-rnns">Module 6: Natural Language Processing with RNNs</h3>
<p>Natural Language Processing (NLP for sort) is a discipline in computing that deals with the communication between natural (human) languages and computer languages. A common example of NLP is something like spellcheck or autocomplete. </p>
<p>This module introduce a new kind of neural network called a recurrent neural network (RNN for short). These networks are often used for NLP.</p>
<p>You will learn how to use an RNN for sentiment analysis and character generation.</p>
<h3 id="heading-module-7-reinforcement-learning-with-q-learning">Module 7: Reinforcement Learning with Q-Learning</h3>
<p>In this module you will learn about Reinforcement Learning.</p>
<p>This technique is different than many of the other machine learning techniques covered earlier in the course. Rather than feeding our machine learning model millions of examples we let our model come up with its own examples by exploring an environment.</p>
<p>You will learn how to create a machine learning model using reinforcement learning.</p>
<h3 id="heading-module-8-conclusion-and-next-steps">Module 8: Conclusion and Next Steps</h3>
<p>In the final module, you will learn about next steps to learn more about TensorFlow and machine learning</p>
<h2 id="heading-time-to-watch">Time to Watch!</h2>
<p>If you are ready to start learning about TensorFlow and machine learning, watch the course below or on <a target="_blank" href="https://www.youtube.com/watch?v=tPYj3fFJGjk">the freeCodeCamp.org YouTube channel</a>.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/tPYj3fFJGjk" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
