<?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 Nikhil Tomar on Medium]]></title>
        <description><![CDATA[Stories by Nikhil Tomar on Medium]]></description>
        <link>https://medium.com/@nikhilroxtomar?source=rss-a4782a8f5e78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VpZG0A1ZdwqSEIbr7ZIyGA.png</url>
            <title>Stories by Nikhil Tomar on Medium</title>
            <link>https://medium.com/@nikhilroxtomar?source=rss-a4782a8f5e78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:58:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikhilroxtomar/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[Subhas Chandra Bose, INA, and the Final Blow to British Rule in India]]></title>
            <link>https://nikhilroxtomar.medium.com/subhas-chandra-bose-ina-and-the-final-blow-to-british-rule-in-india-361417b4c34c?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/361417b4c34c</guid>
            <category><![CDATA[clement-attlee]]></category>
            <category><![CDATA[royal-indian-navy-mutiny]]></category>
            <category><![CDATA[subhas-chandra-bose]]></category>
            <category><![CDATA[ina-trials]]></category>
            <category><![CDATA[indian-national-army]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 07:26:21 GMT</pubDate>
            <atom:updated>2025-05-07T05:49:08.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAEWuqnRQ7R89OY18gWHWA.jpeg" /></figure><p>The Indian freedom struggle witnessed several waves of resistance, but few had as electrifying an impact as the rise of Subhas Chandra Bose and the Indian National Army (INA). Though Bose’s audacious campaign and the cascading effects of the INA Trials shook the very foundation of British authority. It was not just a military endeavor but a psychological and political revolution that set the stage for India’s final push for freedom. The trials, followed by the Royal Indian Navy (RIN) mutiny and labor uprisings, culminated in a mass awakening that eventually forced the British to retreat. This article explores how Bose and INA became the proverbial last nail in the coffin for the British Raj.</p><h3>Bose and the Birth of the Indian National Army (INA)</h3><p>Subhas Chandra Bose, a charismatic nationalist leader and former president of the Indian National Congress, broke away from Mahatma Gandhi’s nonviolent path, believing that only armed struggle could dislodge the British. During World War II, Bose sought international alliances, famously stating:</p><blockquote><em>“ Freedom is not given, it is taken.” — Subhas Chandra Bose</em></blockquote><p>He formed the INA in collaboration with Imperial Japan, using Indian POWs from the British Army captured in Southeast Asia. His call to arms, “ <strong>Give me blood, and I will give you freedom</strong>,” became one of the most iconic slogans in India’s freedom movement.</p><p>With the rallying cry of <strong>“Chalo Dilli” (On to Delhi)</strong>, Bose and the INA fought alongside the Japanese in the Burma campaign. Though militarily defeated, the INA’s march ignited a wave of patriotism across India. Bose had also established a government-in-exile, the <em>Azad Hind Government</em>, which was recognized by several Axis powers.</p><p><strong>Notably, the INA had its own currency, stamps, court, and civil code — further symbolizing sovereignty</strong>. More than its battlefield success, it was the symbolism and psychological warfare of the INA that rattled the British. <strong>The idea that Indian soldiers — once the backbone of the British military — could rise against their colonial masters shook the empire’s confidence.</strong></p><blockquote><em>“ Freedom is not given, it is taken.” — Subhas Chandra Bose</em></blockquote><h3>Legacy of Bose and INA: A Silent Revolution</h3><p>Though Subhas Chandra Bose is sometimes portrayed as a military failure, his legacy is far greater. He planted the idea that <strong>freedom could be taken, not just negotiated</strong>. The INA uniforms, songs like <em>“Kadam Kadam Badhaye Ja,”</em> and the tales of bravery inspired generations of Indians. More than Gandhi’s peaceful satyagraha or Nehru’s diplomacy, Bose gave Indians the hope that they could<strong> fight, resist, and win</strong>.</p><figure><img alt="Subhas Chandra Bose and the Rani of Jhansi Regiment of the INA." src="https://cdn-images-1.medium.com/max/1024/0*1O46W9qY3lfVHM62.jpg" /><figcaption>Subhas Chandra Bose and the Rani of Jhansi Regiment of the INA.</figcaption></figure><p>The INA recruited over 40,000 soldiers, including women like Captain Lakshmi Sahgal, who led the Rani of Jhansi Regiment-one of the world’s first female combat units. This progressive vision of gender equality in a revolutionary army was unique in its time and made Bose even more popular among the Indian masses.</p><p><strong>READ MORE: </strong><a href="https://sciencetonight.com/resignation-of-subhas-chandra-bose-from-congress-presidency-in-1939/"><strong>Resignation of Subhas Chandra Bose from Congress Presidency in 1939</strong></a></p><h3>The INA Trials and the Firestorm of Nationalist Sentiment</h3><p>In late 1945, the British made a critical miscalculation by deciding to court-martial captured INA officers at the Red Fort in Delhi. The trial of <strong>Colonel Prem Sahgal, Colonel Gurbaksh Singh Dhillon, and Major Shah Nawaz Khan</strong> became a national spectacle.</p><p>Rather than alienate the INA from the masses, the trials generated <strong>nationwide sympathy</strong>. Political leaders, cutting across ideological lines — from Jawaharlal Nehru to Sardar Patel and C. Rajagopalachari — defended the INA soldiers publicly. The Congress organized massive rallies, students boycotted classes, and workers walked off their jobs. The entire country seemed to rally behind the INA, making the British rethink their approach.</p><p>The trials transformed INA officers into <strong>national heroes</strong>, and for the first time since the Revolt of 1857, Indians saw military defiance against British rule as legitimate and even glorious.</p><h3>The Royal Indian Navy (RIN) Mutiny: An Armed Rebellion</h3><p>The impact of the INA saga extended beyond civilian life and seeped into the military. On <strong>February 18, 1946</strong>, nearly 20,000 sailors of the Royal Indian Navy mutinied against British officers aboard <strong>HMIS Talwar in Bombay</strong>. Inspired by the INA and fed up with <strong>racial discrimination, poor pay, and bad food</strong>, the ratings declared a strike and took control of several ships and shore establishments.</p><p>They raised the Indian tricolor alongside the British Union Jack and chanted slogans of “Jai Hind” and “Netaji Zindabad.” The mutiny quickly spread to Karachi, Calcutta, and Vizag. Though the Congress and Muslim League both distanced themselves from the uprising (fearing anarchy), the message was clear: <strong>the Indian armed forces were no longer loyal to the Crown</strong>.</p><p>It took days and the intervention of Indian leaders like Sardar Patel to bring the mutiny to an end. But the damage to British prestige was done.</p><h3>Supporting Uprisings: The Air Force and Workers’ Strikes</h3><p>The mutiny inspired smaller revolts within the <strong>Royal Indian Air Force</strong> and triggered <strong>strikes by dock workers, railwaymen, and postal staff</strong> in major cities. The solidarity displayed by civilians and military personnel alike suggested that a <strong>pan-Indian rebellion was brewing</strong>, one the British could no longer control.</p><p>According to the Indian Express archives, February-March 1946 saw more than 100 strikes in Bombay alone, mostly in support of the naval mutineers.</p><h3>British Realization: Commissions and Internal Panic</h3><p>The British response included <strong>commissions of inquiry</strong> into the INA and the naval mutinies, but these were widely perceived as face-saving measures. The deep unrest within the armed forces, once considered the most dependable pillar of British rule, was <strong>an alarming red flag</strong> for British intelligence and administration.</p><p>Field Marshal Claude Auchinleck, the Commander-in-Chief, warned the government that if another trial of INA men was held, the army might revolt. <strong>This was unprecedented</strong>.</p><blockquote><em>“ The Indian Army is no longer a reliable instrument for maintaining British rule.” — Confidential British intelligence memo (1946, British National Archives)</em></blockquote><h3>Clement Attlee, Labour Party, and the Winds of Change</h3><p>The political landscape in Britain itself was shifting. In 1945, <strong>Winston Churchill’s Conservative Party lost to the Labour Party</strong>, led by <strong>Clement Attlee</strong>. The economic exhaustion after World War II and mounting pressure in India made Attlee increasingly convinced that Britain could no longer hold onto India.</p><p>Significantly, in 1956, during a visit to India, Attlee reportedly had a private conversation with <strong>Justice P.B. Chakrabarty</strong>, the then Acting Governor of Bengal and former Chief Justice of the Calcutta High Court. When asked about the real reasons behind the British decision to leave India, Attlee remarked that <strong>Subhas Chandra Bose and the INA had shaken the loyalty of the Indian Army</strong>, which was the cornerstone of British control in India. According to Chakrabarty’s account, Attlee said the British feared another military rebellion like the one during the INA trials and the naval mutiny.</p><p>When asked about <strong>Mahatma Gandhi’s role</strong>, Attlee is said to have <strong>smiled and remarked with a tone of dismissal</strong>:</p><blockquote><em>“ Minimal.”</em></blockquote><p>This candid statement underscores how the <strong>British establishment viewed the threat posed by the INA and the potential collapse of loyalty within the armed forces as far more decisive</strong> than Gandhi’s nonviolent campaigns at that critical juncture. While Gandhi’s long-term influence in mobilizing the masses is undisputed, Attlee’s words reveal that it was <strong>the fear of losing control over the military, not mass civil disobedience, that ultimately led to the British decision to quit India</strong>.</p><h3>Lord Mountbatten and the Hasty Exit</h3><p>In early 1947, <strong>Lord Louis Mountbatten</strong> was appointed the last Viceroy of India. His brief was clear: ensure an orderly British withdrawal. Mountbatten moved swiftly, and the <strong>Indian Independence Act</strong> was passed in July 1947. India was granted independence on <strong>August 15, 1947</strong>, with a hastily drawn plan for Partition.</p><p>While many factors contributed to the British exit — economic strain, political pressure, and global opinion — it is clear that <strong>the INA and the mutinies within the Indian armed forces</strong> had fundamentally altered the equation. The British could no longer rely on Indian soldiers to suppress Indians.</p><h3>Geopolitical Shifts and the Urgency of British Withdrawal</h3><p>While internal rebellions like the INA uprising and the RIN mutiny rocked the British Empire from within, it’s essential to understand how <strong>global geopolitics after World War II</strong> further compelled Britain to relinquish control over India. The world order had changed dramatically between 1939 and 1945, and the British Empire, once the most powerful in the world, now stood <strong>financially crippled, diplomatically isolated, and militarily dependent</strong>.</p><h3>a. Britain’s Economic Ruin After WWII</h3><p>World War II had devastated the British economy. London was bombed, trade routes were disrupted, and the country had borrowed heavily from the United States. By the war’s end, Britain was essentially <strong>bankrupt,</strong> and running its empire had become an unsustainable financial burden. India, once the “jewel in the crown,” had turned into a costly liability.</p><p>The <strong>Sterling Crisis</strong> of 1947 further worsened Britain’s position. With a drained treasury and growing pressure to rebuild its war-torn infrastructure, the British government simply <strong>could not afford to hold on to India</strong> any longer.</p><h3>b. Superpower Pressure and Anti-Colonial Winds</h3><p>The emergence of the <strong>United States and the Soviet Union</strong> as superpowers created global pressure against colonialism. The <strong>U.S. advocated decolonization</strong>, while Britain feared India could fall into <strong>Soviet influence</strong>, especially amidst rising communist uprisings like the Telangana rebellion.</p><h3>c. Global Anti-Imperialist Sentiment</h3><p>The newly formed <strong>United Nations</strong> amplified anti-imperial voices. American President <strong>Roosevelt,</strong> and later <strong>Truman,</strong> made it clear that empires had no place in the post-war world. Britain was diplomatically isolated in defending colonial rule.</p><h3>d. Decolonization Was Sweeping the Empire</h3><p>With revolts simmering in <strong>Burma, Palestine, Egypt, and Africa</strong>, holding on to India meant risking empire-wide collapse. A quick transfer of power was a strategic retreat to preserve Britain’s broader interests.</p><h3>Dr. B.R. Ambedkar’s BBC Interview: A Different Take on Gandhi and the British Exit</h3><p>In 1955, <strong>Dr. B.R. Ambedkar</strong>, the architect of the Indian Constitution and a towering intellectual, was interviewed by the <strong>BBC</strong>. In the interview, Ambedkar offered a <strong>blunt and contrarian view</strong> on Gandhi’s role and the British departure.</p><p>When asked about the British decision to leave India, Ambedkar replied:</p><blockquote>“ My own view is that Gandhi was all the time double-dealing. He kept one thing in the public and another thing in private. Gandhi always said that he was against the partition of India, but I know for certain that he was the man who had in the first instance accepted it.”</blockquote><p>Ambedkar went further and said that it was <strong>not the Quit India Movement</strong>, but the INA and the military unrest that finally forced Britain to exit:</p><blockquote>“ The British quit India for one reason only-the loyalty of the Indian Army was in doubt after Subhas Chandra Bose and his INA. If the British had to rule India by the sword, and if the sword was turning against them, then there was no point in staying.”</blockquote><p>This perspective aligns with Clement Attlee’s later private admission and offers a <strong>striking convergence of views from two politically opposite figures</strong> -the former Prime Minister of Britain and the Dalit revolutionary of India.</p><p>Ambedkar’s interview shattered many nationalist myths and highlighted the real politics behind Indian independence-an outcome of a shifting global order, declining empire, and the terrifying realization that the <strong>Indian soldier was no longer loyal to the Raj</strong>.</p><h3>Conclusion: The Final Nail in the Coffin</h3><p>The INA did not defeat the British militarily, but <strong>defeated their moral right to rule</strong>. The following trials, mutinies, and labor unrest were <strong>symptoms of a dying empire</strong>, no longer feared and increasingly despised. Subhas Chandra Bose, the INA, and the waves of rebellion in 1945–46 delivered the <strong>final, fatal jolt to British imperialism in India</strong>. The empire that had ruled for nearly two centuries now saw its most loyal servants — the Indian soldiers — turn into rebels. And in that moment, the British realized: the jewel in the crown was slipping from their hands forever.</p><h3>Sources/References</h3><ol><li>British National Archives: Records on INA Trials and Naval Mutiny</li><li><a href="https://www.youtube.com/watch?v=Wf3VJCpNMqI">BBC Interview with Dr. B.R. Ambedkar (1955)</a></li><li>Justice P.B. Chakrabarty’s statement published in The Statesman, 1956</li><li>“The Transfer of Power in India, 1945–47” — Nicholas Mansergh</li><li>Netaji: Collected Works, Vol. 12, Netaji Research Bureau</li><li>“India’s Struggle for Independence” — Bipan Chandra</li></ol><p><em>Originally published at </em><a href="https://sciencetonight.com/subhas-chandra-bose-ina-and-the-final-blow-to-british-rule-in-india/"><em>https://sciencetonight.com</em></a><em> on April 24, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=361417b4c34c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Brief History of Large Large Language Models (LLMs) — Idiot Developer]]></title>
            <link>https://medium.com/analytics-vidhya/a-brief-history-of-large-large-language-models-llms-idiot-developer-7a1993c51525?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a1993c51525</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 05:29:50 GMT</pubDate>
            <atom:updated>2024-09-15T16:29:30.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Brief History of Large Large Language Models (LLMs) — Idiot Developer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7g0YfDT9ZOJcRpe6.jpg" /></figure><p><a href="https://idiotdeveloper.com/what-is-artificial-intelligence/">Artificial intelligence (AI)</a> has made remarkable progress in recent years, particularly in natural language processing (NLP). One of the most significant developments has been the rise of large language models (LLMs)-powerful models that can easily understand and generate human language. These models have revolutionized various industries, enabling everything from automatic translation and content creation to more sophisticated conversational agents. This article briefly examines the history of LLMs, tracing their development from early methods to the cutting-edge models we have today.</p><h3>What are Large Language Models (LLMs)?</h3><p>Large Language Models (LLMs) are expansive, general-purpose models for processing human language. They are initially trained on vast datasets covering diverse topics, allowing them to grasp the underlying structure, meaning, and language patterns. The “large” aspect refers to the immense volume of data used during training and the scale of the model itself, which often consists of billions or even trillions of parameters. This extensive pre-training enables LLMs to excel in tasks like text classification, question answering, and summarization.</p><p>Following pre-training, LLMs are often fine-tuned using smaller, domain-specific datasets tailored to specialized fields, such as finance or healthcare. This fine-tuning process enhances their performance for particular applications, making them adaptable to general language tasks and specific, focused problems.</p><h3>Historical Evolution of Large Language Models (LLMs)</h3><ul><li>1990: N-grams</li><li>2000: Neural Networks for Language Modeling</li><li>2013: Word2Vec</li><li>2014: RNN(LSTM &amp; GRU)</li><li>2015: Seq2Seq with Attention</li><li>2017: Transformers (Attention Is All You Need)</li><li>2018: BERT &amp; GPT</li><li>2019: GPT-2</li><li>2020: GPT-3</li><li>2022: ChatGPT</li><li>2023: GPT-4</li></ul><h3>1990: N-grams</h3><p>The introduction of N-gram models in the 1990s marked a crucial milestone in statistical language modeling. These models operate by calculating the likelihood of a word based on the previous few words in a sequence, providing a simple yet effective way of capturing local context in language. N-grams work by analyzing sequences of “n” words to predict the next word, where “n” could represent unigrams (single words), bigrams (two words), trigrams (three words), and so on.</p><p>Although limited by their inability to handle long-range dependencies or capture deeper linguistic patterns, N-gram models laid the foundation for later advancements. Their real-world impact was seen in applications like Google’s PageRank algorithm, which used N-gram analysis to evaluate word co-occurrences across web pages, boosting search result relevance.</p><h3>2000: Neural Networks for Language Modeling</h3><p><strong>Research Paper:</strong> <a href="https://papers.nips.cc/paper_files/paper/2000/file/728f206c2a01bf572b5940d7d9a8fa4c-Paper.pdf">A Neural Probabilistic Language Model</a></p><p>In 2000, Yoshua Bengio introduced neural networks for language modeling, which marked a significant leap forward. Neural networks introduced the ability to learn complex patterns in data, capturing richer, more meaningful linguistic representations than N-grams. Unlike traditional statistical models, neural networks can model non-linear relationships and are better suited for capturing long-range dependencies within text.</p><p>Yoshua Bengio and his team introduced the model, which used a feedforward neural network to predict the next word in a sentence based on previous words. It introduced the concept of a distributed “feature vector” for each word (a real-valued vector in Rm), similar to word embeddings.</p><p>These feature vectors allowed the model to represent words as vectors in a continuous space, significantly improving the understanding of word similarities and relationships and setting the stage for future language models.</p><h3>2013: Word2Vec</h3><p><strong>Research Paper:</strong> <a href="https://arxiv.org/pdf/1301.3781">Efficient Estimation of Word Representations in Vector Space</a></p><p>Google’s Word2Vec, introduced in 2013, revolutionized how words were represented in machine learning models by creating word embeddings-dense vector representations of words in continuous space. Word2Vec uses two main techniques: Continuous Bag of Words (CBOW) and Skip-gram. CBOW predicts a word based on its context (surrounding words), while Skip-gram does the opposite by predicting the context given the word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*I8gSq1UZU_PluxERYfL_Xw.png" /><figcaption>The network architecture of Continous Bag of Words (CBOW) and Skip-gram models. The CBOW architecture predicts the current word based on the context, and the Skip-gram predicts surrounding words given the current word. Source: <a href="https://arxiv.org/pdf/1301.3781">https://arxiv.org/pdf/1301.3781</a></figcaption></figure><p>Word2Vec model can capture semantic relationships between words based on their co-occurrence in text, enabling the model to understand, for example, that “king” is to “queen” as “man” is to “woman.” This shift to vector-based representations marked a massive improvement in handling semantics and was foundational to many NLP systems.</p><h3>2014: RNN (LSTM &amp; GRU)</h3><p><strong>Research Paper:</strong></p><ul><li><strong>LSTM:</strong> <a href="https://www.bioinf.jku.at/publications/older/2604.pdf">Long Short-Term Memory</a></li><li><strong>GRU:</strong> <a href="https://arxiv.org/pdf/1406.1078v3">Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation</a></li></ul><p>Although Long-Short-Term Memory (LSTM) networks were originally introduced in 1997, they gained widespread adoption in 2014 alongside Gated Recurrent Units (GRU). Both LSTM and GRU are advanced variants of Recurrent Neural Networks (RNNs) designed to overcome the limitations of traditional RNNs, particularly the vanishing gradient problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*lIW-0BQcQSJP7onSNbiVjA.png" /><figcaption>The block diagram of Long Short-Term Memory (LSTM) and Gated Recurrent Unit (GRU). Source: <a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21">https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21</a></figcaption></figure><p>LSTMs introduced memory cells and gating mechanisms that allow models to retain important information over long sequences, improving their ability to handle long-range dependencies in text.</p><p>GRUs, introduced in 2014, simplified the architecture of LSTMs by combining certain gates, making them computationally more efficient while retaining similar performance.</p><p>The popularity of LSTM and GRU models in 2014 marked a significant advancement in tasks requiring sequential data processing, such as machine translation, speech recognition, and time-series prediction.</p><h3>2015: Seq2Seq with Attention</h3><p><strong>Research Paper:</strong> <a href="https://arxiv.org/pdf/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a></p><p>The Seq2Seq (Sequence-to-Sequence) model, introduced with attention mechanisms in 2015, transformed how language models handled tasks like translation and summarization. Seq2Seq architecture consists of two parts: an encoder and a decoder.</p><p>The encoder processes input sequences while the decoder generates the output sequence. The attention mechanism was a major innovation, allowing the model to focus on relevant parts of the input sequence when producing each word in the output. This significantly improved performance in tasks involving long sequences by enabling the model to retain and use information from any input part rather than just the final hidden state.</p><h3>2017: Transformers (Attention Is All You Need)</h3><p><strong>Research Paper:</strong> <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a></p><p>In 2017, the Transformer architecture, introduced in the paper “Attention Is All You Need,” revolutionized natural language processing. Transformers replaced the need for recurrence in RNNs with self-attention mechanisms, allowing the model to capture relationships between all words in a sequence simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*UB8n115bJrhyJYg2vuFSag.png" /><figcaption>The network architecture of the Transformer model. Source: <a href="https://arxiv.org/pdf/1706.03762">https://arxiv.org/pdf/1706.03762</a></figcaption></figure><p>This parallel processing significantly boosted computational efficiency and the ability to capture long-range dependencies, making the Transformer model highly scalable for large datasets. It formed the backbone of subsequent language models like BERT and GPT, leading to breakthroughs in tasks like translation, summarization, and question-answering.</p><h3>2018: BERT &amp; GPT</h3><p><strong>Research paper:</strong></p><p>In 2018, two significant models emerged that further advanced the capabilities of LLMs: BERT (Bidirectional Encoder Representations from Transformers) by Google and GPT (Generative Pre-trained Transformer) by OpenAI.</p><p>BERT introduced bidirectional training, which could consider preceding and following words when understanding context, improving tasks like question answering and text classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*KVzBj5tiKxAJl6FcAuO3fA.png" /><figcaption>The overall pre-training and fine-tuning procedures for BERT are as follows: Apart from output layers, the same architectures are used in pre-training and fine-tuning. Source: <a href="https://arxiv.org/pdf/1810.04805">https://arxiv.org/pdf/1810.04805</a></figcaption></figure><p>GPT, on the other hand, focused on generative tasks by pre-training on large datasets and fine-tuning for specific tasks, showcasing remarkable ability in text generation.</p><p>Together, these models showed Transformers’ versatility in understanding and generating language.</p><h3>2019: GPT-2</h3><p><strong>Research Paper:</strong> <a href="https://hayate-lab.com/wp-content/uploads/2023/05/61b1321d512410607235e9a7457a715c.pdf">Language Models are Unsupervised Multitask Learners</a></p><p>GPT-2, launched by OpenAI in 2019, built on GPT’s success by scaling up the model to 1.5 billion parameters, significantly improving its ability to generate coherent, human-like text. GPT-2’s ability to generate high-quality, contextually relevant text across diverse topics without task-specific fine-tuning demonstrated the power of large-scale pre-training.</p><p>However, due to concerns about misuse, GPT-2 was initially withheld from public release, highlighting ethical considerations in deploying powerful language models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FC2NytSr915mRRasks9S2Q.jpeg" /><figcaption>The web user interface of the ChatGPT.</figcaption></figure><h3>2020: GPT-3</h3><p><strong>Research Paper:</strong> <a href="https://arxiv.org/pdf/2005.14165">Language Models are Few-Shot Learners</a></p><p>OpenAI’s GPT-3, released in 2020, further pushed the boundaries of language modeling with a staggering 175 billion parameters. This massive scale enabled GPT-3 to perform various tasks-such as translation, summarization, and even programming-with minimal instruction or fine-tuning. Its ability to generate highly coherent and contextually accurate text set a new standard in NLP, making GPT-3 one of the most influential and versatile language models available. GPT-3 also popularized the concept of few-shot learning, where the model could generalize tasks with just a few examples.</p><h3>2022: ChatGPT</h3><p>In 2022, OpenAI launched ChatGPT, a model fine-tuned from GPT-3.5 specifically for conversational AI. ChatGPT was designed to generate more engaging and human-like dialogue, making it suitable for customer service, virtual assistants, and educational tools. ChatGPT demonstrated the practical applications of large-scale language models in everyday communication by focusing on interactivity and conversation coherence. It became widely used for answering questions, creative writing, and real-time conversations, making AI-driven dialogue more accessible and human-like.</p><h3>2023: GPT-4</h3><p><strong>Research Paper:</strong> <a href="https://arxiv.org/abs/2303.08774">GPT-4 Technical Report</a></p><p>GPT-4, a large multimodel language model, was released in 2023 and built upon the advancements of GPT-3. It offers improved understanding of nuanced prompts, greater accuracy in reasoning, and enhanced handling of ambiguous or incomplete information.</p><p>A significant improvement over its predecessor was the incorporation of fine-tuning through reinforcement learning, where feedback from both humans and AI systems was used to align the model with human values and ensure policy compliance.</p><p>While GPT-3 excelled at general language generation, GPT-4 was designed to handle more complex tasks, including deeper reasoning and problem-solving. GPT-4’s enhanced capabilities make it suitable for specialized domains like legal reasoning, scientific research, and advanced educational tools, representing a further step toward more intelligent, context-aware AI systems.</p><h3>Conclusion</h3><p>The journey of Large Language Models (LLMs) from the simple N-gram models of the 1990s to the sophisticated, multi-billion parameter models like GPT-4 reflects the rapid evolution in natural language processing. Early models, such as N-grams and the first neural networks, laid the groundwork for capturing linguistic patterns and dependencies. With the introduction of word embeddings like Word2Vec and GloVe, language understanding became more nuanced as models began to represent words in vector spaces that captured semantic relationships. Recurrent models such as LSTMs and GRUs brought improvements in handling sequential data, paving the way for Seq2Seq models with attention, which significantly improved performance on tasks like translation.</p><p>The breakthrough came with the Transformer model in 2017, which revolutionized NLP by discarding recurrence in favor of self-attention mechanisms, greatly enhancing efficiency and scalability. This innovation led to developing powerhouse models like BERT and GPT, each excelling in language understanding and generation. The advent of GPT-2 and GPT-3 highlighted the immense potential of large-scale pre-training and fine-tuning, with GPT-3 setting a new standard for few-shot learning and general language tasks.</p><p>Finally, GPT-4 represents the latest achievement in this evolution, combining advanced reasoning with human-aligned training methods. By incorporating reinforcement learning feedback from humans and AI, GPT-4 demonstrates a commitment to ethical considerations and policy compliance, ensuring that AI is powerful and responsible. As LLMs continue to evolve, they promise to revolutionize even more industries, offering sophisticated solutions to various tasks while adhering to ethical standards. This evolution underscores the potential for language models to become even more integrated into daily life, providing intelligent and reliable assistance across various domains.</p><p><em>Originally published at </em><a href="https://idiotdeveloper.com/a-brief-history-of-large-large-language-models-llms"><em>https://idiotdeveloper.com</em></a><em> on September 14, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a1993c51525" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-brief-history-of-large-large-language-models-llms-idiot-developer-7a1993c51525">A Brief History of Large Large Language Models (LLMs) — Idiot Developer</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ColonSegNet Implementation In TensorFlow — Idiot Developer]]></title>
            <link>https://nikhilroxtomar.medium.com/colonsegnet-implementation-in-tensorflow-idiot-developer-4eb328f57e14?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eb328f57e14</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[medical-image-analysis]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 16:56:45 GMT</pubDate>
            <atom:updated>2024-01-26T03:48:21.174Z</atom:updated>
            <content:encoded><![CDATA[<h3>ColonSegNet Implementation In TensorFlow — Idiot Developer</h3><p>In this article, we will embark on a deep dive into the implementation of ColonSegNet in TensorFlow. It is a lightweight and real-time colon segmentation architecture and has garnered attention for its efficiency in medical image analysis. In our previous post, we introduced the architecture and its components. Now, let’s explore the technical intricacies of implementing ColonSegNet in TensorFlow.</p><blockquote><strong>Previous Post: </strong><a href="https://idiotdeveloper.com/colonsegnet-implementation-in-tensorflow/A%20Lightweight%20Real-Time%20Colon%20Segmentation%20Architecture">ColonSegNet: A Lightweight Real-Time Colon Segmentation Architecture</a></blockquote><h3>Install TensorFlow</h3><pre>pip install tensorflow</pre><p>Now, let’s go through the code step by step.</p><h3>Importing Libraries and Functions</h3><p>Import necessary libraries and suppress TensorFlow warnings.</p><pre>import os<br>os.environ[&quot;TF_CPP_MIN_LOG_LEVEL&quot;] = &quot;2&quot;<br>from tensorflow.keras.layers import Conv2D, BatchNormalization, Activation, UpSampling2D, Dense<br>from tensorflow.keras.layers import GlobalAveragePooling2D, Conv2DTranspose, Concatenate, Input<br>from tensorflow.keras.layers import MaxPool2D<br>from tensorflow.keras.models import Model</pre><p>The code starts by importing essential libraries. The os.environ line is used to suppress unnecessary TensorFlow warnings for cleaner output.</p><h3>Squeeze and Excitation (SE) Block</h3><p>The se_layer function defines the <em>Squeeze and Excitation Block</em> block, a key component in enhancing the representational power of ColonSegNet. Let&#39;s break down its implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*T371dBLWR4ml4dFmCp7gjg.png" /><figcaption><em>The block diagram of Squeeze and Excitation Network.</em></figcaption></figure><pre>def se_layer(x, num_filters, reduction=16):<br>    x_init = x<br> <br>    x = GlobalAveragePooling2D()(x)<br>    x = Dense(num_filters//reduction, use_bias=False, activation=&quot;relu&quot;)(x)<br>    x = Dense(num_filters, use_bias=False, activation=&quot;sigmoid&quot;)(x)<br>    x = x * x_init<br>    return x</pre><ul><li><strong>Global Average Pooling</strong>: Reduces the spatial dimensions of the input tensor to a single value per channel, capturing the global context.</li><li><strong>Squeeze</strong>: A fully connected layer with a ReLU activation compresses the channel-wise information, preparing it for excitation.</li><li><strong>Excitation</strong>: Another fully connected layer with a sigmoid activation produces a channel-wise scaling factor, indicating the importance of each channel.</li><li><strong>Scaling:</strong> The input tensor is then scaled element-wise by the excitation output, allowing the network to focus on relevant channels.</li></ul><h3>Residual Block</h3><p>The residual_block function represents a residual block, a crucial element in overcoming the vanishing gradient problem and facilitating information flow. Let&#39;s explore its details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*I-GPuaknNrwS5e9USucqow.png" /><figcaption><em>The block diagram of residual block which uses squeeze and excitation attention mechanism to improve its performance</em></figcaption></figure><pre>def residual_block(x, num_filters):<br>    x_init = x<br> <br>    x = Conv2D(num_filters, 3, padding=&quot;same&quot;)(x)<br>    x = BatchNormalization()(x)<br>    x = Activation(&quot;relu&quot;)(x)<br>     <br>    x = Conv2D(num_filters, 3, padding=&quot;same&quot;)(x)<br>    x = BatchNormalization()(x)<br> <br>    s = Conv2D(num_filters, 1, padding=&quot;same&quot;)(x_init)<br>    s = BatchNormalization()(s)<br>    s = se_layer(s, num_filters)<br> <br>    x = Activation(&quot;relu&quot;)(x + s)<br>    return x</pre><ul><li>The block starts with a convolutional layer, followed by batch normalization and ReLU activation.</li><li>Another convolutional layer is applied, and batch normalization is performed again.</li><li>A shortcut connection is created using a 1×1 convolution followed by batch normalization and the SE layer.</li><li>The final output is obtained by adding the shortcut connection to the output of the second convolutional layer, followed by ReLU activation.</li></ul><h3>Strided Convolution Block</h3><p>The strided_conv_block function defines a block with strided convolution, aiding in downsampling spatial dimensions. This is crucial for capturing hierarchical features.</p><pre>def strided_conv_block(x, num_filters):<br>    x = Conv2D(num_filters, 3, strides=2, padding=&quot;same&quot;)(x)<br>    x = BatchNormalization()(x)<br>    x = Activation(&quot;relu&quot;)(x)<br>    return x</pre><h3>Encoder Block</h3><p>The encoder_block function combines the residual and strided convolution blocks to create an encoder block. It captures and refines features while downsampling the input.</p><pre>def encoder_block(x, num_filters):<br>    x1 = residual_block(x, num_filters)<br>    x2 = strided_conv_block(x1, num_filters)<br>    x3 = residual_block(x2, num_filters)<br>    p = MaxPool2D((2, 2))(x3)<br> <br>    return x1, x3, p</pre><h3>ColonSegNet Architecture</h3><p>The build_colonsegnet function assembles the complete ColonSegNet architecture. It consists of encoder and decoder blocks, making it capable of segmenting colon regions in medical images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*wrnJHqlSJ3jKx40X1BKOyw.png" /><figcaption><em>The block diagram of ColonSegNet</em></figcaption></figure><pre>def build_colonsegnet(input_shape):<br>    &quot;&quot;&quot; Input &quot;&quot;&quot;<br>    inputs = Input(input_shape)<br> <br>    &quot;&quot;&quot; Encoder &quot;&quot;&quot;<br>    s11, s12, p1 = encoder_block(inputs, 64)<br>    s21, s22, p2 = encoder_block(p1, 256)<br> <br>    &quot;&quot;&quot; Decoder 1 &quot;&quot;&quot;<br>    x = Conv2DTranspose(128, 4, strides=4, padding=&quot;same&quot;)(s22)<br>    x = Concatenate()([x, s12])<br>    x = residual_block(x, 128)<br>    r1 = x<br> <br>    x = Conv2DTranspose(128, 4, strides=2, padding=&quot;same&quot;)(s21)<br>    x = Concatenate()([x, r1])<br>    x = residual_block(x, 128)<br> <br>    &quot;&quot;&quot; Decoder 2 &quot;&quot;&quot;<br>    x = Conv2DTranspose(64, 4, strides=2, padding=&quot;same&quot;)(x)<br>    x = Concatenate()([x, s11])<br>    x = residual_block(x, 64)<br>    r2 = x<br> <br>    x = Conv2DTranspose(32, 4, strides=2, padding=&quot;same&quot;)(s12)<br>    x = Concatenate()([x, r2])<br>    x = residual_block(x, 32)<br> <br>    &quot;&quot;&quot; Output &quot;&quot;&quot;<br>    output = Conv2D(1, 1, padding=&quot;same&quot;)(x)<br> <br>    &quot;&quot;&quot; Model &quot;&quot;&quot;<br>    model = Model(inputs, output)<br> <br>    return model</pre><h3>Running the ColonSegNet</h3><p>In the main block, we specify the input shape, build the ColonSegNet model using the defined function, and print the model summary.</p><pre>if __name__ == &quot;__main__&quot;:<br>    input_shape = (512, 512, 3)<br>    model = build_colonsegnet(input_shape)<br>    model.summary()</pre><h3>Conclusion</h3><p>Congratulations! You’ve just explored the implementation details of ColonSegNet in TensorFlow. Feel free to experiment with the code, integrate it into your projects, and contribute to the growing field of medical image segmentation.</p><p>Happy coding!</p><p><em>Originally published at </em><a href="https://idiotdeveloper.com/colonsegnet-implementation-in-tensorflow"><em>https://idiotdeveloper.com</em></a><em> on January 25, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eb328f57e14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ColonSegNet: A Lightweight Real-Time Colon Segmentation Architecture — Idiot Developer]]></title>
            <link>https://medium.com/swlh/colonsegnet-a-lightweight-real-time-colon-segmentation-architecture-idiot-developer-efdc39d81edf?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/efdc39d81edf</guid>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[medical-image-analysis]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 08:13:04 GMT</pubDate>
            <atom:updated>2024-01-24T11:08:56.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>ColonSegNet: A Lightweight Real-Time Colon Segmentation Architecture — Idiot Developer</h3><p>In the ever-evolving landscape of computer vision and medical imaging, achieving real-time performance in segmentation tasks is crucial. ColonSegNet, a novel encoder-decoder architecture, has emerged as a beacon of efficiency, designed for swift and accurate colon <a href="https://idiotdeveloper.com/polyp-segmentation-using-unet-in-tensorflow-2/">polyp segmentation</a>. In this blog post, we’ll delve into the intricacies of ColonSegNet’s architecture and explore why it stands out among other baseline networks.</p><figure><img alt="A detailed block diagram of the ColonSegNet." src="https://cdn-images-1.medium.com/max/721/1*wrnJHqlSJ3jKx40X1BKOyw.png" /><figcaption><em>A detailed block diagram of the ColonSegNet.</em></figcaption></figure><p><strong>Research Paper:</strong> <a href="https://github.com/DebeshJha/ColonSegNet/blob/main/access.pdf">Real-Time Polyp Detection, Localization and Segmentation in Colonoscopy Using Deep Learning</a></p><h3>Architectural Highlights</h3><p>ColonSegNet adopts an encoder-decoder structure, employing residual blocks with a squeeze and excitation network as its cornerstone. The primary objective is to minimize the number of trainable parameters, setting it apart from conventional networks such as U-Net, PSPNet, and DeepLabV3+.</p><h3>Encoder Network</h3><p>The network comprises two encoder blocks, each contributing to extracting essential information from the input image. The first encoder incorporates two residual blocks separated by a 3×3 strided convolution, followed by a 2×2 max-pooling. This strategic design reduces the spatial dimensions of the output feature map to 1/4 of the input image. The second encoder mirrors this structure, reinforcing the network’s ability to capture intricate details.</p><h3>Residual Block</h3><p>The residual blocks within ColonSegNet are the building blocks that enable the model to capture intricate features within the colon images. These blocks consist of convolutional layers, batch normalization, and activation functions, allowing the model to learn and retain important details.</p><figure><img alt="The block diagram of the residual block with squeeze and excitation attention mechanism." src="https://cdn-images-1.medium.com/max/308/1*I-GPuaknNrwS5e9USucqow.png" /><figcaption><em>The block diagram of the residual block with squeeze and excitation attention mechanism.</em></figcaption></figure><p>The residual block consists of two 3×3 convolution layers, each followed by a batch normalization and a ReLU activation function is added between them. Next, we have a 1×1 convolution layer with batch normalization and Squeeze and Excitation attention mechanism. The output of the attention mechanism is added to the output of the main branch and followed by the ReLU activation function.</p><h3>Squeeze and Excitation Attention Mechanism</h3><p>The Squeeze and Excitation Network introduces a novel channel-wise attention mechanism for CNNs (Convolutional Neural Networks) to improve their channel interdependencies. The network adds a parameter that re-weights each channel accordingly so that it becomes more sensitive towards significant features while ignoring the irrelevant features.</p><figure><img alt="The block diagram of the Squeeze and Excitation Attention mechanism" src="https://cdn-images-1.medium.com/max/843/1*T371dBLWR4ml4dFmCp7gjg.png" /><figcaption><em>The block diagram of the Squeeze and Excitation Attention mechanism</em></figcaption></figure><p>The Squeeze and Excitation basically act as a content-aware mechanism that re-weights each channel adaptively.</p><p><strong>Read More: </strong><a href="https://idiotdeveloper.com/squeeze-and-excitation-networks/">Squeeze and Excitation Networks</a></p><h3>Decoder Network</h3><p>ColonSegNet’s decoder begins with a transpose convolution. The first decoder uses a stride value of 4, magnifying the feature map’s spatial dimensions by 4. Similarly, the second decoder utilizes a stride value of 2, increasing dimensions by 2. What sets ColonSegNet apart is its incorporation of skip connections from the encoder. The first connection involves a simple concatenation, while the second traverses a transpose convolution, integrating multi-scale features into the decoder.</p><h3>Efficiency in Action</h3><p>The careful orchestration of operations after skip connection concatenation includes a residual block. This thoughtful design choice contributes to the network’s efficiency. The final decoder block output undergoes a 1×1 convolution and a sigmoid activation function, culminating in the generation of a binary segmentation mask for the input image.</p><figure><img alt="The table shows the number of parameters in each network." src="https://cdn-images-1.medium.com/max/419/1*_wxbp9dssCHscEPIp-cbvw.png" /><figcaption><em>The table shows the number of parameters in each network.</em></figcaption></figure><h3>Results</h3><figure><img alt="The table shows a detailed comparison of the ColonSegNet with different evaluation metrics. The two best results are highlighted in bold." src="https://cdn-images-1.medium.com/max/1024/1*aRg7UwIyufx8sVqB9UQAog.png" /><figcaption><em>The table shows a detailed comparison of the ColonSegNet with different evaluation metrics. The two best results are highlighted in bold.</em></figcaption></figure><h3>Real-Time Application</h3><p>ColonSegNet’s lightweight architecture positions it as an ideal candidate for real-time applications, particularly in colon segmentation. By minimizing trainable parameters, the network ensures swift and accurate results without compromising on semantic understanding.</p><h3>Conclusion</h3><p>ColonSegNet’s ingenious combination of residual blocks, squeeze and excitation network, and efficient skip connections marks a significant leap in real-time colon segmentation. As the demand for faster and more accurate medical imaging solutions continues to grow, architectures like ColonSegNet pave the way for a future where real-time performance is the norm rather than the exception.</p><h3>Read More</h3><ul><li><a href="https://github.com/nikhilroxtomar/Polyp-Segmentation-using-UNET-in-TensorFlow-2.0">Polyp-Segmentation-using-UNET-in-TensorFlow-2.0</a></li><li><a href="http://debeshjha.com/colonsegnet-for-medical-image-segmentation/">ColonSegNet for Real-time Polyp Segmentation</a></li></ul><p><em>Originally published at </em><a href="https://idiotdeveloper.com/colonsegnet-a-lightweight-real-time-colon-segmentation-architecture"><em>https://idiotdeveloper.com</em></a><em> on January 24, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efdc39d81edf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/colonsegnet-a-lightweight-real-time-colon-segmentation-architecture-idiot-developer-efdc39d81edf">ColonSegNet: A Lightweight Real-Time Colon Segmentation Architecture — Idiot Developer</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression in TensorFlow — Idiot Developer]]></title>
            <link>https://nikhilroxtomar.medium.com/logistic-regression-in-tensorflow-idiot-developer-6cd71f8c2b2d?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cd71f8c2b2d</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 04:59:46 GMT</pubDate>
            <atom:updated>2023-06-16T04:19:00.489Z</atom:updated>
            <content:encoded><![CDATA[<h3>Logistic Regression in TensorFlow — Idiot Developer</h3><p>Logistic Regression is a popular machine-learning algorithm that is used for classification tasks. In this tutorial, we will learn how to implement Logistic Regression in TensorFlow 2.0 using the tf.keras.Model API. We will also learn how to split our data into training, validation, and testing sets in order to train and evaluate our model.</p><p><strong>Related Post</strong></p><ul><li><a href="https://idiotdeveloper.com/implementing-linear-regression-in-tensorflow/">Implementing Linear Regression in TensorFlow</a></li></ul><h3>Importing Libraries</h3><p>First, we need to import the necessary libraries. We will be using TensorFlow, Numpy, and Matplotlib.</p><pre>import tensorflow as tf <br>import numpy as np <br>import matplotlib.pyplot as plt <br>from sklearn import datasets <br>from sklearn.model_selection import train_test_split</pre><h3>Loading the Data</h3><p>Next, we will load our data. We will use the Iris dataset for this tutorial. The Iris dataset contains 150 samples of iris flowers, with 50 samples of each species (setosa, versicolor, and virginica). Each sample contains four features: sepal length, sepal width, petal length, and petal width. Our goal is to train a model that can classify the species of an iris flower based on these features.</p><pre>iris = datasets.load_iris() <br>X = iris.data <br>y = iris.target</pre><h3>Splitting the Data</h3><p>Before we can start training our model, we need to split our data into training, validation, and testing sets. We will use 80% of the data for training, 10% for validation, and 10% for testing.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) <br>X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42)</pre><h3>Creating the Model</h3><p>Now we can create our logistic regression model using the tf.keras.Model API. We will start by defining the input layer and the output layer. The input layer will have four neurons, one for each feature in the Iris dataset. The output layer will have three neurons, one for each species of iris.</p><pre>class LogisticRegression(tf.keras.Model):<br>    def __init__(self):<br>        super(LogisticRegression, self).__init__()<br>        self.dense = tf.keras.layers.Dense(3, activation=&#39;softmax&#39;)<br> <br>    def call(self, inputs):<br>        x = self.dense(inputs)<br>        return x<br> <br>model = LogisticRegression()</pre><h3>Compiling the Model</h3><p>Before we can start training our model, we need to compile it. We will use the Adam optimizer and the sparse categorical cross-entropy loss function.</p><pre>model.compile(<br>  optimizer=&#39;adam&#39;, <br>  loss=&#39;sparse_categorical_crossentropy&#39;, <br>  metrics=[&#39;accuracy&#39;]<br>)</pre><h3>Training the Model</h3><p>Now we can train our model using the X_train and y_train data. We will train the model for 200 epochs and use the validation data (X_val, y_val) to evaluate the model during the training.</p><pre>history = model.fit(<br>  X_train, <br>  y_train, <br>  epochs=200, <br>  validation_data=(X_val, y_val)<br>)</pre><h3>Evaluating the Model</h3><p>Once our model is trained, we can use the test data (X_test, y_test) to evaluate its performance.</p><pre>test_loss, test_acc = model.evaluate(X_test, y_test) <br>print(&#39;Test accuracy:&#39;, test_acc)</pre><p>Output</p><pre>1/1 [==============================] - 0s 23ms/step - loss: 0.6563 - accuracy: 0.8000 <br>Test accuracy: 0.800000011920929</pre><h3>Plotting the Results</h3><p>We can also plot the training and validation accuracy and loss to visualize the training process and check for overfitting.</p><pre>plt.plot(history.history[&#39;accuracy&#39;])<br>plt.plot(history.history[&#39;val_accuracy&#39;])<br>plt.title(&#39;Model accuracy&#39;)<br>plt.ylabel(&#39;Accuracy&#39;)<br>plt.xlabel(&#39;Epoch&#39;)<br>plt.legend([&#39;Train&#39;, &#39;Validation&#39;], loc=&#39;upper left&#39;)<br>plt.savefig(&quot;acc.png&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*_KRHQLmJYFu7LXWlwy5t7w.png" /><figcaption>The graph shows the comparison between the training and validation accuracy.</figcaption></figure><pre>plt.clf() plt.plot(history.history[&#39;loss&#39;]) <br>plt.plot(history.history[&#39;val_loss&#39;]) <br>plt.title(&#39;Model loss&#39;) <br>plt.ylabel(&#39;Loss&#39;) <br>plt.xlabel(&#39;Epoch&#39;) <br>plt.legend([&#39;Train&#39;, &#39;Validation&#39;], loc=&#39;upper left&#39;) <br>plt.savefig(&quot;loss.png&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*BSdBNfBevvILmHyELnlWLA.png" /><figcaption>The graph shows the comparison between the training and validation loss.</figcaption></figure><h3>Conclusion</h3><p>In this tutorial, we learned how to implement Logistic Regression in TensorFlow 2.0 using the tf.keras.Model API. We also learned how to split our data into training, validation, and testing sets in order to train and evaluate our model. We also learned how to plot the training and validation accuracy and loss in order to visualize the training process and check for overfitting. With this knowledge, you can now use Logistic Regression to tackle your own classification tasks in TensorFlow 2.0.</p><p>Still, have some questions or queries? Just comment below. For more updates. Follow me.</p><ul><li><a href="https://www.youtube.com/idiotdeveloper">YouTube</a></li><li><a href="https://facebook.com/idiotdeveloper">Facebook</a></li><li><a href="https://twitter.com/nikhilroxtomar">Twitter</a></li><li><a href="https://www.instagram.com/nikhilroxtomar">Instagram</a></li></ul><p><em>Originally published at </em><a href="https://idiotdeveloper.com/logistic-regression-in-tensorflow/"><em>https://idiotdeveloper.com</em></a><em> on February 14, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cd71f8c2b2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Intersection over Union (IoU) in Object Detection? — Idiot Developer]]></title>
            <link>https://nikhilroxtomar.medium.com/what-is-intersection-over-union-iou-in-object-detection-idiot-developer-39448ac56431?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/39448ac56431</guid>
            <category><![CDATA[bounding-box]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[iou]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[intersection-over-union]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 15:18:29 GMT</pubDate>
            <atom:updated>2023-05-09T13:45:45.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Intersection over Union (IoU) in Object Detection? — Idiot Developer</h3><p>Intersection over Union (IoU) is a popular evaluation metric used in the field of computer vision and <a href="https://idiotdeveloper.com/simple-object-detection-with-bounding-box-regression-in-tensorflow/">object detection</a>. It is used to calculate the overlap between two bounding boxes and is used to evaluate the accuracy of object detection algorithms. IoU is a value between 0 and 1 that represents the overlap between the ground truth and predicted bounding boxes. A high IoU value indicates that the predicted bounding box is accurately aligned with the ground truth bounding box.</p><h3>Intersection over Union Calculation</h3><p>The IoU between two bounding boxes is calculated as the ratio of the intersection area over the union area. The intersection area is the overlapping region between the two bounding boxes, while the union area is the total area of the two bounding boxes combined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*za4Hpz8SDUdWg-S6goL4yg.jpeg" /><figcaption>A diagram representing the Intersection over Union (IoU).</figcaption></figure><p>In order to calculate the IoU between two bounding boxes, we need to find the coordinates of the intersection and union regions. The coordinates of the intersection region are given by the minimum and maximum values of the x- and y-coordinates of the two bounding boxes. The union region is the area enclosed by the minimum and maximum values of the x- and y-coordinates of the two bounding boxes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGxW0YdPvukg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGxW0YdPvukg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGxW0YdPvukg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/78f4a3da689b6bfdf44700808e40218f/href">https://medium.com/media/78f4a3da689b6bfdf44700808e40218f/href</a></iframe><h3>IoU Implementation</h3><p>The IoU calculation can be implemented in the Python programming language using different libraries including NumPy, TensorFlow, and PyTorch.</p><h3>Numpy Implementation</h3><pre>import numpy as np<br> <br>def intersection_over_union(boxA, boxB):<br>    # determine the (x, y)-coordinates of the intersection rectangle<br>    x1 = max(boxA[0], boxB[0])<br>    y1 = max(boxA[1], boxB[1])<br>    x2 = min(boxA[2], boxB[2])<br>    y2 = min(boxA[3], boxB[3])<br> <br>    # compute the area of intersection rectangle<br>    intersection_area = max(0, x2 - x1 + 1) * max(0, y2 - y1 + 1)<br> <br>    # compute the area of both the prediction and ground-truth rectangles<br>    boxA_area = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)<br>    boxB_area = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)<br> <br>    # compute the intersection over union by taking the intersection<br>    # area and dividing it by the sum of prediction + ground-truth<br>    # areas - the interesection area<br>    iou = intersection_area / float(boxA_area + boxB_area - intersection_area)<br> <br>    # return the intersection over union value<br>    return iou</pre><p>Now, let us test the above NumPy implementation of the Intersection over Union (IoU).</p><pre># Two bounding boxes<br>boxA = [100, 100, 250, 250]<br>boxB = [150, 150, 300, 300]<br> <br>iou = intersection_over_union(boxA, boxB)<br>print(&quot;IoU: &quot;, iou)<br> <br># A simple 400 x 400 blnk white image<br>image = np.ones((400, 400, 3), dtype=np.float32) * 255<br> <br># Plotting IoU on image<br>cv2.putText(image, f&quot;IoU: {iou:.4f}&quot;, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)<br> <br># Plotting bounding box A<br>image = cv2.rectangle(image, (boxA[0], boxA[1]), (boxA[2], boxA[3]), (255, 0, 0), 2) ## Blue<br>cv2.putText(image, &quot;Box A&quot;, (boxA[0], boxA[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)<br> <br># Plotting bounding box B<br>image = cv2.rectangle(image, (boxB[0], boxB[1]), (boxB[2], boxB[3]), (0, 0, 255), 2) ## Red<br>cv2.putText(image, &quot;Box B&quot;, (boxB[0], boxB[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)<br> <br>cv2.imwrite(&quot;iou.png&quot;, image)</pre><p><strong>Output:</strong></p><p>IoU: 0.2881557018163329</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*i5fGgKs2jl4bCN0n.png" /><figcaption>The Intersection over Union (IoU) score is shown between two boxes</figcaption></figure><h3>TensorFlow Implementation</h3><pre>import tensorflow as tf<br> <br>def intersection_over_union(boxA, boxB):<br>    # determine the (x, y)-coordinates of the intersection rectangle<br>    x1 = tf.maximum(boxA[0], boxB[0])<br>    y1 = tf.maximum(boxA[1], boxB[1])<br>    x2 = tf.minimum(boxA[2], boxB[2])<br>    y2 = tf.minimum(boxA[3], boxB[3])<br> <br>    # compute the area of intersection rectangle<br>    intersection_area = tf.maximum(0, x2 - x1 + 1) * tf.maximum(0, y2 - y1 + 1)<br> <br>    # compute the area of both the prediction and ground-truth rectangles<br>    boxA_area = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)<br>    boxB_area = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)<br> <br>    # compute the intersection over union by taking the intersection<br>    # area and dividing it by the sum of prediction + ground-truth<br>    # areas - the interesection area<br>    iou = intersection_area / (boxA_area + boxB_area - intersection_area)<br> <br>    # return the intersection over union value<br>    return iou<br> <br>boxA = [100, 100, 250, 250]<br>boxB = [150, 150, 300, 300]<br> <br>iou = intersection_over_union(boxA, boxB)<br>print(&quot;IoU: &quot;, iou)</pre><p><strong>Output:</strong></p><pre>IoU: tf.Tensor(0.2881557018163329, shape=(), dtype=float64)</pre><h3>PyTorch Implementation</h3><pre>import torch<br> <br>def intersection_over_union(boxA, boxB):<br>    # determine the (x, y)-coordinates of the intersection rectangle<br>    x1 = torch.max(boxA[0], boxB[0])<br>    y1 = torch.max(boxA[1], boxB[1])<br>    x2 = torch.min(boxA[2], boxB[2])<br>    y2 = torch.min(boxA[3], boxB[3])<br> <br>    # compute the area of intersection rectangle<br>    intersection_area = torch.max(torch.tensor(0.0), x2 - x1 + 1) * torch.max(torch.tensor(0.0), y2 - y1 + 1)<br> <br>    # compute the area of both the prediction and ground-truth rectangles<br>    boxA_area = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)<br>    boxB_area = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)<br> <br>    # compute the intersection over union by taking the intersection<br>    # area and dividing it by the sum of prediction + ground-truth<br>    # areas - the interesection area<br>    iou = intersection_area / (boxA_area + boxB_area - intersection_area)<br> <br>    # return the intersection over union value<br>    return iou<br> <br>boxA = torch.tensor([100, 100, 250, 250])<br>boxB = torch.tensor([150, 150, 300, 300])<br> <br>iou = intersection_over_union(boxA, boxB)<br>print(&quot;IoU: &quot;, iou)</pre><p><strong>Output:</strong></p><p>IoU: tensor(0.2882)</p><h3>Applications of Intersection over Union</h3><p>IoU is widely used in the field of object detection. It is used in evaluating the performance of object detection algorithms. The metric can be used to measure the accuracy of an algorithm in detecting objects in an image. The IoU metric is used in a number of computer vision challenges, such as the Pascal VOC and Microsoft COCO challenges.</p><p>In real-world object detection applications, it is common to have multiple objects in a single image. In such scenarios, IoU can be used to evaluate the overlap between the prediction bounding box and the ground-truth bounding box for each object. The higher the IoU, the more accurate the prediction is.</p><h3>IoU Thresholds</h3><p>In object detection, IoU threshold values are used to determine if a prediction is considered a true positive, false positive, true negative, or false negative. A common IoU threshold used in object detection is 0.5. A prediction is considered a true positive if its IoU with the ground-truth bounding box is greater than 0.5, and a false positive if its IoU is less than 0.5.</p><p>In practice, the choice of the IoU threshold value depends on the specific application and the desired trade-off between precision and recall. For instance, in some applications, high precision is preferred, and in such cases, a lower IoU threshold is used. On the other hand, in applications where recall is more important, a higher IoU threshold may be used.</p><h3>Conclusion</h3><p>In conclusion, Intersection over Union (IoU) is a widely used evaluation metric in the field of object detection. It is used to measure the accuracy of an object detection algorithm by calculating the overlap between the prediction bounding box and the ground-truth bounding box. The IoU metric is used in many computer vision challenges, and it can be implemented in a number of programming languages, including NumPy, TensorFlow, and PyTorch. The choice of the IoU threshold value depends on the specific application and the desired trade-off between precision and recall.</p><h3>Read More</h3><ul><li><a href="https://hasty.ai/docs/mp-wiki/metrics/iou-intersection-over-union">Intersection over Union (IoU)</a></li><li><a href="https://pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/">Intersection over Union (IoU) for object detection</a></li></ul><p><em>Originally published at </em><a href="https://idiotdeveloper.com/what-is-intersection-over-union-iou"><em>https://idiotdeveloper.com</em></a><em> on February 7, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39448ac56431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Human Face Detection using Multi-task Cascaded Convolutional Networks in TensorFlow — Idiot…]]></title>
            <link>https://medium.com/swlh/human-face-detection-using-multi-task-cascaded-convolutional-networks-in-tensorflow-idiot-fe2ca51865e2?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe2ca51865e2</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[facedetection]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 09:22:59 GMT</pubDate>
            <atom:updated>2023-02-08T16:08:44.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>Human Face Detection using Multi-task Cascaded Convolutional Networks in TensorFlow — Idiot Developer</h3><p>In recent years, advances in machine learning and deep learning techniques have revolutionized the field of computer vision. With the help of these techniques, we can now detect and identify objects in real time with remarkable accuracy. One of the most popular tasks in computer vision is <a href="https://idiotdeveloper.com/human-face-landmark-detection-in-tensorflow-using-pre-trained-mobilenetv2/">human face detection</a>, which plays a crucial role in various applications such as biometrics, video surveillance, and many others.</p><p>In this tutorial, we will explore the implementation of Human Face Detection using Multi-task Cascaded Convolutional Networks (MTCNN) in TensorFlow. MTCNN is a deep learning model that is trained to perform facial detection, facial landmark estimation, and face alignment all in one network. This makes it an ideal choice for real-time face-detection applications. In this tutorial, we will be using the pre-trained MTCNN model for face detection and will be discussing the implementation details of the model in TensorFlow.</p><p>First, you will need to install TensorFlow and other required libraries such as opencv-python. You can install these using pip3.</p><pre>pip3 install tensorflow opencv-python mtcnn</pre><p>Next, you import all the required libraries.</p><pre>from mtcnn import MTCNN <br>import tensorflow as tf <br>import cv2</pre><p>We read an image containing multiple humans using OpenCV.</p><pre>image = cv2.imread(&#39;image/face.jpg&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*skhyKDNVL83vlrAQ1Qal1Q.png" /><figcaption><em>An example of an image with multiple persons.</em></figcaption></figure><p>After that, we will call the MTCNN class to use its <strong>detect_faces</strong> function to detect faces from an image.</p><pre>detector = MTCNN() <br>faces = detector.detect_faces(image)</pre><p>The <strong>detect_faces</strong> function returns a list of dictionaries, each containing the bounding box coordinates and facial landmarks for each detected face. You can use these coordinates to draw rectangles around the detected faces.</p><pre>for face in faces:<br>    x, y, width, height = face[&#39;box&#39;]<br>    cv2.rectangle(image, (x, y), (x+width, y+height), (255, 0, 0), 2)</pre><p>Finally, you can display the image with the detected faces using the following code.</p><pre>cv2.imshow(&quot;Face Detection&quot;, image) <br>cv2.waitKey(0) <br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*tGvR2VLPzIZRi_pCbrb11A.png" /><figcaption><em>The output image with a bounding box on the face of each person.</em></figcaption></figure><p>This is a basic example of using the MTCNN model for human face detection in TensorFlow. You can further customize this code to fit your specific needs, such as detecting faces in video streams or detecting multiple faces in one image.</p><h3>Read More</h3><ul><li><a href="https://arsfutura.com/magazine/face-recognition-with-facenet-and-mtcnn/">Face Recognition with FaceNet and MTCNN</a></li><li><a href="https://towardsdatascience.com/face-detection-using-mtcnn-a-guide-for-face-extraction-with-a-focus-on-speed-c6d59f82d49">Face Detection using MTCNN — a guide for face extraction with a focus on speed</a></li></ul><p><em>Originally published at </em><a href="https://idiotdeveloper.com/human-face-detection-using-multi-task-cascaded-convolutional-networks-in-tensorflow"><em>https://idiotdeveloper.com</em></a><em> on February 6, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe2ca51865e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/human-face-detection-using-multi-task-cascaded-convolutional-networks-in-tensorflow-idiot-fe2ca51865e2">Human Face Detection using Multi-task Cascaded Convolutional Networks in TensorFlow — Idiot…</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Linear Regression in TensorFlow — Idiot Developer]]></title>
            <link>https://nikhilroxtomar.medium.com/implementing-linear-regression-in-tensorflow-idiot-developer-f7f649c840e5?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f649c840e5</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 07:29:58 GMT</pubDate>
            <atom:updated>2023-02-04T08:15:42.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Linear Regression in TensorFlow — Idiot Developer</h3><p>TensorFlow is a powerful library for machine learning that allows for the easy implementation of various algorithms, including linear regression. In this tutorial, we will be using TensorFlow tape gradient to implement a linear regression model and plot the loss graph and x and y on matplotlib.</p><p>First, we will start by importing the necessary libraries:</p><pre>import tensorflow as tf <br>import matplotlib.pyplot as plt</pre><p>Next, we will generate some fake data for our linear regression model. We will use the <strong>tf.random.normal()</strong> function to generate random x and y values, and we will use a slope of 2 and an intercept of 1 to generate our y values.</p><pre># Generate fake data <br>num_samples = 1000 <br>x = tf.random.normal([num_samples]) <br>y = 2 * x + 1 + tf.random.normal([num_samples])</pre><p>Now, we will define our model using the <strong>tf.keras.Sequential()</strong> function and add a single layer with one input and one output.</p><pre># Define model <br>model = tf.keras.Sequential([ <br>  tf.keras.layers.Dense(1, input_shape=(1,)) <br>])</pre><p>Next, we will define our loss function and optimizer. We will use the mean squared error loss function and the Adam optimizer.</p><pre># Define loss and optimizer <br>loss_fn = tf.keras.losses.MeanSquaredError() <br>optimizer = tf.keras.optimizers.Adam()</pre><p>Now, we will use the TensorFlow tape gradient method to train our model. We will loop through the data for a specified number of iterations and update the model’s weights using the optimizer.</p><pre># Train model<br>num_epochs = 1000<br>loss_values = []<br>for epoch in range(num_epochs):<br>    with tf.GradientTape() as tape:<br>        y_pred = model(x)<br>        loss = loss_fn(y, y_pred)<br>        loss_values.append(loss.numpy())<br>    grads = tape.gradient(loss, model.trainable_variables)<br>    optimizer.apply_gradients(zip(grads, model.trainable_variables))</pre><p>Finally, we will plot the loss graph and x and y on matplotlib.</p><pre># Plot loss graph<br>plt.plot(loss)<br>plt.title(&#39;Loss vs. Epoch&#39;)<br>plt.xlabel(&#39;Epoch&#39;)<br>plt.ylabel(&#39;Loss&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*087qISvwhPSGtY9c.png" /><figcaption>The graph shows the comparison between the loss and number of epochs.</figcaption></figure><pre># Plot x and y<br>plt.scatter(x, y)<br>plt.plot(x, model(x), &#39;r&#39;)<br>plt.title(&#39;Linear Regression Model&#39;)<br>plt.xlabel(&#39;x&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*zjuOVSO_0H3N7T6U.png" /><figcaption>The scatter graph shows the predicted points around the line.</figcaption></figure><p>And that’s it! We have successfully implemented a linear regression model using TensorFlow tape gradient and plotted the loss graph and x and y on matplotlib. You can experiment with different values for the number of samples, slope, and intercept to see how it affects the model’s performance. Happy coding!</p><h3>Read More</h3><ul><li><a href="https://en.wikipedia.org/wiki/Linear_regression">Linear Regression — Wikipedia</a></li><li><a href="https://www.geeksforgeeks.org/ml-linear-regression/">Linear Regression — GeeksforGeeks</a></li><li><a href="https://idiotdeveloper.com/activation-function-basics-of-deep-learning/">Activation Function — Basics of Deep Learning</a></li><li><a href="https://idiotdeveloper.com/why-deep-learning-is-not-artificial-general-intelligence-agi/">Why Deep Learning is not Artificial General Intelligence (AGI)</a></li></ul><p><em>Originally published at </em><a href="https://idiotdeveloper.com/implementing-linear-regression-in-tensorflow"><em>https://idiotdeveloper.com</em></a><em> on January 21, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f649c840e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activation Function — Basics of Deep Learning — Idiot Developer]]></title>
            <link>https://nikhilroxtomar.medium.com/activation-function-basics-of-deep-learning-idiot-developer-d3ff2625864b?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3ff2625864b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 17:55:47 GMT</pubDate>
            <atom:updated>2023-01-25T15:26:07.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Activation Function — Basics of Deep Learning — Idiot Developer</h3><p><a href="https://idiotdeveloper.com/what-is-deep-learning/">Deep learning</a> is a subset of machine learning that utilizes neural networks with multiple layers to analyze and identify patterns in data. One of the key components of deep learning is the activation function, which is responsible for determining the output of each neuron in the network. In this blog post, we will explore the basics of activation functions and their role in deep learning.</p><h3>What is an Activation Function?</h3><p>An activation function is a mathematical function that is applied to the input of a neuron to determine its output. The output, also known as the activation, is then passed to the next layer in the network. Activation functions are used to introduce non-linearity into the neural network, allowing it to learn and model more complex patterns in the data.</p><p><strong>Read More</strong></p><ol><li><a href="https://idiotdeveloper.com/why-deep-learning-is-not-artificial-general-intelligence-agi/">Why Deep Learning is not Artificial General Intelligence (AGI)</a></li><li><a href="https://idiotdeveloper.com/what-is-transfer-learning-an-introduction/">What is Transfer Learning? — A Simple Introduction.</a></li></ol><h3>Purpose of Activation Functions</h3><p>Activation functions are used in deep learning to introduce non-linearity into a neural network. In a neural network, each neuron receives input from other neurons, performs some mathematical operation on that input, and then passes the output to other neurons. The activation function is used to determine the output of a neuron.</p><p>Without an activation function, the output of a neuron would simply be a linear combination of the input. This would result in a neural network that is only capable of performing linear operations, which would limit its ability to learn complex patterns and relationships in data. By introducing non-linearity through an activation function, a neural network can learn much more complex patterns and relationships in data.</p><h3>Types of Activation Functions</h3><p>There are several types of activation functions that are commonly used in deep learning, each with its own unique properties. Some of the most popular activation functions include:</p><ul><li><strong>Sigmoid: </strong>The sigmoid activation function is used to produce a probability-like output between 0 and 1. It is commonly used in the output layer of a neural network when the network is used for binary classification.</li><li><strong>ReLU (Rectified Linear Unit):</strong> The ReLU activation function is used to introduce non-linearity into a neural network. It is defined as f(x) = max(0, x) and produces an output that is either 0 or the input value.</li><li><strong>Tanh (Hyperbolic Tangent): </strong>The tanh activation function is similar to the sigmoid activation function, but its output range is between -1 and 1. This makes it useful for classification problems where the output is not binary.</li><li><strong>Softmax: </strong>The softmax activation function is used to produce a probability-like output that sums to 1. It is commonly used in the output layer of a neural network when the network is used for multi-class classification.</li></ul><h3>Choosing the Right Activation Function</h3><p>The choice of activation function can have a significant impact on the performance of a deep learning network. Some factors to consider when choosing an activation function include:</p><ul><li>The type of data you are working with: If the data is binary, a sigmoid function may be a good choice, while if the data is continuous, a ReLU function may be more appropriate.</li><li>The complexity of the problem: For more complex problems, a tanh or Leaky ReLU function may be necessary to capture the nuances of the data.</li><li>The number of layers in the network: The deeper the network, the more important it is to use an activation function that can handle the increased complexity.</li></ul><h3>Conclusion</h3><p>Activation functions are a crucial component of deep learning and play a key role in determining the output of each neuron in the network. The choice of activation function can have a significant impact on the performance of the network, so it is important to choose the right one for the task at hand. With the knowledge of the basics of activation functions and their role in deep learning, we can now apply the same to our neural network for better results.</p><p><em>Originally published at </em><a href="https://idiotdeveloper.com/activation-function-basics-of-deep-learning"><em>https://idiotdeveloper.com</em></a><em> on January 20, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3ff2625864b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Human Face Landmark Detection in TensorFlow using Pre-trained MobileNetv2 — Idiot Developer]]></title>
            <link>https://medium.com/analytics-vidhya/human-face-landmark-detection-in-tensorflow-using-pre-trained-mobilenetv2-idiot-developer-bf71ef9850a?source=rss-a4782a8f5e78------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf71ef9850a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[facial-keypoint-detection]]></category>
            <category><![CDATA[face-landmarks]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Nikhil Tomar]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 12:16:39 GMT</pubDate>
            <atom:updated>2022-11-23T14:51:52.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Human Face Landmark Detection in TensorFlow using Pre-trained MobileNetv2 — Idiot Developer</h3><p>Today, in this blog post<strong>, </strong>we will learn how to train a <a href="https://idiotdeveloper.com/convolution-neural-network-cnn-fundamental-of-deep-learning/">Convolutional Neural Network (CNN) </a>to <strong>detect human facial landmarks</strong>, such as eyes, mouth, nose, jawline and more. We will use the pre-trained MobileNetv2 from TensorFlow to build our model and then train it on <a href="https://github.com/JDAI-CV/lapa-dataset"><strong>La</strong>ndmark Guided Face <strong>Pa</strong>rsing (LaPa)</a> dataset.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWVOMGekzbWE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWVOMGekzbWE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWVOMGekzbWE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2caaadd9a33cb79be8ae89fef234b11/href">https://medium.com/media/e2caaadd9a33cb79be8ae89fef234b11/href</a></iframe><p><strong>Outline</strong></p><ol><li>What are Facial Landmarks?</li><li>Landmark Guided Face Parsing Dataset</li><li>Implementation</li><li>Summary</li></ol><p><strong>Download the code: </strong><a href="https://github.com/nikhilroxtomar/Human-Face-Landmark-Detection-in-TensorFlow">Human Face Landmark Detection in TensorFlow</a></p><h3>What are Facial Landmarks?</h3><p>Facial landmarks are the key points which represent the different facial structures, such as eyes, nose, lips, mouth, jawline and more. The combination of all the key points together constitutes the facial landmarks and these landmarks can be used in different computer vision tasks such as identifying gaze direction, detecting facial gestures, and swapping faces.</p><blockquote>These landmarks are simple coordinates points (x and y) which depict a specific region of the human face. The number of facial landmarks points can differ depending on the dataset and the complexity of the task to be performed.</blockquote><p>Facial landmark detection is a computer vision task in which we input the human face and the model is going to predict landmarks.</p><p>In this tutorial, we will train a<strong> pre-trained MobileNetv2 to predict 106 landmarks</strong> for a human face.</p><h3>Landmark Guided Face Parsing Dataset</h3><p>The dataset contains more than <strong>22,000 facial images</strong> with abundant variations in expression, pose and occlusion and each image of the dataset is provided with an <strong>11-category pixel-level label map</strong> and <strong>106-point landmarks</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*J6MXs7I07dPz83e1egzQew.jpeg" /><figcaption>Examples showing the images, 106 landmarks and the segmentation mask from the Landmark Guided Face Parsing (LaPa) dataset.</figcaption></figure><blockquote>To learn more about the dataset please read the research paper: <a href="https://aaai.org/ojs/index.php/AAAI/article/view/6832/6686">A New Dataset and Boundary-Attention Semantic Segmentation for Face Parsing</a></blockquote><h3>Implementation</h3><p>Now, we will start with the implementation, where we will first begin by training the model on the Landmark Guided Face Parsing (LaPa) dataset and then testing it.</p><h3>Training — train.py</h3><p>The training file contains the code for <strong>loading the dataset</strong> and then building the <strong>dataset pipeline</strong> using the tf.data API. Next, we use the <strong>pre-trained MobileNetv2</strong> to build the model and at last, we train the model.</p><p>We import all the required libraries and functions.</p><pre>import os<br>os.environ[&quot;TF_CPP_MIN_LOG_LEVEL&quot;] = &quot;2&quot;<br> <br>import numpy as np<br>import cv2<br>from glob import glob<br> <br>import tensorflow as tf<br>from tensorflow.keras import layers as L<br>from tensorflow.keras.applications import MobileNetV2<br>from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, CSVLogger</pre><p>Next, we define some global variables.</p><pre>global image_h<br>global image_w<br>global num_landmarks</pre><p>During training, we need to save the <strong>model.h5</strong> weight file. So, we will define a function called <strong>create_dir</strong> to create a folder or directory.</p><pre>def create_dir(path):<br>    if not os.path.exists(path):<br>        os.makedirs(path)</pre><p>We will now define the load_dataset function, which is going to load training, validation and testing datasets. Each of the dataset folders contains the following sub-folders:</p><ol><li><strong>images</strong> — contains the images as .jpg files.</li><li><strong>labels</strong> — contains the segmentation mask.</li><li><strong>landmarks</strong> — contains the text file, which has the landmarks (coordinate points).</li></ol><pre>def load_dataset(path):<br>    train_x = sorted(glob(os.path.join(path, &quot;train&quot;, &quot;images&quot;, &quot;*.jpg&quot;)))<br>    train_y = sorted(glob(os.path.join(path, &quot;train&quot;, &quot;landmarks&quot;, &quot;*.txt&quot;)))<br> <br>    valid_x = sorted(glob(os.path.join(path, &quot;val&quot;, &quot;images&quot;, &quot;*.jpg&quot;)))<br>    valid_y = sorted(glob(os.path.join(path, &quot;val&quot;, &quot;landmarks&quot;, &quot;*.txt&quot;)))<br> <br>    test_x = sorted(glob(os.path.join(path, &quot;test&quot;, &quot;images&quot;, &quot;*.jpg&quot;)))<br>    test_y = sorted(glob(os.path.join(path, &quot;test&quot;, &quot;landmarks&quot;, &quot;*.txt&quot;)))<br> <br>    return (train_x, train_y), (valid_x, valid_y), (test_x, test_y)</pre><p>Now, we have loaded the dataset, so we will define a function to read the image and the landmark text file.</p><pre>def read_image_lankmarks(image_path, landmark_path):<br>    &quot;&quot;&quot; Image &quot;&quot;&quot;<br>    image = cv2.imread(image_path, cv2.IMREAD_COLOR)<br>    h, w, _ = image.shape<br>    image = cv2.resize(image, (image_w, image_h))<br>    image = image/255.0<br>    image = image.astype(np.float32)<br> <br>    &quot;&quot;&quot; Lankmarks &quot;&quot;&quot;<br>    data = open(landmark_path, &quot;r&quot;).read()<br>    lankmarks = []<br> <br>    for line in data.strip().split(&quot;\n&quot;)[1:]:<br>        x, y = line.split(&quot; &quot;)<br>        x = float(x)/w<br>        y = float(y)/h<br> <br>        lankmarks.append(x)<br>        lankmarks.append(y)<br> <br>    lankmarks = np.array(lankmarks, dtype=np.float32)<br> <br>    return image, lankmarks</pre><p>Now, we will create <strong>preprocess</strong> and <strong>tf_dataset</strong> functions that would help in building the dataset pipeline using the tf.data API.</p><pre>def preprocess(x, y):<br>    def f(x, y):<br>        x = x.decode()<br>        y = y.decode()<br> <br>        image, landmarks = read_image_lankmarks(x, y)<br>        return image, landmarks<br> <br>    image, landmarks = tf.numpy_function(f, [x, y], [tf.float32, tf.float32])<br>    image.set_shape([image_h, image_w, 3])<br>    landmarks.set_shape([num_landmarks * 2])<br> <br>    return image, landmarks<br> <br>def tf_dataset(x, y, batch=8):<br>    ds = tf.data.Dataset.from_tensor_slices((x, y))<br>    ds = ds.shuffle(buffer_size=5000).map(preprocess)<br>    ds = ds.batch(batch).prefetch(2)<br>    return ds</pre><p>Now, we will build our model using the pre-trained MobileNetv2.</p><pre>def build_model(input_shape, num_landmarks):<br>    inputs = L.Input(input_shape)<br> <br>    backbone = MobileNetV2(include_top=False, weights=&quot;imagenet&quot;, input_tensor=inputs, alpha=0.5)<br>    backbone.trainable = True<br> <br>    x = backbone.output<br>    x = L.GlobalAveragePooling2D()(x)<br>    x = L.Dropout(0.2)(x)<br>    outputs = L.Dense(num_landmarks*2, activation=&quot;sigmoid&quot;)(x)<br> <br>    model = tf.keras.models.Model(inputs, outputs)<br>    return model</pre><p>Till now, we have defined all the functions required for training the model. Now, we will begin with the execution of the functions</p><p>First, we will <strong>seed the environment</strong>, <strong>create a folder</strong> and define some <strong>hyperparameters</strong>.</p><pre>if __name__ == &quot;__main__&quot;:<br>    &quot;&quot;&quot; Seeding &quot;&quot;&quot;<br>    np.random.seed(42)<br>    tf.random.set_seed(42)<br> <br>    &quot;&quot;&quot; Directory for storing files &quot;&quot;&quot;<br>    create_dir(&quot;files&quot;)<br> <br>    &quot;&quot;&quot; Hyperparameters &quot;&quot;&quot;<br>    image_h = 512<br>    image_w = 512<br>    num_landmarks = 106<br>    input_shape = (image_h, image_w, 3)<br>    batch_size = 32<br>    lr = 1e-3<br>    num_epochs = 100<br> <br>    &quot;&quot;&quot; Paths &quot;&quot;&quot;<br>    dataset_path = &quot;dataset/LaPa&quot;<br>    model_path = os.path.join(&quot;files&quot;, &quot;model.h5&quot;)<br>    csv_path = os.path.join(&quot;files&quot;, &quot;data.csv&quot;)</pre><p>Next, we will load the dataset by giving the <strong>dataset_path</strong> and then build the training and validation dataset using the <strong>tf_datset</strong> function.</p><pre>&quot;&quot;&quot; Loading the dataset &quot;&quot;&quot;<br>(train_x, train_y), (valid_x, valid_y), (test_x, test_y) = load_dataset(dataset_path)<br>print(f&quot;Train: {len(train_x)}/{len(train_y)} - Valid: {len(valid_x)}/{len(valid_y)} - Test: {len(test_x)}/{len(test_x)}&quot;)<br>print(&quot;&quot;)<br> <br>&quot;&quot;&quot; Dataset Pipeline &quot;&quot;&quot;<br>train_ds = tf_dataset(train_x, train_y, batch=batch_size)<br>valid_ds = tf_dataset(valid_x, valid_y, batch=batch_size)</pre><p>Now, we call our <strong>build_model</strong> function and compile it by providing the <strong>loss function</strong> and the <strong>optimizer</strong>.</p><pre>&quot;&quot;&quot; Model &quot;&quot;&quot;<br>model = build_model(input_shape, num_landmarks)<br>model.compile(loss=&quot;binary_crossentropy&quot;, optimizer=tf.keras.optimizers.Adam(lr))</pre><p>At last, we will define the <strong>callbacks</strong> and call the <strong>model.fit</strong> to begin the training.</p><pre>&quot;&quot;&quot; Training &quot;&quot;&quot;<br>callbacks = [<br>    ModelCheckpoint(model_path, verbose=1, save_best_only=True, monitor=&#39;val_loss&#39;),<br>    ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.1, patience=5, min_lr=1e-7, verbose=1),<br>    CSVLogger(csv_path, append=True),<br>    EarlyStopping(monitor=&#39;val_loss&#39;, patience=20, restore_best_weights=False)<br>]<br> <br>model.fit(train_ds,<br>    validation_data=valid_ds,<br>    epochs=num_epochs,<br>    callbacks=callbacks<br>)</pre><h3>Testing — test.py</h3><p>Now the model is trained and we have the <strong>model.h5</strong> weight file saved in the files folder along with the <strong>data.csv</strong> file.</p><p>So, first of all, we will import all the required libraries and functions. After that, we will define some global variables.</p><pre>import os<br>os.environ[&quot;TF_CPP_MIN_LOG_LEVEL&quot;] = &quot;2&quot;<br> <br>import numpy as np<br>import cv2<br>from glob import glob<br>from tqdm import tqdm<br>import tensorflow as tf<br>from train import create_dir, load_dataset<br> <br>global image_h<br>global image_w<br>global num_landmarks</pre><p>Next, we will define a function called plot_landmarks, which would take the following arguments:</p><ol><li><strong>image</strong> — the image on which the landmarks are to be plotted.</li><li><strong>landmarks</strong> — these are the normalized x and y coordinates in the form of a list.</li></ol><pre>def plot_lankmarks(image, landmarks):<br>    h, w, _ = image.shape<br>    radius = int(h * 0.005)<br> <br>    for i in range(0, len(landmarks), 2):<br>        x = int(landmarks[i] * w)<br>        y = int(landmarks[i+1] * h)<br> <br>        image = cv2.circle(image, (x, y), radius, (255, 0, 0), -1)<br> <br>    return image</pre><p>The landmarks list contains the coordinates in the following formats: <strong>[x1, y1, x2, y2, x3, y3,..]</strong> and so on. Due to this, we loop over the landmarks list with an increment of two to get the x and y points.</p><p>All these coordinates are normalized, meaning that their values lie between 0 and 1. So, we multiply them by the width and height and convert them to integers. We use these integer coordinate points and plot them on the input image.</p><p>Next, we will begin with the execution of the test.py.</p><pre>if __name__ == &quot;__main__&quot;:<br>    &quot;&quot;&quot; Seeding &quot;&quot;&quot;<br>    np.random.seed(42)<br>    tf.random.set_seed(42)<br> <br>    &quot;&quot;&quot; Directory for storing files &quot;&quot;&quot;<br>    create_dir(&quot;results&quot;)<br> <br>    &quot;&quot;&quot; Hyperparameters &quot;&quot;&quot;<br>    image_h = 512<br>    image_w = 512<br>    num_landmarks = 106<br> <br>    &quot;&quot;&quot; Paths &quot;&quot;&quot;<br>    dataset_path = &quot;/media/nikhil/Seagate Backup Plus Drive/ML_DATASET/LaPa&quot;<br>    model_path = os.path.join(&quot;files&quot;, &quot;model.h5&quot;)<br> <br>    &quot;&quot;&quot; Loading the dataset &quot;&quot;&quot;<br>    (train_x, train_y), (valid_x, valid_y), (test_x, test_y) = load_dataset(dataset_path)<br>    print(f&quot;Train: {len(train_x)}/{len(train_y)} - Valid: {len(valid_x)}/{len(valid_y)} - Test: {len(test_x)}/{len(test_x)}&quot;)<br>    print(&quot;&quot;)<br> <br>    &quot;&quot;&quot; Load the model &quot;&quot;&quot;<br>    model = tf.keras.models.load_model(model_path)<br>    # model.summary()</pre><p>Now, we have loaded our trained model. We will use it to predict the landmarks on the test images.</p><pre>&quot;&quot;&quot; Prediction &quot;&quot;&quot;<br>for x, y in tqdm(zip(test_x, test_y), total=len(test_x)):<br>    &quot;&quot;&quot; Extract the name &quot;&quot;&quot;<br>    name = x.split(&quot;/&quot;)[-1].split(&quot;.&quot;)[0]<br> <br>    &quot;&quot;&quot; Reading the image &quot;&quot;&quot;<br>    image = cv2.imread(x, cv2.IMREAD_COLOR)<br>    image_x = image<br>    image = cv2.resize(image, (image_w, image_h))<br>    image = image/255.0 ## (512, 512, 3)<br>    image = np.expand_dims(image, axis=0) ## (1, 512, 512, 3)<br>    image = image.astype(np.float32)<br> <br>    &quot;&quot;&quot; Landmarks &quot;&quot;&quot;<br>    data = open(y, &quot;r&quot;).read()<br>    landmarks = []<br>    for line in data.strip().split(&quot;\n&quot;)[1:]:<br>        x, y = line.split(&quot; &quot;)<br>        x = float(x)/image_x.shape[1]<br>        y = float(y)/image_x.shape[0]<br> <br>        landmarks.append(x)<br>        landmarks.append(y)<br> <br>    landmarks = np.array(landmarks, dtype=np.float32)<br> <br>    &quot;&quot;&quot; Prediction &quot;&quot;&quot;<br>    pred = model.predict(image, verbose=0)[0]<br>    pred = pred.astype(np.float32)<br> <br>    &quot;&quot;&quot; Saving the results &quot;&quot;&quot;<br>    gt_landmarks = plot_lankmarks(image_x.copy(), landmarks)<br>    pred_landmarks = plot_lankmarks(image_x.copy(), pred)<br>    line = np.ones((image_x.shape[0], 10, 3)) * 255<br> <br>    cat_images = np.concatenate([gt_landmarks, line, pred_landmarks], axis=1)<br>    cv2.imwrite(f&quot;results/{name}.png&quot;, cat_images)</pre><p>In the above code, we read the image, resize and normalize it. Then we read the landmarks from the text file and normalize them by dividing the x and y points by the width and height of the image.</p><p>The normalized image is fed to the model which predicts the normalized landmarks. We plot both the real and predicted landmarks on the image.</p><h3>Results</h3><p>A few examples show the comparison and the real and the predicted landmarks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*_RzzCFMZ0zvcCjwE2cKL3w.jpeg" /><figcaption>A comparison between the real and the predicted landmarks</figcaption></figure><h3>Summary</h3><p>In this blog post, we have built a human face landmark detector using the pre-trained MobileNetv2. The model takes the human face and predicts the 106 landmarks.</p><p>To learn about it in detail, please watch the YouTube tutorial: <a href="https://youtu.be/WVOMGekzbWE">Human Face Landmark Detection in TensorFlow using MobileNetv2</a></p><p>Hopefully, I was able to give you some new information and you learn something from this article.</p><p>If YES, then, Follow me:</p><ul><li><a href="https://www.youtube.com/idiotdeveloper">YouTube</a></li><li><a href="https://facebook.com/idiotdeveloper">Facebook</a></li><li><a href="https://twitter.com/nikhilroxtomar">Twitter</a></li><li><a href="https://www.instagram.com/nikhilroxtomar">Instagram</a></li></ul><p><em>Originally published at </em><a href="https://idiotdeveloper.com/human-face-landmark-detection-in-tensorflow-using-pre-trained-mobilenetv2/"><em>https://idiotdeveloper.com</em></a><em> on November 23, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf71ef9850a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/human-face-landmark-detection-in-tensorflow-using-pre-trained-mobilenetv2-idiot-developer-bf71ef9850a">Human Face Landmark Detection in TensorFlow using Pre-trained MobileNetv2 — Idiot Developer</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>