<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yannick Serge Obam on Medium]]></title>
        <description><![CDATA[Stories by Yannick Serge Obam on Medium]]></description>
        <link>https://medium.com/@yannicksergeobam?source=rss-50600c47fed6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c5LbMKEtMjPgDcTCLmY6MQ.png</url>
            <title>Stories by Yannick Serge Obam on Medium</title>
            <link>https://medium.com/@yannicksergeobam?source=rss-50600c47fed6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 03:01:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yannicksergeobam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Aligning LLMs for Safety : Tunix Post-Training on Anthropic HH-RLHF]]></title>
            <link>https://yannicksergeobam.medium.com/aligning-llms-for-safety-tunix-post-training-on-anthropic-hh-rlhf-3fe52621e8b9?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fe52621e8b9</guid>
            <category><![CDATA[tpu]]></category>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[google-developer-expert]]></category>
            <category><![CDATA[tunix]]></category>
            <category><![CDATA[vllm]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 03:26:01 GMT</pubDate>
            <atom:updated>2026-04-30T03:26:01.520Z</atom:updated>
            <content:encoded><![CDATA[<p>A production-grade ML engineering lifecycle — from preference data curation through distributed JAX training, rigorous dual-benchmark safety evaluation, production vLLM serving, and a professional Python package structure that is tested, linted, and installable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*QQW16NK65wINvcYxtW3OWw.png" /></figure><h3>What does “alignment” actually mean?</h3><p>Imagine you hire a brilliant new employee. They’ve read every book in the world. They can answer almost any question, write code, summarise meetings, and explain complex ideas in plain English. But sometimes — just sometimes — they say whatever sounds most confident rather than what is actually true. They’ll occasionally invent a fact, deliver a stereotype, or repeat a popular misconception with total conviction.</p><p>That, in short, is what every modern language model is like out of the box. It has absorbed an enormous amount of text, but it has no built-in sense of honesty, kindness, or harm. It’s optimised to predict the next word in a sentence — nothing more, nothing less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*iZxzOb3j0FwGPa2JgoX0JQ.png" /></figure><p>“<strong>Alignment</strong>” is the technical word for this process — teaching a model to prefer responses that humans actually want. Helpful instead of unhelpful. Honest instead of confidently wrong. Harmless instead of careless.</p><p>This guide walks through one specific alignment project, called Tunix DPO, end to end. By the time we’re done, you’ll understand:</p><ul><li>How human preferences get turned into training data</li><li>What actually happens during training, conceptually</li><li>How we measured a real safety improvement</li><li>How the trained model gets served to actual users</li></ul><p>No machine learning background needed. We’ll explain every concept the first time it shows up.</p><h3>DPO: learning from comparisons</h3><p>The technique we used is called <strong>DPO</strong>, short for Direct Preference Optimisation. The name sounds intimidating but the underlying idea is genuinely simple: instead of telling the model the right answer, we show it pairs of responses and tell it which one is better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*pL1nZkyci7bCefL1bL0Pxw.png" /></figure><h4>How DPO compares to the older approach</h4><p>Before DPO, the standard alignment technique was called <strong>RLHF </strong>— Reinforcement Learning from Human Feedback. It’s what trained the first version of ChatGPT. RLHF works, but it’s complicated: you train a separate “reward model” first, then use that to guide the actual language model in a feedback loop. Many things can go wrong.</p><p>DPO collapses all of that into a single, mathematically clean training step. Here’s how the two compare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*2oZmrvyToOgx8wkiquehpg.png" /></figure><p>For a project where you want to measure whether a specific change made the model better, DPO is the better choice. It’s predictable. It’s simple. And it works remarkably well.</p><h3>Phase 1 : Curating the training data</h3><p>To teach a model to prefer good answers, you need examples of good answers and bad answers. The dataset we used is called HH-RLHF, published by Anthropic. The “HH” stands for Helpful and Harmless — the two qualities we want the model to learn.</p><p>It contains roughly 160,000 conversations. Each one has a question, two possible responses, and a human annotator’s choice of which response was better. Here’s what one row looks like in the raw data:</p><pre>// One row from HH-RLHF<br>{<br>  &quot;prompt&quot;: &quot;Human: I&#39;m feeling anxious before a job interview. Any advice?\n\nAssistant:&quot;,<br>  &quot;chosen&quot;: &quot;That&#39;s a really common feeling. A few things that help: prepare 2-3 concrete examples of past work, take slow breaths before going in, and remember they invited you because they&#39;re already interested...&quot;,<br>  &quot;rejected&quot;: &quot;Don&#39;t worry about it, just be yourself. Anxiety is all in your head.&quot;<br>}</pre><p>The chosen response is genuinely helpful. The rejected one dismisses the person&#39;s feelings. A human looked at both and clearly preferred the first.</p><p>Real-world data is never clean, though. Some rows have malformed conversation turns. Some have responses that are essentially identical, which gives the model no useful signal. Phase 1 of the project is about filtering these out and producing a clean dataset.</p><p>The cleanup is handled by a single command:</p><pre># After installing the project with: pip install -e .<br>tunix-curate \<br>    --format   dpo \<br>    --subsets  helpful-base harmless-base \<br>    --output_dir ./data</pre><p>This produces ~150,000 cleaned-up preference pairs ready to be fed into training. The actual filtering logic is in pure Python functions that have no side effects, which (as we’ll see in Chapter 7) is a deliberate design choice that makes the code much easier to test.</p><h3>Phase 2 : Training on a TPU supercomputer</h3><p>This is where the actual learning happens. You take your cleaned-up dataset and run it through the model many, many times, slowly nudging the model’s internal parameters toward producing more of the “chosen” responses and less of the “rejected” ones.</p><p>Training a 2-billion-parameter model on 150,000 conversations is computationally expensive. We used a <strong>Google Cloud TPU v5e </strong>— a specialised chip Google designed specifically for this kind of work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*lfajJix99bc9mYMSCs52uA.png" /></figure><h4>DPO loss</h4><p>Direct Preference Optimisation (Rafailov et al., 2023) derives a closed-form loss from the RLHF objective that avoids fitting a separate reward model. For a preference pair (<em>yw</em> chosen, <em>yl</em> rejected) given prompt <em>x</em>:</p><pre>ℒDPO = −𝔼 log σ( β·[log πθ(yw|x) − log πref(yw|x)] − β·[log πθ(yl|x) − log πref(yl|x)] )</pre><p>β = 0.1 controls KL divergence from the reference policy. The reference model is passed through jax.lax.stop_gradient and is never updated. The training step is compiled with jax.pmap across all 8 chips and gradients are all-reduced with jax.lax.pmean. Both the DPO loss function and the SFT cross-entropy function live in tunix_dpo.training.losses as pure JAX — no I/O, no side effects, independently unit-tested.</p><h4>Loss trajectory comparison</h4><p>A key requirement is logging both the DPO loss and the SFT (next-token prediction) loss at every step, on the same data, so the divergence in training dynamics is directly visible. Both are always computed regardless of sft_loss_weight. The DPO loss converges faster and to a lower asymptote — direct evidence that preference data is being used effectively beyond standard autoregressive training. The TrajectoryLogger in tunix_dpo.training.logger writes to both TensorBoard and a metrics.jsonl sidecar file for offline plotting.</p><pre>import jax<br>import jax.numpy as jnp<br><br>def dpo_loss(<br>    policy_chosen_logp,    # log p_θ(chosen | prompt)<br>    policy_rejected_logp,  # log p_θ(rejected | prompt)<br>    ref_chosen_logp,       # log p_ref(chosen | prompt) — frozen<br>    ref_rejected_logp,     # log p_ref(rejected | prompt) — frozen<br>    beta: float = 0.1,<br>):<br>    &quot;&quot;&quot;ℒ = −E[ log σ( β·((logπ_θ(y_w|x) − logπ_ref(y_w|x))<br>                       − (logπ_θ(y_l|x) − logπ_ref(y_l|x))) ) ]&quot;&quot;&quot;<br><br>    # How much more confident is the policy than the reference?<br>    chosen_logratio   = policy_chosen_logp   - ref_chosen_logp<br>    rejected_logratio = policy_rejected_logp - ref_rejected_logp<br><br>    # The whole alignment objective in one line:<br>    logits = beta * (chosen_logratio - rejected_logratio)<br>    return -jax.nn.log_sigmoid(logits).mean()<br></pre><p>Read that bottom-up. The final line says: we want the policy to be <em>more</em> confident than the reference about the chosen response and <em>less</em> confident than the reference about the rejected response. The β knob (we use 0.1) controls how aggressively the policy is allowed to drift from the reference.</p><blockquote><em>The whole DPO algorithm is one well-named loss function. Everything else is plumbing</em></blockquote><h4>Provisioning the hardware with Terraform</h4><p>Setting up a TPU manually involves clicking through a lot of forms in the Google Cloud Console: create a project, enable APIs, request quota, configure networking, provision the chip. This is error-prone and impossible to reproduce reliably.</p><p>Instead, we wrote the entire infrastructure as code using Terraform — a tool that lets you describe what you want in a configuration file, then creates everything for you with one command.</p><p>The whole module is about 150 lines and brings up the TPU VM, a co-located GCS bucket for checkpoints, a service account with the right IAM bindings, and a startup script that installs JAX-with-TPU-support on first boot.</p><pre> ─── TPU VM ────────────────────────────────────────────────────────────────<br># v5e-8 in us-west4-a — Google&#39;s canonical zone for TPU v5e.<br># The &quot;v5litepod-8&quot; name is the gcloud / Compute Engine convention; the<br># Terraform google_tpu_v2_vm resource accepts the same accelerator types.<br>resource &quot;google_tpu_v2_vm&quot; &quot;training&quot; {<br><br>  provider = google-beta<br>  name             = var.tpu_name<br>  zone             = var.zone<br>  description      = &quot;Tunix DPO training VM (Gemma 3 1B IT, DPO, v5e-8)&quot;<br>  accelerator_type = var.accelerator_type<br>  runtime_version  = var.runtime_version<br><br>  network_config {<br>    network    = &quot;default&quot;<br>    subnetwork = &quot;default&quot;<br>    enable_external_ips = true<br>  }<br><br>  service_account {<br>    email = google_service_account.tpu_sa.email<br>    scope = [&quot;https://www.googleapis.com/auth/cloud-platform&quot;]<br>  }<br><br>  metadata = {<br>    startup-script = file(&quot;${path.module}/scripts/startup.sh&quot;)<br>    bucket         = google_storage_bucket.checkpoints.name<br>  }<br><br>  labels = {<br>    project = &quot;tunix-dpo&quot;<br>    env     = var.env<br>    model   = &quot;gemma-3-1b-it&quot;<br>  }<br><br>  depends_on = [<br>    google_project_service.tpu,<br>    google_project_iam_member.tpu_sa_storage,<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2CCR1Z4XLU_Rg55TeqW7Q.png" /></figure><p>Then with two commands and you’re ready to train</p><pre># 1. Provision the cloud infrastructure<br>$ cd infra/terraform &amp;&amp; terraform apply -auto-approve<br><br># 2. Copy the project to the TPU VM and SSH in<br>$ gcloud compute tpus tpu-vm scp --recurse ./tunix_dpo \<br>       tunix-dpo-v5e:~ --zone=us-west4-a<br><br>$ gcloud compute tpus tpu-vm ssh tunix-dpo-v5e --zone=us-west4-a<br><br># 3. On the VM - kick off DPO training<br>[on TPU]$ tunix-train --config configs/dpo_v5e.yaml<br><br># Training output streams to stdout:<br>#   step=  100  loss=0.589  reward_acc=0.612<br>#   step=  500  loss=0.521  reward_acc=0.683<br>#   step= 1000  loss=0.498  reward_acc=0.694<br>#   ...</pre><h4>The four-step training loop</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*KSDIlDpJ7LRR8RSsolXCOw.png" /></figure><p>Conceptually, training repeats the same four steps thousands of times:</p><ol><li><strong>Sample a batch</strong> of preference pairs from the dataset.</li><li><strong>Compute log-probabilities</strong>: how likely was the model to produce each response, before we trained it?</li><li><strong>Calculate the DPO loss</strong>: a single number that’s small when the model already prefers the chosen response, and large when it prefers the rejected one.</li><li><strong>Update the model</strong>: nudge its internal parameters slightly to reduce the loss on this batch.</li></ol><p>Repeat 50,000 times. Each step is tiny, but the cumulative effect is the model genuinely shifting its preferences.</p><p>Then with two commands and you’re ready to train</p><h3>Phase 3: Benchmarking — TruthfulQA + ToxiGen</h3><p>This is the most important question in the whole project, and the easiest one to fool yourself about. The trained model <em>feels</em> better when you chat with it. But feelings aren’t evidence. We need standardised tests with known baselines and proper statistical treatment.</p><p>We run two benchmarks. <em>TruthfulQA</em> tests whether the model gives true answers to questions humans typically get wrong. <em>ToxiGen</em> tests whether the model produces harmful generalisations about demographic groups, and whether it can recognise such generalisations when shown them.</p><h4>The headline numbers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*JNeQBo4RXpwkWWXNo2b4Xw.png" /></figure><p>All three primary metrics moved in the right direction. The 47% drop in toxicity is especially striking because HH-RLHF doesn’t contain ToxiGen-style prompts at all — the model generalised from “be helpful and harmless” to specific demographic content it had never been directly trained on.</p><blockquote><em>A 19.9% gain in truthfulness and a 47% reduction in toxic output, on benchmarks the model has never seen. Both are statistically significant</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*zNLi3G6S3aBPdxdF4GilZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*QnxiyS07mKFuyPdt5Rr7QQ.png" /></figure><p>The base model was weakest where popular misconceptions are densest, and DPO closed those gaps disproportionately. That’s the shape you want to see — alignment is doing the most work where it’s most needed.</p><h4>How we know it’s not noise</h4><p>A 19.9% improvement on 800 questions could be a fluke. We use a non-parametric bootstrap confidence interval to find out. It’s a one-line idea: take the per-question results, resample them with replacement 1000 times, compute the mean each time, and report the 2.5th and 97.5th percentiles of those means. If the base and tuned intervals don’t overlap, the difference is statistically significant.</p><pre>#src/tunix_dpo/evaluation/stats.py - pure stats, no torch<br>import numpy as np<br><br>def bootstrap_ci(values, n_boot: int = 1000, confidence: float = 0.95):<br>    &quot;&quot;&quot;Returns (lo, hi) percentile bounds on the mean of `values`.&quot;&quot;&quot;<br>    rng = np.random.default_rng(42)<br>    arr = np.asarray(values, dtype=np.float64)<br>    means = np.empty(n_boot)<br>    for i in range(n_boot):<br>        sample = rng.choice(arr, size=arr.size, replace=True)<br>        means[i] = sample.mean()<br>    alpha = 1.0 - confidence<br>    return (<br>        float(np.percentile(means, 100 * alpha / 2)),<br>        float(np.percentile(means, 100 * (1 - alpha / 2))),</pre><p>The full evaluator runs both benchmarks, computes the bootstrap CI for every metric, adds Cohen’s h for effect size, and writes everything to a JSON file. Then a separate compare.py module — also pure — produces the headline numbers shown above</p><h3>Phase 4 : Weight export &amp; production inference</h3><p>Trained model sitting in a checkpoint file is useless. To matter, it needs to answer real questions from real users with reasonable speed and reliability. This is the production-serving phase.</p><p>We used vLLM, an open-source inference engine specifically optimised for serving large language models. The key feature: it uses something called PagedAttention to dramatically reduce the GPU memory needed per concurrent user, which means a single GPU can serve dozens of requests in parallel.</p><p>The server exposes a full OpenAI-compatible API — /v1/chat/completions with SSE streaming, /v1/completions, /health with per-request telemetry, and /metrics in Prometheus plain-text format. The VLLMEngine wrapper in tunix_dpo.serving.engine provides a clean async generator interface so the FastAPI routes in server.py contain zero vLLM-specific code. The server supports GPTQ/AWQ INT4 quantisation and tensor parallelism:</p><pre># Boot up the server<br>$ tunix-serve \<br>    --model ./exports/tunix_dpo_gemma_3_1b_it \<br>    --port 8000<br><br># In another terminal — talk to it like OpenAI<br>$ curl http://localhost:8000/v1/chat/completions \<br>    -H &quot;Content-Type: application/json&quot; \<br>    -d &#39;{<br>      &quot;model&quot;: &quot;tunix-dpo-gemma-3-1b-it&quot;,<br>      &quot;messages&quot;: [<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Are vaccines linked to autism?&quot;}<br>      ]<br>    }&#39;<br><br># Aligned model response:<br># &quot;No. The original 1998 study suggesting a link was retracted in<br>#  2010 due to data falsification, and the lead author was struck<br>#  off the medical register. Subsequent studies of millions of<br>#  children have found no link between vaccines and autism.&quot;Measured with max_model_len=4096, gpu_memory_utilization=0.90, 128 output tokens per request. TTFT = time to first token, measured via the streaming SSE endpoint:</pre><h4>Telemetry from day one</h4><p>Every inference server should ship with metrics from the very first request. Ours exposes Prometheus-compatible counters at /metrics — request count, token throughput, latency distribution, error rate. Nothing fancy, but it lets us see what the model is actually doing in production:</p><pre># HELP tunix_requests_total Total inference requests served<br># TYPE tunix_requests_total counter<br>tunix_requests_total 14823<br><br># HELP tunix_tokens_generated_total Total tokens generated<br># TYPE tunix_tokens_generated_total counter<br>tunix_tokens_generated_total 2104812<br><br># HELP tunix_avg_latency_ms Average request latency in ms<br># TYPE tunix_avg_latency_ms gauge<br>tunix_avg_latency_ms 187.4<br><br># HELP tunix_uptime_seconds Server uptime in seconds<br># TYPE tunix_uptime_seconds counter<br>tunix_uptime_seconds 42851.2</pre><p>That’s the whole pipeline. Five tools, five phases, one trained model. From raw preference data to a measurable safety improvement to a live API — about a hundred hours of engineering, sixty dollars of TPU time, and one unmistakable result.</p><h3>Project Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*BAurknz7IKwFxMMEyOzaqw.png" /></figure><p>Github repository :</p><p><a href="https://github.com/obeshor/tunix-dpo">GitHub - obeshor/tunix-dpo</a></p><h3>Thanks to Google Cloud</h3><p><strong>Google Cloud credits are provided for this project. #TPUSprint</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fe52621e8b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Deploying a Semantic Book Recommender with Gradio, LangChain, and Google Cloud Run]]></title>
            <link>https://yannicksergeobam.medium.com/building-and-deploying-a-semantic-book-recommender-with-gradio-langchain-and-google-cloud-run-d6e2048ef3a9?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e2048ef3a9</guid>
            <category><![CDATA[google-developer-expert]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 06:29:40 GMT</pubDate>
            <atom:updated>2025-12-11T07:02:44.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1o0OJEL4fO3CkoJ-Twr-6g.png" /></figure><p>For developers venturing into the world of AI and machine learning, building and deploying a practical application is one of the most rewarding experiences. In this tutorial, we’ll walk through the process of creating a semantic book recommender using Gradio for the user interface and LangChain for the core AI logic. We’ll then deploy it to Google Cloud Run, making it a scalable, serverless application.</p><p>This project is perfect for beginners who want to understand how to build and deploy a simple, yet powerful, AI application.</p><h3>What We’re Building</h3><p>We’ll be building a web-based application that allows users to enter a description of a book they’re interested in, and the application will recommend books with similar themes and concepts. This is a “semantic” recommender because it understands the *meaning* of the user’s query, rather than just matching keywords.</p><p>Here’s a quick look at the technologies we’ll be using:</p><ul><li><strong>Gradio: </strong>To create a simple and interactive web interface for our application.</li><li><strong>LangChain:</strong> A framework for developing applications powered by language models.</li><li><strong>Hugging Face Transformers or Google Gemini:</strong> To generate the embeddings (numerical representations) of the book descriptions.</li><li><strong>Chroma</strong>: A vector database to store and efficiently search through the book description embeddings.</li><li><strong>Pandas:</strong> For data manipulation and loading our book dataset.</li><li><strong>Docker: </strong>To containerize our application for deployment.</li><li><strong>Google Cloud Run:</strong> A fully managed serverless platform to run our container.</li></ul><h3>Prerequisites</h3><p>Before we start, make sure you have the following installed:</p><ul><li>Python</li><li>Docker</li><li>Google Cloud SDK</li></ul><p>You’ll also need a Google Cloud project with billing enabled.</p><h3><strong>Project Structure</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0d24wlyg6FdpaTcE3rRog.png" /></figure><p>Our project will have the following structure:</p><pre>book-recommender/<br>├── src/<br>│   └── dashboard.py<br>├── data/<br>│   ├── books_with_emotions.csv<br>│   └── tagged_descriptions.txt<br>├── requirements.txt<br>├── Dockerfile<br>└── blog_post.md</pre><ul><li>src/dashboard.py: The main Python script for our application.</li><li>data/: This directory contains our dataset.</li><li>requirements.txt: A list of Python dependencies.</li><li>Dockerfile: Instructions to build a Docker image for our application.</li><li>blog_post.md: The blog post you are reading right now.</li></ul><h3>Code Walkthrough</h3><p>Let’s dive into the code in src/dashboard.py.</p><h4>1. Choosing Your Embedding Model</h4><p>We’ve updated the script to support both traditional Hugging Face embeddings and Google’s advanced Gemini models. You can switch between them by setting the USE_GOOGLE_EMBEDDINGS environment variable.</p><pre># Select the embedding model (HuggingFace or Google)<br># To use Google, set USE_GOOGLE_EMBEDDINGS=True in your environment<br>USE_GOOGLE_EMBEDDINGS = os.getenv(&quot;USE_GOOGLE_EMBEDDINGS&quot;, &quot;False&quot;).lower() == &quot;true&quot;<br>EMBEDDING_MODEL_HF = &#39;all-MiniLM-L6-v2&#39;<br>EMBEDDING_MODEL_GOOGLE = &quot;models/embedding-001&quot;<br><br># ...<br><br>def setup_vector_db(desc_path: str) -&gt; Chroma:<br>    # ...<br>    if USE_GOOGLE_EMBEDDINGS:<br>        print(&quot;Using Google Gemini embeddings.&quot;)<br>        # Ensure you have your GOOGLE_API_KEY set in your environment<br>        embeddings = GoogleGenerativeAIEmbeddings(model=EMBEDDING_MODEL_GOOGLE)<br>    else:<br>        print(&quot;Using Hugging Face embeddings.&quot;)<br>        embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL_HF)<br>    # ...</pre><p>To use Gemini, you’ll need to get an API key from Google AI Studio and set it as an environment variable named GOOGLE_API_KEY.</p><h4>2. Preparing for Cloud Run</h4><p>Cloud Run requires applications to listen on a specific host and port, which are provided through environment variables. We’ve modified the dashboard.launch() call to accommodate this.</p><pre>if __name__ == &quot;__main__&quot;:<br>    # ...<br>    dashboard = create_gradio_dashboard(books_df, db_books)<br>    # For Cloud Run, Gradio needs to listen on 0.0.0.0 and a specific port<br>    server_name = os.getenv(&quot;SERVER_NAME&quot;, &quot;127.0.0.1&quot;)<br>    server_port = int(os.getenv(&quot;PORT&quot;, 7860))<br>    dashboard.launch(server_name=server_name, server_port=server_port</pre><p>Now, let’s get our application into the cloud!</p><h3>Deploying to Google Cloud Run</h3><p>Now, let’s get our application into the cloud!</p><h4>1. The Dockerfile</h4><p>The Dockerfile is our recipe for building a container image. It sets up the environment, installs dependencies, and copies our code.</p><pre># Use an official Python runtime as a parent image<br>FROM python:3.11-slim</pre><pre># Use an official Python runtime as a parent image<br>FROM python:3.11-slim</pre><pre>#  Ensures logs are flushed immediately to Cloud Logging<br>ENV PYTHONUNBUFFERED=True</pre><pre># Set the working directory in the container<br>WORKDIR /app</pre><pre># Copy the requirements file into the container at /app<br>COPY requirements.txt .</pre><pre># Install any needed packages specified in requirements.txt<br>RUN  apt-get update &amp;&amp; apt-get install -y build-essential &amp;&amp;  pip install --no-cache-dir -r requirements.txt</pre><pre># Copy the rest of the application&#39;s code into the container at /app<br>COPY . .</pre><pre># Make port 8080 available to the world outside this container<br># Cloud Run expects the container to listen on the port defined by the PORT env var.<br># Gradio defaults to 7860, so we&#39;ll use that and Cloud Run will map it to 8080.<br>EXPOSE 8080</pre><pre># Define environment variable<br>ENV PORT 8080<br>ENV SERVER_NAME &quot;0.0.0.0&quot;</pre><pre># Run dashboard.py when the container launches<br>CMD [&quot;python&quot;, &quot;src/dashboard.py&quot;]<br></pre><h4>2. Building the image</h4><p>First, make sure you’ve authenticated with Google Cloud:</p><pre>sudo chown -R $USER ~/.config/gcloud<br>gcloud auth login<br>gcloud config set project YOUR_PROJECT_ID</pre><p>Then, enable the necessary services:</p><pre>gcloud services enable run.googleapis.com<br>gcloud services enable artifactregistry.googleapis.com</pre><p>Now, build the Docker image and push it to Google Artifact Registry:</p><pre>export PROJECT_ID=$(gcloud config get-value project)<br>export REPO_NAME=&quot;book-recommender-repo&quot;<br>export IMAGE_NAME=&quot;book-recommender&quot;</pre><pre>gcloud artifacts repositories create $REPO_NAME --repository-format=docker --location=us-central1</pre><pre>gcloud auth configure-docker us-central1-docker.pkg.dev</pre><pre>docker build -t us-central1-docker.pkg.dev/$PROJECT_ID/$REPO_NAME/$IMAGE_NAME:latest .</pre><pre>docker push us-central1-docker.pkg.dev/$PROJECT_ID/$REPO_NAME/$IMAGE_NAME:latest</pre><h4>3. Deploying to Cloud Run</h4><p>Finally, deploy the container to Cloud Run. If you’re using Gemini, you’ll need to include your GOOGLE_API_KEY.</p><p><strong>For Hugging Face Embeddings:</strong></p><pre>gcloud run deploy book-recommender \<br>    --image=us-central1-docker.pkg.dev/$PROJECT_ID/$REPO_NAME/$IMAGE_NAME:latest \<br>    --platform=managed \<br>    --region=us-central1 \<br>    --allow-unauthenticated</pre><p><strong>For Gemini Embeddings:</strong></p><pre>gcloud run deploy book-recommender \<br>    --image=us-central1-docker.pkg.dev/$PROJECT_ID/$REPO_NAME/$IMAGE_NAME:latest \<br>    --platform=managed \<br>    --region=us-central1 \<br>    --allow-unauthenticated \<br>    --set-env-vars=&quot;USE_GOOGLE_EMBEDDINGS=True&quot; \<br>    --set-env-vars=&quot;GOOGLE_API_KEY=YOUR_GOOGLE_API_KEY&quot;</pre><p>After the deployment is complete, you’ll get a URL where you can access your book recommender!</p><h3>Conclusion</h3><p>Congratulations! You’ve not only built a semantic book recommender but also deployed it as a scalable, serverless application on Google Cloud Run. This project serves as a solid foundation for building more complex AI applications and exploring the power of cloud-native development.</p><p>Happy coding!</p><p>Click this <a href="https://github.com/obeshor/book-recommender">link</a> for all code</p><p>Credit : <a href="https://www.youtube.com/watch?v=Q7mS1VHm3Yw&amp;t=1s">FreeCodeCamp — LLM Course — Build a Semantic Book Recommender</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e2048ef3a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construire des Systèmes d’IA Agentique Évolutifs sur Google Cloud — Partie 1]]></title>
            <link>https://yannicksergeobam.medium.com/construire-des-syst%C3%A8mes-dia-agentique-%C3%A9volutifs-sur-google-cloud-partie-1-2308f90322f0?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2308f90322f0</guid>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google-developer-expert]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[google-cloud]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 02:23:49 GMT</pubDate>
            <atom:updated>2025-12-05T02:45:43.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>Construire des Systèmes d’IA Agentique Évolutifs sur Google Cloud — Partie 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7ezNE9TDCEJk-WiEJo3Gw.png" /><figcaption>Base AI Agent runtime</figcaption></figure><h3>Le Changement d’Infrastructure Cognitive</h3><p>Avez-vous déjà utilisé un chatbot qui semblait non seulement “parler”, mais aussi “réfléchir” et “agir” pour vous ? Ce n’est pas de la magie, c’est de l’ingénierie.</p><p>L’informatique cloud vit une métamorphose fondamentale. Nous passons d’une ère dominée par les microservices déterministes à celle de l’<strong>Architecture Agentique</strong>, où l’unité de calcul centrale est une entité probabiliste capable de raisonner, de planifier et d’agir de manière autonome.</p><p>Ce changement exige une refonte de l’infrastructure. Un agent IA n’est pas un simple chatbot ; c’est un système qui perçoit, raisonne, agit et apprend. Google Cloud Platform (GCP) répond à cette exigence avec une architecture de référence qui sépare le système en deux couches symbiotiques : le <strong>Model Runtime</strong> (le cerveau) et l’<strong>Agent Runtime</strong> (le corps).</p><p>Aujourd’hui, nous allons décortiquer l’anatomie d’un tel système d’Intelligence Artificielle (IA) en nous basant sur une architecture standard. Imaginez ce système comme <strong>un assistant personnel ultra-compétent</strong></p><h4>Illustration Principale : L’Anatomie de l’Agent</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zggnEEtIv-n2CkunCcp6Sw.png" /><figcaption>Google Cloud team — Samantha He</figcaption></figure><p><strong>Description Visuelle :</strong> Le diagramme d’architecture montre le flux de données :</p><p>Tout commence en haut du schéma.</p><ol><li><strong>Users (Utilisateurs)</strong> : C’est vous — <strong>L’Utilisateur</strong> interagit via une <strong>Frontend</strong></li><li><strong>Frontend Application</strong> : C’est l’interface avec laquelle vous interagissez (une page web, une application mobile, une fenêtre de chat). C’est le “guichet d’accueil”. Vous posez une question, et l’application la transmet au cerveau du système.</li><li>La demande atteint l’<strong>Agent Runtime</strong> (le chef d’orchestre). Pensez à <strong>l’agent </strong>comme à un chef de projet. Il ne sait pas tout faire lui-même, mais il sait <strong>qui</strong> appeler et <strong>quoi</strong> faire. Il reçoit votre demande et décide de la stratégie à adopter. <strong>Agent Development Framework </strong>quant à lui<strong> </strong>est la structure logique (le code) créée par les développeurs pour définir comment l’agent doit se comporter.</li><li>La Mémoire — L’agent consulte sa <strong>Mémoire</strong> (Court/Long terme). C’est la partie rose à droite. Une IA sans mémoire serait comme un poisson rouge : elle oublierait votre nom dès la phrase suivante.</li></ol><ul><li><strong>Short-term memory (Mémoire à court terme) :</strong> Elle se souvient de la conversation actuelle (ex: “Ah oui, il m’a demandé une recette de pizza juste avant”).</li><li><strong>Long-term memory (Mémoire à long terme) :</strong> Elle stocke des documents, des préférences utilisateur ou des historiques passés pour apprendre sur la durée.</li></ul><p>5. Il interroge le <strong>Model Runtime</strong> pour raisonner :</p><ul><li><strong>AI Model :</strong> C’est ici que réside le “cerveau” brut (comme Gemini de Google). L’Agent envoie une requête (ce qu’on appelle une <em>inférence</em>) au modèle.</li><li><em>Exemple :</em> L’agent demande “Le client veut savoir la météo, comment dois-je formuler la réponse ?”. Le modèle génère le texte et la compréhension du langage.</li></ul><p>6. Il exécute des actions via des <strong>Outils</strong> (APIs, Bases de données): C’est ce qui différencie un simple chatbot (qui ne fait que parler) d’un véritable <strong>Agent</strong>. L’agent peut utiliser des outils pour agir sur le monde réel :</p><ul><li><strong>Databases :</strong> Chercher une info précise dans une base de données client.</li><li><strong>APIs :</strong> Se connecter à une application météo ou boursière.</li><li><strong>Files :</strong> Lire un PDF que vous lui avez envoyé.</li><li><strong>Services :</strong> Envoyer un email ou réserver une réunion.</li></ul><h3>Le Paradigme Agentique : Déconstruire le “Cerveau” et le “Corps”</h3><p>Contrairement au logiciel traditionnel linéaire (Entrée → Traitement → Sortie), l’IA agentique suit une <strong>Boucle Perception-Action</strong> cyclique.</p><h4>Le Model Runtime (Le Cerveau)</h4><p>C’est le moteur de raisonnement, principalement servi par <strong>Vertex AI</strong>.</p><ul><li><strong>Rôle :</strong> Il ne fait pas l’action. Il reçoit un contexte et génère un plan ou une décision d’outil.</li><li><strong>Caractéristiques :</strong> Apatride (stateless), éphémère et coûteux en calcul. Il peut être mis à jour indépendamment (passer de Gemini 1.5 Pro à 2.0) sans casser le reste de l’application.</li></ul><h4>L’Agent Runtime (Le Corps)</h4><p>C’est le code applicatif qui ancre les probabilités du modèle dans la réalité déterministe.</p><ul><li><strong>Rôle :</strong> Il gère la boucle de contrôle, exécute les outils (ex: requêtes SQL) et applique les garde-fous de sécurité.</li><li><strong>Options de Calcul :</strong> <strong>Cloud Run</strong> (pour la flexibilité) — image d’un conteneur Docker ouvert, symbolisant le contrôle total et le code personnalisé (Python/Go) ou <strong>Vertex AI Agent Engine</strong> (pour une solution gérée) — Image d’une boîte noire connectée, symbolisant la rapidité de déploiement et la gestion automatique de la sessio</li></ul><h4>Analyse des Composants Architecturaux</h4><p>Voici comment mapper les fonctions agentiques aux services Google Cloud</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFDzsJ7MfrFBTwcJe0ZuWQ.png" /></figure><h3>Le Choix du Calcul : Cloud Run vs Vertex AI Agent Engine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHG5XYzQjCOdm-Ypl3gVMA.png" /></figure><h4>Cloud Run : Le Choix de l’Architecte</h4><p>Idéal pour les experts nécessitant un contrôle granulaire.</p><ul><li><strong>Économie :</strong> Le modèle de concurrence permet de traiter plusieurs requêtes (I/O bound) sur une seule instance, réduisant drastiquement les coûts.</li><li><strong>Flexibilité :</strong> Vous pouvez utiliser n’importe quelle librairie Python ou binaire système nécessaire pour vos outils.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BofZOLW1LwwsbY1JvmYfIw.png" /><figcaption>image fro Vinay kumar blog</figcaption></figure><h4>Vertex AI Agent Engine : La Solution Managée</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxL-vskiZvNDgxJgkteLSQ.png" /></figure><p>Idéal pour les cas d’usage RAG (Retrieval-Augmented Generation) rapides.</p><ul><li><strong>Avantage :</strong> Intégration native avec Vertex AI Search et gestion automatique de l’état de la session.</li><li><strong>Limite :</strong> Moins flexible pour les logiques d’orchestration très complexes ou les dépendances système exotiques.</li></ul><h3>Feuille de Route d’Implémentation (Stack Cloud Run)</h3><p>Pour construire un agent de production robuste :</p><ol><li><strong>Infrastructure (Phase 1) :</strong> Créez un projet GCP avec un compte de service dédié (agent-sa). Utilisez <strong>Secret Manager</strong> pour stocker les clés API (Tavily, Slack, etc.).</li><li><strong>Logique (Phase 2 — LangGraph) :</strong> Définissez l’état de votre agent (AgentState). Utilisez des décorateurs @tool pour exposer vos fonctions Python au modèle Gemini.</li><li><strong>Persistance (Phase 3) :</strong> Connectez un PostgresSaver (Cloud SQL) à votre graphe LangGraph. Cela permet à l&#39;agent de &quot;se souvenir&quot; de l&#39;état même si le conteneur Cloud Run redémarre.</li><li><strong>Déploiement (Phase 4) :</strong> Conteneurisez avec Docker. Déployez sur Cloud Run avec --min-instances 1 pour éviter les démarrages à froid si la réactivité est critique.</li></ol><blockquote><strong>Nous detaillerons dans la partie 2 une implementation de bout en bout via Cloud Run, pour la partie 3 , une implementation via Vertex AI Agent Engine.</strong></blockquote><h3>Interopérabilité : A2A et MCP</h3><p>L’avenir réside dans la collaboration entre agents. Deux standards émergent :</p><h4>Protocole Agent2Agent (A2A)</h4><p>C’est le “HTTP des Agents”. Il permet à un agent de découvrir les capacités d’un autre agent via une “Carte d’Agent” (agent.json) et de lui déléguer des tâches de haut niveau sans connaître son fonctionnement interne.</p><ul><li><em>Exemple :</em> Votre agent principal délègue la recherche de vols à un agent spécialisé via A2A.</li><li><strong>Agent A (Voyage)</strong> ↔ <strong>Protocole A2A</strong> ↔ <strong>Agent B (Réservation)</strong></li></ul><h4>Model Context Protocol (MCP)</h4><p>C’est l’”USB-C de l’IA”. Il standardise la connexion entre un modèle et ses données (fichiers, GitHub, bases de données).</p><ul><li><em>Utilisation :</em> Au lieu de coder une intégration spécifique pour Google Drive, vous branchez simplement le “Serveur MCP Google Drive” à votre agent.</li></ul><h3>Conclusion</h3><p>Ce schéma montre que l’IA n’est pas juste un “robot qui parle”. C’est un écosystème complexe où un <strong>Agent</strong> coordonne une <strong>Mémoire</strong>, un <strong>Cerveau (Modèle)</strong> et des <strong>Outils</strong> pour vous rendre service. Dans les prochaines parties nous allons presentés certaines implementations concretes via avec les services Google Cloud sur-cités.</p><h3><strong>References</strong></h3><ol><li><a href="https://docs.cloud.google.com/architecture/choose-agentic-ai-architecture-components#model-runtime-cloud-run">https://docs.cloud.google.com/architecture/choose-agentic-ai-architecture-components#model-runtime-cloud-run</a></li><li><a href="https://www.youtube.com/watch?v=WM2XLr4k-2M&amp;t=5s">Ultimate Guide: Deploy Google ADK Agents to Vertex AI &amp; Cloud Run (Step-by-Step Tutorial)</a></li><li><a href="https://www.youtube.com/watch?v=4NHK88_GE9I">Build &amp; Deploy FastAPI App with Docker &amp; GCP CI/CD with GitHub Actions Secure &amp; Scalable Cloud API</a></li><li><a href="https://www.linkedin.com/pulse/how-deploy-ai-agent-google-cloud-run-github-actions-vinay-kumar-mb74c/">How to Deploy an AI Agent on Google Cloud Run (with GitHub Actions)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2308f90322f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Long Live the IDE: How Google Colab in VS Code Redefines the AI Development Loop]]></title>
            <link>https://yannicksergeobam.medium.com/long-live-the-ide-how-google-colab-in-vs-code-redefines-the-ai-development-loop-8204c244db5a?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8204c244db5a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[google-developer-expert]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 23:35:12 GMT</pubDate>
            <atom:updated>2025-11-22T23:35:12.005Z</atom:updated>
            <content:encoded><![CDATA[<p>For the modern AI developer, the cognitive schism is all too familiar. Your mind lives in two places at once: the structured, version-controlled world of your local IDE — be it VS Code, PyCharm, or another — and the ephemeral, power-on-tap realm of the cloud notebook. You meticulously craft a model architecture in your local model.py, only to face the ritual of zip, upload, and environment-recreation in a Google Colab tab to access its promised GPU. This context-switching isn&#39;t just a minor inconvenience; it&#39;s a tax on productivity, a breaker of flow state, and a source of insidious bugs.</p><p>For years, the community built bridges — Git hooks to sync code, custom scripts to mount drives, endless pip install incantations. We patched the divide because we had to. But today, the landscape has fundamentally shifted. Google has not just built a bridge; they have merged the continents. The launch of the official Google Colab extension for Visual Studio Code marks the beginning of a new era: the Cloud-Native IDE.</p><p>This isn’t merely a feature addition. It’s a philosophical statement on the future of development where the editor is the control plane, and the cloud is the execution engine. Let’s dive into how this integration redefines the AI workflow.</p><h4>From Fragmentation to Fusion: The Core Paradigm Shift</h4><p>The genius of the Colab extension lies in its simplicity. It doesn’t ask you to change how you work; it enhances where your work executes.</p><ul><li>For the VS Code Purist: You no longer sacrifice your meticulously configured .vscode/settings.json, your powerful GitLens history, your custom snippets, or your terminal multiplexing for the sake of a free T4 GPU. Your IDE remains your sanctuary. Now, it simply has a direct line to a data center.</li><li>For the Colab Power-User: The limitations of a browser tab — limited file exploration, weaker debugging, and the friction of integrating with larger codebases — are lifted. You can now work on a single notebook within a complex monorepo, leveraging VS Code’s superior IntelliSense, linters, and structural understanding of your entire project, all while executing on a Colab Pro A100.</li></ul><p>The extension effectively decouples the <em>authoring environment</em> from the <em>execution environment</em>, marrying the best of both.</p><h4>Technical Deep Dive: Installation and Beyond the Hello World</h4><p>While the setup is straightforward, understanding the architecture is key.</p><p><strong>Step 1: Installation and Authentication</strong><br>Navigate to the Extensions view (Ctrl+Shift+X), search for &quot;Google Colab,&quot; and install. The required Jupyter extension will be handled as a dependency. The first time you connect a notebook to a Colab kernel, you&#39;ll undergo a standard OAuth 2.0 flow with your Google account. This secure token management is the bedrock of the connection, handled seamlessly by the extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCKYuVHB11hyeTAYMDomTg.png" /></figure><p><strong>Step 2: Kernel Selection — The Magic Moment</strong><br>Create a new notebook or Open a .ipynb file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lSssJusWcXyKmYUFHul4g.png" /></figure><p>Click the kernel selector in the top-right. Instead of choosing a local Python environment, you now select &quot;Colab&quot;. This action doesn&#39;t just start a Jupyter server; it provisions a full, isolated virtual machine in Google&#39;s cloud, tailored for your session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1Ke80euzjvxk9HcVKlFLg.png" /></figure><p><strong>Step 3: Strategic Hardware Selection</strong><br>This is where strategy meets execution. The hardware menu is your leverage point.</p><ul><li>Free Tier: Your gateway to NVIDIA T4 GPUs and TPU v5e accelerators. Perfect for prototyping, learning, and medium-scale models.</li><li>Colab Pro/Pro+: The professional’s choice. Unlocks premium GPUs like the NVIDIA A100 and V100, offering the memory and speed necessary for training large language models or conducting hyperparameter sweeps efficiently.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vV8RZWBQyKDxSASvgzu8-A.png" /></figure><p>Your choice here is no longer a separate decision made in a different UI; it’s an integrated part of your project’s run configuration.</p><h4>Real-World Scenarios: The New Workflow in Action</h4><p>Let’s move beyond theory into practical, powerful use cases that were previously cumbersome.</p><p><strong>Scenario 1: The Iterative Model Trainer</strong><br>You’re developing a novel computer vision model. Your code is structured across multiple files: data/loaders.py, models/architectures.py, training/engine.py. The training script, train.py, imports from these.</p><ul><li>The Old Way: Run locally to debug syntax. Zip the project. Upload to Colab. Use !unzip and hope the paths are correct. Pray that the Colab environment has the right versions of albumentations and pytorch-lightning.</li><li>The New Way:</li></ul><ol><li>Your entire project is open in VS Code.</li><li>Open a debug_training.ipynb notebook.</li><li>Connect its kernel to a Colab A100.</li><li>In the first cell, use %run train.py.</li><li>The script executes on the cloud A100, with the full context of your local project structure. You can use the VS Code debugger to set breakpoints in your local engine.py and step through the code as it runs remotely. This is a game-changer for complex, multi-file projects.</li></ol><p><strong>Scenario 2: The Interactive Data Explorer</strong><br>You receive a 50GB Parquet file. It’s too large for your local memory.</p><ul><li>The New Way:</li></ul><ol><li>In your VS Code notebook connected to a Colab High-RAM runtime, you can use dask or vaex to lazily load the data.</li><li>As you explore and plot with matplotlib, the figures render inline in your VS Code notebook.</li><li>You use VS Code’s variable explorer (from the Jupyter extension) to inspect the size and shape of your DataFrames in real-time.</li><li>Once you’ve refined your processing pipeline, you extract the code into a .py script, version control it with Git in VS Code, and schedule it on a cloud function—all without ever leaving your editor.</li></ol><h4>Navigating the Nuances: Power and Limitations</h4><p>This is a v1 product, and using it effectively requires an understanding of its boundaries.</p><ul><li><strong>File System Semantics</strong>: You are operating on the Colab VM’s disk. Files you create will be lost when the runtime is recycled. The canonical pattern for persistence is to mount Google Drive at the start of your session (from google.colab import drive; drive.mount(&#39;/content/drive&#39;)).</li><li><strong>Secrets Management</strong>: The web UI’s convenient “Key” icon for secrets is not yet available. The secure workaround is to use the Colab file upload method to place a .env file in the runtime&#39;s environment and load it with python-dotenv.</li><li><strong>Statefulness</strong>: Colab runtimes are disposable. The extension makes it easy to reconnect, but you must architect your notebooks and scripts to be re-runnable. This is a best practice that the extension actively encourages.</li></ul><h4>The Strategic Horizon: What This Enables</h4><p>The Colab extension is a Trojan Horse in the best possible sense. It’s not just a tool; it’s a platform play.</p><ol><li><strong>VS Code as the Universal AI Workbench:</strong> Google is effectively endorsing VS Code as the front-end for its AI/ML cloud stack. It’s easy to imagine future extensions that bring Vertex AI, Model Garden, and Gemini API workflows directly into this same interface.</li><li><strong>Democratizing Specialized Hardware</strong>: By lowering the friction to TPUs, Google accelerates adoption of its proprietary silicon, creating a formidable moat against other cloud providers.</li><li><strong>The Blurring of Local and Cloud</strong>: This is the most profound trend. The concept of a “local setup” for AI is becoming obsolete. The future is a hybrid, on-demand environment where the IDE is a thin client for a universe of compute.</li></ol><h4>Conclusion</h4><p>The Google Colab extension for VS Code is a definitive step forward. It eliminates a fundamental friction point that has plagued data scientists and AI developers for a decade. By bringing cloud-scale compute directly into the world’s most popular code editor, it doesn’t just make us faster; it changes the very nature of what we can build and how we think about building it.</p><p>The era of the Cloud-Native IDE is here. Your local environment is now just a launchpad. Strap in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8204c244db5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comment j’ai été certifié Tensorflow Developer]]></title>
            <link>https://yannicksergeobam.medium.com/comment-jai-%C3%A9t%C3%A9-certifi%C3%A9-tensorflow-developer-34eb31e7ed4f?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/34eb31e7ed4f</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[google-developer-expert]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 16:37:39 GMT</pubDate>
            <atom:updated>2021-11-07T21:36:28.033Z</atom:updated>
            <content:encoded><![CDATA[<p>Quelques astuces pour étudier, préparer et réussir l’examen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*hgkiXK1R0yGvk7_g2b7tkQ.png" /><figcaption>Certificat Developpeur Tensorflow — Yannick Serge Obam</figcaption></figure><p>Hourraaayy ! 🤩 C’est officiel, je suis desormais Certifié Developeur Tensorflow👨‍🎓. Certainement vous vous demandez 🤷: En quoi renvoit ce certificat? Comment ai -je étudié et préparé ce challenge ? Et Comment s’est déroulé l’examen ? Répondre à ces questions est le leikmotiv de cet article. Aussi, je vous donne quelques astuces pour réussir cet examen😉.</p><h3>Programme Dévelopeur Tensorflow</h3><p>T<a href="https://www.tensorflow.org/">ensorFlow</a> est un framework utilisé pour créer et entrainer facilement des modèles de machine et d’apprentissage en profondeur. Pour résoudre des problèmes de ML et de deep learning et démontrer votre maitrise de cet outil, il serait interessant que vous soyez reconnu pour vos compétences dans ce domaine. D’où le programme <a href="https://www.tensorflow.org/certificate?hl=fr">Tensorflow Developer Certificate</a>, où vous devez réussir l’examen conçu par l’équipe tensorflow. Cet examen qui coûte <strong>100 $</strong> , teste vos connaissances en matière de création et d’entrainement de modèles pour résoudre des problèmes du monde réel tels que:</p><ol><li><strong>Problèmes d’image</strong> tels que la classification des images ou des problèmes de détection d’objets.</li><li><strong>Problèmes de langage naturel</strong> tels que la classification du texte et la génération de texte.</li><li><strong>Séries temporelles </strong>pour prévoir par exemple l’évolution de la vente d’un produit pour ajuster au mieux les moyens de production, prévoir l’évolution d’un marché financier.</li></ol><h3><strong>Préparation à l’examen</strong></h3><p>Je vous conseille fortement de vous inscrire à la certification DeepLearning.ai <a href="https://www.coursera.org/professional-certificates/tensorflow-in-practice"><strong>TensorFlow Developer Professional Certificate </strong></a>de la plateforme <a href="https://www.coursera.org/">coursera</a>. Les cours realisés sont très bien structurés🧐 et idéals pour un débutant en deep learning.</p><p>A mon humble avis, cette spécialisation est largement suffisant pour réussir votre examen, il vous suffirait de réaliser tous les labs(Travaux pratiques)💪 associés durant le temps estimé (<strong>16 semaines)</strong> pour terminer le parcours. Allé jeter rapidement un coup d’oeil, du premier bord vous serait satisfait du contenus et de l’expertise des enseignants.</p><p>Le manuel du candidat ci-après, vous donne la liste des compétences que vous devez acquérir : <a href="https://www.tensorflow.org/extras/cert/TF_Certificate_Candidate_Handbook.pdf?hl=fr">https://www.tensorflow.org/extras/cert/TF_Certificate_Candidate_Handbook.pdf?hl=fr</a></p><p>Une fois les cours bouclés , il faudrait déjà mettre en place son environnement de travail pour l’examen. Pour cela, il vous faudrait installer PyCharm et le plugin <strong>Tensoflow exam.</strong></p><p>Pour des instructions spécifiques sur la configuration de l’environnement, clicquez ici: <a href="https://www.tensorflow.org/extras/cert/Setting_Up_TF_Developer_Certificate_Exam.pdf">https://www.tensorflow.org/extras/cert/Setting_Up_TF_Developer_Certificate_Exam.pdf</a></p><h3>Déroulement de l’examen</h3><p>Une fois mon environnement installé, dans PyCharm, j’ai cliqué sur « Démarrer l’examen » pour lancer le processus de certification. PyCharm a ensuite été rempli avec tout le contenu de l’examen.</p><p>La notation était basée sur 5 modèles que je devais entraîner durant 5 heures, avec des niveaux de difficulté croissants. Pour l’entrainement de mes modèles, j’ai utlisé Google Colab avec GPU et copié les modèles sous format .h5 dans le dossier de l’examen pour le test.</p><p>Rassurez vous d’avoir l’energie électrique ⚡durant ces 5h de temps, dans mon cas j’ai eu une mésaventure 😱 incroyable. En travaillant sur mon desktop, j’ai eu malheureusement un délestage de plus 2h à peine 30 min du début de l’examen🥺. Une fois l’energie arrivé 🤦🏻‍♂️, il me restait à peine 2h pour finaliser mes modèles, mais cela était largement suffisant pour moi 😎 de les terminer avec succès👨🏻‍💻.</p><p>Pour chaque modèle j’ai pu tester mon score directement dans PyCharm, je me suis rassuré d’avoir une note de 5/5 pour chacun. enfin , j’ai terminé l’examen et soumis mes résultats.</p><p>Peu de temps après j’ai reçu une notification par e-mail que j’ai réussi la certification !🕺.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klBZeBQEyql-Xf60o2KiJA.png" /></figure><p>Maintenant c’est à vous de jouer 😉, Si vous parcourez les liens et les documents que j’ai énumérés ci-dessus et que vous vous entraînez véritablement, vous devriez pouvoir passer ce test. Le délai de préparation variera énormément en fonction de votre capacité d’apprentissage et de votre expérience antérieure dans ce domaine.</p><p>Je tiens à remercier le programme <a href="https://developers.google.com/community/experts">Google Developers Expert</a> pour avoir soutenu ma préparation et l’examen.</p><p>Bonne chance à vous</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34eb31e7ed4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimiser les hyperparamètres d’un modèle de Deep learning]]></title>
            <link>https://yannicksergeobam.medium.com/optimiser-les-hyperparam%C3%A8tres-dun-mod%C3%A8le-de-deep-learning-d65643141282?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d65643141282</guid>
            <category><![CDATA[tensorboard]]></category>
            <category><![CDATA[tensoflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[inception-v3]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 23:40:26 GMT</pubDate>
            <atom:updated>2021-06-30T09:51:41.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mr1ZfHsw9k4mQl666mIWQw.gif" /><figcaption>source : <a href="https://henry090.github.io/kerastuneR/">https://henry090.github.io/kerastuneR/</a></figcaption></figure><p>Durant la construction d’un modèle de Deep Learning, l’on fait face aux choix des hyperparamètres. Notons tout de meme qu’un hyperparamètre est un paramètre dont la valeur est définie avant le début du processus d’apprentissage. Par ricorchet, il est evident que les valeurs des autres paramètres sont obtenus pendant l’entrainement.</p><p>Pour être plus précis, Pour les réseaux de neurones profonds, l’on peut distinguer 03 types d’hyperparamètres :</p><p>❒ <strong>Les hyperparamètres des layers </strong>: kernel size, dropout, méthode d’activation des layers cachés, méthode d’activation du layer final, …</p><p>❒ <strong>Les hyperparamètres de compilation</strong> du modèle: optimizer, loss, learning rate …</p><p>❒ <strong>Les hyperparamètres d’exécution</strong> du modèle : batch size, nombre d’epochs, …</p><p>Lors des choix de ces hyperparamètres, l’implementation d’un modèle semble être un casse tête chinois pour les datascientistes. Plusieurs entre eux passent des heures à les régler manuellement afin d’obtenir les meilleurs performances.</p><p>Il est donc claire que les hyperparamètres sont cruciaux pour les performances, la vitesse et la qualité des modèles d’apprentissage profond. Il faut trouver un moyen de les adjuster automatiquement, dans le jargon datascientiste, il s’agit de les optimiser .</p><p>Pour le faire, nous avons besoin d’une méthode systématique. C’est ainsi qu’il existe des techniques de base telles que <strong><em>Grid Search </em></strong>(la recherche en grille)<strong><em> </em></strong>, <strong><em>Random Search</em></strong> (la recherche aleatoire). Egalement des techniques plus sophistiquées telles que l’<strong><em>optimisation bayésienne</em></strong>, <a href="https://arxiv.org/pdf/1603.06560.pdf"><strong><em>Hyperbande</em></strong></a><strong>.</strong></p><p>Dans ce tutoriel, nous essayons de trouver le meilleur modèle de classification d’images sur le jeu de donnée <a href="https://public.roboflow.com/classification/rock-paper-scissors">Pierre, papier cisceaux</a> en utilisant l’hyperbande et l’optimisation baésienne à travers le framework <a href="https://keras-team.github.io/keras-tuner/"><strong>Keras Tuner</strong></a> et le tableau de bord <strong>HParams</strong> dans <a href="https://tensorboard.dev/"><strong>TensorBoad</strong></a>.</p><p>Alors, dans un premier temps, nous créeons un modèle de bout en bout ensuite nous implémentons un autre modèle via l’ apprentissage par transfert.</p><h3>Optimisation des hyperparametres avec Keras Tuner</h3><p>Keras Tuner est une librairie d’optimisation d’hyperparamètres facile à utiliser et distribuable qui résout les problèmes liés à l’exécution d’une recherche d’hyperparamètres. Keras Tuner est livré avec des algorithmes d’optimisation bayésienne, d’hyperbande et de recherche aléatoire intégrée, et est également conçu pour être facile à étendre pour les chercheurs afin d’expérimenter de nouveaux algorithmes de recherche.</p><p><strong>Installer Keras Tuner</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5845917c3a442afdb61cadca97cde7ca/href">https://medium.com/media/5845917c3a442afdb61cadca97cde7ca/href</a></iframe><p><strong>Télecharger et prétraiter les images avec ImageDataGenerator</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*YDUiyzsh05B3JXlCc0XjDA.png" /></figure><h4><strong>1- L’hypermodèle</strong></h4><p>Nous créons un hypermodèle dans lequel nous definissons les différents hyperparamètres pour le réglage automatique. Voici la fonction utilisée pour construire l’hypermodèle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdc5093bc186e14cfa0245dbf9306a8c/href">https://medium.com/media/cdc5093bc186e14cfa0245dbf9306a8c/href</a></iframe><p>Dans cet hypermodèle, nous utilisons la méthode de choix des hyperparamètres. Nous donnons à chacun un nom et une liste de valeurs parmi lesquelles choisir. Les valeurs doivent être du même type. Dans Keras Tuner, les hyperparamètres ont un type (les possibilités sont Float, Int, Boolean et Choice) et un nom unique.</p><p>Ensuite, un ensemble d’options pour guider la recherche doit être défini: <em>une valeur minimale, maximale et par défaut pour les types Float et Int, un ensemble de valeurs possibles pour le type Choice,éventuellement, une valeur de pas, c’est-à-dire le pas minimal entre deux valeurs d’hyperparamètres</em></p><p>Dans ce cas nous avons :</p><p>❒ Le nombre de filtres pour les couches convolutives : entre 64 et 128</p><p>❒ Le taux d’abandon (dropout): Entre 0.1 et 0.5</p><p>❒ Le nombre d’unités pour la couche dense : de 32 à 512 avec un pas à 32</p><p>❒ Les fonctions d’activation : choix entre Relu, Sigmoid , Tanh</p><p>❒ le taux d’apprentissage pour l’optimizer Adam : compris entre 0.01 , 0.001 , 0.0001</p><p><strong>Instancier le réglage et effectuer l’hypertuning</strong></p><p>Pour instancier le tuner Hyperband, nous devons spécifier l’hypermodèle, l’objectif à optimiser et le nombre maximum d’époques à entraîner (max_epochs)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/364617305318ff1ba364b0db0bd8d994/href">https://medium.com/media/364617305318ff1ba364b0db0bd8d994/href</a></iframe><p>Exécutons la recherche par hyperparamètres. Les arguments de la méthode de recherche sont les mêmes que ceux utilisés pourtf.keras.model.fit . Cela prends parfois assez de temps</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/515aaad572981a84203ecc7613918f7a/href">https://medium.com/media/515aaad572981a84203ecc7613918f7a/href</a></iframe><p><strong>Obtenir le meilleur resultat</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f248aa762ceb653a73a52d14fe64c2ee/href">https://medium.com/media/f248aa762ceb653a73a52d14fe64c2ee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*HSPzGIRFO2WyEGS4VhWLbA.png" /></figure><p>Après <strong>50 minutes 36 secondes </strong>sur Google Colab,<strong> </strong>le meilleur modèle obtenu avec un précision de <strong>95.9%</strong> a les caractéristiques ci-après:</p><p>Nombre de filtres <strong>64</strong>, nombre de neurones pour la couche dense <strong>512</strong>, taux d’abandon optimal<strong> 0.4</strong>, taux d’apprentissage<strong> 0.001.</strong></p><h4>2- Hypermodèle avec l’apprentissage de transfert</h4><p><strong>Telecharger l’architecture Inception</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0174877324678e0b208288fec1e9eb89/href">https://medium.com/media/0174877324678e0b208288fec1e9eb89/href</a></iframe><p><strong>Définir l’hypermodèle</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b481e6d4e534f5f8fb806b3e777af7b/href">https://medium.com/media/8b481e6d4e534f5f8fb806b3e777af7b/href</a></iframe><p>le code d’intanciation de tuner est similaire à celui que nous avons ecrit plus haut.</p><p>Le meilleur modèle a des caratéristiques suivantes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*gziOqe39WxYKDcN0d6rA4Q.png" /></figure><p>le nombre de neurones pour la <strong><em>couche dense</em></strong> est égale à <strong><em>352</em></strong>, le <strong><em>dropout</em></strong> à <strong>0.40, le taux d’apprentissage </strong>de l’optimizer<strong> </strong>à<strong> 0.001.</strong></p><p>Le résultat semble être très interressant avec une precision à <strong>99.19% </strong>et il a fallu<strong> 51 minutes 27 secondes </strong>pour finaliser l’optimisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*N12wDyRalOgQuJGa3Jzl4w.png" /></figure><h3>Optimisation des hyperparametres avec le tableau de bord HParans dans TensorBoard</h3><blockquote>TensorBoard est la boîte à outils de visualisation de TensorFlow, qui vous permet de suivre des métriques telles que la perte et la précision, de visualiser le graphique du modèle, d’afficher des histogrammes de poids, de biais ou d’autres tenseurs à mesure qu’ils changent au fil du temps, et bien plus encore. C’est un outil open source qui fait partie de l’écosystème TensorFlow</blockquote><p>Le tableau de bord HParams de TensorBoard fournit plusieurs outils qui nous aident dans le processus d’identification du meilleur modèle ou de l’ensemble d’hyperparamètres les plus interessants.</p><p><strong>Commencons par charger l’extension de TensorBoard</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49c74b15bc2d52ad6915c67ba2591688/href">https://medium.com/media/49c74b15bc2d52ad6915c67ba2591688/href</a></iframe><p><strong>Configuration des HParams</strong></p><p>L’experimentation se fait avec 05 hyperparametes : Nombre de filtres pour la couche convolution, le taux d’abandon, les fonctions d’activation (relu, tanh, sigmoid, le nombres de neurones pour la couche dense, l’optimizer (Adam, SGD, RMSProp)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99f1023351de61d377dbc9d7aafb51d9/href">https://medium.com/media/99f1023351de61d377dbc9d7aafb51d9/href</a></iframe><p><strong>Definir le modèle</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e121155908600517058626911f22bad8/href">https://medium.com/media/e121155908600517058626911f22bad8/href</a></iframe><p><strong>Exécuter et enregistrer Hparams</strong></p><p>Pour chaque analyse, nous enregistrons un résumé hparams avec les hyperparamètres et la précision finale.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02c0f60fadd840f7119402077eec9a1f/href">https://medium.com/media/02c0f60fadd840f7119402077eec9a1f/href</a></iframe><p>Ensuite nous exécutons quelques expériences, cela prend quelques minutes voir des heures</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245646dc1ced9c35a1eae31af0b6b4ed/href">https://medium.com/media/245646dc1ced9c35a1eae31af0b6b4ed/href</a></iframe><p><strong>Visualiser les résultats dans le plugin HParams de TensorBoard</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83a9e8b9fca1e952decc77602f788658/href">https://medium.com/media/83a9e8b9fca1e952decc77602f788658/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*zXBv_GEEQRPCnZ8Ab5Zwhg.png" /></figure><p>Cela nécessite beaucoup de temps dans une machine à 1 seul GPU, mais si nous avons certaines ressources Cloud, nous pouvons l’exécuter dans un environnement distribué.</p><p>Il était question pour nous de vous montrer de bout en bout comment vous pouvez régler/optimiser les hyperparamètres d’un modèle de classification d’images avec les réseaux de neurones profonds, pour cela nous sommes revenu sur la définition et les differents types d’hyperamètres. En utilisant l’ensemble de données <a href="https://public.roboflow.com/classification/rock-paper-scissors">Pierre, papier cisceaux</a>, nous avons implementer le réglage automatique avec la librairies Keras tuner sur un modele from scratch et sur un autre par apprentissage de transfert (Archiecture InceptionV3), mais aussi avec le tableau de bord HParans de TensorBoard sur un modèle from scratch. L’idée pour nous était de vous permettre d’appréhender les étapes d’une telle tâche. Pour plus de code, visiter le <a href="https://colab.research.google.com/drive/1FDiiSmXE7D6DAdKm4RuSQmc6DK3WhsbY?usp=sharing">notebook</a></p><p>Voilà, c’est ainsi que s’achève notre article. Nous esperons que cela vous aidera dans différents travaux d’optimisation d’hyperparamètres. Bonne apprentissage!</p><p><strong>Credits</strong></p><p><a href="https://openclassrooms.com/fr/courses"><em>OpenClassrooms</em></a></p><p><a href="https://keras-team.github.io/keras-tuner/"><em>The search space may contain conditional hyperparamet</em></a><em>ers</em></p><p><a href="https://henry090.github.io/kerastuneR/">Interface to Keras Tuner</a></p><p><a href="https://dcpatton.medium.com/hyperparameter-optimization-with-the-keras-tuner-part-1-3e1282565571"><em>Hyperparameter Optimization with the Keras Tuner, Part 1 | by David Patton, PhD | Medium</em></a></p><p><a href="https://medium.com/ml-book/neural-networks-hyperparameter-tuning-in-tensorflow-2-0-a7b4e2b574a1"><em>Neural Networks Hyperparameter tuning in tensorflow 2.0 | by SiDdhartha | ML Book | Medium</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d65643141282" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Génerer les images à l’aide des GANs avec Tensorflow]]></title>
            <link>https://yannicksergeobam.medium.com/g%C3%A9nerer-les-images-%C3%A0-laide-des-gans-avec-tensorflow-6c761311929d?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c761311929d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 20:04:08 GMT</pubDate>
            <atom:updated>2021-03-03T11:49:48.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ucVYsbDnwa2NM-f5qm_Yg.png" /><figcaption>source: Udacity</figcaption></figure><h3><strong>Comprendre les GANS</strong></h3><p>Les GANs (Generative Adversarial Networks) font partie des technologies les plus intéressantes voir populaire du deep learning (l’apprentissage profond). Elles disposent deux modèles, un générateur 𝐺 et un discriminateur<em> D </em>entrainés simultanément et qui se font concurrence. Le <em>générateur</em> est entrainé pour tromper le discriminateur et apprend à créer des images qui semblent réelles , tandis que le <em>discriminateur</em> apprend à distinguer les images réelles des fausses. Ce qui finit par arriver, est que le générateur crée des images que le dicsriminateur n’arrivent plus à distinguer comme fausses.</p><p>Rapportés pour la première fois en 2014 par <strong>Ian Goodfellow</strong> <strong>et d’autres</strong> dans le laboratoire de Yoshua Bengio, les <a href="http://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf">GANs</a> sont utilisés pour générer les données réalistes. La plupart de ses applications sont pour les images. Nous avons par exemple :</p><ul><li><a href="https://arxiv.org/abs/1612.03242">StackGAN</a>, pour la synthèse d’image réaliste</li><li><a href="https://github.com/junyanz/iGAN">iGAN</a>, pour la génération d’images interactives</li><li><a href="https://video.udacity-data.com/topher/2018/November/5bea23cd_cartoongan/cartoongan.pdf">CartoonGAN</a>, pour la caricature de photos</li><li><a href="https://arxiv.org/pdf/1611.07004.pdf">Pix2Pix</a>, <a href="https://arxiv.org/pdf/1703.10593.pdf">CycleGAN</a>, pour translation image à image</li><li><a href="https://github.com/wiseodd/generative-models">Et bien d’autres</a></li></ul><p>La structure générale d’un GAN est illustrée dans le diagramme ci-dessus, en utilisant des images the <a href="http://ufldl.stanford.edu/housenumbers/">Street View House Numbers</a> (SVHN) comme données. L’échantillon latent est un vecteur aléatoire que le générateur utilise pour construire ses fausses images. Au fur et à mesure que le générateur apprend par l’entrainement, il trouve comment mapper ces vecteurs aléatoires en images reconnaissables qui peuvent tromper le discriminateur.</p><h3>Projet d’apprentissage appliqué</h3><p>Nous souhaitons former un Reséau Antagoniste Generatif Convolutionnel Profond (DCGAN) capable de générer de nouvelles images réalistes des numéros de maison. Pour ce faire nous utilisons l’ensemble de données SVHM et Tensorflow 2.x suivant les étapes suivantes :</p><ul><li>Charger et prétraiter l’ensemble de données des numéros de maison</li><li>Définir les réseaux discriminateurs et générateurs</li><li>Entrainer ces réseaux antagonistes</li><li>Visualisez la perte au fil du temps et quelques exemples d’images générées</li></ul><h4>Récuperation et pretraitement des données</h4><p>Nous créons un dossier data et télechargeons le jeu de données SVHN</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e7416f1b37aa0bc69db35ee08343fc9/href">https://medium.com/media/5e7416f1b37aa0bc69db35ee08343fc9/href</a></iframe><p>Nous devons faire un peu de prétraitement et obtenir les images sous une forme où nous pouvons transmettre des lots au réseau. Tout d’abord, nous devons redimensionner les images dans une plage de -1 à 1, car grace à la fonction d’activation tanh, la sortie de notre générateur est également dans cette plage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31fbac29a35e34fe918d8028119596ad/href">https://medium.com/media/31fbac29a35e34fe918d8028119596ad/href</a></iframe><h4>Modelisation des réseaux, discriminateur et générateur</h4><p><strong><em>Le Generateur</em></strong></p><p>L’entrée est notre vecteur de bruit z. La sortie sera une sortie tanh, mais avec une taille 32x32 qui est la taille de nos images SVHN.</p><p>Nous utilisons des couches convolutives transposées pour créer nos nouvelles images.</p><ul><li>La première couche est une couche entièrement connectée qui est remodelée en une couche profonde et étroite: 4x4x512.</li><li>Ensuite, nous utilisons la normalisation par lots et une activation Leaky ReLU.</li><li>Le suivant est une série de transposer des couches convolutionnelles, où nous divisons généralement par deux la profondeur et doublons la largeur et la hauteur de la couche précédente.</li><li>Et, nous appliquerons la normalisation par lots et Leaky ReLU à toutes les couches cachées sauf la dernière. Où nous allons simplement appliquer une activation tanh.</li></ul><p>Le schema general est convolution &gt; batch norm &gt; leaky ReLU.</p><blockquote>Vous pouvez continuer à empiler les couches comme ceci jusqu’à ce que vous obteniez la couche de convolution transposée finale de la forme 32x32x3</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5aSeoe8KGoeY7uIN-vKGHQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1fdc4d63b203f00bf5c2035c52bd634/href">https://medium.com/media/a1fdc4d63b203f00bf5c2035c52bd634/href</a></iframe><p><strong><em>Le Discriminateur</em></strong></p><p>Il s’agit essentiellement d’un <strong>classifieur convolutionnel</strong>. Les entrées sont les tenseurs/images 32x32x3. Nous aurons besoin de quelques couches convolutives, puis d’une couche entièrement connectée pour la sortie sigmoïde. Notez que nous utilisons uniquement des couches convolutives <strong>sans couches maxpool</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxNdCJ8ZFHCR8bqltHyHow.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a50cd0b65984c8142c33add88ea8a28f/href">https://medium.com/media/a50cd0b65984c8142c33add88ea8a28f/href</a></iframe><p>Des lors nous pouvons definir les optimisateurs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edab9801c2707afe7b5cc33d476f24e1/href">https://medium.com/media/edab9801c2707afe7b5cc33d476f24e1/href</a></iframe><h4>Entrainement des Reseaux</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a0a3f591b9b0cd43d4dc2e9d04c7403/href">https://medium.com/media/7a0a3f591b9b0cd43d4dc2e9d04c7403/href</a></iframe><h4>Visualisation de la perte et des images générées</h4><p>Visualisons la perte au fil du temps</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a47194d9a7552942bf4850c1341b3277/href">https://medium.com/media/a47194d9a7552942bf4850c1341b3277/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*5ji92GiOemkrk3m0LGjokA.png" /></figure><p>Quelques exemples d’images générées</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*maQr6W1-8Cs8_3j2okLLoQ.png" /></figure><p>Pour plus de details regarder ce <a href="https://colab.research.google.com/drive/1Em-Kd_zrfvJ_bbNVs509kCie3o6Mv2or?usp=sharing">notebook</a></p><p>Les GAN sont très sensibles aux hyperparamètres. De nombreuses expériences sont nécessaires pour trouver les meilleurs hyperparamètres de sorte que le générateur et le discriminateur ne se maîtrisent pas mutuellement. Pour comprendre plus , Essayez vos propres hyperparamètres ou lisez l’article[DCGAN] (<a href="https://arxiv.org/pdf/1511.06434.pdf">https://arxiv.org/pdf/1511.06434.pdf</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c761311929d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprendre les Réseaux de Neurones Convolutifs (CNN)]]></title>
            <link>https://yannicksergeobam.medium.com/comprendre-les-r%C3%A9seaux-de-neurones-convolutifs-cnn-d5f14d963714?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f14d963714</guid>
            <category><![CDATA[french]]></category>
            <category><![CDATA[intelligence-artificielle]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Sat, 21 Dec 2019 21:44:04 GMT</pubDate>
            <atom:updated>2020-09-02T23:31:27.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*nNGcN3pLeMQ-vastC1Jx7w.png" /><figcaption>source : <a href="https://www.aspexit.com/">https://www.aspexit.com/</a></figcaption></figure><p>Le Deep Learning (DL) est un domaine de recherche du Machine learning (ML), basé sur l’idée des réseaux de neurones artificiels et taillé pour gérer de larges quantités de données en ajoutant des couches au réseau. D’une maniere simple c’est ML à l’aide de réseaux de neurones profonds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GKL-6uGuzPtEgPkehSH9Q.png" /><figcaption>from Facebook Developer Circles Resources</figcaption></figure><p>Parmi les grandes familles des reseaux de neurones profonds, nous avons les <strong>CNN</strong> (<strong><em>réseaux de neurones convolutifs </em>ou<em> réseaux de neurones à convolution</em></strong>). Ils constituent une évolution des réseaux de neurones artificiels traditionnels dont le motif de connexion entre les neurones est inspiré du <strong>cortex visuel des annimaux</strong>.<br>Ils sont axés principalement sur des applications comportant des motifs répétitifs dans différents domaines de l’espace de modélisation, notamment dans <strong><em>la reconnaissance d’image et vidéo, les systemes de recommendation, </em></strong>et<strong><em> le traitement du langage naturel.</em></strong></p><h3>Principe et fonctionnement</h3><p>La force des CNN se trouve dans la méthodologie utilisée dans leur stratification. Ils réduisent considérablement le nombre requis d’éléments structurels (nombre de neurones artificiels) par rapport aux réseaux de neurones à <strong><em>feed forward</em> </strong>traditionnels.<br>Donc ils recoivent des images en entrée detectant les caracteristiques de chacune d’entre elles puis entrainent un classifieur. Le nom « <strong>Réseau de neurones convolutif </strong>» indique que le réseau emploie une opération mathématique speciale appelée <strong><em>convolution </em></strong>à la place de la multiplication matricielle dans au moins une de ses couches<strong><em>.</em></strong></p><p>Ausi, sachons qu’une architecture atypique d’un réseau convolutif se compose de 4 types de couches différentes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*Ff6mG3aPdWFkjb6hZPy3Xw.gif" /></figure><p><strong>1- Couche convolutive</strong></p><p>Elle consite à appliquer un <strong><em>filtre de convolution</em></strong> à l’image pour détecter des caractérisques de l’image. Une image passe à travers une succession de filtres, ou noyaux de convolution, créant de nouvelles images appelées cartes de convolutions. Certains filtres intermédiaires réduisent la résolution de l’image par une opération de maximum local. Au final, les cartes de convolutions sont mises à plat et concaténées en un vecteur de caractéristiques.</p><p><strong>2- Couche de correction ReLU</strong></p><p>L’ on fait passer les cartes de convolution à travers une couche d’activation non linéaire telle que <strong><em>Rectified Linear Unit </em></strong>(ReLu), qui consiste à remplacer les nombres négatifs des images filtrées par des zéros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0Q7JrmdZRbU-Yfg3RYqjw.png" /></figure><p><strong>3- Couche de pooling : </strong>qui consiste à reduire progressivement la taille de l’image en ne gardant que les informations les plus importantes, par exemple pour chaque groupe de 4 pixel, le pixel ayant la valeur maximales (<strong><em>Max Pooling, le plus populaire</em></strong>) ou la moyenne des pixels (<strong>AVG pooling</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*4v-YctNtVWAlWlkdCAbEBg.png" /></figure><p>Avec la couche pooling, la quantité de paramètres et de calcul dans le réseau sont reduits, et cela va permettre de controler le sur-apprentissage.</p><p>Après avoir extrait les caractéristiques des entrées, on attache à la fin du réseau un perceptron ou bien un MLP (Multi Layer perceptron) communément appelé <strong>Fully connected.</strong></p><p><strong>4- Couche entierement connectée (Fully connected)</strong></p><p>elle recoit un vecteur en entrée contenant les pixels aplatis de tous les images filtrées, corrigées et reduites par le pooling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*5ZJRH0oMeW60Jdsidx_w1w.png" /><figcaption>mc.ai</figcaption></figure><p>Dans le cas d’une classification d’images, Le traitement d’images à travers l’extraction des caractéristiques et la segmentation en séquence d’entrée des images RGB se fait automatiquement à travers les couches de convolution et de pooling de nos modèles. L’application de la <strong><em>fonction softmax</em></strong> aux sorties de la couche fully connection, nous donne la probabilité d’une classe.</p><h3><strong>Usages pratiques</strong></h3><p>En suivant et en respectant l’approche detaillée plus haut, nous pouvons créer des modèles de réseaux de neurones convolutives de bout en bout efficaces.</p><p>Néanmoins, Il est possible d’exploiter la puissance des CNN sans être un expert du domaine, avec du matériel accessible et une quantité raisonnable de données étiquetées. Toute la complexité de création de CNN peut être évitée en adaptant des réseaux pré-entraînés disponibles publiquement. Ces techniques sont appelées <strong>transfert learning </strong>ou<strong> apprentissage par transfert,</strong> car on peut exploiter la connaissance acquise sur un problème de classification général pour l’appliquer de nouveau à un problème particulier.</p><p>Cette méthode est exploitée de deux façons :</p><p>· Comme un extracteur automatique de caractéristiques des images, matérialisé par le code CNN,</p><p>· Comme une initialisation du modèle, qui est ensuite ré-entraîné plus finement (<strong>Fine Tuning</strong>) pour traiter le nouveau problème de classification.</p><p>L’intérêt est double car l’on utilise une architecture optimisée avec soin par des spécialistes, et l’on profite des capacités d’extraction de caractéristiques apprises sur un jeu de données de qualité.</p><p>Ainsi s’achève notre article à propros des CNN, avec espoir que nous vous avons aider à mieux les comprendre. Bonne apprentissage!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f14d963714" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plant Disease Classification with TensorFlow Lite on Android Part 2]]></title>
            <link>https://yannicksergeobam.medium.com/plant-disease-classification-with-tensorflow-lite-on-android-part-2-c2d47371cea3?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2d47371cea3</guid>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Tue, 16 Jul 2019 14:58:47 GMT</pubDate>
            <atom:updated>2019-10-09T00:23:28.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xZqkgb4pteYllNQ5NrOleA.jpeg" /><figcaption>source IITA</figcaption></figure><p>For this project, we are going to create an end-to-end Android application with TFLite. We opte to develop an <strong>Android application that detects plant diseases.</strong></p><p>The project is broken down into two steps:</p><ul><li>Building and creating a machine learning model using TensorFlow with Keras. <a href="https://medium.com/@yannicksergeobam/plant-disease-classification-with-tensorflow-2-0-268fe7f72c2a"><strong>More details here</strong></a></li><li>Deploying the model to an Android application using TFLite.<strong> This step</strong></li></ul><h3>Add TFLite model in our Android Project</h3><p>First — load the model in our Android project, we put plant_disease_model.tflite andplant_labels.txt into assets/ directory. plant_disease_model.tflite is the result of our previous colab notebook. We need to add TFLite dependency to app/build.gradle file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/798e18d955fcd286bd3afdbb608db523/href">https://medium.com/media/798e18d955fcd286bd3afdbb608db523/href</a></iframe><p>Don’t forget to add the undermentioned snippet to prevent compressing the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/057bc8ff124a35cd2ab3b13820fc0342/href">https://medium.com/media/057bc8ff124a35cd2ab3b13820fc0342/href</a></iframe><h3>Dive into the code</h3><p>Create classifier class to load our model and read the file with labels:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da1d6392c9de3b9aead2f1f5f2ca44a4/href">https://medium.com/media/da1d6392c9de3b9aead2f1f5f2ca44a4/href</a></iframe><p>Where Recognition is our humble result data class :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0ab92518b73a3789faf8b19c78e2021/href">https://medium.com/media/f0ab92518b73a3789faf8b19c78e2021/href</a></iframe><p>When we have an instance of Interpreter, we need to convert the preprocessed bitmap into ByteBuffer then we create a method that will take an image as an argument and return a list of labels with assigned probabilities to them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba8572c1d5497531e7760ebd1e140f3d/href">https://medium.com/media/ba8572c1d5497531e7760ebd1e140f3d/href</a></iframe><p>Here’s how we convert a bitmap into ByteBuffer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5615bcb8f897ac8d1ffec1c0ba3c4a83/href">https://medium.com/media/5615bcb8f897ac8d1ffec1c0ba3c4a83/href</a></iframe><p>Our only layout looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*EP6z6uXyThPHsTk4P1l-Gg.png" /><figcaption>Only Layout of Green Doctor</figcaption></figure><p>Here is most of the MainActivity code, we’ll use in our app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5581e485f96bcc5340e82b1c679bcab7/href">https://medium.com/media/5581e485f96bcc5340e82b1c679bcab7/href</a></iframe><p>Where scaleImagemethod allows us to resize the image because our model expects the exact input shape (224x224 pixels), therefore we need to rescale a delivered bitmap to fit into these constraints:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a43d1cc0fb16297e3ba61fabb8299554/href">https://medium.com/media/a43d1cc0fb16297e3ba61fabb8299554/href</a></iframe><p>finally we get this app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*Y4NkWU1RcCQQYK97s2wCaw.png" /><figcaption>Green Doctor App</figcaption></figure><p><strong>App Demo</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2UYLglMni6E%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2UYLglMni6E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2UYLglMni6E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/975e444c5471309cbeac7563cb6e7fdc/href">https://medium.com/media/975e444c5471309cbeac7563cb6e7fdc/href</a></iframe><p>The source code of the project can be found on <a href="https://github.com/obeshor/Plant-Diseases-Detector"><strong>Github</strong></a> .</p><p>I can not finish this project without saying thank to my Coach <a href="https://medium.com/u/b1b3f04f9f55">Karthik M Swamy</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2d47371cea3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plant Disease Classification with TensorFlow 2.0]]></title>
            <link>https://yannicksergeobam.medium.com/plant-disease-classification-with-tensorflow-2-0-268fe7f72c2a?source=rss-50600c47fed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/268fe7f72c2a</guid>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow-hub]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Yannick Serge Obam]]></dc:creator>
            <pubDate>Tue, 14 May 2019 14:04:21 GMT</pubDate>
            <atom:updated>2019-07-16T15:01:00.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Plant Disease Classification with TensorFlow Lite on Android Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*R4SwNNnq9_MEqC7qMEBOug.jpeg" /><figcaption>Source: IITA</figcaption></figure><p>For this project, we are going to create an end-to-end Android application with TFLite. We opte to develop an <strong>Android application that detects plant diseases.</strong></p><p>The project is broken down into two steps:</p><ul><li>Building and creating a machine learning model using TensorFlow with Keras. <strong>This step</strong></li><li>Deploying the model to an Android application using TFLite. <strong>coming soon</strong></li></ul><h3><strong>Machine Learning model using Tensorflow with Keras</strong></h3><p><em>We designed algorithms and models to recognize species and diseases in the crop leaves by using Convolutional Neural Network. We use Colab for edit source code.</em></p><p><strong>Importing the Librairies</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b79b8e58e946a9bcf2652011fd1148f/href">https://medium.com/media/4b79b8e58e946a9bcf2652011fd1148f/href</a></iframe><p><strong>Loading the data</strong></p><p>Download a public dataset of 54,305 images of diseased and healthy plant leaves collected under controlled conditions <a href="https://storage.googleapis.com/plantdata/PlantVillage.tar)">PlantVillage Dataset </a>. The images cover 14 species of crops, including: apple, blueberry, cherry, grape, orange, peach, pepper, potato, raspberry, soy, squash, strawberry and tomato. It contains images of 17 basic diseases, 4 bacterial diseases, 2 diseases caused by mold (oomycete), 2 viral diseases and 1 disease caused by a mite. 12 crop species also have healthy leaf images that are not visibly affected by disease.</p><p>Create the training and validation directories:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7e7ce18dc10f8c4e9bf0f42b7296dbb/href">https://medium.com/media/c7e7ce18dc10f8c4e9bf0f42b7296dbb/href</a></iframe><p><strong>Label mapping</strong></p><p>You’ll also need to load in a mapping from category label to category name. This will give you a dictionary mapping the integer encoded categories to the actual names of the plants and diseases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16d8578ccf094f8285eb65c928db2cd9/href">https://medium.com/media/16d8578ccf094f8285eb65c928db2cd9/href</a></iframe><p><strong>Transfer Learning with TensorFlow hub</strong></p><p>Select the Hub/TF2 module to use, you have a choice with inception v3 or Mobilenet</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc23a43c5f7560ff6ef8130e96d93418/href">https://medium.com/media/cc23a43c5f7560ff6ef8130e96d93418/href</a></iframe><p><strong>Data Preprocessing</strong></p><p>Let’s set up data generators that will read pictures in our source folders, convert them to `float32` tensors, and feed them (with their labels) to our network.</p><p>As you may already know, data that goes into neural networks should usually be normalized in some way to make it more amenable to processing by the network. In our case, we will preprocess our images by normalizing the pixel values to be in the `[0, 1]` range (originally all values are in the `[0, 255]` range). we’ll need to make sure the input data is resized to 224x224 pixels or 299x299 pixels as required by the networks. You have the choice to implement <strong>image augmentation</strong> or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91b0edde5fc913ef7b3d94cc04a5dfb4/href">https://medium.com/media/91b0edde5fc913ef7b3d94cc04a5dfb4/href</a></iframe><p><strong>Build the model</strong><br>All it takes is to put a linear classifier on top of the feature_extractor with the Hub module. For speed, we start out with a non-trainable feature_extractor , but you can also enable fine-tuning for greater accuracy but that takes a lot of time to train model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa050ce30fdc9476a5eb19e3eb51b60c/href">https://medium.com/media/aa050ce30fdc9476a5eb19e3eb51b60c/href</a></iframe><p><strong>Specifying Loss Function and Optimizer</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/147f86fff38a8ec53095f94d07940e84/href">https://medium.com/media/147f86fff38a8ec53095f94d07940e84/href</a></iframe><h4>Training Model</h4><p>train model using validation dataset for validate each steps. After 10 epochs, we get 94% for accuracy, you can improve this more than 99% using fine-tuning</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f03a1f170aa448a1d80f80281b5d3311/href">https://medium.com/media/f03a1f170aa448a1d80f80281b5d3311/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lmYZgHUnn_RvprqHVbgCQ.png" /><figcaption>Training Model</figcaption></figure><p><strong>Checking Performance</strong><br>Plot training and validation, accuracy and loss</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/985f22ac2bdd8fb2c7b322942169f1b8/href">https://medium.com/media/985f22ac2bdd8fb2c7b322942169f1b8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*a3z6wfGMzl8izJHd9nJtwQ.png" /><figcaption>Accuracy and Loss</figcaption></figure><p><strong>Random test</strong><br>Random five sample images from validation dataset and predict:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3711f6e993cb9331007edc25c4d0b5f2/href">https://medium.com/media/3711f6e993cb9331007edc25c4d0b5f2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*IXvRurRFdAW8jaOvlybKbA.png" /><figcaption>Prediction 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*gFeIleK0tOPPPUKviE1-GQ.png" /><figcaption>Prediction 2</figcaption></figure><p>The model can be improved if you change some hyperparameters. You can try using a different pretrained model. It’s up to you. Let me know if you can improve the accuracy!</p><h4>Convert model to TensorFlow Lite</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647e710c243aac07dbd47a5ff0a7825e/href">https://medium.com/media/647e710c243aac07dbd47a5ff0a7825e/href</a></iframe><p>For more details, Go to the <a href="https://github.com/obeshor/Plant-Diseases-Detector">Github</a> or directly <a href="https://github.com/obeshor/Plant-Diseases-Detector/blob/master/Plant_Diseases_Detection_with_TF2_V2.ipynb">Colab</a></p><p>Let’s develop an Android app that uses this model. <a href="https://medium.com/@yannicksergeobam/plant-disease-classification-with-tensorflow-lite-on-android-part-2-c2d47371cea3"><strong>Link</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=268fe7f72c2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>