<?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 Sadak Vali on Medium]]></title>
        <description><![CDATA[Stories by Sadak Vali on Medium]]></description>
        <link>https://medium.com/@rebirth4vali?source=rss-ea37c88adbcb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nKm-udJEjEfQm8po.jpg</url>
            <title>Stories by Sadak Vali on Medium</title>
            <link>https://medium.com/@rebirth4vali?source=rss-ea37c88adbcb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:19:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rebirth4vali/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[ Zakaat: Connecting Donors with the Truly Deserving Applicants]]></title>
            <link>https://medium.com/@rebirth4vali/zakaat-connecting-donors-with-the-truly-deserving-applicants-486a60f3897e?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/486a60f3897e</guid>
            <category><![CDATA[siamese-neural-network]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[turborepo]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Sun, 11 May 2025 13:01:20 GMT</pubDate>
            <atom:updated>2025-06-11T03:41:45.226Z</atom:updated>
            <content:encoded><![CDATA[<p>A Turborepo-based, 6-Microservice Web App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzmIBt73Ekw5T5VW6hd0dw.png" /></figure><h3>👋 Hey there!</h3><p>I’m <strong>Sadiq Vali,</strong> a Computer Vision Deep Learning Engineer turned Figma UI Designer, Full-Stack Web Developer, React Native Mobile Dev, and budding DevOps Engineer.</p><p>Recently, I built something close to my heart <strong>Zakaat</strong>, a platform that directly connects donors with those in genuine need, without middlemen or delays.</p><p>This blog walks you through the <strong>journey, design, architecture, tech stack</strong>, and <strong>key user flows</strong> that make Zakaat a one-of-a-kind solution.</p><h3>🚀 Why Zakaat?</h3><p>Charity often gets lost in <strong>middlemen</strong>, <strong>lack of trust</strong>, and <strong>delayed impact</strong>.<br> <strong>Zakaat</strong> changes that inspired by Islamic giving principles and powered by modern tech.</p><p>💡 <strong>How it works:</strong></p><ul><li>Donations go <em>directly</em> to applicants’ bank accounts — <strong>no platform cut</strong></li><li><strong>Instant transfers</strong> — powered by UPI &amp; Razorpay</li><li><strong>Borderless support</strong> — including for global causes like <strong>Gaza relief</strong></li></ul><p>✅ No middlemen<br>✅ No delays<br>✅ No hidden fees</p><h3>🎨 Design System From Figma, With Love</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hD33bNwnSZqBFxK-FQ65Q.png" /></figure><p>I crafted the <strong>entire UI/UX from scratch</strong> for both web and mobile Apps using the <strong>Figma</strong>.</p><p>🎨 <strong>Highlights</strong>:</p><ul><li>Custom <strong>typography</strong>, <strong>color palette</strong>, and <strong>glassmorphism styling</strong></li><li>Modular components with structured <strong>variants &amp; properties</strong></li><li>Smart, responsive layouts using <strong>clamp()</strong></li><li>Prototypes with real user interaction flows</li><li><strong>Figma Wrap</strong> used for consistency &amp; automation</li></ul><p>💬 <em>It’s more than pretty — it’s scalable, structured, and developer-first.</em></p><p>🔗 <strong>Explore the Figma Design</strong>: <a href="https://www.figma.com/design/VO5aSBXfFWmi5T31LDIQs3/HaqqueZakat?node-id=1215-10091&amp;t=P4iG4ypETgXvG2Ih-1"><strong>https://www.figma.com/design/VO5aSBXfFWmi5T31LDIQs3/HaqqueZakat?node-id=1215-10091&amp;t=P4iG4ypETgXvG2Ih-1</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4glpqjjurHzHjSqserXXQ.png" /></figure><h3>⚙️ Tech Stack Built for Speed and Scale</h3><p><strong>Frontend</strong>: Next.js 15, TypeScript, TailwindCSS, Zustand, Shadcn, Magic UI<br><strong>Backend</strong>: FastAPI, Prisma ORM, MongoDB, AuthJS v5, Zod, UploadThing<br><strong>Infra</strong>: TurboRepo, Docker, K8s (AWS EKS), Helm, ACM, NGINX + NLB<br><strong>Real-time</strong>: WebSockets, Redis, PeerJS, Nodemailer, React Email<br><strong>Payments</strong>: Razorpay + Instant webhook-based capture<br><strong>AI/Fraud</strong>: DeepFace + FAISS for face similarity search</p><p>🚀 Built with <strong>Bun</strong> for blazing-fast dev workflows</p><p>🧠 <strong>Coming Soon</strong>:</p><ul><li>TRPC, Stripe/PayPal</li><li>React Native Expo</li><li>React Query + TanStack Router</li><li>AI-powered recommendations</li><li>Golang for performance-critical services</li></ul><h3>✨ <strong>HIghlights of this Project</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XRmAyNLVUazzmbbwJGxPg.png" /></figure><ul><li><strong>Twitter-style tweeting</strong></li><li><strong>WhatsApp-style chat</strong> with real-time messaging</li><li><strong>Omegle-style video calling</strong> using <strong>PeerJS</strong></li><li><strong>Face verification for fraud detection</strong> leveraging my Computer Vision Deep Learning background</li><li><strong>Face embedding similarity search</strong> using <strong>native MongoDB Atlas</strong></li><li><strong>Proximity-based search</strong> natively supported by <strong>MongoDB’s geo queries</strong></li><li><strong>Instant UPI payments</strong> via Razorpay, fully automated using webhooks</li><li><strong>Seamless scrolling-based pagination</strong> no jarring page reloads</li></ul><h3>🔄 Core User Flows</h3><h3>1️⃣ Fluid Responsive UI &amp; Onboarding New User</h3><p>Using clamp() across typography, margins, and paddings makes the layout feel <strong>naturally adaptive.</strong> No breakpoints and No media queries just smooth scaling. Using break points just for changing the layouts on UI.</p><p>A personalized <strong>onboarding email</strong> is sent automatically to all the new Users. All secured via AuthJS <strong>v5</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2Fdc7e6fa17a6a470382eeff9331fad3e8&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2Fdc7e6fa17a6a470382eeff9331fad3e8%3Fsid%3D7b9d0876-d655-4450-a4a8-d968e07deb8e&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2Fdc7e6fa17a6a470382eeff9331fad3e8-5ee37c72233b5e7b.gif&amp;type=text%2Fhtml&amp;schema=loom" width="1444" height="1083" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef39ac5819c19dcdb52310dfabdc1e1/href">https://medium.com/media/cef39ac5819c19dcdb52310dfabdc1e1/href</a></iframe><h3>2️⃣ Apply for Zakaat (Deep Learning, Computer Vision, Siamese Models, FAISS)</h3><p>Before an applicant can submit, our backend performs <strong>face verification</strong> using <strong>Siamese models</strong>.<br> Duplicate detection ensures only genuine applicants move forward.</p><p>📊 Powered by FAISS — handles <strong>millions of faces</strong> in under 2–3 seconds.<br> 🧪 Accuracy: <strong>98.56% Top-4</strong> tested on a high-variance dataset.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2F3fcd737c51314655922979eecae8fe75&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2F3fcd737c51314655922979eecae8fe75%3Fsid%3Dddfcabc8-0642-4742-8476-a3bd32c4e625&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2F3fcd737c51314655922979eecae8fe75-d0f4152bb9d8af39.gif&amp;type=text%2Fhtml&amp;schema=loom" width="1444" height="1083" frameborder="0" scrolling="no"><a href="https://medium.com/media/b75b1c866b1aa0df826255dfb89fdf4c/href">https://medium.com/media/b75b1c866b1aa0df826255dfb89fdf4c/href</a></iframe><h3>3️⃣ Proximity Search &amp; Bookmark/Unbookmark Applications</h3><p>Discover local applicants using <strong>geo-queries in MongoDB Atlas</strong>.<br> Turn on location, and the platform auto-surfaces nearby applicants.</p><p>❤️ Bookmark now, donate later. it’s that simple.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2F8c8f92e97b4744aba9b9d2886de57b17&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2F8c8f92e97b4744aba9b9d2886de57b17%3Fsid%3D710d61db-0c96-4b42-b75c-489fc0228a18&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2F8c8f92e97b4744aba9b9d2886de57b17-557fa9efbe091cf0.gif&amp;type=text%2Fhtml&amp;schema=loom" width="1444" height="1083" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7ef141559434caa5b6f4b8cf7e2afd1/href">https://medium.com/media/a7ef141559434caa5b6f4b8cf7e2afd1/href</a></iframe><h3>4️⃣ Real-time Chat like in WhatsApp</h3><p>Donors and applicants can chat <strong>without exchanging numbers between them</strong>. Messages are delivered instantly and saved even if users are offline.</p><p>🔒 Secure, private, and smooth.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2F5a67806f5c65487faa3512c109c74825&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2F5a67806f5c65487faa3512c109c74825%3Fsid%3D53c6805a-495b-4c36-bdee-f432f7c63a31&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2F5a67806f5c65487faa3512c109c74825-faa8804182de9c87.gif&amp;type=text%2Fhtml&amp;schema=loom" width="1920" height="1440" frameborder="0" scrolling="no"><a href="https://medium.com/media/c03f72e282d63db5d311f5fee2c5e3ba/href">https://medium.com/media/c03f72e282d63db5d311f5fee2c5e3ba/href</a></iframe><h3>5️⃣ Video Calls Like Omegle</h3><p>Private video calls using <strong>PeerJS + WebRTC</strong>.</p><p>🔹 Only <strong>donors</strong> can initiate<br> 🔹 Applicants receive popup prompts to accept/reject<br> 🔹 Live draggable video windows<br> 🔹 Toggle video/audio anytime<br> 🔐 No numbers exchanged. Just real conversations.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAGnHWSaWZ0%2FDMWkDE9GQO5iRslv-A-jKQ%2Fwatch%3Futm_content%3DDAGnHWSaWZ0%26utm_campaign%3Ddesignshare%26utm_medium%3Dlink2%26utm_source%3Duniquelinks%26utlId%3Dhef0d90a6d4&amp;type=text%2Fhtml&amp;schema=canva&amp;display_name=Canva&amp;src=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAGnHWSaWZ0%2FDMWkDE9GQO5iRslv-A-jKQ%2Fwatch%3Fembed%26meta" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/f33624a010dc551c7d0b3f2757c2ab82/href">https://medium.com/media/f33624a010dc551c7d0b3f2757c2ab82/href</a></iframe><h3>6️⃣ Instant UPI Donations (Video)</h3><p>🔸 Click “Donate”<br> 🔸 UPI ID is fetched securely<br> 🔸 Razorpay handles the transaction<br> 🔸 Webhook confirms and records donation<br> 🔔 Donors receive an instant thank-you note</p><p>💸 No delays. No middlemen. Just impact.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2Feec491c5df4040d8ade21cb2081af885&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2Feec491c5df4040d8ade21cb2081af885%3Fsid%3D67e3eb91-b179-4373-9e20-92eea8e81533&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2Feec491c5df4040d8ade21cb2081af885-35edaac12defe880.gif&amp;type=text%2Fhtml&amp;schema=loom" width="1444" height="1083" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6587aac167fe020a677e44429499711/href">https://medium.com/media/d6587aac167fe020a677e44429499711/href</a></iframe><h3>7️⃣ Donor Tweets</h3><p>Let generosity be social. Donors can tweet short messages endorsing applicants they trust.</p><p>📣 Their followers see it → more trust → more donations<br> 🔁 Amplifying impact, one tweet at a time.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2Fa268385d75684ec6b18e3c45eb6542d0&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2Fa268385d75684ec6b18e3c45eb6542d0%3Fsid%3Dfe86f32a-ed15-4d3f-8637-9336e296f0a0&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2Fa268385d75684ec6b18e3c45eb6542d0-cb9bde1d5171a210.gif&amp;type=text%2Fhtml&amp;schema=loom" width="1444" height="1083" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eaeae069bbf78d8a9222a479d639924/href">https://medium.com/media/8eaeae069bbf78d8a9222a479d639924/href</a></iframe><h3>8️⃣ Scrolling Based Pagination</h3><p>No jarring page reloads. No “Next Page” buttons.<br>Just smooth, infinite scrolling.<br>Every list, from Zakaat applications to donor tweets, loads seamlessly as you scroll, providing a native app-like experience on the web.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAGnHuPdfTU%2FiTocr0CfPHoctKtxHN04mw%2Fwatch%3Futm_content%3DDAGnHuPdfTU%26utm_campaign%3Ddesignshare%26utm_medium%3Dlink2%26utm_source%3Duniquelinks%26utlId%3Dh50618d5dbb&amp;type=text%2Fhtml&amp;schema=canva&amp;display_name=Canva&amp;src=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAGnHuPdfTU%2FiTocr0CfPHoctKtxHN04mw%2Fwatch%3Fembed%26meta" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcd19d4a3dbbc8ec5db2799c864b6536/href">https://medium.com/media/fcd19d4a3dbbc8ec5db2799c864b6536/href</a></iframe><h3>9️⃣ AWS EKS Kubernetes Deployment Files</h3><p>🛠️ If you’re curious or want a detailed walkthrough of deploying this project on EKS, 👇 <strong>Drop a comment below</strong>, and I’ll share a complete guide soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*modCSkYBj7f3EEIzdSPafQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9kEk_BSC4aO6GKzST6SyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cp7_BfL75Yl5C-jO0Ap1Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*KfIcRNMA6Hhb3-R8zJw87Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcN-1M6aRU9rRqZ0xUCjvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQAMqaaTVxkID2o98FAQVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*ieWE7M5cVfRpKxQW93cIQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMdxFggS0TS4ueZforGWPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*0Yf1YafK1nbp-vZgh4SudQ.png" /></figure><h3>🌍 <strong>Explore the Platform</strong></h3><p>Experience Zakaat in action — designed, built, and deployed with ❤️</p><p>🔗 <strong>Live Demo:</strong> <a href="https://zakaat.sadiqvali.in/">zakaat.sadiqvali.in</a><br> <em>Note: If the link is temporarily down, it’s likely because this powerful platform costs around ₹400/day to run and I may be pausing it due to budget constraints.</em><br> 🐦 <strong>Twitter/X:</strong> <a href="https://x.com/rebirth4vali">https://x.com/rebirth4vali</a><br> 💼 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sadiq-vali/">https://www.linkedin.com/in/sadiq-vali/</a><br> 💻 <strong>GitHub:</strong> <a href="https://github.com/SadiqVali786/zakaat-micro-services">https://github.com/SadiqVali786/zakaat-micro-services</a></p><p>✨ If this project inspired you, let’s connect. Whether it’s for <strong>collaboration</strong>, <strong>contribution</strong>, or just to share your thoughts. I’m always up for meaningful conversations around tech and impact.</p><p>— <strong>Sadiq Vali</strong> 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=486a60f3897e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Translation with Attention in TensorFlow Python from Scratch]]></title>
            <link>https://medium.com/@rebirth4vali/machine-translation-with-attention-in-tensorflow-python-from-scratch-1db2e100db18?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1db2e100db18</guid>
            <category><![CDATA[machine-translation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[language-translation]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 06:45:17 GMT</pubDate>
            <atom:updated>2023-03-29T06:45:17.958Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Sequence to Sequence (Seq2Seq) models have been used extensively in various Natural Language Processing (NLP) tasks such as machine translation, text summarization, and question answering. In this blog post, we will implement a Seq2Seq model for Italian-to-English machine translation using TensorFlow and Python OOPs. The model architecture will consist of an Encoder, a Decoder, and an Attention mechanism.</p><h3>Requirements</h3><ul><li>TensorFlow 2.0 or higher</li><li>Numpy</li><li>Pandas</li><li>NLTK</li><li>Scikit-learn</li></ul><h3>Constants</h3><pre>BATCH_SIZE = 1024<br>MAX_ENC_SEQ_LEN = 20<br><br>ENCODER_SEQ_LEN = 20<br>ENCODER_EMBEDD_DIM = 50<br>NUM_OF_ENC_LSTM_UNITS = 256<br><br>DECODER_OUT_SEQ_LEN = 20<br>DECODER_EMBEDD_DIM = 100<br>NUM_OF_DEC_LSTM_UNITS = 256<br><br>TARGET_VOCAB_SIZE = 12500<br>INPUT_VOCAB_SIZE = 26500</pre><h3>Data Preprocessing</h3><p>The first step in any machine learning task is to preprocess the data. We will be using a dataset of Italian-English sentence pairs for our translation task. The dataset can be downloaded from <a href="http://www.manythings.org/anki/ita-eng.zip">here</a>.</p><p>After downloading the dataset, we can unzip it and load it into a pandas data frame using the following code:</p><pre>with open(&#39;ita.txt&#39;, &#39;r&#39;, encoding=&quot;utf8&quot;) as f:<br>    eng=[]<br>    ita=[]<br>    for i in f.readlines():<br>        eng.append(i.split(&quot;\t&quot;)[0])<br>        ita.append(i.split(&quot;\t&quot;)[1])<br>data = pd.DataFrame(data=list(zip(eng, ita)), columns=[&#39;english&#39;,&#39;italian&#39;])<br>print(data.shape)<br>data.head()</pre><p>We will then clean the data by removing any unnecessary characters, converting the text to lowercase, and tokenizing the sentences using the NLTK library.</p><pre>def decontractions(phrase):<br>    &quot;&quot;&quot;decontracted takes text and convert contractions into natural form.<br>     ref: https://stackoverflow.com/questions/19790188/expanding-english-language-contractions-in-python/47091490#47091490&quot;&quot;&quot;<br>    # specific<br>    phrase = re.sub(r&quot;won\&#39;t&quot;, &quot;will not&quot;, phrase)<br>    phrase = re.sub(r&quot;can\&#39;t&quot;, &quot;can not&quot;, phrase)<br>    phrase = re.sub(r&quot;won\’t&quot;, &quot;will not&quot;, phrase)<br>    phrase = re.sub(r&quot;can\’t&quot;, &quot;can not&quot;, phrase)<br><br>    # general<br>    phrase = re.sub(r&quot;n\&#39;t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;re&quot;, &quot; are&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;s&quot;, &quot; is&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;d&quot;, &quot; would&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;ll&quot;, &quot; will&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;ve&quot;, &quot; have&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;m&quot;, &quot; am&quot;, phrase)<br><br>    phrase = re.sub(r&quot;n\’t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\’re&quot;, &quot; are&quot;, phrase)<br>    phrase = re.sub(r&quot;\’s&quot;, &quot; is&quot;, phrase)<br>    phrase = re.sub(r&quot;\’d&quot;, &quot; would&quot;, phrase)<br>    phrase = re.sub(r&quot;\’ll&quot;, &quot; will&quot;, phrase)<br>    phrase = re.sub(r&quot;\’t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\’ve&quot;, &quot; have&quot;, phrase)<br>    phrase = re.sub(r&quot;\’m&quot;, &quot; am&quot;, phrase)<br><br>    return phrase<br><br>def preprocess(text):<br>    # convert all the text into lower letters<br>    # use this function to remove the contractions: https://gist.github.com/anandborad/d410a49a493b56dace4f814ab5325bbd<br>    # remove all the spacial characters: except space &#39; &#39;<br>    text = text.lower()<br>    text = decontractions(text)<br>    text = re.sub(&#39;[^A-Za-z0-9 ]+&#39;, &#39;&#39;, text)<br>    return text<br><br>def preprocess_ita(text):<br>    # convert all the text into lower letters<br>    # remove the words betweent brakets ()<br>    # remove these characters: {&#39;$&#39;, &#39;)&#39;, &#39;?&#39;, &#39;&quot;&#39;, &#39;’&#39;, &#39;.&#39;,  &#39;°&#39;, &#39;!&#39;, &#39;;&#39;, &#39;/&#39;, &quot;&#39;&quot;, &#39;€&#39;, &#39;%&#39;, &#39;:&#39;, &#39;,&#39;, &#39;(&#39;}<br>    # replace these spl characters with space: &#39;\u200b&#39;, &#39;\xa0&#39;, &#39;-&#39;, &#39;/&#39;<br>    # we have found these characters after observing the data points, feel free to explore more and see if you can do find more<br>    # you are free to do more proprocessing<br>    # note that the model will learn better with better preprocessed data <br>    <br>    text = text.lower()<br>    text = decontractions(text)<br>    text = re.sub(&#39;[$)\?&quot;’.°!;\&#39;€%:,(/]&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;\u200b&#39;, &#39; &#39;, text)<br>    text = re.sub(&#39;\xa0&#39;, &#39; &#39;, text)<br>    text = re.sub(&#39;-&#39;, &#39; &#39;, text)<br>    return text<br><br><br>data[&#39;english&#39;] = data[&#39;english&#39;].apply(preprocess)<br>data[&#39;italian&#39;] = data[&#39;italian&#39;].apply(preprocess_ita)<br>data.head()</pre><h3>Teacher Forcing Instructions &amp; dataset Preparation</h3><pre>data[&#39;english_inp&#39;] = &#39;&lt;start&gt; &#39; + data[&#39;english&#39;].astype(str)<br>data[&#39;english_out&#39;] = data[&#39;english&#39;].astype(str) + &#39; &lt;end&gt;&#39;<br><br>data = data.drop([&#39;english&#39;,&#39;italian_len&#39;,&#39;english_len&#39;], axis=1)</pre><h3>Splitting data into train and test</h3><pre>from sklearn.model_selection import train_test_split<br>train, validation = train_test_split(data, <br>                                     test_size=0.2)</pre><h3>Creating Tokenizer on the Train Data and Learning Vocabulary</h3><pre>tknizer_ita = Tokenizer(oov_token=&#39;&lt;OOV&gt;&#39;)<br>tknizer_ita.fit_on_texts(train[&#39;italian&#39;].values)<br><br>tknizer_eng = Tokenizer(oov_token=&#39;&lt;OOV&gt;&#39;,<br>                        filters=&#39;!&quot;#$%&amp;()*+,-./:;=?@[\\]^_`{|}~\t\n&#39;)<br>tknizer_eng.fit_on_texts(train[&#39;english_inp&#39;].values)<br><br>train.iloc[0][&#39;english_inp&#39;] = str(train.iloc[0][&#39;english_inp&#39;])[:-6]<br><br><br><br>TARGET_VOCAB_SIZE = len(tknizer_eng.word_index.keys())<br>INPUT_VOCAB_SIZE = len(tknizer_ita.word_index.keys())</pre><h3>Creating Embeddings for English Sentences</h3><pre>embeddings_index = dict()<br><br>f = open(&#39;glove.6B.100d.txt&#39;)<br><br>for line in f:<br>    values = line.split()<br>    word = values[0]<br>    coefs = np.asarray(values[1:], <br>                       dtype=&#39;float32&#39;)<br>    embeddings_index[word] = coefs<br>    <br>f.close()<br><br># embedding_matrix = np.zeros((INPUT_VOCAB_SIZE+1, 100))<br>EMBEDDING_MATRIX = np.zeros((TARGET_VOCAB_SIZE+1, 100))<br><br>for word, word_index in tknizer_eng.word_index.items():<br>    embedding_vector = embeddings_index.get(word)<br>    if embedding_vector is not None and word_index &lt;= TARGET_VOCAB_SIZE:<br>        EMBEDDING_MATRIX[word_index] = embedding_vector</pre><h3>Creating Data Pipeline</h3><pre>class Dataset:<br>    <br>    def __init__(self, <br>                 data, <br>                 tknizer_ita, <br>                 tknizer_eng, <br>                 max_len):<br>        <br>        self.encoder_inps = data[&#39;italian&#39;].values<br>        self.decoder_inps = data[&#39;english_inp&#39;].values<br>        self.decoder_outs = data[&#39;english_out&#39;].values<br>        <br>        self.tknizer_eng = tknizer_eng<br>        self.tknizer_ita = tknizer_ita<br>        self.max_len = max_len<br><br>    def __getitem__(self, i):<br>        # need to pass list of values<br>        self.encoder_seq = self.tknizer_ita.texts_to_sequences([self.encoder_inps[i]])<br>        self.decoder_inp_seq = self.tknizer_eng.texts_to_sequences([self.decoder_inps[i]])<br>        self.decoder_out_seq = self.tknizer_eng.texts_to_sequences([self.decoder_outs[i]])<br><br>        self.encoder_seq = pad_sequences(self.encoder_seq, <br>                                         maxlen=self.max_len, <br>                                         dtype=&#39;int32&#39;, <br>                                         padding=&#39;post&#39;)<br>        <br>        self.decoder_inp_seq = pad_sequences(self.decoder_inp_seq, <br>                                             maxlen=self.max_len, <br>                                             dtype=&#39;int32&#39;, <br>                                             padding=&#39;post&#39;)<br>        <br>        self.decoder_out_seq = pad_sequences(self.decoder_out_seq, <br>                                             maxlen=self.max_len, <br>                                             dtype=&#39;int32&#39;, <br>                                             padding=&#39;post&#39;)<br>        <br>        return self.encoder_seq, self.decoder_inp_seq, self.decoder_out_seq<br><br>    def __len__(self): <br>        # your model.fit_gen requires this function<br>        return len(self.encoder_inps)<br><br>    <br>class Dataloder(tf.keras.utils.Sequence):   <br>    <br>    def __init__(self, <br>                 dataset, <br>                 batch_size=1):<br>        <br>        self.dataset = dataset<br>        self.batch_size = batch_size<br>        self.indexes = np.arange(len(self.dataset.encoder_inps))<br><br>    def __getitem__(self, i):<br>        start = i * self.batch_size<br>        stop = (i + 1) * self.batch_size<br>        data = []<br>        for j in range(start, stop):<br>            data.append(self.dataset[j])<br><br>        batch = [np.squeeze(np.stack(samples, axis=1), axis=0) for samples in zip(*data)]<br>        # we are creating data like ([italian, english_inp], english_out) these are already converted into seq<br>        return tuple([[batch[0], batch[1]], batch[2]])<br><br>    def __len__(self):  <br>        # your model.fit_gen requires this function<br>        return len(self.indexes) // self.batch_size<br><br>    def on_epoch_end(self):<br>        self.indexes = np.random.permutation(self.indexes)</pre><pre>train_dataset = Dataset(train, <br>                        tknizer_ita, <br>                        tknizer_eng, <br>                        20)<br><br>test_dataset  = Dataset(validation, <br>                        tknizer_ita, <br>                        tknizer_eng, <br>                        20)<br><br>train_dataloader = Dataloder(train_dataset, <br>                             batch_size=BATCH_SIZE)<br><br>test_dataloader = Dataloder(test_dataset, <br>                            batch_size=BATCH_SIZE)<br><br><br>print(train_dataloader[0][0][0].shape, train_dataloader[0][0][1].shape, train_dataloader[0][1].shape)</pre><h3>Implementing Encoder from Scratch</h3><pre>class Encoder(tf.keras.Model):<br>    <br>    &#39;&#39;&#39;<br>    Encoder model -- That takes an input sequence and returns memory_state, cell_state and output @ <br>    each time step of the last encoder LSTM Layer.<br>    &#39;&#39;&#39;<br>    <br>    def __init__(self, <br>                 encoder_vocab_size,    # INPUT_VOCAB_SIZE = 5000<br>                 encoder_embedding_dim, # ENCODER_EMBEDD_DIM = 50<br>                 num_of_enc_lstm_units, # NUM_OF_ENC_LSTM_UNITS = 256<br>                 encoder_input_seq_len, # ENCODER_SEQ_LEN = 20<br>                 **kwargs):<br>        <br>        super().__init__(**kwargs)<br>        self.encoder_vocab_size = encoder_vocab_size<br>        self.encoder_embedding_dim = encoder_embedding_dim<br>        self.encoder_input_seq_len = encoder_input_seq_len<br>        self.num_of_enc_lstm_units = num_of_enc_lstm_units<br>        <br>        self.lstm_output, \<br>        self.lstm_memory_state_h, \<br>        self.lstm_cell_state_c = 0, 0, 0<br>        <br>        # Initialize Embedding layer<br>        self.embedding = Embedding(input_dim=self.encoder_vocab_size,<br>                                   output_dim=self.encoder_embedding_dim,<br>                                   input_length=self.encoder_input_seq_len,<br>                                   mask_zero=True,<br>                                   name=&#39;encoder_embedding_layer&#39;)<br>        <br>        # Intialize Encoder LSTM layer<br>        self.lstm = RNN(tf.keras.layers.LSTMCell(self.num_of_enc_lstm_units),<br>                        return_sequences=True,<br>                        return_state=True,<br>                        name=&#39;encoder_lstm_layer&#39;)<br>        <br>        &quot;&quot;&quot;<br>        self.lstm = LSTM(units=self.num_of_enc_lstm_units, <br>                         return_sequences=True,<br>                         return_state=True,<br>                         name=&#39;encoder_lstm_layer&#39;)<br>        &quot;&quot;&quot;<br>        <br>    def call(self, <br>             enc_input_seq, # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20)<br>             lst_of_enc_lstm_mem_and_cell_initial_states, # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256)<br>             training=True):<br>        <br>        &#39;&#39;&#39;<br>        This function takes a sequence input and the initial states of the encoder.<br>        1. Pass the input_sequence input to the Embedding layer, <br>        2. &amp; Pass the embedding layer ouput to encoder_lstm<br>        :returns -- All encoder_time_steps_outputs, last_time_step_hidden_state and cell_state<br>        &#39;&#39;&#39;<br>        <br>        if len(enc_input_seq.shape) == 1: enc_input_seq = tf.expand_dims(enc_input_seq, 0)<br><br>        # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20) ===&gt; <br>        # (BATCH_SIZE, ENCODER_SEQ_LEN, ENCODER_EMBEDD_DIM) : (1024, 20, 50)<br>        embedded_enc_input_seq = self.embedding(enc_input_seq)<br>        <br>        <br>        # (BATCH_SIZE, ENCODER_SEQ_LEN, ENCODER_EMBEDD_DIM) : (1024, 20, 50) <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256)  ===&gt; <br>        # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256), <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256)<br>        self.encoder_lstm_output, \<br>        self.encoder_lstm_memory_state_h, \<br>        self.encoder_lstm_cell_state_c = self.lstm(embedded_enc_input_seq,<br>                                                   initial_state=lst_of_enc_lstm_mem_and_cell_initial_states)<br>        <br>        return self.encoder_lstm_output, self.encoder_lstm_memory_state_h, self.encoder_lstm_cell_state_c<br>    <br>    def get_states(self, ):<br>        &quot;&quot;&quot;<br>        returns the current hidden_state and cell_state of the encoder LSTM layer.<br>        &quot;&quot;&quot;<br>        return self.encoder_lstm_memory_state_h, self.encoder_lstm_cell_state_c<br>    <br>    def initialize_states(self, <br>                          batch_size):<br>        &#39;&#39;&#39;<br>        Given a batch size it will return intial hidden state and intial cell state.<br>        If batch_size is 32 then - <br>        Hidden state is zeros of size [32, num_of_enc_lstm_units], <br>        cell state zeros is of size [32, num_of_enc_lstm_units]<br>        &#39;&#39;&#39;<br>        # BATCH_SIZE : 1024 ==&gt; (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS)<br>        shape = (batch_size, self.num_of_enc_lstm_units)<br>        return [tf.zeros(shape), tf.zeros(shape)]</pre><h3>Attention Mechanism</h3><p>The Attention mechanism is used to weigh the importance of different parts of the input sequence when generating each word of the output sequence.</p><pre>class Attention(tf.keras.layers.Layer):<br>    <br>    &#39;&#39;&#39;<br>    Class that calculates similarity score based on the scoring_function using Bahdanu attention mechanism.<br>    &#39;&#39;&#39;<br>    <br>    def __init__(self, <br>                 scoring_function, <br>                 att_units): # NUM_OF_ENC_LSTM_UNITS = 256<br>        <br>        super().__init__()<br>        self.scoring_function = scoring_function<br>        <br>        # Please go through the reference notebook and research paper to complete the scoring functions<br>        <br>        if scoring_function == &#39;dot&#39;:<br>            pass<br>        <br>        elif scoring_function == &#39;general&#39;: <br>            # Intialize variables needed for General score function here<br>            shape = (NUM_OF_ENC_LSTM_UNITS, NUM_OF_DEC_LSTM_UNITS)<br>            self.W = tf.Variable(initial_value=tf.random.uniform(shape=shape))<br>            <br>        elif scoring_function == &#39;concat&#39;: # Intialize variables needed for Concat score function here<br>            <br>            shape = (NUM_OF_ENC_LSTM_UNITS, 100) # (256, 100)<br>            self.W_enc = tf.Variable(initial_value=tf.random.uniform(shape=shape))<br>            <br>            shape = (NUM_OF_DEC_LSTM_UNITS, 100) # (512, 100)<br>            self.W_dec = tf.Variable(initial_value=tf.random.uniform(shape=shape))<br>            <br>            shape = (100, )<br>            self.v = tf.Variable(initial_value=tf.random.uniform(shape=shape))            <br>            <br>    def call(self, <br>             decoder_hidden_state, # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512)<br>             encoder_output): # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256)<br>        <br>        &#39;&#39;&#39;<br>        Attention mechanism takes two inputs current step -- decoder_hidden_state and all the encoder_outputs.<br>        * Based on the scoring function we will find the score or similarity between decoder_hidden_state <br>          and encoder_output.<br>          Multiply the score function with your encoder_outputs to get the context vector.<br>          Function returns context vector and attention_weights(softmax - scores)<br>        &#39;&#39;&#39;<br>        <br>        if self.scoring_function == &#39;dot&#39;: # Implement Dot score function here<br>            # similarity score b/w decoder_last_hidden_memory_state and <br>            # encoder_output (enc_h_state_at_all_time_steps)<br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256), <br>            # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512) ===&gt;<br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20)<br>            # t reps encoder time steps<br>            # &#39;bte,bd-&gt;bt&#39; is same as &#39;bte,be-&gt;bt&#39; because e = d in dot scoring method<br>            # ie  NUM_OF_DEC_LSTM_UNITS === DECODER_OUT_SEQ_LEN<br>            attention_weights = tf.einsum(&#39;bte,be-&gt;bt&#39;, <br>                                          encoder_output, <br>                                          decoder_hidden_state)<br>            <br>            # scaling the weight/importance value of each hidden_memory_state in the encoder_output OR<br>            # each word in the encoder input in predicting the next word in the decoder part<br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20) ===&gt; (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20)<br>            normalized_attention_weights = tf.nn.softmax(attention_weights)<br>            normalized_attention_weights = tf.expand_dims(normalized_attention_weights, -1)<br>            <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256),<br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20) ===&gt;<br>            # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256)<br>            context_vec = tf.einsum(&#39;bte,bti-&gt;be&#39;, <br>                                    encoder_output, <br>                                    normalized_attention_weights)<br>            <br>            # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (1024, 20, 1)<br>            return context_vec, normalized_attention_weights<br>        <br>        elif self.scoring_function == &#39;general&#39;: # Implement General score function here<br>            <br>            # (1024, 20, 256) * (256, 512) * (1024, 512)<br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256),<br>            # (NUM_OF_ENC_LSTM_UNITS, NUM_OF_DEC_LSTM_UNITS) : (256, 512) ===&gt; <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_DEC_LSTM_UNITS) : (1024, 20, 512)<br>            intermidiate = tf.einsum(&#39;bte,ed-&gt;btd&#39;, <br>                                     encoder_output, <br>                                     self.W)<br>            # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512) ===&gt; <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20)<br>            attention_weights = tf.einsum(&#39;btd,bd-&gt;bt&#39;, <br>                                          intermidiate, <br>                                          decoder_hidden_state)<br>            attention_weights = tf.nn.softmax(attention_weights)<br>            <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20) ===&gt; <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (1024, 20, 1)<br>            attention_weights = tf.expand_dims(attention_weights, -1)<br>            <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256),<br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (1024, 20, 1) ===&gt; <br>            # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS, 1) : (1024, 256, 1)<br>            context_vec = tf.einsum(&#39;bte,bti-&gt;be&#39;, <br>                                    encoder_output, <br>                                    attention_weights)<br>            <br>            # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (1024, 20, 1)<br>            return context_vec, attention_weights<br>        <br>        elif self.scoring_function == &#39;concat&#39;: # Implement concat score function here<br>            <br>            # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512), <br>            # (NUM_OF_DEC_LSTM_UNITS, 100) : (512, 100) ===&gt;<br>            # (BATCH_SIZE, 100) : (1024, 100)<br>            intermediate_dec = tf.matmul(decoder_hidden_state, self.W_dec)<br>            <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256),<br>            # (NUM_OF_ENC_LSTM_UNITS, 100) : (256, 100) ===&gt; <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 100) : (1024, 20, 100)<br>            intermediate_enc = tf.einsum(&#39;bte,ek-&gt;btk&#39;, <br>                                         encoder_output, <br>                                         self.W_enc)<br>            <br>            # (BATCH_SIZE, 100) : (1024, 100)  ===&gt; <br>            # (BATCH_SIZE, 1, 100) : (1024, 1, 100), <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 100) : (1024, 20, 100) ===&gt;  <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 100) : (1024, 20, 100)<br>            intermideate = tf.expand_dims(intermediate_dec, 1) + intermediate_enc <br>            intermideate = tf.nn.tanh(intermideate) <br>            <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 100) : (1024, 20, 100)<br>            # (100, ) : (100, ) ===&gt; <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20) ===&gt; <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20) ===&gt; <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20, 1)<br>            attention_weights = tf.einsum(&#39;btk,k-&gt;bt&#39;, <br>                                          intermideate, <br>                                          self.v)<br>            attention_weights = tf.nn.softmax(attention_weights) <br>            attention_weights = tf.expand_dims(attention_weights, -1)<br>            <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256),<br>            # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20, 1) ===&gt; <br>            # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256)<br>            context_vec = tf.einsum(&#39;bte,bti-&gt;be&#39;, <br>                                    encoder_output, <br>                                    attention_weights)<br>            <br>            # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (1024, 20, 1)<br>            return context_vec, attention_weights</pre><h3>OneStepDecoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QebRTWSmv8gJPtn4amnGJQ.jpeg" /></figure><p>The Decoder takes in the input sequence of English words and uses the hidden state and cell state from the Encoder to generate the output sequence of English words. In this implementation, we will be using a Unidirectional LSTM as the Decoder. At each time step, the Decoder takes in the previous output word and the context vector from the Attention mechanism to generate the next output word.</p><pre>class OneStepDecoder(tf.keras.Model):<br>    <br>    def __init__(self,<br>                 decoder_vocab_size, # TARGET_VOCAB_SIZE : 5000<br>                 decoder_embedding_dim, # DECODER_EMBEDD_DIM : 50<br>                 decoder_output_seq_len, # TARGET_VOCAB_SIZE : 5000<br>                 num_of_dec_lstm_units, # NUM_OF_DEC_LSTM_UNITS : 512<br>                 simi_score_fuc,<br>                 num_of_enc_lstm_units, # att_units NUM_OF_ENC_LSTM_UNITS : 256<br>                 grader=True,<br>                 **kwargs):<br>        <br>        # Initialize decoder embedding layer, LSTM and any other objects needed<br>        super().__init__(**kwargs)<br>        <br>        self.embedding = Embedding(input_dim=decoder_vocab_size,<br>                                   output_dim=decoder_embedding_dim,<br>                                   input_length=decoder_output_seq_len,<br>                                   # mask_zero=True,<br>                                   name=&#39;decoder_embedding_layer&#39;,<br>                                   weights=[EMBEDDING_MATRIX], <br>                                   trainable=False)<br>        <br>        if decoder_embedding_dim &lt; 100:<br>            self.embedding = Embedding(input_dim=decoder_vocab_size,<br>                                       output_dim=decoder_embedding_dim,<br>                                       input_length=decoder_output_seq_len,<br>                                       name=&#39;decoder_embedding_layer&#39;)<br>        <br>        self.lstm = RNN(tf.keras.layers.LSTMCell(num_of_dec_lstm_units),<br>                        return_sequences=True,<br>                        return_state=True,<br>                        name=&#39;decoder_lstm_layer&#39;)<br>        <br>        &quot;&quot;&quot;<br>        self.lstm = LSTM(units=num_of_dec_lstm_units, <br>                         return_sequences=True,<br>                         return_state=True,<br>                         name=&#39;decoder_lstm_layer&#39;)<br>        &quot;&quot;&quot;<br>        <br>        self.attention_layer = Attention(simi_score_fuc, <br>                                         num_of_enc_lstm_units)<br>        <br>        self.drop_out = tf.keras.layers.Dropout(.5)<br>        <br>        self.dense = Dense(decoder_vocab_size,<br>#                            activation=&#39;softmax&#39;,<br>                           name=&#39;decoder_output_layer&#39;)<br><br>    def call(self,<br>             input_to_decoder, # (BATCH_SIZE, 1) : (1024, 1)<br>             encoder_output, # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256),<br>             dec_lstm_memory_state_h, # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512),<br>             dec_lstm_cell_state_c, # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512),<br>             drop_out_status=True): <br>        <br>        &#39;&#39;&#39;<br>        One step decoder mechanisim step by step:<br>        A. Pass the input_to_decoder to the embedding layer and then get the output <br>            (batch_size, 1, embedding_dim)<br>        B. Using the encoder_output and decoder hidden state, compute the context vector.<br>        C. Concat the context vector with the step A output<br>        D. Pass the Step-C output to LSTM/GRU and get the decoder output and states(hidden and cell state)<br>        E. Pass the decoder output to dense layer(vocab size) and store the result into output.<br>        F. Return the states from step D, output from Step E, attention weights from Step -B<br>        &#39;&#39;&#39;<br>        <br>        # (BATCH_SIZE, 1) : (1024, 1) ===&gt;  (BATCH_SIZE, 1, DECODER_EMBEDD_DIM) : (1024, 1, 50)<br>        embedded_target = self.embedding(input_to_decoder)<br>        <br>        # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512), <br>        # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256) ===&gt; <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>        # (BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (1024, 20, 1)<br>        context_vector, \<br>        attention_weights = self.attention_layer(dec_lstm_memory_state_h,<br>                                                 encoder_output)<br>        <br>        # (BATCH_SIZE, 1, DECODER_EMBEDD_DIM) : (1024, 1, 50) ===&gt; <br>        # (BATCH_SIZE, DECODER_EMBEDD_DIM) : (1024, 50)<br>        embedded_target = tf.squeeze(embedded_target)<br>        <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>        # (BATCH_SIZE, DECODER_EMBEDD_DIM) : (1024, 50) ===&gt; <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS+DECODER_EMBEDD_DIM) : (1024, 306)<br>        concated_dec_inp = tf.concat([context_vector, embedded_target], -1)<br>        <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS+DECODER_EMBEDD_DIM) : (1024, 306) ===&gt; <br>        # (BATCH_SIZE, 1, NUM_OF_ENC_LSTM_UNITS+DECODER_EMBEDD_DIM) : (1024, 1, 306)<br>        concated_dec_inp = tf.expand_dims(concated_dec_inp, 1)<br>        <br>        # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512),<br>        # (BATCH_SIZE, 1, NUM_OF_ENC_LSTM_UNITS+DECODER_EMBEDD_DIM) : (1024, 1, 306),<br>        # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512), <br>        # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512) ===&gt; <br>        # (BATCH_SIZE, 1, NUM_OF_DEC_LSTM_UNITS) : (1024, 1, 512), <br>        # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512), <br>        # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512)<br>        dec_lstm_output, \<br>        dec_lstm_memory_state_h, \<br>        dec_lstm_cell_state_c = self.lstm(concated_dec_inp, <br>                                          initial_state=[dec_lstm_memory_state_h, dec_lstm_cell_state_c])<br>        <br>        # (BATCH_SIZE, 1, NUM_OF_DEC_LSTM_UNITS) : (1024, 1, 512) ===&gt; <br>        # (BATCH_SIZE, 1, TARGET_VOCAB_SIZE) : (1024, 1, 5000)<br>        dec_lstm_output = self.drop_out(dec_lstm_output, <br>                                        training=drop_out_status)<br>        output = self.dense(dec_lstm_output)<br>        <br>        # (BATCH_SIZE, 1, TARGET_VOCAB_SIZE) : (1024, 1, 5000) ===&gt; <br>        # (BATCH_SIZE, TARGET_VOCAB_SIZE) : (1024, 5000)<br>        output = tf.squeeze(output)<br>        <br>        # ===&gt; (BATCH_SIZE, TARGET_VOCAB_SIZE) : (1024, 5000), <br>        # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512), <br>        # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512), <br>        # (BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (1024, 20, 1), <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>        return output, dec_lstm_memory_state_h, dec_lstm_cell_state_c, attention_weights, context_vector</pre><h3>Decoder</h3><pre>class Decoder(tf.keras.Model):<br>    <br>    def __init__(self,<br>                 decoder_vocab_size, # TARGET_VOCAB_SIZE : 5000<br>                 decoder_embedding_dim, # DECODER_EMBEDD_DIM : 50<br>                 decoder_output_seq_len, # TARGET_VOCAB_SIZE : 5000<br>                 num_of_dec_lstm_units, # NUM_OF_DEC_LSTM_UNITS : 512<br>                 simi_score_fuc,<br>                 num_of_enc_lstm_units): # att_units NUM_OF_ENC_LSTM_UNITS : 256<br>        <br>        # Intialize necessary variables and create an object from the class onestepdecoder<br>        <br>        super().__init__()<br>        self.onestepdecoder = OneStepDecoder(decoder_vocab_size, <br>                                             decoder_embedding_dim, <br>                                             decoder_output_seq_len, <br>                                             num_of_dec_lstm_units,<br>                                             simi_score_fuc,<br>                                             num_of_enc_lstm_units)<br><br>    def call(self, <br>             input_to_decoder, # (BATCH_SIZE, DECODER_OUT_SEQ_LEN) : (1024, 20)<br>             encoder_output, # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256),<br>             dec_lstm_memory_state_h, # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512)<br>             dec_lstm_cell_state_c): # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512)<br><br>        if len(input_to_decoder.shape) == 1: input_to_decoder = tf.expand_dims(input_to_decoder, 0)<br>        <br>        # Initialize an empty Tensor array, that will store the outputs at each and every time step<br>        # Create a tensor array as shown in the reference notebook<br>        all_outputs = tf.TensorArray(tf.float32, <br>                                     size=DECODER_OUT_SEQ_LEN,# tf.shape(input_to_decoder)[1], <br>                                     name=&#39;output_arrays&#39;)<br>        <br>        # Iterate till the length of the decoder input<br>        for time_step in range(DECODER_OUT_SEQ_LEN):<br>            # Call onestepdecoder for each token in input_to_decoder<br>            # (BATCH_SIZE, 1) : (1024, 1), <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256), <br>            # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512)<br>            # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512) ===&gt; <br>            # (BATCH_SIZE, TARGET_VOCAB_SIZE) : (1024, 5000), <br>            # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512), <br>            # (BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (1024, 512), <br>            # (BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (1024, 20, 1), <br>            # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>            output, \<br>            dec_lstm_memory_state_h, \<br>            dec_lstm_cell_state_c, \<br>            attention_weights, \<br>            context_vector = self.onestepdecoder(input_to_decoder[:, time_step], <br>                                                 encoder_output, <br>                                                 dec_lstm_memory_state_h,<br>                                                 dec_lstm_cell_state_c)<br>            <br>            # Store the output in tensorarray<br>            all_outputs = all_outputs.write(time_step, output)<br>        <br>        # ===&gt; (BATCH_SIZE, DECODER_OUT_SEQ_LEN, TARGET_VOCAB_SIZE) : (1024, 20, 5000)<br>        all_outputs = tf.transpose(all_outputs.stack(), [1, 0, 2])<br>        <br>        # Return the tensor array<br>        # ===&gt; (BATCH_SIZE, DECODER_OUT_SEQ_LEN, TARGET_VOCAB_SIZE) : (1024, 20, 5000)<br>        return all_outputs</pre><h3>Encoder-Decoder model</h3><pre>class EncoderDecoderModel(tf.keras.Model):<br>    <br>    def __init__(self,<br>                 encoder_input_seq_len, # ENCODER_SEQ_LEN : 20<br>                 encoder_vocab_size, # INPUT_VOCAB_SIZE : 5000<br>                 encoder_embedding_dim, # ENCODER_EMBEDD_DIM :50<br>                 num_of_enc_lstm_units, # NUM_OF_ENC_LSTM_UNITS :256<br>                 decoder_vocab_size, # TARGET_VOCAB_SIZE : 5000<br>                 decoder_embedding_dim, # DECODER_EMBEDD_DIM : 50<br>                 decoder_output_seq_len, # DECODER_OUT_SEQ_LEN : 20<br>                 num_of_dec_lstm_units,  # NUM_OF_DEC_LSTM_UNITS : 512<br>                 score_fun,<br>                 **kwargs):<br>        <br>        # Intialize objects from encoder decoder<br>        super().__init__(**kwargs)<br>        <br>        self.encoder = Encoder(encoder_vocab_size=encoder_vocab_size+1, <br>                               encoder_embedding_dim=encoder_embedding_dim, <br>                               encoder_input_seq_len=encoder_input_seq_len, <br>                               num_of_enc_lstm_units=num_of_enc_lstm_units,<br>                               name=&#39;naive_encoder&#39;)<br><br>        self.decoder = Decoder(decoder_vocab_size=decoder_vocab_size+1,<br>                               decoder_embedding_dim=decoder_embedding_dim, <br>                               decoder_output_seq_len=decoder_output_seq_len,  <br>                               num_of_dec_lstm_units=num_of_dec_lstm_units,  <br>                               simi_score_fuc=score_fun,<br>                               num_of_enc_lstm_units=num_of_dec_lstm_units)<br>        <br>    def call(self, <br>             data):<br>        <br>        # parse the encoder and decider input data<br>        # ===&gt; (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20), <br>        # (BATCH_SIZE, DECODER_OUT_SEQ_LEN) : (1024, 20)<br>        encoder_input, \<br>        decoder_input = data[0], data[1] # print(encoder_input.shape, decoder_input.shape)<br>        <br>        # Intialize encoder states, <br>        # BATCH_SIZE : 1024 ===&gt; <br>        # [(BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS),(BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS)] : [(1024, 256),(1024, 256)]<br>        encoder_initial_states = self.encoder.initialize_states(BATCH_SIZE)<br>        <br>        # Pass the encoder_sequence to the embedding layer<br>        # (BATCH_SIZE, ENCODER_SEQ_LEN) : (1024, 20), <br>        # [(BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS),(BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS)] : [(1024, 256),(1024, 256)]<br>        # ===&gt; (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256), <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256)<br>        encoder_lstm_output, \<br>        encoder_lstm_memory_state_h, \<br>        encoder_lstm_cell_state_c = self.encoder(enc_input_seq=encoder_input,<br>                                            lst_of_enc_lstm_mem_and_cell_initial_states=encoder_initial_states)<br><br>        # Decoder initial states are encoder final states, Initialize it accordingly<br>        # Pass the decoder sequence, encoder_output, decoder states to Decoder<br>        # (BATCH_SIZE, DECODER_OUT_SEQ_LEN) : (1024, 20)<br>        # (BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (1024, 20, 256), <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256), <br>        # (BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (1024, 256) ===&gt; <br>        # (BATCH_SIZE, DECODER_OUT_SEQ_LEN, TARGET_VOCAB_SIZE) : (1024, 20, 5000)<br>        decoder_dense_layer_output = self.decoder(decoder_input, <br>                                                  encoder_lstm_output,<br>                                                  encoder_lstm_memory_state_h, <br>                                                  encoder_lstm_cell_state_c)<br>        <br>        # return the decoder output<br>        # ===&gt; (BATCH_SIZE, DECODER_OUT_SEQ_LEN, TARGET_VOCAB_SIZE) : (1024, 20, 5000)<br>        return decoder_dense_layer_output</pre><h3>Custom loss function</h3><pre># https://www.tensorflow.org/tutorials/text/image_captioning#model<br>loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, <br>                                                            reduction=&#39;none&#39;)<br><br>def loss_function(real, pred):<br>    &quot;&quot;&quot; <br>    Custom loss function that will not consider the loss for padded zeros.<br>    why are we using this, can&#39;t we use simple sparse categorical crossentropy?<br>    <br>    Yes, you can use simple sparse categorical crossentropy as loss like we did in task-1. But in this loss <br>    function we are ignoring the loss for the padded zeros. <br>    <br>    i.e when the input is zero then we donot need to worry what the output is. This padded zeros are added <br>    from our end during preprocessing to make equal length for all the sentences.<br>    &quot;&quot;&quot;<br>    mask = tf.math.logical_not(tf.math.equal(real, 0))<br>    loss_ = loss_object(real, <br>                        pred)<br><br>    mask = tf.cast(mask, <br>                   dtype=loss_.dtype)<br>    loss_ *= mask<br><br>    return tf.reduce_mean(loss_)</pre><h3>Training the Model</h3><pre># Create an object of encoder_decoder Model class, <br>model = EncoderDecoderModel(encoder_input_seq_len=ENCODER_SEQ_LEN,<br>                            encoder_vocab_size=INPUT_VOCAB_SIZE,<br>                            encoder_embedding_dim=ENCODER_EMBEDD_DIM,<br>                            num_of_enc_lstm_units=NUM_OF_ENC_LSTM_UNITS,<br>                            decoder_vocab_size=TARGET_VOCAB_SIZE,<br>                            decoder_embedding_dim=DECODER_EMBEDD_DIM,<br>                            decoder_output_seq_len=DECODER_OUT_SEQ_LEN,<br>                            num_of_dec_lstm_units=NUM_OF_DEC_LSTM_UNITS, <br>                            score_fun=&#39;concat&#39;)<br><br># Compile the model and fit the model<br>model.compile(optimizer=tf.keras.optimizers.Adam(),<br>              loss=loss_function)<br><br>model.fit(train_dataloader, <br>          steps_per_epoch=len(train_dataloader), <br>          epochs=100, <br>          validation_data=test_dataloader, <br>          validation_steps=len(test_dataloader), <br>          verbose=1, <br>          callbacks=return_all_call_backs())</pre><h3>Inference</h3><pre>class production_pipeline():<br>    <br>    &quot;&quot;&quot;<br>    A pipeline to return Italian transformed representation of each sentenses.<br>    : data =&gt; List of English sentenses<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, <br>                model,<br>                tknizer_ita,<br>                tknizer_eng):<br>        <br>        &quot;&quot;&quot;<br>        Used to initialize the <br>        1. trained Language translation model, <br>        2. enceoder and decoder Language tokenizers and <br>        3. decoder predicted word index to word converter<br>        &quot;&quot;&quot;<br>        <br>        self.model = model<br>        self.tknizer_ita = tknizer_ita<br>        self.tknizer_eng = tknizer_eng<br>        self.dec_index_to_word = dict([(v, k) for k, v in tknizer_eng.word_index.items()])<br>        self.end_ind_num = tknizer_eng.word_index.get(&#39;&lt;end&gt;&#39;)<br>        <br>    def encode_the_raw_text_input(self, enc_input_data):<br>        <br>        &quot;&quot;&quot;<br>        used to convert the raw input encoder Language text to padded sequense.<br>        INPUT:<br>        :: input_data : list of raw italian text data to be transformed into english language.<br>        RETURN:<br>        :: padded sequense of word indexes. ===&gt; (self.BATCH_SIZE, MAX_ENC_SEQ_LEN)<br>        &quot;&quot;&quot;<br>        <br>        self.enc_input_data = enc_input_data<br>        self.BATCH_SIZE = len(enc_input_data)<br>        <br>        # list of raw text of size BATCH_SIZE ===&gt; list of indexed text of size self.BATCH_SIZE<br>        tkn_enc_input_data = self.tknizer_ita.texts_to_sequences(enc_input_data)<br>        <br>        # list of indexed text of size self.BATCH_SIZE ===&gt; <br>        # (self.BATCH_SIZE, MAX_ENC_SEQ_LEN) with zero post padding &amp; truncation<br>        return pad_sequences(tkn_enc_input_data, <br>                             maxlen=MAX_ENC_SEQ_LEN, <br>                             dtype=&#39;int32&#39;, <br>                             padding=&#39;post&#39;,<br>                             truncating=&#39;post&#39;)<br>    <br>    def pass_through_the_encoder(self, encoded_input_data):<br>        <br>        # Intialize encoder states, <br>        # self.BATCH_SIZE : None ===&gt; <br>        # [(self.BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS), <br>        #  (self.BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS)] : [(None, 256), (None, 256)]<br>        lst_of_enc_lstm_mem_and_cell_initial_states = self.model.layers[0].initialize_states(self.BATCH_SIZE)<br>        <br>        # (self.BATCH_SIZE, ENCODER_SEQ_LEN) : (None, 20) ===&gt; <br>        # (self.BATCH_SIZE, ENCODER_SEQ_LEN, ENCODER_EMBEDD_DIM) : (None, 20, 50)<br>        #embedded_enc_input_data = self.embedding(encoded_input_data)<br>        embedded_enc_input_data = self.model.layers[0].embedding(encoded_input_data)<br>        <br>        # (self.BATCH_SIZE, ENCODER_SEQ_LEN, ENCODER_EMBEDD_DIM) : (None, 20, 50) ===&gt; <br>        # (self.BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (None, 20, 256), <br>        # (self.BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (None, 256), <br>        # (self.BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (None, 256)<br>        self.encoder_lstm_output, \<br>        self.encoder_lstm_memory_state_h, \<br>        self.encoder_lstm_cell_state_c = self.model.layers[0].lstm(<br>            embedded_enc_input_data,<br>            initial_state=lst_of_enc_lstm_mem_and_cell_initial_states)<br>        <br>    def pass_through_the_decoder(self, ):<br>        <br>        # initializing a matrix to store decoder predicted word indexes.<br>        self.pred_word_indexes = np.zeros((self.BATCH_SIZE, DECODER_OUT_SEQ_LEN), dtype=int)<br>        <br>        # initialize input to the decoder<br>        input_to_decoder = [self.tknizer_eng.word_index.get(&#39;&lt;start&gt;&#39;)]*self.BATCH_SIZE      <br>        input_to_decoder = np.array(input_to_decoder).reshape((self.BATCH_SIZE, 1))<br>        <br>        # initialize the states of the decoder lstms<br>        # (self.BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (None, 256), <br>        # (self.BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (None, 256)<br>        self.dec_lstm_memory_state_h = self.encoder_lstm_memory_state_h<br>        self.dec_lstm_cell_state_c = self.encoder_lstm_cell_state_c<br>        <br>        # initializing attention weights<br>        self.atten_weights = []<br>        <br>        # Iterate till the length of the decoder input<br>        for time_step in range(DECODER_OUT_SEQ_LEN):<br>            # Call onestepdecoder for each token in input_to_decoder<br>            # (self.BATCH_SIZE, 1) : (1024, 1), <br>            # (self.BATCH_SIZE, ENCODER_SEQ_LEN, NUM_OF_ENC_LSTM_UNITS) : (None, 20, 256), <br>            # (self.BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (None, 512)<br>            # (self.BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (None, 512) ===&gt; <br>            # (self.BATCH_SIZE, TARGET_VOCAB_SIZE) : (None, 5000), <br>            # (self.BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (None, 512), <br>            # (self.BATCH_SIZE, NUM_OF_DEC_LSTM_UNITS) : (None, 512), <br>            # (self.BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (None, 20, 1), <br>            # (self.BATCH_SIZE, NUM_OF_ENC_LSTM_UNITS) : (None, 256), <br>            output, \<br>            self.dec_lstm_memory_state_h, \<br>            self.dec_lstm_cell_state_c, \<br>            attention_weights, \<br>            context_vector = self.model.layers[1].onestepdecoder(input_to_decoder, <br>                                                                 self.encoder_lstm_output, <br>                                                                 self.dec_lstm_memory_state_h,<br>                                                                 self.dec_lstm_cell_state_c, <br>                                                                 drop_out_status=False)<br>            <br>            # storing the attention weights <br>            # (self.BATCH_SIZE, ENCODER_SEQ_LEN, 1) : (None, 20, 1) ===&gt; <br>            # (self.BATCH_SIZE, ENCODER_SEQ_LEN, DECODER_OUT_SEQ_LEN) : (None, 20, 20)<br>            if len(self.atten_weights):<br>                self.atten_weights = tf.concat([self.atten_weights, attention_weights], -1)<br>            else:<br>                self.atten_weights = attention_weights<br>            <br>            # next time step input to the decoder<br>            # tf.reshape(tf.argmax(tf.random.uniform((100, 500)), axis=1), shape=(100,1))<br>            # (self.BATCH_SIZE, TARGET_VOCAB_SIZE) : (None, 5000), ===&gt; <br>            # (self.BATCH_SIZE, 1) : (None, 1)<br>            #print(f&quot;output {output.shape}&quot;)<br>            input_to_decoder = tf.argmax(output, axis=1)[:, None]<br>            <br>            # (self.BATCH_SIZE, DECODER_OUT_SEQ_LEN) : (None,20)[:,row_index] = (self.BATCH_SIZE,1) : (None,1)<br>            #print(f&quot;input_to_decoder {input_to_decoder.shape} self.pred_word_indexes[:, {time_step}]\<br>            #{self.pred_word_indexes[:, time_step].shape}&quot;)<br>            self.pred_word_indexes[:, time_step] = tf.squeeze(input_to_decoder)<br>            # input_to_decoder (5001, 1) self.pred_word_indexes[:, 0]            (3,)<br>        <br>    # https://www.tensorflow.org/text/tutorials/nmt_with_attention#translate<br>    def plot_attention_heat_map(self, ):<br>        # Extracting the first 3 attention weights, input language sentenses, predicted sentenses.<br>        # (self.BATCH_SIZE, ENCODER_SEQ_LEN, DECODER_OUT_SEQ_LEN) : (None, 20, 20) ===&gt; <br>        # (3, ENCODER_SEQ_LEN, DECODER_OUT_SEQ_LEN) : (3, 20, 20)<br>        weights = self.atten_weights[:3, :, :]<br>        pred_seq = self._return_predicted_decoder_seq()[:3]<br>        actual_seq = self.enc_input_data[:3]<br><br>        for index, (weight_vector, input_seq, output_seq) in enumerate(zip(weights, actual_seq, pred_seq)):<br><br>            sentence = input_seq.split()#tf_lower_and_split_punct(sentence).numpy().decode().split()<br>            predicted_sentence = output_seq+[&#39;&lt;end&gt;&#39;]#predicted_sentence.numpy().decode().split() + [&#39;[END]&#39;]<br>            <br>            fig = plt.figure(figsize=(10, 10))<br>            ax = fig.add_subplot(1, 1, 1)<br><br>            attention = np.array(weight_vector[:len(sentence), :len(predicted_sentence)])<br><br>            ax.matshow(attention, cmap=&#39;viridis&#39;, vmin=0.0)<br><br>            fontdict = {&#39;fontsize&#39;: 14}<br><br>            ax.set_yticklabels([&#39;&#39;] + sentence, fontdict=fontdict)<br>            ax.set_xticklabels([&#39;&#39;] + predicted_sentence, fontdict=fontdict, rotation=90)<br><br>            ax.xaxis.set_major_locator(ticker.MultipleLocator(1))<br>            ax.yaxis.set_major_locator(ticker.MultipleLocator(1))<br><br>            ax.set_ylabel(&#39;Input text&#39;)<br>            ax.set_xlabel(&#39;Output text&#39;)<br>            plt.suptitle(&#39;Attention weights&#39;)<br>            plt.show()<br><br>    def convert_index_to_words_L2(self, pred_seq_indexes):<br>        # a list of &lt;= DECODER_OUT_SEQ_LEN number of word indexes<br>        return [self.dec_index_to_word.get(word_index, &#39;&#39;) for word_index in pred_seq_indexes]<br><br>    def preprocess_predicted_decoder_seq(self, ):<br>            <br>        # For each decoder time step<br>        for row_index in range(self.BATCH_SIZE):<br><br>            # (self.BATCH_SIZE, DECODER_OUT_SEQ_LEN) : (None, 20) ===&gt; <br>            # list of size DECODER_OUT_SEQ_LEN : 20<br>            pred_seq_indexes = list(self.pred_word_indexes[row_index, :])<br><br>            # list of size DECODER_OUT_SEQ_LEN : 20 ===&gt; <br>            # list of size DECODER_OUT_SEQ_LEN : ind_of_end_word_in_pred_seq<br>            try: ind_of_end_word_in_pred_seq = pred_seq_indexes.index(self.end_ind_num)<br>            except: ind_of_end_word_in_pred_seq = DECODER_OUT_SEQ_LEN<br><br>            pred_seq_indexes = pred_seq_indexes[:ind_of_end_word_in_pred_seq]<br><br>            self.pred_word_indexes[row_index, :ind_of_end_word_in_pred_seq] = pred_seq_indexes<br>            self.pred_word_indexes[row_index, ind_of_end_word_in_pred_seq:] = 0<br>        <br>    def return_predicted_decoder_seq(self, ):<br>        for data_point_index, each_pred_sent in enumerate(self._return_predicted_decoder_seq()):<br>            for time_stamp, pred_word in enumerate(each_pred_sent):<br>                print(f&quot;At time stamp {time_stamp} the decoder predicted word is : {pred_word}&quot;)<br>            print(f&quot;\nEnd of the {data_point_index} input data point&#39;s, decoder output sequence\n\n&quot;)<br>        <br>    def _return_predicted_decoder_seq(self, ):<br>        <br>        pred_seq_words = []<br>        <br>        # For each decoder time step<br>        for row_index in range(self.BATCH_SIZE):<br>            <br>            # (self.BATCH_SIZE, DECODER_OUT_SEQ_LEN) : (None, 20) ===&gt; <br>            # list of size DECODER_OUT_SEQ_LEN : 20<br>            pred_seq_indexes = list(self.pred_word_indexes[row_index, :])<br>            <br>            temp = &quot; &quot;.join(self.convert_index_to_words_L2(pred_seq_indexes)).strip().split()<br>            pred_seq_words.append(temp)<br>        <br>        return pred_seq_words<br>        <br>    def return_calculated_blue_score(self, ):<br>            <br>        # ===&gt; list of list of size self.BATCH_SIZE<br>        predictions = self._return_predicted_decoder_seq()<br><br>        # ===&gt; list of list of size self.BATCH_SIZE<br>        actual_data = self.dec_output_data<br><br>        # Transforming from the list of sequenses to list of lists with words<br>        reference = [[each_sen.split()] for each_sen in actual_data] # the original<br>        translation = predictions # trasilated using model<br><br>        final_blue_score = bleu.corpus_bleu(reference, translation)<br>        print(f&#39;BLEU score on the given input query dataset is : {final_blue_score}&#39;)<br><br>        return final_blue_score<br>    <br>    def __call__(self, <br>                 enc_input_data, <br>                 dec_output_data=None):<br>        <br>        self.dec_output_data = dec_output_data<br>        encoded_input_data = self.encode_the_raw_text_input(enc_input_data)<br>        self.pass_through_the_encoder(encoded_input_data)<br>        self.pass_through_the_decoder()<br>        self.preprocess_predicted_decoder_seq()</pre><pre>inference = production_pipeline(model, <br>                                tknizer_ita, <br>                                tknizer_eng)<br><br>infere_data = validation.sample(10000)<br>val_in, val_out = list(infere_data.italian), list(infere_data.english_out)<br><br>inference(val_in, val_out)<br><br>inference.return_calculated_blue_score()</pre><pre>BLEU score on the given input query dataset is : 0.5527537228912403<br>0.5527537228912403</pre><pre>inference.plot_attention_heat_map()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*teFUNKyLJnU-DpXKhc2_sg.png" /></figure><pre>It was really good at predicting the short sentenses like below.<br> At time stamp 0 the decoder predicted word is : i<br> At time stamp 1 the decoder predicted word is : will<br> At time stamp 2 the decoder predicted word is : accept<br> At time stamp 3 the decoder predicted word is : the<br> At time stamp 4 the decoder predicted word is : suggestions<br><br>It was also good with long sentenses like below<br> At time stamp 0 the decoder predicted word is : you<br> At time stamp 1 the decoder predicted word is : are<br> At time stamp 2 the decoder predicted word is : a<br> At time stamp 3 the decoder predicted word is : little<br> At time stamp 4 the decoder predicted word is : early<br> At time stamp 5 the decoder predicted word is : are<br> At time stamp 6 the decoder predicted word is : not<br> At time stamp 7 the decoder predicted word is : you<br><br>But it was bad with some long sentenses like<br> At time stamp 0 the decoder predicted word is : sometimes<br> At time stamp 1 the decoder predicted word is : we<br> At time stamp 2 the decoder predicted word is : need<br> At time stamp 3 the decoder predicted word is : to<br> At time stamp 4 the decoder predicted word is : be<br> At time stamp 5 the decoder predicted word is : leaving<br> At time stamp 6 the decoder predicted word is : to<br> At time stamp 7 the decoder predicted word is : know<br> At time stamp 8 the decoder predicted word is : to<br> At time stamp 9 the decoder predicted word is : know<br> At time stamp 10 the decoder predicted word is : we<br> At time stamp 11 the decoder predicted word is : are<br> At time stamp 12 the decoder predicted word is : going<br><br>Still by training even more we can improve the performance of this model.</pre><h3>Conclusion</h3><p>In this blog post, we learned how to implement a Sequence to Sequence machine translation model using an encoder-decoder architecture with an attention mechanism in TensorFlow using Python. We used Italian-English translation as an example and trained our model using a dataset of sentence pairs.</p><p>We first preprocessed the data.</p><p>Next, we created our encoder and decoder models using TensorFlow’s Keras API. The encoder takes in a sequence of Italian words, embeds each word into a vector, and passes the sequence through an LSTM to obtain the final encoder state. The decoder takes in an English sequence and generates one word at a time using a unidirectional LSTM. Attention weights are computed for each decoder step, allowing the model to focus on different parts of the input sequence as it generates the output.</p><p>We trained the model using a combination of teacher forcing to prevent overfitting and improve training stability. We also monitored the loss on a validation set to prevent overfitting.</p><p>Finally, we evaluated the model by translating some sample Italian sentences into English and visualized the attention weights using matplotlib.</p><p>Overall, we have demonstrated how to implement a sequence-to-sequence machine translation model with an attention mechanism in TensorFlow using Python. This approach can be applied to any language pair for which a suitable dataset is available, allowing us to automatically translate text between languages with high accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1db2e100db18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing the CANet Architecture from Scratch in TensorFlow and Python OOPs]]></title>
            <link>https://medium.com/@rebirth4vali/implementing-the-canet-architecture-from-scratch-in-tensorflow-and-python-oops-ed31c1c7e309?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed31c1c7e309</guid>
            <category><![CDATA[autonomous-driving]]></category>
            <category><![CDATA[canet]]></category>
            <category><![CDATA[semantic-segmentation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 09:55:09 GMT</pubDate>
            <atom:updated>2023-03-28T09:55:09.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFJsz3CGhZjYHksdiLP34A.jpeg" /></figure><p>Image segmentation is a fundamental task in computer vision that involves partitioning an image into multiple segments, where each segment corresponds to a distinct object or region of interest. The CANet (Contextual Attention Network) is a state-of-the-art architecture for image segmentation that uses an attention mechanism to selectively focus on relevant regions of an image for segmentation. In this blog post, we’ll walk through the implementation of the CANet architecture from scratch in TensorFlow and Python OOP.</p><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*dSBgHlt-YuGdoP9-kJ9AWg.png" /></figure><p>The Context-Aware Network (CANet) is a state-of-the-art deep learning architecture for image segmentation. In this blog post, we will walk through the implementation of the CANet architecture from scratch using TensorFlow and Python OOP. We will define each component of the CANet model as a separate class, and then use these classes to construct the complete CANet model. By the end of this post, you will have a solid understanding of the CANet architecture and be able to train it on your own datasets.</p><h3>Step 1: Define the Convolutional Block</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*grzaVeD2vuLLuqPxfyxt2Q.png" /></figure><p>The first component of the CANet architecture is the convolutional block. This is a standard building block for deep learning architectures, and it consists of a series of convolutional layers followed by batch normalization and activation functions. Here is the code for the ConvolutionalBlock class:</p><pre>import tensorflow as tf<br><br>class ConvolutionalBlock(tf.keras.layers.Layer):<br>    def __init__(self, filters, kernel_size, strides):<br>        super(ConvolutionalBlock, self).__init__()<br>        self.conv1 = tf.keras.layers.Conv2D(filters, kernel_size, strides=strides, padding=&#39;same&#39;)<br>        self.bn1 = tf.keras.layers.BatchNormalization()<br>        self.relu1 = tf.keras.layers.ReLU()<br>        self.conv2 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn2 = tf.keras.layers.BatchNormalization()<br>        self.relu2 = tf.keras.layers.ReLU()<br><br>    def call(self, inputs):<br>        x = self.conv1(inputs)<br>        x = self.bn1(x)<br>        x = self.relu1(x)<br>        x = self.conv2(x)<br>        x = self.bn2(x)<br>        x = self.relu2(x)<br>        return x</pre><p>In this class, we define a convolutional block with two convolutional layers, each followed by batch normalization and ReLU activation functions. We also specify the number of filters, kernel size, and strides as arguments to the constructor.</p><h3>Step 2: Define the Identity Block</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*ufRQDi0NjMA-fCRV_5AGHg.png" /></figure><p>The second component of the CANet architecture is the identity block. This is similar to the convolutional block, but it includes a skip connection to preserve information from the input. Here is the code for the IdentityBlock class:</p><pre>import tensorflow as tf<br><br>class IdentityBlock(tf.keras.layers.Layer):<br>    def __init__(self, filters, kernel_size):<br>        super(IdentityBlock, self).__init__()<br>        self.conv1 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn1 = tf.keras.layers.BatchNormalization()<br>        self.relu1 = tf.keras.layers.ReLU()<br>        self.conv2 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn2 = tf.keras.layers.BatchNormalization()<br>        self.relu2 = tf.keras.layers.ReLU()<br><br>    def call(self, inputs):<br>        x = self.conv1(inputs)<br>        x = self.bn1(x)<br>        x = self.relu1(x)<br>        x = self.conv2(x)<br>        x = self.bn2(x)<br>        x = tf.keras.layers.Add()([x, inputs])<br>        x = self.relu2(x)<br>        return x</pre><p>In this class, we define an identity block with two convolutional layers, each followed by batch normalization and ReLU activation functions, as well as a skip connection to add the input to the output. Again, we specify the number of filters and kernel size as arguments to the constructor.</p><h3>Step 3: Define the Global Flow Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*EmOuHRJOvkrAz3hr3RGb4g.png" /></figure><p>The third component of the CANet architecture is the Global Flow layer. This layer takes in the input image and produces a global feature map, which contains information about the entire image. Here is the code for the GlobalFlow class:</p><pre>import tensorflow as tf<br><br>class GlobalFlow(tf.keras.layers.Layer):<br>    def __init__(self, filters, kernel_size):<br>        super(GlobalFlow, self).__init__()<br>        self.conv1 = tf.keras.layers.Conv2D(filters, kernel_size, strides=2, padding=&#39;same&#39;)<br>        self.bn1 = tf.keras.layers.BatchNormalization()<br>        self.relu1 = tf.keras.layers.ReLU()<br>        self.conv2 = tf.keras.layers.Conv2D(filters, kernel_size, strides=2, padding=&#39;same&#39;)<br>        self.bn2 = tf.keras.layers.BatchNormalization()<br>        self.relu2 = tf.keras.layers.ReLU()<br>        self.conv3 = tf.keras.layers.Conv2D(filters, kernel_size, strides=2, padding=&#39;same&#39;)<br>        self.bn3 = tf.keras.layers.BatchNormalization()<br>        self.relu3 = tf.keras.layers.ReLU()<br><br>    def call(self, inputs):<br>        x = self.conv1(inputs)<br>        x = self.bn1(x)<br>        x = self.relu1(x)<br>        x = self.conv2(x)<br>        x = self.bn2(x)<br>        x = self.relu2(x)<br>        x = self.conv3(x)<br>        x = self.bn3(x)<br>        x = self.relu3(x)<br>        return x</pre><p>In this class, we define a Global Flow layer with three convolutional layers, each followed by batch normalization and ReLU activation functions. We also specify the number of filters and kernel size as arguments to the constructor. The strides of 2 in each convolutional layer downsamples the input by a factor of 8, which creates a global feature map that is much smaller than the original input image.</p><h3>Step 4: Define the Context Flow Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*4RO8XvmwfZejyJy2NtUANw.png" /></figure><p>The fourth component of the CANet architecture is the Context Flow layer. This layer takes in the global feature map from the Global Flow layer and produces a context-aware feature map, which contains information about the global context of the image. Here is the code for the ContextFlow class:</p><pre>import tensorflow as tf<br><br>class ContextFlow(tf.keras.layers.Layer):<br>    def __init__(self, filters, kernel_size):<br>        super(ContextFlow, self).__init__()<br>        self.conv1 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn1 = tf.keras.layers.BatchNormalization()<br>        self.relu1 = tf.keras.layers.ReLU()<br>        self.conv2 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn2 = tf.keras.layers.BatchNormalization()<br>        self.relu2 = tf.keras.layers.ReLU()<br>        self.conv3 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn3 = tf.keras.layers.BatchNormalization()<br>        self.relu3 = tf.keras.layers.ReLU()<br>        self.conv4 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn4 = tf.keras.layers.BatchNormalization()<br>        self.relu4 = tf.keras.layers.ReLU()<br><br>    def call(self, inputs):<br>        x = self.conv1(inputs)<br>        x = self.bn1(x)<br>        x = self.relu1(x)<br>        x = self.conv2(x)<br>        x = self.bn2(x)<br>        x = self.relu2(x)<br>        x = self.conv3(x)<br>        x = self.bn3(x)<br>        x = self.relu3(x)<br>        x = self.conv4(x)<br>        x = self.bn4(x)<br>        x = self.relu4(x)<br>        return x</pre><p>In this class, we define a Context Flow layer with four convolutional layers, each followed by batch normalization and ReLU activation functions. We also specify the number of filters and kernel size as arguments to the constructor. The stride of 1 in each convolutional layer maintains the same spatial resolution as the input.</p><h3>Step 5: Define the Fusion and Aggregation Layer</h3><p>The final component of the CANet architecture is the Fusion and Aggregation layer. This layer combines the context-aware feature map from the Context Flow layer and the feature maps from each of the Convolutional Blocks using an Attention-Gated Convolutional Network (AGCN). Here is the code for the FSM and AGCN classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*70FK4dS9Xlb0tnM5Q5o_Pw.png" /></figure><pre>import tensorflow as tf<br><br>class FSM(tf.keras.layers.Layer):<br>    def __init__(self, filters):<br>        super(FSM, self).__init__()<br>        self.conv1 = tf.keras.layers.Conv2D(filters, 1, strides=1, padding=&#39;same&#39;)<br>        self.bn1 = tf.keras.layers.BatchNormalization()<br>        self.sigmoid1 = tf.keras.layers.Activation(&#39;sigmoid&#39;)<br>        self.conv2 = tf.keras.layers.Conv2D(filters, 1, strides=1, padding=&#39;same&#39;)<br>        self.bn2 = tf.keras.layers.BatchNormalization()<br>        self.sigmoid2 = tf.keras.layers.Activation(&#39;sigmoid&#39;)<br><br>    def call(self, x1, x2):<br>        y1 = tf.concat([x1, x2], axis=3)<br>        y2 = tf.concat([x1, y1, x2*y1], axis=3)<br>        y = self.conv1(y2)<br>        y = self.bn1(y)<br>        y = self.sigmoid1(y)<br>        y = y*y1 + y1<br>        z = self.conv2(y2)<br>        z = self.bn2(z)<br>        z = self.sigmoid2(z)<br>        z = z*y + y<br>        return z</pre><p>In the FSM class, we define a Feature Selection Module (FSM) that takes in the output feature maps from a Convolutional Block and the context-aware feature map from the Context Flow layer. We concatenate these feature maps along the channel axis and use two convolutional layers with sigmoid activation functions to compute gating masks for each feature map. We then apply these masks to the input feature maps and add the resulting features to the original feature maps to obtain the final output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*I_Uy8t0U2suLLkrtDKrdRw.png" /></figure><pre>class AGCN(tf.keras.layers.Layer):<br>    def __init__(self, filters, kernel_size):<br>        super(AGCN, self).__init__()<br>        self.conv1 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn1 = tf.keras.layers.BatchNormalization()<br>        self.sigmoid1 = tf.keras.layers.Activation(&#39;sigmoid&#39;)<br>        self.conv2 = tf.keras.layers.Conv2D(filters, kernel_size, strides=1, padding=&#39;same&#39;)<br>        self.bn2 = tf.keras.layers.BatchNormalization()<br>        self.sigmoid2 = tf.keras.layers.Activation(&#39;sigmoid&#39;)<br><br>    def call(self, inputs):<br>        x1, x2 = inputs<br>        y = self.conv1(x1)<br>        y = self.bn1(y)<br>        y = self.sigmoid1(y)<br>        y = y*x2<br>        z = self.conv2(x2)<br>        z = self.bn2(z)<br>        z = self.sigmoid2(z)<br>        z = z*y + y<br>        return z</pre><p>In the AGCN class, we define an Attention-Gated Convolutional Network (AGCN) that takes in the output feature maps from a Convolutional Block and the context-aware feature map from the Context Flow layer. We first apply a convolutional layer to the input feature maps and use a sigmoid activation function to compute an attention map for the context-aware feature map. We then multiply the attention map with the input feature maps and add the resulting features to the original feature maps to obtain the final output.</p><h3>Step 6: Define the CANet Model</h3><p>Now that we have defined all the individual components of the CANet architecture, we can define the entire model by chaining together the Convolutional Block, Global Flow, Context Flow, and Fusion and Aggregation layers. Here is the code for the CANet class:</p><pre>class CANet(tf.keras.Model):<br>    def __init__(self, num_classes=1000):<br>        super(CANet, self).__init__()<br>        self.conv_block1 = ConvolutionalBlock(64, 3)<br>        self.conv_block2 = ConvolutionalBlock(128, 4, stride=2)<br>        self.conv_block3 = ConvolutionalBlock(256, 6, stride=2)<br>        self.conv_block4 = ConvolutionalBlock(512, 3, stride=1, dilation_rate=2)<br>        self.conv_block5 = ConvolutionalBlock(512, 3, stride=1, dilation_rate=4)<br>        self.conv_block6 = ConvolutionalBlock(512, 3, stride=1, dilation_rate=8)<br>        self.global_flow = GlobalFlow(512, 3)<br>        self.context_flow = ContextFlow(512, 3)<br>        self.fsm1 = FSM(256)<br>        self.fsm2 = FSM(128)<br>        self.agcn1 = AGCN(256, 3)<br>        self.agcn2 = AGCN(128, 3)<br>        self.conv = tf.keras.layers.Conv2D(num_classes, 1, padding=&#39;same&#39;)<br><br>    def call(self, inputs):<br>        x = self.conv_block1(inputs)<br>        x = self.conv_block2(x)<br>        x = self.conv_block3(x)<br>        x = self.conv_block4(x)<br>        x = self.conv_block5(x)<br>        x = self.conv_block6(x)<br>        x_global = self.global_flow(x)<br>        x_context = self.context_flow(x)<br>        y = self.fsm1(x, x_context)<br>        y = self.agcn1([y, x_global])<br>        z = self.fsm2(x, y)<br>        z = self.agcn2([z, x_global])<br>        output = self.conv(z)<br>        return output</pre><p>In the CANet class, we define a model that consists of six Convolutional Blocks, followed by the Global Flow, Context Flow, FSM, and AGCN layers. Finally, we apply a 1x1 convolutional layer to obtain the final output feature maps.</p><p>Visualize the representation of the architecture of the CANet model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiqsyW_EOaSntV7mzL3jTw.png" /></figure><h3>Step 7: Train and Evaluate the Model</h3><p>Now that we have defined the CANet model, we can train and evaluate it on a dataset of our choice. Here is some example code to train the CANet model on the CIFAR-10 dataset:</p><pre>import tensorflow as tf<br><br># Load the CIFAR-10 dataset<br>(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()<br><br># Preprocess the data<br>x_train = x_train / 255.0<br>x_test = x_test / 255.0<br>y_train = tf.keras.utils.to_categorical(y_train, 10)<br>y_test = tf.keras.utils.to_categorical(y_test, 10)<br><br># Create the CANet model<br>model = CANet(num_classes=10)<br><br># Compile the model<br>model.compile(<br>    optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),<br>    loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),<br>    metrics=[tf.keras.metrics.CategoricalAccuracy()]<br>)</pre><h3>Train the model</h3><pre>model.fit(<br>    x_train, <br>    y_train, <br>    batch_size=64, <br>    epochs=40, <br>    validation_data=(x_test, y_test)<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kDOaqRcZX3lQcvi0aR5JQ.png" /></figure><p>As you can see the model is not overfitting so you resume the training process and try 100 epochs with the EarlyStopping callback method.</p><h3>Evaluate the model</h3><pre>test_loss, test_accuracy = model.evaluate(<br>    x_test, <br>    y_test, <br>    verbose=2<br>)<br><br>print(&#39;Test loss:&#39;, test_loss)<br>print(&#39;Test accuracy:&#39;, test_accuracy)</pre><p>In the code above, we pass in the test data x_test and y_test to the evaluate method. We also set the verbose parameter to 2 so that the progress during evaluation is shown. The evaluate the method returns the test loss and test accuracy, which are then printed to the console.</p><p>After running the code, we should see the test loss and test accuracy printed to the console. The test accuracy is a measure of how well the model can classify the images in the test set, with a higher accuracy indicating better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iW_5wGB_ctJoM1MVOrGd7g.png" /></figure><p>You can still improve your segmentation performance just by training with more epochs. Happy coding.</p><h3>Conclusion</h3><p>In this blog post, we have implemented the CANet architecture for semantic segmentation using TensorFlow and Python. We started by discussing the architecture and its various components, including the Convolutional Block, Global Flow, Context Flow, FSM, and AGCN layers. We then showed how to implement the architecture using TensorFlow and Python, and how to train and evaluate the model using the CIFAR-10 dataset.</p><p>The CANet architecture is a powerful model for semantic segmentation that has achieved state-of-the-art results on various benchmark datasets. By understanding its architecture and implementation, you can apply it to your own semantic segmentation tasks and achieve similar results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed31c1c7e309" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing DenseNet-BC (L=100, k=12) in Tensorflow Python from Scratch]]></title>
            <link>https://medium.com/@rebirth4vali/implementing-densenet-bc-l-100-k-12-in-tensorflow-python-from-scratch-c8a5ffe942a2?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8a5ffe942a2</guid>
            <category><![CDATA[densenet]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 11:10:19 GMT</pubDate>
            <atom:updated>2023-03-27T11:10:19.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*c-TykhnrNieqwUQhmbug4g.png" /><figcaption>Figure 1: A 5-layer dense block (Source: Original DenseNet Paper)</figcaption></figure><p>DenseNet is a type of convolutional neural network (CNN) that has shown impressive results in image classification tasks. It was introduced by Huang et al. in their paper “Densely Connected Convolutional Networks” in 2017. DenseNet consists of dense blocks, which are made up of densely connected layers. Each layer receives the feature maps of all preceding layers as input, and its own feature maps are passed on to all subsequent layers. This connectivity pattern leads to the highly efficient use of parameters and better accuracy.</p><p>In this blog post, we will implement the DenseNet-BC (L=100, k=12) architecture using TensorFlow and Python. This architecture has 100 layers and a growth rate of 12. It also uses bottleneck layers to reduce the number of parameters and improve efficiency.</p><h3>Dataset</h3><p>We will use the CIFAR-10 dataset, which consists of 60,000 32x32 color images in 10 classes. There are 50,000 training images and 10,000 test images. The dataset is available in the TensorFlow Keras API, so we can load it directly.</p><pre>import tensorflow as tf<br><br>(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.cifar10.load_data()</pre><h3>Preprocessing</h3><p>We will preprocess the data by normalizing the pixel values and one-hot encoding the labels.</p><pre>train_images = train_images.astype(&#39;float32&#39;) / 255<br>test_images = test_images.astype(&#39;float32&#39;) / 255<br><br>train_labels = tf.keras.utils.to_categorical(train_labels)<br>test_labels = tf.keras.utils.to_categorical(test_labels)</pre><h3>Building the Model</h3><p>We will define the DenseNet-BC (L=100, k=12) architecture using TensorFlow and Python. This architecture consists of three dense blocks, each followed by a transition layer.</p><pre>class DenseLayer(tf.keras.layers.Layer):<br>    def __init__(self, growth_rate):<br>        super(DenseLayer, self).__init__()<br>        self.bn1 = tf.keras.layers.BatchNormalization()<br>        self.relu1 = tf.keras.layers.Activation(&#39;relu&#39;)<br>        self.conv1 = tf.keras.layers.Conv2D(filters=4 * growth_rate, kernel_size=(1, 1), padding=&#39;same&#39;, use_bias=False)<br>        self.bn2 = tf.keras.layers.BatchNormalization()<br>        self.relu2 = tf.keras.layers.Activation(&#39;relu&#39;)<br>        self.conv2 = tf.keras.layers.Conv2D(filters=growth_rate, kernel_size=(3, 3), padding=&#39;same&#39;, use_bias=False)<br>    <br>    def call(self, inputs):<br>        x = self.bn1(inputs)<br>        x = self.relu1(x)<br>        x = self.conv1(x)<br>        x = self.bn2(x)<br>        x = self.relu2(x)<br>        x = self.conv2(x)<br>        output = tf.keras.layers.concatenate([inputs, x], axis=-1)<br>        return output<br><br>class DenseBlock(tf.keras.layers.Layer):<br>    def __init__(self, num_layers, growth_rate):<br>        super(DenseBlock, self).__init__()<br>        self.layers = [DenseLayer(growth_rate) for _ in range(num_layers)]<br>        <br>    def call(self, inputs):<br>        x = inputs<br>        for layer in self.layers:<br>            x = layer(x)<br>        return x<br><br>class TransitionLayer(tf.keras.layers.Layer):<br>    def __init__(self, filters):<br>        super(TransitionLayer, self).__init__()<br>        self.bn = tf.keras.layers.BatchNormalization()<br>        self.relu = tf.keras.layers.Activation(&#39;relu&#39;)<br>        self.conv = tf.keras.layers.Conv2D(filters=filters, kernel_size=(1, 1), padding=&#39;same&#39;, use_bias=False)<br>        self.pool = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), strides=(2, 2), padding=&#39;same&#39;)<br>    <br>    def call(self, inputs):<br>        x = self.bn(inputs)<br>        x = self.relu(x)<br>        x = self.conv(x)<br>        output = self.pool(x)<br>        return output<br><br>class DenseNet(tf.keras.Model):<br>    def __init__(self, num_blocks=3, num_layers=16, growth_rate=12, num_classes=10):<br>        super(DenseNet, self).__init__()<br>        self.conv1 = tf.keras.layers.Conv2D(filters=2 * growth_rate, kernel_size=(3, 3), padding=&#39;same&#39;, use_bias=False)<br>        self.blocks = [DenseBlock(num_layers, growth_rate) for _ in range(num_blocks)]<br>        self.trans_layers = [TransitionLayer(num_layers * growth_rate) for _ in range(num_blocks - 1)]<br>        self.bn = tf.keras.layers.BatchNormalization()<br>        self.relu = tf.keras.layers.Activation(&#39;relu&#39;)<br>        self.pool = tf.keras.layers.GlobalAveragePooling2D()<br>        self.fc = tf.keras.layers.Dense(units=num_classes, activation=&#39;softmax&#39;)<br>    <br>    def call(self, inputs):<br>        x = self.conv1(inputs)<br>        for i in range(len(self.blocks)):<br>            x = self.blocks[i](x)<br>            if i != len(self.blocks) - 1:<br>                x = self.trans_layers[i](x)<br>        x = self.bn(x)<br>        x = self.relu(x)<br>        x = self.pool(x)<br>        output = self.fc(x)<br>        return output</pre><h3>Training the Model</h3><p>We will compile and train the DenseNet-BC (L=100, k=12) model on the CIFAR-10 dataset.</p><pre>model = DenseNet(num_blocks=3, num_layers=16, growth_rate=12, num_classes=10)<br><br>model.compile(<br>  optimizer=tf.keras.optimizers.Adam(), <br>  loss=tf.keras.losses.categorical_crossentropy, <br>  metrics=[&#39;accuracy&#39;]<br>)<br><br>model.fit(<br>  train_images, <br>  train_labels, <br>  epochs=100, <br>  batch_size=64, <br>  validation_data=(test_images, test_labels)<br>)</pre><p>In the above code, we create an instance of the DenseNet model and compile it with the Adam optimizer, categorical cross-entropy loss, and accuracy metric. We then train the model on the training data for 100 epochs with a batch size of 64 and evaluate it on the test data after each epoch.</p><h3>Evaluation</h3><p>We will evaluate the model on the test dataset.</p><pre>test_loss, test_acc = model.evaluate(test_images, test_labels)<br><br>print(&#39;Test loss:&#39;, test_loss)<br>print(&#39;Test accuracy:&#39;, test_acc)</pre><p>In the above code, we evaluate the model on the test dataset and print the test loss and test accuracy.</p><h3>Conclusion</h3><p>In this blog post, we have implemented the DenseNet-BC (L=100, k=12) architecture using TensorFlow and Python. We have explained the architecture of DenseNet and its advantages over other convolutional neural networks. We have also provided the complete code to train and evaluate the DenseNet-BC (L=100, k=12) model on the CIFAR-10 dataset. By following the steps provided in this blog post, you can train and evaluate the DenseNet-BC (L=100, k=12) model on your own datasets.</p><p>DenseNet is a powerful architecture that achieves state-of-the-art performance on a wide range of computer vision tasks. It is widely used in academia and industry for various applications such as image classification, object detection, and semantic segmentation. We hope that this blog post has provided you with a clear understanding of the DenseNet architecture and its implementation in TensorFlow. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8a5ffe942a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Matrix Factorization Technique for Recommender Systems from scratch]]></title>
            <link>https://medium.com/@rebirth4vali/implementing-matrix-factorization-technique-for-recommender-systems-from-scratch-7828c9166d3c?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7828c9166d3c</guid>
            <category><![CDATA[sgd]]></category>
            <category><![CDATA[matrix-factorization]]></category>
            <category><![CDATA[netflix-recommendations]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 10:45:52 GMT</pubDate>
            <atom:updated>2023-03-26T10:50:22.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QuK-dyK7j8equezsRYZ9hQ.png" /></figure><h3>Introduction</h3><p>Here we are implementing the approach discussed in “Matrix Factorization Techniques for Recommender Systems” by Yehuda Koren, Robert Bell, and Chris Volinsky. It is a seminal paper in the field of recommender systems and proposes a matrix factorization approach for collaborative filtering.</p><p>Recommender systems have become ubiquitous in our daily lives. They are used by companies like Netflix, Amazon, and Spotify to recommend movies, products, and music to their users. Recommender systems use data to predict users’ preferences and make recommendations based on those predictions.</p><p>There are two main types of recommender systems: content-based and collaborative filtering. Content-based recommender systems recommend items similar to those that a user has liked in the past. Collaborative filtering recommender systems, on the other hand, recommend items based on the preferences of similar users.</p><p>Matrix factorization is a popular method for collaborative filtering. The idea behind matrix factorization is to decompose the user-item matrix into two lower-rank matrices: one that represents the users’ preferences and one that represents the items’ characteristics. The user-item matrix is then reconstructed by taking the dot product of these two matrices.</p><p>In this blog post, we will explain matrix factorization for recommender systems and provide a Python implementation from scratch.</p><h3>The Data</h3><p>You can download the dataset used in this blog from <a href="https://drive.google.com/file/d/1-1z7iDB52cB6_JpO7Dqa-eOYSs-mivpq/view">here</a>. After downloading and extracting the dataset, we can load it into a Pandas data frame as follows:</p><pre>import pandas as pd<br>from scipy.sparse import csr_matrix<br><br>data = pd.read_csv(&#39;ratings_train.csv&#39;)<br>ratings = csr_matrix(<br>    (data.rating.values, (data.user_id.values, data.item_id.values)), <br>    shape=(len(data.user_id.unique()), len(data.item_id.unique()))<br>).toarray()</pre><h3>Matrix Factorization</h3><p>The user-item matrix can be represented as a matrix R, where each row represents a user and each column represents an item. The entries of the matrix are the ratings that the users gave to the items. However, the matrix is usually very sparse because each user has only rated a small fraction of the items.</p><p>Matrix factorization aims to factorize the user-item matrix R into two lower-rank matrices P and Q, such that their product approximates R. The matrix P represents the users&#39; preferences and the matrix Q represents the items&#39; characteristics. Each row of the matrix P represents a user&#39;s preferences as a vector, and each row of the matrix Q represents an item&#39;s characteristics as a vector.</p><p>The user-item matrix R can be approximated by taking the dot product of the corresponding rows of P and Q. That is, the (i,j) entry of R can be approximated as P[i,:] dot Q[:,j].</p><p>The goal of matrix factorization is to find the matrices P and Q that minimize the error between the approximated matrix and the actual matrix. This error is usually measured using the root mean squared error (RMSE) between the predicted ratings and the actual ratings but here in this experiment we are just using the simple error:</p><pre>def predict(self, u, i):<br>    return self.global_bias+self.user_biases[u]+self.item_biases[i]+self.user_vecs[u]@self.item_vecs[i]<br><br>def error(self, u, i):<br>    pred_rat = self.predict(u, i)<br>    return self.ratings[u, i] - pred_rat </pre><p>The optimization problem can be solved using gradient descent. The idea behind gradient descent is to iteratively update the matrices P and Q in the direction of the negative gradient of the RMSE with respect to the matrices. The updated rules for the matrices are as follows:</p><pre>def update_biases_and_vectors(self, error, u, i):<br>    # Update biases<br>    self.user_biases[u] += self.l_rate*(error - self.alpha*self.user_biases[u])<br>    self.item_biases[i] += self.l_rate*(error - self.alpha*self.item_biases[i])<br>    # Update User and item Vectors<br>    self.user_vecs[u, :] += self.l_rate*(error*self.item_vecs[i, :] - self.alpha*self.user_vecs[u, :])<br>    self.item_vecs[i, :] += self.l_rate*(error*self.user_vecs[u, :] - self.alpha*self.item_vecs[i, :])</pre><p>Here in this setting, you can use L2 Regularization but we are not using this, since the input dataset is very simple.</p><p>The optimization problem can be solved by iteratively updating the matrices P and Q until the error converges.</p><h3>Python Implementation</h3><p>Now that we have explained matrix factorization for recommender systems, we can implement it in Python from scratch. Here is the code:</p><pre>import time, numpy as np<br>import matplotlib.pyplot as plt<br><br>class MatrixFactorization():<br>    <br>    def __init__(self, ratings, n_factors=100, l_rate=0.01, alpha=0.01, n_iter=100):<br>        self.ratings = ratings<br>        self.n_users, self.n_items = ratings.shape<br>        self.non_zero_row_ind, self.non_zero_col_ind = ratings.nonzero()<br>        self.n_interac = len(ratings[np.where(ratings != 0)])<br>        self.ind_lst = list(range(self.n_interac))<br>        self.n_factors = n_factors<br>        self.l_rate = l_rate  # eta0 Constant that multiplies the update term<br>        self.alpha = alpha  # lambda Constant that multiplies the regularization term<br>        self.n_iter = n_iter<br>        self.mse_lst = []<br>        self.wait = 10<br>        self.tol = 1e-3<br>        self.n_iter_no_change = 10<br>        self.verbose = True<br>        self.stop = False<br>        <br>    def initialize(self, ):<br>        self.now = time.time()<br>        # Initialize Bias Values<br>        self.user_biases = np.zeros(self.n_users)<br>        self.item_biases = np.zeros(self.n_items)<br>        # initialize user &amp; item vectors        <br>        self.user_vecs = np.random.normal(scale=1/self.n_factors, size=(self.n_users, self.n_factors))<br>        self.item_vecs = np.random.normal(scale=1/self.n_factors, size=(self.n_items, self.n_factors))<br>        # compute global bias<br>        self.global_bias = np.mean(self.ratings[np.where(self.ratings != 0)])<br>        self.evaluate_the_model(0)<br>        <br>        <br>    def predict(self, u, i):<br>        return self.global_bias+self.user_biases[u]+self.item_biases[i]+self.user_vecs[u]@self.item_vecs[i]<br>        <br>    def update_biases_and_vectors(self, error, u, i):<br>        # Update biases<br>        self.user_biases[u] += self.l_rate*(error - self.alpha*self.user_biases[u])<br>        self.item_biases[i] += self.l_rate*(error - self.alpha*self.item_biases[i])<br>        # Update User and item Vectors<br>        self.user_vecs[u, :] += self.l_rate*(error*self.item_vecs[i, :] - self.alpha*self.user_vecs[u, :])<br>        self.item_vecs[i, :] += self.l_rate*(error*self.user_vecs[u, :] - self.alpha*self.item_vecs[i, :])<br>        <br>    def evaluate_the_model(self, epoch):<br>        tot_square_error = 0<br>        for index in self.ind_lst:<br>            # Extracting user item information indices in which we have a rating<br>            u, i = self.non_zero_row_ind[index], self.non_zero_col_ind[index]<br>            pred_rat = self.predict(u, i)<br>            tot_square_error += (self.ratings[u, i]-pred_rat)**2<br>        mse = tot_square_error/self.n_interac<br>        self.mse_lst.append(mse)<br>        if self.verbose: <br>            print(f&quot;---&gt; Epoch {epoch}&quot;)<br>            temp = np.round(time.time()-self.now, 3)<br>            print(f&quot;ave mse {np.round(self.mse_lst[-1], 3)} ===&gt; Total training time: {temp} seconds.&quot;)<br>        <br>    def early_stopping(self, epoch):<br>        if (self.mse_lst[-2] - self.mse_lst[-1]) &lt;= self.tol:<br>            if self.wait == self.n_iter_no_change:<br>                temp = np.round(time.time()-self.now, 3)<br>                if self.verbose: print(f&quot;Convergence after {epoch} epochs time took: {temp} seconds.&quot;)<br>                self.stop = True<br>                self.conv_epoch_num = epoch<br>            self.wait += 1<br>        else:<br>            self.wait = 0<br>        <br>    def fit(self, ):<br>        self.initialize()<br>        for epoch in range(1, self.n_iter):<br>            np.random.shuffle(self.ind_lst)<br>            if self.stop == False:<br>                for index in self.ind_lst:<br>                    # Extracting user item information indices in which we have a rating<br>                    u, i = self.non_zero_row_ind[index], self.non_zero_col_ind[index]<br>                    pred_rat = self.predict(u, i)<br>                    error = self.ratings[u, i]-pred_rat<br>                    self.update_biases_and_vectors(error, u, i)<br>                self.evaluate_the_model(epoch)<br>                self.early_stopping(epoch)<br>        self.plot_the_score()<br>                <br>    def plot_the_score(self, ):<br>        plt.figure(figsize=(18,6))<br>        plt.plot(range(1, 1+len(self.mse_lst)), self.mse_lst, marker=&#39;o&#39;)<br>        plt.title(&quot;SGD Custom Prepared USER &amp; ITEM vector&#39;s Tr MSE loss vs epochs&quot;, fontsize=20)<br>        plt.xlabel(&#39;Number of epochs&#39;, fontsize=18)<br>        plt.ylabel(&#39;mean square error&#39;, fontsize=18)<br>        plt.xticks(range(1, self.conv_epoch_num+5), fontsize=15, rotation=90)<br>        plt.yticks(np.linspace(min(self.mse_lst), max(self.mse_lst),15), fontsize=15)<br>        plt.grid()<br>        plt.show()</pre><p>The code above defines a class MatrixFactorization that takes in four hyperparameters: n_factors which is the number of factors to use in the matrix factorization, l_rate which controls the step size of the update, alpha which is the regularization parameter, and n_iter which is the number of iterations to run the optimization algorithm.</p><h3>Testing the Model</h3><p>Next, the code fits the matrix factorization model to the training data using the fit method of the MatrixFactorization class. We use n_factors=100, l_rate=0.01, alpha=0.01, and n_iter=100 as hyperparameters for the model.</p><pre>obj = MatrixFactorization(ratings)<br>obj.fit()</pre><pre>---&gt; Epoch 0<br>ave mse 1.267 ===&gt; Total training time: 0.67 seconds.<br>---&gt; Epoch 1<br>ave mse 0.926 ===&gt; Total training time: 3.7 seconds.<br>---&gt; Epoch 2<br>ave mse 0.884 ===&gt; Total training time: 6.746 seconds.<br>---&gt; Epoch 3<br>ave mse 0.867 ===&gt; Total training time: 9.976 seconds.<br>---&gt; Epoch 4<br>ave mse 0.856 ===&gt; Total training time: 13.864 seconds.<br><br><br>---&gt; Epoch 70<br>ave mse 0.025 ===&gt; Total training time: 253.703 seconds.<br>---&gt; Epoch 71<br>ave mse 0.025 ===&gt; Total training time: 257.261 seconds.<br>---&gt; Epoch 72<br>ave mse 0.024 ===&gt; Total training time: 260.886 seconds.<br>---&gt; Epoch 73<br>ave mse 0.023 ===&gt; Total training time: 264.487 seconds.<br>---&gt; Epoch 74<br>ave mse 0.023 ===&gt; Total training time: 268.097 seconds.<br>Convergence after 74 epochs time took: 268.097 seconds.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDnM8JWoXiNZsCv2nqeOvg.png" /></figure><h3>Conclusion</h3><p>In this blog post, we have explained matrix factorization for recommender systems and implemented it in Python from scratch. We have also tested the model and evaluated its performance.</p><p>Please let me know your Feed Back. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7828c9166d3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bagging and Random Forest Regressor from scratch in python by using Decision Tree Regressor from…]]></title>
            <link>https://medium.com/@rebirth4vali/bagging-and-random-forest-regressor-from-scratch-in-python-by-using-decision-tree-regressor-from-22364fc2fd57?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/22364fc2fd57</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[bagging]]></category>
            <category><![CDATA[bootstrapping]]></category>
            <category><![CDATA[sklearn]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 07:05:53 GMT</pubDate>
            <atom:updated>2023-03-26T07:05:53.626Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bagging and Random Forest Regressor from scratch in python by using Decision Tree Regressor from sklearn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*7AxWhp2UMm7smg9ZmXlRHg.png" /></figure><h3>Introduction</h3><p>The Random Forest Regressor is a powerful ensemble learning technique that can be used for regression problems. It works by combining multiple decision trees, which reduces overfitting and improves the accuracy of predictions. In this blog post, we will see how to implement a Random Forest Regressor from scratch in Python using the Decision Tree Regressor class from Scikit-learn (sklearn).</p><h3>Implementing Bagging</h3><pre>class bootstrap():<br>    <br>    def __init__(self, data, target, n_estimaters):<br>        self.n_estimaters = n_estimaters<br>        self.data, self.target = data, target<br>        self.in_bag_indices_for_each_base_learner = self.np.array([])<br>        self.oob_indices_for_each_base_learner = self.np.array([])<br>        self.col_indices_for_each_base_learner = self.np.array([])<br>        <br>    def sampling_in_bag_data_for_a_base_learner(self, data_indices):<br>        # sampling tr data indices without replacement for a base model<br>        unique_in_bag_indices_of_a_sample = data_indices[:int(0.6*self.num_of_data_points)]<br>        # sampling tr data indices with replacement for a base model<br>        repea_in_bag_indices_of_a_sample = self.np.random.choice(len(unique_in_bag_indices_of_a_sample), <br>                                                self.num_of_data_points-len(unique_in_bag_indices_of_a_sample))<br>        # merging the indices<br>        in_bag_indices_of_a_sample = self.np.concatenate((unique_in_bag_indices_of_a_sample, <br>                                                          repea_in_bag_indices_of_a_sample))[None, :]<br>        return in_bag_indices_of_a_sample<br>        <br>    def sam_col_without_replace(self, ):<br>        # here adding+1 because randint is an exclusive([3, self.num_of_feat+1)]) generater<br>        num_of_col_to_samp = self.np.random.randint(3, self.num_of_feat+1)<br>        col_indices_of_a_sample = self.np.random.choice(self.num_of_feat, num_of_col_to_samp, replace=False)<br>        # padding extra zeros at the end ===&gt; by doing this we can make equal length of arrays column indices <br>        # for each base learner, so we can save it in future<br>        temp =([num_of_col_to_samp], col_indices_of_a_sample, np.zeros(self.num_of_feat-num_of_col_to_samp+1))<br>        col_indices_of_a_sample = self.np.concatenate(temp).astype(&#39;int&#39;)[None, :]<br>        return col_indices_of_a_sample<br>    <br>    def create_boot_straped_sample(self, estimater_num):<br>        # creating the an array of indices of the given dataset<br>        data_indices = self.np.arange(self.data.shape[0])<br>        # shufling the indices before sampling for each base learner<br>        self.np.random.shuffle(data_indices)<br>        in_bag_indices_of_a_sample = self.sampling_in_bag_data_for_a_base_learner(data_indices)<br>        # sampling oob data indices for a base learner<br>        oob_row_indices_of_a_sample = data_indices[int(0.6*self.num_of_data_points):][None, :]<br>        # sampling columns without replacement<br>        col_indices_of_a_sample = self.sam_col_without_replace()<br>        # save the in_bag, oob and the respective column indexes of a single base model<br>        self.concate_indices(estimater_num, in_bag_indices_of_a_sample, oob_row_indices_of_a_sample, <br>                             col_indices_of_a_sample)<br>    <br>    def concate_indices(self, estimater_num, in_bag_indices_of_a_sample, oob_row_indices_of_a_sample, <br>                        col_indices_of_a_sample):<br>        if estimater_num:<br>            temp = (self.in_bag_indices_for_each_base_learner, in_bag_indices_of_a_sample)<br>            self.in_bag_indices_for_each_base_learner = self.np.concatenate(temp)<br>            temp = (self.oob_indices_for_each_base_learner, oob_row_indices_of_a_sample)<br>            self.oob_indices_for_each_base_learner = self.np.concatenate(temp)<br>            temp = (self.col_indices_for_each_base_learner, col_indices_of_a_sample)<br>            self.col_indices_for_each_base_learner = self.np.concatenate(temp)<br>        else:<br>            self.in_bag_indices_for_each_base_learner = in_bag_indices_of_a_sample<br>            self.oob_indices_for_each_base_learner = oob_row_indices_of_a_sample<br>            self.col_indices_for_each_base_learner = col_indices_of_a_sample<br>        <br>    def sample_data_for_each_base_learner(self, ):<br>        for estimater_num in range(self.n_estimaters):<br>            self.create_boot_straped_sample(estimater_num)</pre><h3>Implementing a Random Forest Regressor</h3><p>To create a Random Forest Regressor, we will create multiple instances of the MyDecisionTreeRegressor class and combine their predictions to make the final prediction. Here’s an example implementation of the Random Forest Regressor class:</p><pre>class random_forest_reg(bootstrap):<br>    <br>    import numpy as np<br>    <br>    def __init__(self, data=[], target=[], n_estimaters=30):<br>        super().__init__(data, target, n_estimaters)<br>        self.base_models = dict()<br>        <br>    def initializations(self, data, target):<br>        self.data, self.target = data, target<br>        self.num_of_data_points, self.num_of_feat = self.data.shape<br>        self.pred_of_each_base_learner_on_in_bag = self.np.zeros((self.n_estimaters, self.data.shape[0]))<br>        self.pred_of_each_base_learner_on_oob = self.np.zeros((self.n_estimaters, self.data.shape[0]))<br>        <br>    def fit(self, data, target):<br>        self.initializations(data, target)<br>        self.sample_data_for_each_base_learner()<br>        generater = zip(self.in_bag_indices_for_each_base_learner, <br>                        self.oob_indices_for_each_base_learner, <br>                        self.col_indices_for_each_base_learner)<br>        for sample_num, (in_bag_ind, oob_ind, col_ind) in enumerate(generater):<br>            num_of_col = col_ind[0]<br>            col_ind = col_ind[1:num_of_col+1]<br>            x_in_bag, y_in_bag = self.data[in_bag_ind][:, col_ind], self.target[in_bag_ind]<br>            x_oob, y_oob = self.data[oob_ind][:, col_ind], self.target[oob_ind]<br>            self.base_models[sample_num] = DecisionTreeRegressor().fit(x_in_bag, y_in_bag)<br>            self.evaluate_each_base_model(sample_num, in_bag_ind, oob_ind, x_in_bag, y_in_bag, x_oob, y_oob)<br>        self.evaluate_rf()<br>        <br>    def predict(self, query_data_point):<br>        temp = []<br>        for estimater_num, col_ind in enumerate(self.col_indices_for_each_base_learner):<br>            num_of_col = col_ind[0]<br>            col_ind = col_ind[1:num_of_col+1]<br>            x_q = query_data_point[col_ind][None, :]<br>            temp.append(self.base_models[estimater_num].predict(x_q))<br>        return self.np.sum(temp)/self.n_estimaters<br>        <br>    def evaluate_each_base_model(self, estimater_num, in_bag_ind, oob_ind, x_in_bag, y_in_bag, x_oob, y_oob):<br>        self.pred_of_each_base_learner_on_in_bag[estimater_num][in_bag_ind] = self.base_models[estimater_num].predict(x_in_bag)<br>        self.pred_of_each_base_learner_on_oob[estimater_num][oob_ind] = self.base_models[estimater_num].predict(x_oob)<br>        <br>    def evaluate_rf(self, ):<br>        self.agg_pred_on_tr = self.np.divide(self.pred_of_each_base_learner_on_in_bag.sum(axis=0), <br>                                             self.np.count_nonzero(self.pred_of_each_base_learner_on_in_bag, axis=0))<br>        self.agg_pred_on_oob = self.np.divide(self.pred_of_each_base_learner_on_oob.sum(axis=0), <br>                                              self.np.count_nonzero(self.pred_of_each_base_learner_on_oob, axis=0))<br>        self.tr_mse = self.np.mean(self.np.square(self.agg_pred_on_tr - self.target))<br>        self.oob_mse = self.np.mean(self.np.square(self.agg_pred_on_oob - self.target))</pre><p>This implementation of the Random Forest Regressor class creates multiple instances of the MyDecisionTreeRegressor class and fits them to bootstrap samples of the training data. The predictions of all the decision trees are combined to make the final prediction.</p><h3>Using the Random Forest Regressor</h3><pre>import random<br>import numpy as np<br>from sklearn.datasets import load_boston<br>from sklearn.tree import DecisionTreeRegressor<br><br>boston = load_boston()<br>x = boston.data     # independent variables<br>y = boston.target   # target variable<br><br>model = random_forest_reg()<br>model.fit(x, y)<br>model.tr_mse, model.oob_mse</pre><pre>(0.00867828517476405, 12.540483289442912)</pre><h3>Conclusion</h3><p>In this blog post, we have seen how to implement a Random Forest Regressor from scratch in Python using the Decision Tree Regressor class from Scikit-learn (sklearn). The Random Forest Regressor is a powerful ensemble learning technique that can be used for regression problems. By combining multiple decision trees, it is able to reduce overfitting and improve the accuracy of predictions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22364fc2fd57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stochastic Gradient Descent (SGD) from scratch in Python]]></title>
            <link>https://medium.com/@rebirth4vali/stochastic-gradient-descent-sgd-from-scratch-in-python-661480ddf5fa?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/661480ddf5fa</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[stochastic-gradient]]></category>
            <category><![CDATA[sgd]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 06:30:56 GMT</pubDate>
            <atom:updated>2023-03-26T06:30:56.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPqY05GURD5ZFh63HDtwvw.png" /></figure><p>Stochastic Gradient Descent (SGD) is a widely used optimization algorithm for machine learning models. It is a variant of the gradient descent algorithm that updates the model parameters on a small random subset of the training data, making it much faster and scalable for large datasets. In this blog post, we will learn how to implement SGD from scratch in Python.</p><h3>Understanding SGD</h3><p>SGD is an iterative optimization algorithm that aims to minimize a cost function by updating the model parameters in the opposite direction of the gradient of the cost function. The cost function represents the difference between the predicted outputs of the model and the actual outputs in the training data. The gradient of the cost function is a vector that points in the direction of the steepest increase in the cost function, and the negative gradient points in the direction of the steepest decrease.</p><p>The standard gradient descent algorithm updates the model parameters after computing the gradient over the entire training data. However, in practice, computing the gradient over the entire dataset is computationally expensive and impractical for large datasets. SGD addresses this issue by randomly selecting a small batch of data points at each iteration and computing the gradient on this batch. This allows SGD to converge much faster and scale to large datasets.</p><h3>Implementing SGD in Python</h3><p>Here I am providing code of SGD with batch size = 1, we can extend it easily to any k value just by averaging the gradients.</p><pre>%matplotlib inline<br>import matplotlib.pyplot as plt<br>import sys, time, numpy as np<br><br>class logistic_regression():<br>    <br>    def __init__(self, <br>                 lr_rate=0.001, <br>                 alpha=0.001, <br>                 n_iter_no_change=5, <br>                 max_iter=1000, <br>                 tol=1e-9):<br>        <br>        self.lr_rate = lr_rate # eta (constant that multiplies the weight update term in update function)<br>        self.alpha = alpha #lambda (constant that multiplies the regularization term in optimization function)<br>        self.n_iter_no_change = n_iter_no_change<br>        self.max_iter = max_iter<br>        self.tol = tol<br>        self._early_stoing = False<br>        <br>    def sigmoid(self, x):<br>        return 1/(1+np.exp(-(x@self.w+self.b)))<br>        <br>    def log_loss(self, x, y):<br>        log_loss, infi = 0, 1e-90<br>        for x1, y1 in zip(x, y):<br>            prob_pos_class = self.sigmoid(x1)<br>            # adding 1e-90 to avoid log(0) math error<br>            log_loss += y1*np.log(prob_pos_class+infi) + (1-y1)*np.log(1-prob_pos_class+infi)<br>        return -log_loss/x.shape[0]<br>        <br>    def initializations(self, <br>                        x_tr, <br>                        y_tr, <br>                        x_cv, <br>                        y_cv):<br>        self.wait = 0<br>        self.n = x_tr.shape[0]<br>        self.x_tr, self.y_tr = x_tr, y_tr<br>        self.x_cv, self.y_cv = x_cv, y_cv<br>        self.w, self.b = self.np.zeros_like(x_tr[0]), 0<br>        self.tr_log_loss_lst = [self.log_loss(self.x_tr, self.y_tr)]<br>        self.cv_log_loss_lst = [self.log_loss(self.x_cv, self.y_cv)]<br>        <br>    def evaluate_the_model(self, epoch):<br>        self.tr_log_loss_lst.append(self.log_loss(self.x_tr, self.y_tr))<br>        self.cv_log_loss_lst.append(self.log_loss(self.x_cv, self.y_cv))<br>        print(f&quot;---&gt; Epoch {epoch}&quot;)<br>        print(f&quot;Tr ave loss {self.tr_log_loss_lst[-1]} &amp; CV ave loss {self.cv_log_loss_lst[-1]}.&quot;)<br>        print(f&quot;Total training time: {np.round(time.time()-self.now, 3)} seconds.&quot;)<br>        <br>    def early_stopping(self, epoch):<br>        if (self.tr_log_loss_lst[-2] - self.tr_log_loss_lst[-1]) &lt;= self.tol:<br>            if self.wait == self.n_iter_no_change:<br>                temp = np.round(time.time()-self.now, 3)<br>                print(f&quot;Convergence after {epoch} epochs time took: {temp} seconds.&quot;)<br>                self._early_stoing = True<br>            self.wait += 1<br>        else:<br>            self.wait = 0<br>        <br>    def fit(self, <br>            x_tr, <br>            y_tr, <br>            x_cv, <br>            y_cv):<br>        <br>        self.initializations(x_tr, <br>                             y_tr, <br>                             x_cv, <br>                             y_cv)<br>        self.now = time.time()<br>        for epoch in range(1, self.max_iter+1):<br>            if self._early_stoing == False:<br>                for x, y in zip(self.x_tr, self.y_tr):<br>                    common = self.alpha*(y-self.sigmoid(x))<br>                    self.w = (1-self.lr_rate*self.alpha/self.n)*self.w + common*x<br>                    self.b += common<br>                self.evaluate_the_model(epoch)<br>                self.early_stopping(epoch)<br>            else: break<br>    <br>    def predict_class(self, x):<br>        return np.array([1 if (self.sigmoid(x1)&gt;0.5) else 0 for x1 in x])<br>    <br>    def plot_log_loss_per_epoch(self, ):<br>        plt.figure(figsize=(18, 8))<br>        plt.suptitle(&#39;Ploting the log_loss VS Epochs with our Custom SGD Results&#39;, fontsize=30)<br>        <br>        plt.plot(range(1, len(self.tr_log_loss_lst)+1), <br>                 self.tr_log_loss_lst, <br>                 marker=&#39;o&#39;, <br>                 label=&#39;Change in the tr_log_loss per each epoch&#39;)<br>        plt.plot(range(1, len(self.cv_log_loss_lst)+1), <br>                 self.cv_log_loss_lst, <br>                 marker=&#39;o&#39;, <br>                 label=&#39;Change in the te_log_loss per each epoch&#39;)<br>        <br>        plt.xticks(range(1, len(self.tr_log_loss_lst)+1), fontsize=15)<br>        plt.yticks(fontsize=15)<br>        plt.xlabel(&#39;Number of Epochs&#39;, fontsize=15)<br>        plt.ylabel(&#39;log_loss Value&#39;, fontsize=15)<br>        plt.legend(fontsize=15)<br>        <br>        plt.grid()<br>        plt.show()</pre><h3>Testing SGD on a toy dataset</h3><p>Creating a dummy dataset by using the sklearn’s builtin method</p><pre>X, y = make_classification(n_samples=50000, <br>                           n_features=15, <br>                           n_informative=10, <br>                           n_redundant=5,<br>                           n_classes=2, <br>                           weights=[0.7], <br>                           class_sep=0.7, <br>                           random_state=15)</pre><pre>model = logistic_regression()<br>model.fit(X_train, y_train, X_test, y_test)</pre><p>The output of the above code is</p><pre>---&gt; Epoch 1<br>Tr ave loss 0.40400578983455926 &amp; CV ave loss 0.4051507727476775.<br>Total training time: 1.25 seconds.<br>---&gt; Epoch 2<br>Tr ave loss 0.38838064528675104 &amp; CV ave loss 0.39005633543659096.<br>Total training time: 2.504 seconds.<br>---&gt; Epoch 3<br>Tr ave loss 0.3831310028679692 &amp; CV ave loss 0.3850058410469716.<br>Total training time: 3.755 seconds.<br>---&gt; Epoch 4<br>Tr ave loss 0.38077452653654115 &amp; CV ave loss 0.3827291966296756.<br>Total training time: 4.99 seconds.<br>---&gt; Epoch 5<br>Tr ave loss 0.3795974430539163 &amp; CV ave loss 0.3815834683699449.<br>Total training time: 6.236 seconds.<br>---&gt; Epoch 6<br>Tr ave loss 0.37897833657912716 &amp; CV ave loss 0.38097553119337235.<br>Total training time: 7.489 seconds.</pre><p>model.plot_log_loss_per_epoch()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0IRr3H_hezLrn6uWkSyhw.png" /></figure><h3>Conclusion</h3><p>In this blog post, we have learned how to implement the SGD algorithm from scratch in Python. We have also demonstrated how to apply SGD to a toy dataset and evaluate its performance on a test set. SGD is a powerful and widely used optimization algorithm in machine learning that can significantly speed up the training process and improve the scalability of the models.</p><p>Thanks for reading my blog. Feel free to give feedback. Please press the clap button if you like the blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=661480ddf5fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[External Count Vectorizer(BOW) to vectorize Dataset]]></title>
            <link>https://medium.com/@rebirth4vali/external-count-vectorizer-bow-to-vectorize-dataset-2b08b5cc89e3?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b08b5cc89e3</guid>
            <category><![CDATA[bag-of-words]]></category>
            <category><![CDATA[out-of-memory]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[external-memory]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 05:48:45 GMT</pubDate>
            <atom:updated>2023-03-26T05:50:53.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Wd44OAzlONayHuaCx7f6yQ.jpeg" /></figure><p>Link to the Dataset used in this experiment ===&gt; <a href="https://www.kaggle.com/c/malware-classification">https://www.kaggle.com/c/malware-classification</a></p><p>The 147 GB OF ASM FILES(Microsoft Malware Detection Dataset) TOOK 48 hours with sklearn’s default count vectorizer with some RAM management(accessing some files at a time with parallelization) code to accommodate 147 GB data to calculate 1-GRAM BOW.</p><p>But I have written ExternalCountVectorizer which took just&lt; 29 mins only. I will share the code and explain how I did it.</p><h3>What is an External Bag of Words?</h3><p>In literature, an external Bag of Words is a model that uses a pre-built vocabulary of words to represent text. But here in our code, you can give pre-built vocabulary but it is not necessary it will create vocabulary by itself with the help of the input dataset itself very efficiently.</p><p>When a new document needs to be analyzed, the external Bag of Words model first preprocesses the text by removing punctuation, converting all text to lowercase, and removing stop words. It then constructs a bag of words representation</p><h3>Implementing External Bag of Words in Python</h3><pre>from itertools import cycle<br>import os, pandas as pd, time, numpy as np, pickle as pkl<br>from concurrent.futures import ProcessPoolExecutor<br>from sklearn.feature_extraction.text import CountVectorizer<br>from pathlib import Path<br><br>class ExternalCountVectorizer():<br>    <br>    def __init__(<br>        self, <br>        vocabulary=[], <br>        ngram_range=(1,2), <br>        obs_path_of_train_files=&#39;&#39;,<br>        encoding=&quot;utf-8&quot;, #&#39;cp1252&#39;<br>        decode_error=&#39;strict&#39;, #&#39;replace&#39;<br>        pkl_address=&#39;&#39;,<br>        max_workers=None<br>    ):<br>        self.encoding = encoding <br>        self.pkl_address = pkl_address<br>        self.decode_error = decode_error<br>        self.max_workers = max_workers<br>        self.ngram_range = ngram_range<br>        self.obs_path_of_train_files = obs_path_of_train_files<br>        self.vocabulary = dict(zip(vocabulary, cycle([True])))<br><br>        if not os.path.isdir(self.pkl_address): os.makedirs(self.pkl_address)<br>        <br>    def add_rows_in_pandas_df(self, outputs):<br>        for (file_name, count_bow_val) in outputs:<br>            self.df.loc[[file_name], :] = count_bow_val<br>        del file_name, count_bow_val<br>        <br>    def initialize_pandas_df(self, ):<br>        self.df = pd.DataFrame(<br>            0, <br>            dtype=&#39;int32&#39;, <br>            columns=self.vocabulary,<br>            index=self.file_names<br>        )<br>        <br>    def prepare_df(self, outputs):<br>        start = time.time()<br>        print(&#39;Building the df from BOW vectorizer...&#39;)<br>        self.initialize_pandas_df()<br>        self.add_rows_in_pandas_df(outputs)<br>        del outputs<br>        print(f&#39;Building df Completed in : {round((time.time()-start)/60, 3)} Mins\n&#39;)<br>        del start<br><br>    def transform_bow_enc_on(self, obs_file_path):<br>        # https://stackoverflow.com/a/57424308<br>        encoder = CountVectorizer(<br>            input=&#39;filename&#39;,<br>            dtype=np.int32,<br>            ngram_range=self.ngram_range,<br>            token_pattern=&#39;[a-zA-Z0-9$&amp;+,:;=?@#|&lt;&gt;.^*()%!-]+&#39;,<br>            vocabulary=self.vocabulary,<br>            encoding=self.encoding, #&#39;cp1252&#39;<br>            decode_error=self.decode_error, #&#39;replace&#39;<br>        )<br>        return encoder.transform([obs_file_path]).toarray()<br>    <br>    def fit_bow_enc_on(self, obs_file_path):<br>        # https://stackoverflow.com/a/57424308<br>        encoder = CountVectorizer(<br>            input=&#39;filename&#39;,<br>            dtype=np.int32,<br>            ngram_range=(2, self.ngram_range[-1]),<br>            token_pattern=&#39;[a-zA-Z0-9$&amp;+,:;=?@#|&lt;&gt;.^*()%!-]+&#39;,<br>            encoding=self.encoding, #&#39;cp1252&#39;<br>            decode_error=self.decode_error, #&#39;replace&#39;<br>        )<br>        encoder.fit([obs_file_path])<br>        count_bow_fea = encoder.get_feature_names_out()<br>        del encoder<br>        return count_bow_fea<br>        <br>    def transform_a_single_file(self, obs_file_path):<br>        count_bow_val = self.transform_bow_enc_on(obs_file_path)<br>        file_name = str(obs_file_path).split(&#39;/&#39;)[-1].split(&#39;.&#39;)[0]<br>        return (file_name, count_bow_val)<br><br>    def create_vocab(self, ):<br>        for pkl_file in os.listdir(self.pkl_address):<br>            with open(self.pkl_address / pkl_file, &#39;rb&#39;) as pkl_file:<br>                count_bow_fea = pkl.load(pkl_file)<br>            for word in count_bow_fea:<br>                self.vocabulary[word] = True<br>            del count_bow_fea<br>        del pkl_file, word<br><br>    def fit_on_a_single_file(self, obs_file_path):<br>        count_bow_fea = self.fit_bow_enc_on(obs_file_path)<br>        for index, ngram_word in enumerate(count_bow_fea):<br>            if all([self.vocabulary.get(word, False) for word in ngram_word.split()]): continue<br>            count_bow_fea[index] = &#39;&#39;<br>        del index, ngram_word<br>        count_bow_fea = [word for word in count_bow_fea if word != &#39;&#39;]<br>        file_name = str(obs_file_path).split(&#39;/&#39;)[-1].split(&#39;.&#39;)[0]<br>        with open(self.pkl_address / f&#39;{file_name}.pkl&#39;, &#39;wb&#39;) as pkl_file:<br>            pkl.dump(<br>                count_bow_fea, <br>                pkl_file<br>            )<br>        del count_bow_fea, file_name<br>    <br>    def transform(self, file_names):<br>        self.file_names = [file_name.split(&#39;.&#39;)[0] for file_name in file_names]<br>        start, file_names = self._initialize_variables_of_fit_and_transform(file_names)<br>        print(&#39;Transforming the Given data...&#39;)<br>        with ProcessPoolExecutor(max_workers=self.max_workers) as executor:<br>            outputs = list(executor.map(self.transform_a_single_file, file_names))<br>        del file_names<br>        print(f&#39;Vectorization Completed in : {round((time.time()-start)/60, 3)} Mins\n&#39;)<br>        del start<br>        self.prepare_df(outputs)<br>        del outputs<br>        <br>    def _initialize_variables_of_fit_and_transform(self, file_names):<br>        start = time.time()<br>        file_names = [Path(self.obs_path_of_train_files, file) for file in file_names]<br>        return start, file_names<br>        <br>    def fit(self, file_names):<br>        start, file_names = self._initialize_variables_of_fit_and_transform(file_names)<br>        print(&#39;Building the Vocabulary...&#39;)<br>        if self.ngram_range[1] &gt; 1:<br>            with ProcessPoolExecutor(max_workers=self.max_workers) as executor:<br>                executor.map(self.fit_on_a_single_file, file_names)<br>            del file_names<br>            self.create_vocab()<br>        self.vocabulary = sorted(list(self.vocabulary.keys()))<br>        print(f&#39;Time Taken to build the Vocabulary : {round((time.time()-start)/60, 3)} Mins\n&#39;)<br>        del start<br>        <br>    def fit_transform(self, file_names):<br>        self.fit(file_names)<br>        self.transform(file_names)</pre><p>This code will preprocess the text by converting it to lowercase, removing stop words and punctuation, and tokenizing it into words. It will then build a vocabulary of words from the corpus using the default CountVectorizer class from sklearn then by using this we will update the external vocabulary of 147 GB of data.</p><p>Link to the GitHub page where I have executed the code in a jupyter notebook for your reference <a href="https://github.com/SadakVali/ExternalCountVectorizer/blob/main/My%20Custom%20External%20BOW%20implimentation.ipynb">https://github.com/SadakVali/ExternalCountVectorizer/blob/main/My%20Custom%20External%20BOW%20implimentation.ipynb</a></p><h3>Conclusion</h3><p>In this blog post, we discussed the concept of an external Bag of Words and how to implement it using Python. If you like the blog please clap and let me know your FeedBack by leaving a message below. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b08b5cc89e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TF-IDF from scratch with Python]]></title>
            <link>https://medium.com/@rebirth4vali/tf-idf-from-scratch-with-python-e22033bb99f?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e22033bb99f</guid>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[tfidf-vectorizer]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 04:57:16 GMT</pubDate>
            <atom:updated>2023-03-26T04:58:12.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQ-FCEYoioz6tOlYFssXeg.png" /></figure><p>TF-IDF stands for term frequency-inverse document frequency. It is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The TF-IDF weight of a word is proportional to the number of times it appears in the document but is offset by the frequency of the word in the corpus.</p><p>In this blog post, we will implement the TF-IDF vectorizer from scratch using Python.</p><h3>Preprocessing the Text</h3><p>Before we begin, we need to preprocess the text by removing punctuation, converting all text to lowercase, and removing stop words. We can use the nltk library to do this.</p><pre>import string<br>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br><br>def preprocess_text(text):<br>    # Remove punctuation<br>    text = text.translate(str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation))<br><br>    # Convert to lowercase<br>    text = text.lower()<br><br>    # Tokenize the text<br>    words = word_tokenize(text)<br><br>    # Remove stop words<br>    words = [word for word in words if word not in stopwords.words(&#39;english&#39;)]<br><br>    return words</pre><h3>Building the Corpus</h3><pre>corpus = [<br>    &quot;This is the first document.&quot;,<br>    &quot;This document is the second document.&quot;,<br>    &quot;And this is the third one.&quot;,<br>    &quot;Is this the first document?&quot;,<br>]</pre><h3>Calculating TF-IDF</h3><p>Now, we can calculate the TF-IDF values for each word in each document. To do this, we will first calculate the term frequency (TF) of each word in each document. We will then calculate the inverse document frequency (IDF) of each word in the corpus. Finally, we will multiply the TF and IDF values to get the TF-IDF value for each word in each document.</p><pre>from collections import Counter<br>from math import log<br>from scipy.sparse import csr_matrix<br>from sklearn.preprocessing import normalize<br><br>class tfidf_vectorizer():<br>    <br>    def __init__(<br>            self, <br>            data_corpus = [], <br>            top_imp_words = None<br>            ):<br>        self.idf_ = dict()<br>        self.feature_names = []<br>        self.feature_names_in_each_doc = []<br>        <br>        self.top_imp_words = top_imp_words<br>        self.corpus_size = len(data_corpus)<br>        self.data_corpus = [doc.lower() for doc in data_corpus]<br>        <br>    def extract_features_from_text(self):<br>        # looping through data_corpus, to get a list of unique words at a document level.<br>        for each_document in self.data_corpus:<br>            self.feature_names.extend(list(set(each_document.split()) - set(self.feature_names)))<br>            self.feature_names_in_each_doc.extend(list(set(each_document.split())))<br>        self.feature_names = sorted(self.feature_names)<br>        <br>    def count_frequency_of_feature(self, ):<br>        # counting number of documents which have a specific word in them<br>        return dict(Counter(self.feature_names_in_each_doc))<br>        <br>    def calculate_idf_of_each_feature(self, freq_of_feat):<br>        return dict([(feat, 1+log((1+self.corpus_size)/(1+freq))) for feat, freq in freq_of_feat.items()])<br>        <br>    def fit(self, <br>            data_corpus, <br>            top_imp_words = None):<br>        <br>        self.__init__(data_corpus, <br>                      top_imp_words)<br>        self.extract_features_from_text()<br>        freq_of_feat = self.count_frequency_of_feature()<br>        self.idf_ = self.calculate_idf_of_each_feature(freq_of_feat)<br>        if not top_imp_words: top_imp_words = len(self.feature_names)<br>        self.idf_ = dict(sorted(self.idf_.items(), <br>                                key = lambda kv: kv[1], <br>                                reverse = True)[:top_imp_words])<br>        self.feature_names = sorted(list(self.idf_.keys()))<br>        self.idf_ = dict([(feat, (self.idf_.get(feat), dim)) for dim, feat in enumerate(self.feature_names)])<br>        <br>    def transform(self, <br>                  dataset):<br>        doc_index = []; tf_idf = []; dimension = []<br>        for index, each_doc in enumerate(dataset):<br>            leng_of_doc = len(each_doc)<br>            word_freq_in_doc = dict(Counter(each_doc.split()))<br>            for word in each_doc.split():<br>                if self.idf_.get(word):<br>                    idf, dim = self.idf_.get(word)<br>                    doc_index.append(index)<br>                    dimension.append(dim)<br>                    tf_idf.append((word_freq_in_doc.get(word)/leng_of_doc)*idf)<br>        temp = csr_matrix((tf_idf, (doc_index, dimension)), <br>                          shape = (len(dataset), len(self.idf_)))<br>        return normalize(temp)<br>    <br>    def fit_transform(self, <br>                      data_corpus, <br>                      top_imp_words = None):<br>        self.fit(data_corpus, <br>                 top_imp_words)<br>        return self.transform(data_corpus)</pre><h3>Conclusion</h3><p>In this blog post, we implemented the TF-IDF vectorizer from scratch using Python. We first preprocessed the text by removing punctuation, converting all text to lowercase, and removing stop words. We then built a corpus of documents and calculated the TF-IDF values for each word in each document. Finally, we represented each document as a vector in the TF-IDF space using a TF-IDF matrix. The TF-IDF vectorizer is a powerful tool for natural language processing and can be used for various tasks, such as clustering, classification, and information retrieval.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e22033bb99f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intuitive Understanding of Bagging In Random Forest ML Algorithm]]></title>
            <link>https://medium.com/@rebirth4vali/intuitive-understanding-of-bagging-in-random-forest-ml-algorithm-4058986aee4c?source=rss-ea37c88adbcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4058986aee4c</guid>
            <category><![CDATA[bagging]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Sadak Vali]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 02:36:16 GMT</pubDate>
            <atom:updated>2023-03-26T02:47:30.925Z</atom:updated>
            <content:encoded><![CDATA[<p>Let us consider a practical scenario, in which you have to shoot an arrow at some specific target.</p><p>While shooting the arrow you realized that the wind is flowing from the right side to the left direction at some constant velocity. Then if you shoot the arrow without considering the wind then you will miss the target even though you are perfect at aiming.</p><p>If you consider the wind velocity, you will aim at a point that is slightly to the right side of the target with respect to your position. Then the arrow may reach the target correctly.</p><p>Here 2 forces are collaborating together to do a specific task, human and wind flow direction. Here human is not aiming at the target &amp; wind direction is also not aiming at the target.</p><p>But their combined effort is responsible for success.</p><p>Consider wind direction and human shooting angles as 2 overfitted base learners in different directions. Individually they can not reach the target but by combining their performances, we are reaching the target even though they are overfitted in different directions.</p><p>We get a low variance by combining their performances. In this analogy, high variance means ===&gt; human is aiming not at the correct position he is overfitting to his past experiences(specific properties in the dataset), and the wind also not aiming correctly but when combined they reach the target.</p><p>In BootStraped Aggregation, we use Sampling with Replacement and Aggregation of the Base model’s performance on different sampling. Since we use Sampling with replacement we get repeated samples(analogous upsampling of some rows) &amp; Training on one of these sampled data will lead to overfitting of the base learner towards these specific repeated samples.</p><p>Since we repeat this process for each base model, hence each base model will overfit to the specific repeated samples in the sampled dataset but base model performance is not correlated to each other since each base model is overfitted on different rows/repeated samples due to resampling.</p><p>Hence each base model is overfitted to a different aspect/different property of the population dataset. Since each model is overfitted in a different direction their aggregation will point us to the resultant of all the possible over fittings that will lead us to lower variance (low variance model).</p><h3>Conclusion</h3><p>Hi, I hope you like the content, if you do please clap. let me know what you think. Feel free to leave a message. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4058986aee4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>