<?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"><channel><title><![CDATA[SmartRS – Remote Sensing, GIS & Data Science Tutorials]]></title><description><![CDATA[Step-by-step tutorials on remote sensing, GIS, climate data and data science with R, Python and JavaScript, by Dr. Azad Rasul.]]></description><link>https://smartrs.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 30 Nov 2026 04:27:37 GMT</lastBuildDate><atom:link href="https://smartrs.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[5 Lessons from Building a Multilingual Recipe App with React, Node.js and MongoDB]]></title><description><![CDATA[Cross-language search without translation, Arabic-script normalisation, free PWA and Android installs, and fixing SMTP blocked on Railway.]]></description><link>https://smartrs.hashnode.dev/5-lessons-from-building-a-multilingual-recipe-app-with-react-node-js-and-mongodb</link><guid isPermaLink="true">https://smartrs.hashnode.dev/5-lessons-from-building-a-multilingual-recipe-app-with-react-node-js-and-mongodb</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[MongoDB]]></category><category><![CDATA[PWA]]></category><category><![CDATA[i18n]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Tue, 15 Sep 2026 21:01:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/60c1e87e31808952a1d0b7a0/685e6a22-463a-4238-9ac7-dcdd1fdb147a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently built <strong>Flaavo</strong>, a recipe-sharing web app with a React (Vite) front end, a Node.js/Express API and MongoDB. Most of its recipes are written in Kurdish, while its users search in Kurdish, Arabic, English and Turkish. Getting that to work, and shipping the app to phones without paying app-store fees, taught me five lessons that apply to many small projects.</p>
<h2>1. When search returns nothing, check the collection first</h2>
<p>My first bug report said "search gives no results". I started debugging the regex. The real cause was simpler: the search route imported the <code>Post</code> and <code>User</code> models but <strong>never imported</strong> <code>Recipe</code>, so more than a hundred recipes were invisible.</p>
<p>There was a second, hidden bug. Posts stored ingredients as plain strings, but recipes stored objects:</p>
<pre><code class="language-js">// posts:   ingredients: ["tomato", "onion"]
// recipes: ingredients: [{ name: "tomato", quantity: 2, unit: "pcs" }]

// $elemMatch with a regex never matches an object:
{ ingredients: { $elemMatch: { $regex: re } } }   // recipes -&gt; 0 results

// query the nested field instead:
{ "ingredients.name": { $regex: re } }            // recipes -&gt; works
</code></pre>
<p><strong>Lesson:</strong> when an endpoint returns an empty array, first confirm <em>which collection and which field</em> it queries. Only then debug the query itself.</p>
<h2>2. Cross-language search without a translation API</h2>
<p>Users type <em>cucumber</em>, <em>خيار</em> or <em>salatalık</em> and expect the same Kurdish recipes. Translating every recipe was too heavy. Instead, I used the fact that <strong>cooking vocabulary is a small, bounded domain</strong>. A few hundred ingredient names cover most real searches.</p>
<p>A small dictionary maps each concept to every spelling I know. The query is expanded into one regex:</p>
<pre><code class="language-js">// simplified illustration
const CONCEPTS = [
  ["cucumber", "خيار", "خەیار", "salatalık"],
  ["tomato", "طماطة", "تەماتە", "domates"],
  // ...
];

function searchPatterns(q) {
  const term = normalize(q);
  const hit = CONCEPTS.find(row =&gt; row.some(w =&gt; normalize(w) === term));
  return hit ? hit.map(normalize) : [term]; // unknown words fall through unchanged
}

const re = new RegExp(searchPatterns(q).map(escapeRegex).join("|"), "i");
</code></pre>
<p>This approach needs no API, no re-indexing and no extra latency, and it works offline.</p>
<p><strong>Gotcha:</strong> substring matching can swallow a short word that is the start of a longer one. In Kurdish, <em>بادەم</em> (almond) matched <em>بادەمجان</em> (eggplant). The fix was to prefer exact dictionary hits over partial ones, and to test every new short term against the real data.</p>
<h2>3. Fold Arabic-script letter variants</h2>
<p>Kurdish and Arabic share letters that have several Unicode forms: ك/ک, ي/ى/ی, ه/ة/ە, and أ/إ/آ/ا. Someone typing Kurdish on an Arabic keyboard produces different code points, so <strong>even same-language search failed</strong>. Normalising both the query and the pattern fixed it:</p>
<pre><code class="language-js">const FOLD = [
  [/[كک]/g, "ک"],
  [/[يىی]/g, "ی"],
  [/[هةە]/g, "ە"],
  [/[أإآا]/g, "ا"],
];
const normalize = s =&gt; FOLD.reduce((t, [re, to]) =&gt; t.replace(re, to), s.trim().toLowerCase());
</code></pre>
<p>If your app handles Arabic-script text, this one step removes a whole class of "no results" reports. To keep matching accent-insensitive in the database, apply the same folding when you build the regex, for example with a character class for each letter.</p>
<h2>4. Installable on iPhone and Android without app-store fees</h2>
<ul>
<li><p><strong>iPhone:</strong> a Progressive Web App (PWA) installs from Safari via <em>Share → Add to Home Screen</em>, with no $99/year developer account. Three surprises:</p>
<ul>
<li><p>iOS <strong>ignores</strong> <code>manifest.json</code> for the home-screen name and icon. You need the <code>apple-mobile-web-app-*</code> meta tags and an <code>apple-touch-icon</code>.</p>
</li>
<li><p>The touch icon must have <strong>no transparency</strong>, or iOS renders the transparent area as black.</p>
</li>
<li><p>There is <strong>no install prompt API on iOS</strong> (<code>beforeinstallprompt</code> never fires), so the UI has to show the three steps instead of an Install button.</p>
</li>
</ul>
</li>
<li><p><strong>Android:</strong> I wrapped the same build with <strong>Capacitor</strong> and serve a signed APK from the website. Keep the signing keystore safe, because every future update must be signed with the same key.</p>
</li>
</ul>
<p>My service worker is deliberately narrow:</p>
<pre><code class="language-js">// hashed build files never change -&gt; cache-first
if (url.pathname.startsWith("/assets/")) return cacheFirst(event);
// HTML and icons -&gt; network-first, so a new deploy is never hidden behind a stale shell
if (url.origin === location.origin) return networkFirst(event);
// API, images and fonts on other origins -&gt; not intercepted at all
</code></pre>
<h2>5. Your host may silently block SMTP</h2>
<p>Sign-up emails hung for about 21 seconds and never arrived, although the same credentials worked on my laptop. The host (Railway) <strong>blocks outbound SMTP ports</strong> 25, 465 and 587. No SMTP setting can fix that. Switching to the email provider's <strong>HTTPS API</strong> fixed it immediately:</p>
<pre><code class="language-js">await fetch("https://api.resend.com/emails", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.RESEND_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ from: "App &lt;noreply@example.com&gt;", to, subject, html }),
});
</code></pre>
<p>Two related lessons:</p>
<ul>
<li><p><strong>Sending and receiving are separate.</strong> A sending service does not create a mailbox, so the support address needed its own mail-forwarding rule.</p>
</li>
<li><p><strong>A quick way to diagnose:</strong> list the emails on the provider's API. An empty list proves your app never reached the provider, which rules out spam filters and DNS.</p>
</li>
</ul>
<h2>Bonus: link previews need an absolute image URL</h2>
<p>X and Facebook showed a grey card because <code>og:image</code> was a relative path (<code>/og-image.png</code>). It must be a full <code>https://</code> URL, and <code>twitter:card</code> should be <code>summary_large_image</code>. The image should be 1200×630.</p>
<h2>Can you help me test it?</h2>
<p>The app is live at <a href="https://flaavo.app"><strong>flaavo.app</strong></a> and is still early. If you have ten minutes, I would value your review, especially of:</p>
<ul>
<li><p>search in Kurdish, Arabic or Turkish</p>
</li>
<li><p>right-to-left (RTL) layout on small screens</p>
</li>
<li><p>installing the app on iPhone or Android</p>
</li>
<li><p>sign-up emails</p>
</li>
<li><p>any errors in the browser console</p>
</li>
</ul>
<p>Please send bugs and suggestions to <strong><a href="mailto:support@flaavo.app">support@flaavo.app</a></strong>. Include the steps to reproduce the problem, your device and browser, and a screenshot. If you find a security issue, please report it privately.</p>
<p>Thanks for reading. I'm happy to answer questions in the comments.</p>
]]></content:encoded></item><item><title><![CDATA[Step-by-Step Guide to GPU Setup for Machine Learning & Deep Learning!]]></title><description><![CDATA[Hello everyone, and welcome to this tutorial on how to use your GPU for AI tasks, including machine learning and deep learning, instead of relying on your…]]></description><link>https://smartrs.hashnode.dev/step-by-step-guide-to-gpu-setup-for-machine-learning-deep-learning</link><guid isPermaLink="true">https://smartrs.hashnode.dev/step-by-step-guide-to-gpu-setup-for-machine-learning-deep-learning</guid><category><![CDATA[AI]]></category><category><![CDATA[ML]]></category><category><![CDATA[GPU]]></category><category><![CDATA[Python]]></category><category><![CDATA[Jupyter Notebook ]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Wed, 15 Jan 2025 21:03:15 GMT</pubDate><content:encoded><![CDATA[<p>Hello everyone, and welcome to this tutorial on how to use your GPU for AI tasks, including machine learning and deep learning, instead of relying on your CPU. Using a GPU can significantly accelerate computations, especially for deep learning models. Let's get started step by step.</p>
<hr />
<p><strong>Step 1: Create a New Environment and Install Required Packages</strong></p>
<p>First, open the Anaconda Prompt and create a new environment with TensorFlow GPU support. Use the following command:</p>
<p><code>conda create –n tf-GPU tensorflow-gpu</code></p>
<p>This will create a new environment named tf-GPU with the necessary TensorFlow GPU version installed.</p>
<hr />
<p><strong>Step 2: Activate the New Environment</strong></p>
<p>Activate the newly created environment by typing:</p>
<p><code>conda activate tf-GPU</code></p>
<p>This ensures all your installations and tasks are isolated to this environment.</p>
<hr />
<p><strong>Step 3: Install TensorFlow 2.10</strong></p>
<p>TensorFlow 2.10 is compatible with many GPUs. Install it using:</p>
<p><code>python -m pip install "tensorflow==2.10.0"</code></p>
<hr />
<p><strong>Step 4: Install the Jupyter Kernel for This Environment</strong></p>
<p>To use this environment in Jupyter Notebook, run the following commands:</p>
<p><code>pip install ipykernel</code></p>
<p><code>python -m ipykernel install --user --name=tf-GPU --display-name "Python (tf-GPU)"</code></p>
<p>This makes the tf-GPU environment available as a kernel in Jupyter Notebook.</p>
<hr />
<p><strong>Step 5: Open Jupyter Notebook</strong></p>
<p>Now, open Jupyter Notebook:</p>
<p><code>jupyter notebook</code></p>
<p>In Jupyter, go to the <strong>Kernel</strong> menu, select <strong>Change Kernel</strong>, and choose <strong>Python (tf-GPU)</strong>.</p>
<hr />
<p><strong>Step 6: Verify GPU Availability in Jupyter Notebook</strong></p>
<p>To check if TensorFlow recognizes your GPU, run the following code:</p>
<p><code>import tensorflow as tf</code></p>
<p><code>print("GPU Details:", tf.config.list_physical_devices('GPU'))</code></p>
<p>This should display details of your GPU.</p>
<hr />
<p><strong>Step 7: First Example - Comparing CPU and GPU Performance</strong></p>
<p>Here’s a simple example to compare the time taken for matrix multiplication on GPU and CPU:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
<span class="hljs-keyword">import</span> time

<span class="hljs-comment"># Check available GPU</span>
print(<span class="hljs-string">"Available GPU:"</span>, tf.config.list_physical_devices(<span class="hljs-string">'GPU'</span>))

<span class="hljs-comment"># Create large random matrices</span>
matrix_size = <span class="hljs-number">10000</span>
a = tf.random.normal((matrix_size, matrix_size))
b = tf.random.normal((matrix_size, matrix_size))

<span class="hljs-comment"># Perform matrix multiplication on GPU</span>
start_time = time.time()
c = tf.matmul(a, b)
end_time = time.time()
print(<span class="hljs-string">f"Matrix multiplication on GPU completed in <span class="hljs-subst">{end_time - start_time:<span class="hljs-number">.4</span>f}</span> seconds"</span>)

<span class="hljs-comment"># Perform matrix multiplication on CPU</span>
<span class="hljs-keyword">with</span> tf.device(<span class="hljs-string">'/CPU:0'</span>):
    start_time = time.time()
    c_cpu = tf.matmul(a, b)
    end_time = time.time()
    print(<span class="hljs-string">f"Matrix multiplication on CPU completed in <span class="hljs-subst">{end_time - start_time:<span class="hljs-number">.4</span>f}</span> seconds"</span>)
</code></pre>
<hr />
<p><strong>Step 8: Second Example - Training a Neural Network Using the GPU</strong></p>
<p>Let’s now train a simple neural network on the MNIST dataset using the GPU:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
<span class="hljs-keyword">from</span> tensorflow.keras.datasets <span class="hljs-keyword">import</span> mnist
<span class="hljs-keyword">from</span> tensorflow.keras.models <span class="hljs-keyword">import</span> Sequential
<span class="hljs-keyword">from</span> tensorflow.keras.layers <span class="hljs-keyword">import</span> Dense, Flatten
<span class="hljs-keyword">from</span> tensorflow.keras.optimizers <span class="hljs-keyword">import</span> Adam

<span class="hljs-comment"># Load MNIST dataset</span>
(x_train, y_train), (x_test, y_test) = mnist.load_data()

<span class="hljs-comment"># Normalize the data (scale pixel values to 0-1)</span>
x_train, x_test = x_train / <span class="hljs-number">255.0</span>, x_test / <span class="hljs-number">255.0</span>

<span class="hljs-comment"># Build a simple neural network model</span>
model = Sequential([
    Flatten(input_shape=(<span class="hljs-number">28</span>, <span class="hljs-number">28</span>)),  <span class="hljs-comment"># Flatten 28x28 images into 1D vectors</span>
    Dense(<span class="hljs-number">128</span>, activation=<span class="hljs-string">'relu'</span>), <span class="hljs-comment"># First dense layer with 128 units</span>
    Dense(<span class="hljs-number">10</span>, activation=<span class="hljs-string">'softmax'</span>) <span class="hljs-comment"># Output layer with 10 classes (digits 0-9)</span>
])

<span class="hljs-comment"># Compile the model</span>
model.compile(optimizer=Adam(),
              loss=<span class="hljs-string">'sparse_categorical_crossentropy'</span>,
              metrics=[<span class="hljs-string">'accuracy'</span>])

<span class="hljs-comment"># Train the model</span>
model.fit(x_train, y_train, epochs=<span class="hljs-number">10</span>, batch_size=<span class="hljs-number">32</span>, validation_data=(x_test, y_test))

<span class="hljs-comment"># Evaluate the model on the test set</span>
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=<span class="hljs-number">2</span>)
print(<span class="hljs-string">f"Test Accuracy: <span class="hljs-subst">{test_accuracy:<span class="hljs-number">.4</span>f}</span>"</span>)
</code></pre>
<p><strong>Summary</strong></p>
<p>In this tutorial, we learned how to set up a GPU-enabled TensorFlow environment, verify GPU usage, and perform computations using TensorFlow. We also compared GPU and CPU performance and trained a simple neural network using the GPU. By leveraging GPUs, you can significantly speed up your AI tasks and focus on building better models faster.</p>
<p>For a more comprehensive learning experience, check out my Udemy course: <a target="_blank" href="https://www.udemy.com/course/ai-for-geospatial-analysis/?referralCode=756925DC2106C34C6DBE">AI for Geospatial Analysis</a>. This course dives deeper into AI and machine learning applications for geospatial data analysis.</p>
]]></content:encoded></item><item><title><![CDATA[Unlock the Power of Programming for Scientific Research with Python and R]]></title><description><![CDATA[Scientific research is evolving, and the tools you use can make all the difference. If you're a researcher, data analyst, or student eager to harness the…]]></description><link>https://smartrs.hashnode.dev/unlock-the-power-of-programming-for-scientific-research-with-python-and-r</link><guid isPermaLink="true">https://smartrs.hashnode.dev/unlock-the-power-of-programming-for-scientific-research-with-python-and-r</guid><category><![CDATA[Python]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[udemy]]></category><category><![CDATA[learning]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sun, 07 Jul 2024 14:09:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724479004848/2e707ca2-3e27-4af4-af09-65e36bc114eb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-are-you-ready-to-revolutionize-your-research">Are You Ready to Revolutionize Your Research?</h3>
<p>Scientific research is evolving, and the tools you use can make all the difference. If you're a researcher, data analyst, or student eager to harness the power of programming for your projects, our Udemy course, <a target="_blank" href="https://www.udemy.com/course/programming-for-scientific-research/?referralCode=6B1CDFAB54BF528832BF"><strong>Programming for Scientific Research with Python and R</strong></a>, is your ultimate guide.</p>
<h3 id="heading-course-highlights">Course Highlights</h3>
<p>This comprehensive course is meticulously designed to equip you with the programming skills necessary to tackle real-world scientific research challenges. Here's a sneak peek into what you'll learn:</p>
<h4 id="heading-1-introduction-to-programming"><strong>1. Introduction to Programming</strong></h4>
<ul>
<li><p><strong>Python Setup and Basics</strong>: From installing Miniconda and Python 3 to running your first Python program, we cover it all.</p>
</li>
<li><p><strong>R Fundamentals</strong>: Learn how to download R, work with functions, and choose the right language for your research.</p>
</li>
</ul>
<h4 id="heading-2-data-fundamentals"><strong>2. Data Fundamentals</strong></h4>
<ul>
<li><p><strong>Python File Handling</strong>: Manage files and directories seamlessly.</p>
</li>
<li><p><strong>R Data Manipulation</strong>: Import, export, and manipulate data with ease.</p>
</li>
</ul>
<h4 id="heading-3-scientific-computing"><strong>3. Scientific Computing</strong></h4>
<ul>
<li><p><strong>Numerical Libraries</strong>: Dive into NumPy and SciPy for scientific computation in Python.</p>
</li>
<li><p><strong>Statistical Analysis</strong>: Conduct descriptive statistics, correlations, ANOVA, and more in R.</p>
</li>
</ul>
<h4 id="heading-4-data-visualization"><strong>4. Data Visualization</strong></h4>
<ul>
<li><p><strong>Plotting with Python and R</strong>: Create stunning visualizations, from basic plots to advanced, animated graphs.</p>
</li>
<li><p><strong>Reporting</strong>: Learn to generate comprehensive reports in R.</p>
</li>
</ul>
<h4 id="heading-5-artificial-intelligence"><strong>5. Artificial Intelligence</strong></h4>
<ul>
<li><strong>AI Fundamentals</strong>: Get introduced to AI and learn how to process geospatial data and implement deep learning in both Python and R.</li>
</ul>
<h4 id="heading-6-case-studies-in-scientific-research"><strong>6. Case Studies in Scientific Research</strong></h4>
<ul>
<li><strong>Real-World Applications</strong>: Apply your skills to case studies such as analyzing India's air quality data, climate data analysis, and calculating remote sensing indices.</li>
</ul>
<h3 id="heading-why-choose-this-course">Why Choose This Course?</h3>
<ul>
<li><p><strong>Hands-On Learning</strong>: Engage with practical exercises, quizzes, and real-world case studies.</p>
</li>
<li><p><strong>Expert Guidance</strong>: Benefit from the insights and experience of seasoned instructors.</p>
</li>
<li><p><strong>Comprehensive Content</strong>: From programming basics to advanced AI applications, this course covers everything you need to know.</p>
</li>
</ul>
<h3 id="heading-join-a-community-of-learners">Join a Community of Learners</h3>
<p>By enrolling in this course, you'll join a vibrant community of learners. Share your progress, seek help, and collaborate with peers to enhance your learning experience.</p>
<h3 id="heading-enroll-today">Enroll Today!</h3>
<p>Don't miss the opportunity to elevate your research capabilities. Enroll in <strong>Programming for Scientific Research with Python and R</strong> today and take the first step towards mastering the tools that are shaping the future of scientific research.</p>
<p><a class="post-section-overview" href="#">Enroll Now on Udemy</a></p>
<h3 id="heading-about-the-instructor">About the Instructor</h3>
<p>Our instructor has extensive experience in scientific research and programming. They are dedicated to helping you succeed in your research endeavors by providing clear, concise, and practical instruction.</p>
<h3 id="heading-testimonials">Testimonials</h3>
<p>"An excellent course that bridges the gap between programming and scientific research. Highly recommended!" - Student Review</p>
<p>"Comprehensive and practical. It’s exactly what I needed for my research projects." - Student Review</p>
<h3 id="heading-get-in-touch">Get in Touch</h3>
<p>Have questions? Feel free to reach out to us. We're here to help you on your learning journey.</p>
<hr />
<p>Unlock the potential of programming in your scientific research today. Transform your data, gain new insights, and advance your career with our Udemy course.</p>
<p><a target="_blank" href="https://www.udemy.com/course/programming-for-scientific-research/?referralCode=6B1CDFAB54BF528832BF">Enroll Now</a></p>
<p><a target="_blank" href="https://www.udemy.com/course/programming-for-scientific-research/?referralCode=6B1CDFAB54BF528832BF">https://www.udemy.com/course/programming-for-scientific-research/?referralCode=6B1CDFAB54BF528832BF</a></p>
]]></content:encoded></item><item><title><![CDATA[Unlock the Power of Python for Scientific Research with Our Comprehensive Udemy Course!]]></title><description><![CDATA[Are you a researcher, scientist, or student looking to leverage the power of Python for your scientific endeavors? Look no further! Our Udemy course…]]></description><link>https://smartrs.hashnode.dev/unlock-the-power-of-python-for-scientific-research-with-our-comprehensive-udemy-course</link><guid isPermaLink="true">https://smartrs.hashnode.dev/unlock-the-power-of-python-for-scientific-research-with-our-comprehensive-udemy-course</guid><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[udemy]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sun, 07 Jul 2024 14:03:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724478971045/8619ea45-f2e8-4402-9b5f-cf164f8afe3a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Are you a researcher, scientist, or student looking to leverage the power of Python for your scientific endeavors? Look no further! Our Udemy course, <strong>"</strong><a target="_blank" href="https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7"><strong>Python for Scientific Research</strong></a><strong>"</strong>, is designed to equip you with the essential skills and knowledge needed to excel in your field.</p>
<h4 id="heading-why-enroll-in-this-course">Why Enroll in This Course?</h4>
<p>Python has become the go-to programming language for scientific research due to its simplicity, versatility, and powerful libraries. This course offers a structured and comprehensive approach to mastering Python for various scientific applications. Here’s what you can expect:</p>
<h4 id="heading-course-highlights">Course Highlights</h4>
<ol>
<li><p><strong>Getting Started with Python</strong></p>
<ul>
<li><p>Learn how to install Miniconda and Python 3 on Windows.</p>
</li>
<li><p>Understand how to create environments and install packages.</p>
</li>
<li><p>Get hands-on with Jupyter Notebook, an essential tool for scientific computing.</p>
</li>
</ul>
</li>
<li><p><strong>Python Programming Fundamentals</strong></p>
<ul>
<li><p>Master the basics of running Python programs.</p>
</li>
<li><p>Explore different data types, control flow, functions, and modules in Python.</p>
</li>
<li><p>Test your knowledge with quizzes designed to reinforce learning.</p>
</li>
</ul>
</li>
<li><p><strong>File Handling</strong></p>
<ul>
<li><p>Learn the ins and outs of file handling and directory management in Python.</p>
</li>
<li><p>Practical exercises to ensure you can manage files efficiently in your research projects.</p>
</li>
</ul>
</li>
<li><p><strong>Statistics and Scientific Computation</strong></p>
<ul>
<li><p>Dive into scientific computation using libraries like NumPy and SciPy.</p>
</li>
<li><p>Gain expertise in statistical analysis and zonal statistics with Python.</p>
</li>
</ul>
</li>
<li><p><strong>Plotting in Python</strong></p>
<ul>
<li><p>Create stunning visualizations using popular libraries such as Matplotlib and Seaborn.</p>
</li>
<li><p>Develop skills to effectively communicate your research findings through graphs and plots.</p>
</li>
</ul>
</li>
<li><p><strong>Geospatial Artificial Intelligence</strong></p>
<ul>
<li><p>Get introduced to processing geospatial data and applying artificial intelligence techniques.</p>
</li>
<li><p>Explore practical applications like the FourCastNet global weather emulator.</p>
</li>
</ul>
</li>
<li><p><strong>Case Studies</strong></p>
<ul>
<li><p>Apply what you've learned in real-world scenarios.</p>
</li>
<li><p>Analyze India's air quality data, perform climate data analysis, and calculate remote sensing indices.</p>
</li>
</ul>
</li>
</ol>
<h4 id="heading-who-should-enroll">Who Should Enroll?</h4>
<ul>
<li><p><strong>Researchers and Scientists:</strong> Enhance your data analysis and visualization capabilities.</p>
</li>
<li><p><strong>Students:</strong> Gain a competitive edge in your academic pursuits.</p>
</li>
<li><p><strong>Professionals:</strong> Apply Python skills to real-world scientific problems.</p>
</li>
</ul>
<h4 id="heading-course-benefits">Course Benefits</h4>
<ul>
<li><p><strong>Hands-on Learning:</strong> Interactive lectures and practical exercises.</p>
</li>
<li><p><strong>Quizzes and Assignments:</strong> Reinforce your learning and test your understanding.</p>
</li>
<li><p><strong>Real-world Applications:</strong> Case studies that connect theory with practice.</p>
</li>
<li><p><strong>Lifetime Access:</strong> Learn at your own pace with lifetime access to course materials.</p>
</li>
</ul>
<h4 id="heading-join-us-today">Join Us Today!</h4>
<p>Don’t miss out on the opportunity to advance your scientific research skills with Python. Enroll now in <strong>"</strong><a target="_blank" href="https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7"><strong><mark>Python for Scientific Research</mark></strong></a><strong>"</strong> on Udemy and take the first step towards transforming your research with the power of Python.</p>
<p><a target="_blank" href="https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7"><strong>Enroll Now</strong></a></p>
<hr />
<p>Elevate your research capabilities with our expertly designed curriculum and hands-on approach. We look forward to seeing you in the course!</p>
<p><a target="_blank" href="https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7">https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7</a></p>
]]></content:encoded></item><item><title><![CDATA[Unlock the Power of R Programming for Research: Join Our Comprehensive Udemy Course!]]></title><description><![CDATA[Are you ready to elevate your research skills with the robust and versatile R programming language? Look no further! Our new Udemy course, "How To Use R…]]></description><link>https://smartrs.hashnode.dev/unlock-the-power-of-r-programming-for-research-join-our-comprehensive-udemy-course</link><guid isPermaLink="true">https://smartrs.hashnode.dev/unlock-the-power-of-r-programming-for-research-join-our-comprehensive-udemy-course</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[R Programming]]></category><category><![CDATA[udemy]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sun, 07 Jul 2024 13:55:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724479363595/c060d7c8-88a3-4149-9a18-8e04b57214e4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Are you ready to elevate your research skills with the robust and versatile R programming language? Look no further! Our new Udemy course, <strong>"</strong><a target="_blank" href="https://www.udemy.com/course/r-for-research/?referralCode=B6DCFDE343F0592EA61A"><strong>How To Use R Programming for Research</strong></a><strong>,"</strong> is meticulously designed to equip you with the essential tools and knowledge to excel in your research projects.</p>
<h3 id="heading-course-highlights">Course Highlights:</h3>
<p><strong>1. R Programming Fundamentals</strong></p>
<ul>
<li><p><strong>Course Script and Download R:</strong> Start with a comprehensive guide on setting up R.</p>
</li>
<li><p><strong>Functions in R Programming:</strong> Learn to create and utilize functions effectively.</p>
</li>
<li><p><strong>Packages in R Programming:</strong> Discover how to leverage R's extensive package ecosystem.</p>
</li>
<li><p><strong>Working Directory:</strong> Understand and manage your working environment in R.</p>
</li>
</ul>
<p><strong>2. Dealing with Data in R</strong></p>
<ul>
<li><p><strong>Data Types:</strong> Explore different data types and their applications.</p>
</li>
<li><p><strong>Importing Data:</strong> Master the art of importing data from various sources.</p>
</li>
<li><p><strong>Prepare and Download Annual Weather Data with R:</strong> Practical exercise on handling real-world data.</p>
</li>
<li><p><strong>Exporting Data:</strong> Learn techniques for exporting your processed data.</p>
</li>
<li><p><strong>Data Manipulation:</strong> Dive deep into data wrangling and transformation.</p>
</li>
</ul>
<p><strong>3. Statistics for Research in R</strong></p>
<ul>
<li><p><strong>Descriptive Statistics:</strong> Get a grip on summarizing and describing data.</p>
</li>
<li><p><strong>Correlations:</strong> Understand relationships between variables.</p>
</li>
<li><p><strong>ANOVA:</strong> Learn to perform analysis of variance.</p>
</li>
<li><p><strong>Student’s t.test:</strong> Conduct t-tests to compare means.</p>
</li>
<li><p><strong>Multiple Linear Regression:</strong> Apply regression techniques to model data.</p>
</li>
</ul>
<p><strong>4. AI in R Programming</strong></p>
<ul>
<li><p><strong>Introduction to Deep Learning in R Programming:</strong> Two-part series introducing you to the exciting world of AI.</p>
</li>
<li><p><strong>Introduction to AI in R:</strong> Get started with artificial intelligence concepts and applications.</p>
</li>
</ul>
<p><strong>5. Create Graphs for Research in R</strong></p>
<ul>
<li><p><strong>Create a Report:</strong> Learn to compile your findings into a professional report.</p>
</li>
<li><p><strong>Wind Rose Plots for Different Time Periods in R:</strong> Visualize wind data with specialized plots.</p>
</li>
<li><p><strong>Basic Plotting:</strong> Start with the basics of creating graphs.</p>
</li>
<li><p><strong>Advanced and Animated Graphs:</strong> Take your visualization skills to the next level with advanced and dynamic graphs.</p>
</li>
</ul>
<h3 id="heading-why-enroll-in-this-course">Why Enroll in This Course?</h3>
<ul>
<li><p><strong>Interactive Learning:</strong> Engage with quizzes, coding exercises, and practical activities to reinforce your understanding.</p>
</li>
<li><p><strong>Expert Guidance:</strong> Benefit from clear, step-by-step instructions and expert insights.</p>
</li>
<li><p><strong>Comprehensive Curriculum:</strong> Covering everything from basic R programming to advanced statistical analysis and AI applications.</p>
</li>
<li><p><strong>Real-World Applications:</strong> Apply what you learn to real-world research scenarios, making your work more impactful and efficient.</p>
</li>
</ul>
<h3 id="heading-bonus-content">Bonus Content:</h3>
<ul>
<li><p><strong>Extra Resources:</strong> Access additional materials to deepen your knowledge.</p>
</li>
<li><p><strong>Community Support:</strong> Join a vibrant community of learners and researchers to share insights and get support.</p>
</li>
</ul>
<p>Whether you are a student, researcher, or data enthusiast, <a target="_blank" href="https://www.udemy.com/course/r-for-research/?referralCode=B6DCFDE343F0592EA61A">this course</a> is tailored to help you harness the full potential of R programming for your research endeavors. Don't miss out on this opportunity to boost your skills and advance your career!</p>
<p><strong>Enroll today and start your journey towards mastering R programming for research!</strong></p>
<p><a target="_blank" href="https://www.udemy.com/course/r-for-research/?referralCode=B6DCFDE343F0592EA61A">https://www.udemy.com/course/r-for-research/?referralCode=B6DCFDE343F0592EA61A</a></p>
]]></content:encoded></item><item><title><![CDATA[Comparison of Different ML Classifiers on Synthetic Dataset]]></title><description><![CDATA[Hello everyone! In this lesson, we will compare different machine learning classifiers on a synthetic dataset using Python. First, let's import the…]]></description><link>https://smartrs.hashnode.dev/comparison-of-different-ml-classifiers-on-synthetic-dataset</link><guid isPermaLink="true">https://smartrs.hashnode.dev/comparison-of-different-ml-classifiers-on-synthetic-dataset</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Python]]></category><category><![CDATA[classification]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Fri, 14 Jun 2024 22:07:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724479581908/4009db5c-a8b3-4113-b38d-d9e0ae97ee58.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone! In this lesson, we will compare different machine learning classifiers on a synthetic dataset using Python.</p>
<p>First, let's import the necessary <strong>libraries.</strong> We will use <code>matplotlib</code> for plotting, <code>numpy</code> for numerical operations, and <code>sklearn</code> for machine learning functions.</p>
<pre><code class="language-python"># Importing necessary libraries
import matplotlib.pyplot as plt  # Library for plotting
import numpy as np  # Library for numerical operations
from sklearn.ensemble import RandomForestClassifier
from matplotlib.colors import ListedColormap  # For customizing colormap
from sklearn.datasets import make_classification  # For generating synthetic datasets
from sklearn.inspection import DecisionBoundaryDisplay  # For displaying decision boundaries
from sklearn.model_selection import train_test_split  # For splitting dataset into train and test sets
from sklearn.neighbors import KNeighborsClassifier  # k-Nearest Neighbors classifier
from sklearn.neural_network import MLPClassifier  # Multi-layer Perceptron classifier
from sklearn.pipeline import make_pipeline  # For creating a pipeline of transformers and estimators
from sklearn.preprocessing import StandardScaler  # For standardizing features
from sklearn.tree import DecisionTreeClassifier  # Decision Tree classifier
</code></pre>
<p>Next, we will create a <strong>list of classifier names</strong>. These are "Nearest Neighbors," "Decision Tree," "Random Forest," and "Neural Net."</p>
<p>We will also create a list of classifiers. For this, we will use k-Nearest Neighbors with k=3, Decision Tree with a max depth of 5, Random Forest with a max depth of 5 and 10 estimators, and a Multi-layer Perceptron.</p>
<pre><code class="language-python"># List of classifier names
names = [
    "Nearest Neighbors",
    "Decision Tree",
    "Random Forest",
    "Neural Net"
]

# List of classifiers
classifiers = [
    KNeighborsClassifier(3),  # k-Nearest Neighbors with k=3
    DecisionTreeClassifier(max_depth=5, random_state=42),  # Decision Tree Classifier with max depth of 5
    RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1, random_state=42),  # Random Forest Classifier
    MLPClassifier(alpha=1, max_iter=1000, random_state=42)  # Multi-layer Perceptron Classifier
]
</code></pre>
<p>Now, let's <strong>generate a complex synthetic dataset</strong> with 1000 samples and 20 features. We will add some noise to the dataset to make it more interesting.</p>
<pre><code class="language-python"># Generating a complex synthetic dataset
X, y = make_classification(
    n_samples=1000,  # Number of samples in the dataset
    n_features=20,  # Number of features in the dataset
    n_redundant=2,  # Number of redundant features
    n_informative=10,  # Number of informative features
    n_clusters_per_class=2,  # Number of clusters per class
    random_state=1  # Random seed for reproducibility
)
rng = np.random.RandomState(2)
X += 2 * rng.uniform(size=X.shape)  # Adding noise to the dataset
</code></pre>
<p>We will only use the first two features for visualization. We will <strong>split the dataset</strong> into training and testing sets, with 40% of the data used for testing.</p>
<pre><code class="language-python"># Using only the first two features for visualization
X = X[:, :2]

# Splitting the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.4, random_state=42
)
</code></pre>
<p>Next, we will <strong>create a figure for plotting the data</strong>. We will set the range for the x and y axes based on the dataset values. We will plot the dataset using red and blue colors for different classes.</p>
<p>We will then iterate over the classifiers. For each classifier, we will create a pipeline with a standard scaler and the classifier. We will fit the classifier on the training data and calculate the accuracy score on the test data.</p>
<p>We will plot the decision boundaries for each classifier. We will also plot the training and testing points on the same plot.</p>
<p>Finally, we will adjust the layout and display the plot.</p>
<pre><code class="language-python"># Creating a figure for plotting
figure = plt.figure(figsize=(18, 6))
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5

# Plotting the dataset
cm = plt.cm.RdBu
cm_bright = ListedColormap(["#FF0000", "#0000FF"])
ax = plt.subplot(1, len(classifiers) + 1, 1)
ax.set_title("Input data")
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k")
ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6, edgecolors="k")
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xticks(())
ax.set_yticks(())

# Iterate over classifiers
for i, (name, clf) in enumerate(zip(names, classifiers), start=2):
    ax = plt.subplot(1, len(classifiers) + 1, i)

    # Constructing a pipeline with standard scaler and the classifier
    clf = make_pipeline(StandardScaler(), clf)
    # Fitting the classifier
    clf.fit(X_train, y_train)
    # Calculating the accuracy score
    score = clf.score(X_test, y_test)
    # Plotting decision boundaries
    DecisionBoundaryDisplay.from_estimator(
        clf, X, cmap=cm, alpha=0.8, ax=ax, eps=0.5
    )

    # Plotting training and testing points
    ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k")
    ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, edgecolors="k", alpha=0.6)

    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_max)
    ax.set_xticks(())
    ax.set_yticks(())
    ax.set_title(name)
    # Adding accuracy score as text on each subplot
    ax.text(x_max - 0.3, y_min + 0.3, ("%.2f" % score).lstrip("0"), size=15, horizontalalignment="right")

# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1718402720856/8b5326d6-652d-4cef-97f5-b14d03bc2571.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Results:</strong> Our analysis of the classifier performance reveals that the Neural Net emerged victorious, achieving an impressive accuracy of 81% on the test data. This suggests that the Neural Net was more adept at capturing the intricate patterns within the data compared to the other classifiers.</p>
<p>Following closely behind was the Decision Tree classifier, boasting an accuracy of 80%. Meanwhile, the Nearest Neighbors and Random Forest classifiers achieved slightly lower accuracies of 76% and 79%, respectively.</p>
]]></content:encoded></item><item><title><![CDATA[Calculating Common Remote Sensing Indices in Python]]></title><description><![CDATA[Hey there! Today, we're diving into some Python code to analyze satellite imagery. We'll be using data from Landsat, specifically focusing on a location…]]></description><link>https://smartrs.hashnode.dev/calculating-common-remote-sensing-indices-in-python</link><guid isPermaLink="true">https://smartrs.hashnode.dev/calculating-common-remote-sensing-indices-in-python</guid><category><![CDATA[#RemoteSensing]]></category><category><![CDATA[Python]]></category><category><![CDATA[index]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sun, 12 May 2024 07:57:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724479684824/8572af3a-26a4-4650-abfc-66f4ab2f5371.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there! Today, we're diving into some Python code to analyze satellite imagery. We'll be using data from Landsat, specifically focusing on a location near Erbil, the capital of the Kurdistan Region of Iraq.</p>
<h3>Import necessary libraries</h3>
<pre><code class="language-python">import rasterio  # Library for reading and writing raster data
import matplotlib.pyplot as plt  # Plotting library
</code></pre>
<p>First off, we'll access the satellite data stored on Google Cloud. Landsat imagery is organized by paths and rows, and for our analysis, we're interested in Landsat Path 168 and Row 35.</p>
<p>We'll grab the necessary bands from Landsat: the Red, Near Infrared (NIR), and Shortwave Infrared (SWIR) bands. These bands are essential for calculating various indices like NDVI (Normalized Difference Vegetation Index), NDBI (Normalized Difference Built-up Index), and NDWI (Normalized Difference Water Index).</p>
<pre><code class="language-python">url = "https://storage.googleapis.com/gcp-public-data-landsat/LC08/"+\
       "01/168/035/LC08_L1TP_168035_20170923_20171013_01_T1/"
# The url variable holds the base URL for Landsat data on Google Cloud Storage.

redband = 'LC08_L1TP_168035_20170923_20171013_01_T1_B{}.TIF'.format(4)
nirband = 'LC08_L1TP_168035_20170923_20171013_01_T1_B{}.TIF'.format(5)
swirband = 'LC08_L1TP_168035_20170923_20171013_01_T1_B{}.TIF'.format(6)
</code></pre>
<pre><code class="language-python">with rasterio.open(url+redband) as src:
    redImage = src.read(1).astype('f4')
# rasterio.open(url+redband) as src: This line opens the raster file specified by the URL concatenated
# with the redband variable. The redband variable typically contains the filename of
# the red band image. The with statement ensures that the raster file is properly closed after use.
# The raster data is read from band 1 (read(1)) and converted to a floating-point array (astype('f4')).
# The resulting array is stored in the redImage variable.

with rasterio.open(url+nirband) as src:
    nirImage = src.read(1).astype('f4')

with rasterio.open(url+swirband) as src:
    swirImage = src.read(1).astype('f4')
</code></pre>
<p>Once we have our bands, we'll calculate NDVI, NDBI, and NDWI. These indices help us understand vegetation, built-up areas, and water bodies in the satellite imagery.</p>
<h3>Normalized Difference Vegetation Index (NDVI)</h3>
<pre><code class="language-python">def calc_ndvi(nir, red):
    '''Calculate NDVI from integer arrays'''
    ndvi = (nir - red) / (nir + red) # This line calculates the NDVI using the formula: (NIR - Red) / (NIR + Red).
    return ndvi

# Apply a function
ndvi = calc_ndvi(nirImage, redImage)

# Display NDVI
plt.imshow(ndvi, cmap='RdYlGn')
plt.colorbar()
plt.title("NDVI", fontsize=20)
plt.xlabel('Column #')
plt.ylabel('Row #')
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715500052112/61cd9c12-5ff1-460e-96fe-5eeeb5afdf3c.png" alt="" style="display:block;margin:0 auto" />

<h3>Normalized Difference Built-up Index (NDBI)</h3>
<pre><code class="language-python">def calc_ndbi(swir,nir):
    '''Calculate NDBI from integer arrays'''
    ndbi = (swir - nir) / (swir + nir)
    return ndbi
# Apply a function
ndbi = calc_ndbi(swirImage,nirImage)

# Display NDBI
plt.imshow(ndbi, cmap='RdYlGn')
plt.colorbar()
plt.title("NDBI", fontsize=20)
plt.xlabel('Column #')
plt.ylabel('Row #')
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715500130566/c01fe795-a691-449d-ba30-ac364f51754c.png" alt="" style="display:block;margin:0 auto" />

<h3>Normalized Difference Water Index (NDWI)</h3>
<pre><code class="language-python"># define a function
def calc_ndwi(nir,swir):
    '''Calculate NDWI from integer arrays'''
    ndwi = (nir - swir) / (nir + swir)
    return ndwi
# Apply a function
ndwi = calc_ndwi(nirImage,swirImage)

# Diasplay NDWI
plt.imshow(ndwi, cmap='RdYlGn')
plt.colorbar()
plt.title("NDWI", fontsize=20)
plt.xlabel('Column #')
plt.ylabel('Row #')
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715500182473/3eedaf62-50ed-4a1e-a7e7-e587664cb0f1.png" alt="" style="display:block;margin:0 auto" />

<p>Now, let's talk about NBR (Normalized Burn Ratio). It's another important index, especially for assessing fire damage. We'll calculate NBR using the NIR and SWIR bands.</p>
<p>After calculating NBR, we'll export it as a GeoTIFF file for further analysis or sharing with others. This file will contain valuable information about burn severity in the area.</p>
<p>Finally, we'll visualize the NBR map to get a clearer picture of the burn severity distribution. This visualization will help us interpret the results and understand the extent of the fire damage.</p>
<h3>Normalized Burn Ratio (NBR) Index</h3>
<pre><code class="language-python"># Define a function
def calc_nbr(nir, swir):
    '''Calculate NBR using NIR and SWIR bands.'''
    nbr = (nir - swir) / (nir + swir)
    return nbr

# Landsat data URL
url = "https://storage.googleapis.com/gcp-public-data-landsat/LC08/"+\
       "01/168/035/LC08_L1TP_168035_20170923_20171013_01_T1/"
nirband = 'LC08_L1TP_168035_20170923_20171013_01_T1_B5.TIF'
swirband = 'LC08_L1TP_168035_20170923_20171013_01_T1_B6.TIF'

# Open NIR and SWIR bands
with rasterio.open(url + nirband) as src_nir, rasterio.open(url + swirband) as src_swir:
    nir = src_nir.read(1).astype('f4')
    swir = src_swir.read(1).astype('f4')

    # Calculate NBR
    nbr = calc_nbr(nir, swir)

    # Export the output to a local GeoTIFF file
    output_file = "nbr_output.tif"
    with rasterio.open(
        output_file,
        'w',
        driver='GTiff',
        width=nir.shape[1],
        height=nir.shape[0],
        count=1,
        dtype=nbr.dtype,
        crs=src_nir.crs,
        transform=src_nir.transform
    ) as dst:
        dst.write(nbr, 1)

    # Display nbr
    plt.imshow(nbr, cmap='RdYlGn')
    plt.colorbar()
    plt.title("NBR", fontsize=20)
    plt.xlabel('Column #')
    plt.ylabel('Row #')
    plt.show()
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715500248068/f95d19d3-0ff4-4686-835a-afbcfdc8c776.png" alt="" style="display:block;margin:0 auto" />

<p>And that's it! By leveraging Python and satellite imagery, we can gain valuable insights into environmental changes and make informed decisions.</p>
]]></content:encoded></item><item><title><![CDATA[Enhance the accuracy of crop classification in Google Earth Engine using the Random Forest]]></title><description><![CDATA[Hello everyone, in today's tutorial, we're going to dive into Random Forest classification. It's a powerful tool in machine learning that helps categorize…]]></description><link>https://smartrs.hashnode.dev/enhance-the-accuracy-of-crop-classification-in-google-earth-engine-using-the-random-forest</link><guid isPermaLink="true">https://smartrs.hashnode.dev/enhance-the-accuracy-of-crop-classification-in-google-earth-engine-using-the-random-forest</guid><category><![CDATA[Google Earth Engine]]></category><category><![CDATA[Random Forest]]></category><category><![CDATA[sentinel]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sun, 05 May 2024 13:43:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724478075173/16d67b51-121f-4fba-9755-ea86b6f8c9e9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone, in today's tutorial, we're going to dive into Random Forest classification. It's a powerful tool in machine learning that helps categorize data into different classes. Let's break it down step by step.</p>
<p><strong>1. Building Decision Trees:</strong> Firstly, the algorithm creates numerous decision trees. Each tree uses a random subset of the training data and features. Think of these trees as a series of questions—like "if this, then that"—that ultimately classify a data point.</p>
<p><strong>2. Introducing Randomness:</strong> Now, why random? Well, by picking different data and features randomly for each tree, we prevent the model from becoming too good at the training data but bad at new data. This randomness helps combat overfitting, a common issue in machine learning.</p>
<p><strong>3. Making Predictions:</strong> Once we've built all the decision trees, a new data point goes through each tree. Each tree then makes its own prediction about which class the data point belongs to. Finally, the most common prediction among all trees becomes the final classification for the new data point.</p>
<p><strong>Advantages:</strong> Let's talk about the pros of Random Forest classification:</p>
<ul>
<li><p><strong>High Accuracy:</strong> It can achieve impressive accuracy on classification tasks.</p>
</li>
<li><p><strong>Robust to Overfitting:</strong> Random forests are great at handling overfitting.</p>
</li>
<li><p><strong>Handles Missing Data:</strong> They can effectively deal with missing data points in the training dataset.</p>
</li>
<li><p><strong>Feature Importance:</strong> The algorithm provides insights into the importance of different features in the classification process.</p>
</li>
</ul>
<p><strong>Disadvantages:</strong> But, like everything, there are drawbacks:</p>
<ul>
<li><p><strong>Black Box Model:</strong> Random forests can be complex, making it tricky to interpret how they make predictions.</p>
</li>
<li><p><strong>High Computational Demands:</strong> Building large random forests requires substantial computer power, especially with big datasets.</p>
</li>
</ul>
<h2 id="heading-enhancing-crop-classification-accuracy-with-gee-a-case-study">Enhancing Crop Classification Accuracy with GEE: A Case Study</h2>
<p>Now, we're diving into some exciting GEE (Google Earth Engine) code used in our recent paper titled "Improving Crop Classification Accuracy with Integrated Sentinel-1 and Sentinel-2 Data: a Case Study of Barley and Wheat", published by me (Azad Rasul, Dr. Gaylan Ibrahim, and Dr. Haidi Abdullah.</p>
<p>If you used the code for your research, please cite our paper as follows: (Faqe Ibrahim, G.R., Rasul, A. and Abdullah, H., 2023. Improving crop classification accuracy with integrated Sentinel-1 and Sentinel-2 data: A case study of barley and wheat. Journal of Geovisualization and Spatial Analysis, 7(2), p.22.)</p>
<p><strong>Let's get started with the code.</strong></p>
<h3 id="heading-sentinel-1-sar"><strong>Sentinel-1 SAR</strong></h3>
<p>First, we'll work with Sentinel-1 SAR (Synthetic Aperture Radar) data. We're specifically loading the C-band SAR Ground Range collection for both VV (vertical-vertical) and VH (vertical-horizontal) polarizations.</p>
<p>We filter these collections based on instrument mode, polarization, orbit direction, resolution, and a region of interest (ROI). Then, we clip the images to our ROI and select the VV or VH bands.</p>
<p>Next, we filter the SAR collections by date, focusing on a specific range. We create mosaics of VV and VH images for this date range.</p>
<p>To visualize these images, we add them as layers to the map. We set center and zoom parameters, then display the SAR VV and VH layers.</p>
<p>Moving on, we apply a filter to reduce speckles in the SAR images. We use a focal mean filter with a specified smoothing radius.</p>
<p>Finally, we add the filtered SAR images as additional layers to the map. This allows us to compare the original and filtered SAR images for both VV and VH polarizations.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//----------------------------------- SAR -----------------------------------</span>
<span class="hljs-comment">// Load Sentinel-1 C-band SAR Ground Range collection (log scale, VV, descending)</span>
<span class="hljs-comment">// roi</span>
<span class="hljs-keyword">var</span> roi = ee.Geometry.Polygon(
  [[[<span class="hljs-number">44.253</span>, <span class="hljs-number">36.569</span>],
    [<span class="hljs-number">44.293</span>, <span class="hljs-number">36.596</span>],
    [<span class="hljs-number">44.367</span>, <span class="hljs-number">36.526</span>],
    [<span class="hljs-number">44.328</span>, <span class="hljs-number">36.5</span>]]], <span class="hljs-literal">null</span>, <span class="hljs-literal">false</span>);
<span class="hljs-keyword">var</span> collectionVV = ee.ImageCollection(<span class="hljs-string">'COPERNICUS/S1_GRD'</span>)
  .filter(ee.Filter.eq(<span class="hljs-string">'instrumentMode'</span>, <span class="hljs-string">'IW'</span>))
  .filter(ee.Filter.listContains(<span class="hljs-string">'transmitterReceiverPolarisation'</span>, <span class="hljs-string">'VV'</span>))
  .filter(ee.Filter.eq(<span class="hljs-string">'orbitProperties_pass'</span>, <span class="hljs-string">'DESCENDING'</span>))
  .filterMetadata(<span class="hljs-string">'resolution_meters'</span>, <span class="hljs-string">'equals'</span> , <span class="hljs-number">10</span>)
  .filterBounds(roi)
  .map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">image</span>)</span>{<span class="hljs-keyword">return</span> image.clip(roi)})
  .select(<span class="hljs-string">'VV'</span>);
print(collectionVV, <span class="hljs-string">'Collection VV'</span>);

<span class="hljs-comment">// Load Sentinel-1 C-band SAR Ground Range collection (log scale, VH, descending)</span>
<span class="hljs-keyword">var</span> collectionVH = ee.ImageCollection(<span class="hljs-string">'COPERNICUS/S1_GRD'</span>)
  .filter(ee.Filter.eq(<span class="hljs-string">'instrumentMode'</span>, <span class="hljs-string">'IW'</span>))
  .filter(ee.Filter.listContains(<span class="hljs-string">'transmitterReceiverPolarisation'</span>, <span class="hljs-string">'VH'</span>))
  .filter(ee.Filter.eq(<span class="hljs-string">'orbitProperties_pass'</span>, <span class="hljs-string">'DESCENDING'</span>))
  .filterMetadata(<span class="hljs-string">'resolution_meters'</span>, <span class="hljs-string">'equals'</span> , <span class="hljs-number">10</span>)
  .filterBounds(roi)
  .map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">image</span>)</span>{<span class="hljs-keyword">return</span> image.clip(roi)})
  .select(<span class="hljs-string">'VH'</span>);
print(collectionVH, <span class="hljs-string">'Collection VH'</span>);

<span class="hljs-comment">// Filter SAR collections by date</span>
<span class="hljs-keyword">var</span> SARVV = collectionVV.filterDate(<span class="hljs-string">'2022-04-19'</span>, <span class="hljs-string">'2022-04-24'</span>).mosaic();
<span class="hljs-keyword">var</span> SARVH = collectionVH.filterDate(<span class="hljs-string">'2022-04-19'</span>, <span class="hljs-string">'2022-04-24'</span>).mosaic();

<span class="hljs-comment">// Add the SAR images to the map for visualization</span>
<span class="hljs-built_in">Map</span>.centerObject(roi, <span class="hljs-number">12</span>);
<span class="hljs-built_in">Map</span>.addLayer(SARVV, {<span class="hljs-attr">min</span>:<span class="hljs-number">-15</span>,<span class="hljs-attr">max</span>:<span class="hljs-number">0</span>}, <span class="hljs-string">'SAR VV'</span>, <span class="hljs-number">0</span>);
<span class="hljs-built_in">Map</span>.addLayer(SARVH, {<span class="hljs-attr">min</span>:<span class="hljs-number">-25</span>,<span class="hljs-attr">max</span>:<span class="hljs-number">0</span>}, <span class="hljs-string">'SAR VH'</span>, <span class="hljs-number">0</span>);

<span class="hljs-comment">// Apply filter to reduce speckle</span>
<span class="hljs-keyword">var</span> SMOOTHING_RADIUS = <span class="hljs-number">50</span>;
<span class="hljs-keyword">var</span> SARVV_filtered = SARVV.focal_mean(SMOOTHING_RADIUS, <span class="hljs-string">'circle'</span>, <span class="hljs-string">'meters'</span>);
<span class="hljs-keyword">var</span> SARVH_filtered = SARVH.focal_mean(SMOOTHING_RADIUS, <span class="hljs-string">'circle'</span>, <span class="hljs-string">'meters'</span>);

<span class="hljs-comment">// Display the filtered SAR images</span>
<span class="hljs-built_in">Map</span>.addLayer(SARVV_filtered, {<span class="hljs-attr">min</span>:<span class="hljs-number">-15</span>,<span class="hljs-attr">max</span>:<span class="hljs-number">0</span>}, <span class="hljs-string">'SAR VV Filtered'</span>,<span class="hljs-number">0</span>);
<span class="hljs-built_in">Map</span>.addLayer(SARVH_filtered, {<span class="hljs-attr">min</span>:<span class="hljs-number">-25</span>,<span class="hljs-attr">max</span>:<span class="hljs-number">0</span>}, <span class="hljs-string">'SAR VH Filtered'</span>,<span class="hljs-number">0</span>);
</code></pre>
<p>And that's it! We've successfully loaded, filtered, and visualized SAR images using Google Earth Engine.</p>
<h3 id="heading-sentinel-2"><strong>Sentinel-2</strong></h3>
<p>Now, let's move on to Sentinel-2A. First, we'll start by masking out clouds and cirrus in Sentinel-2 imagery. This helps us get clearer images for our analysis. We'll use a function called "maskS2clouds" to do this. It selects the quality assessment band, defines cloud and cirrus bits, and creates a mask to indicate clear conditions. Then, we'll load the Sentinel-2 imagery, filter it by date and cloud cover, apply the cloud masking function we just created, and clip it to our region of interest.</p>
<p>Now, let's visualize the Sentinel-2 imagery on the map. We'll set some parameters for better visualization and add the imagery to the map. We can also get some basic information about the imagery by printing it.</p>
<p>Next, we'll take the mean of the Sentinel-2 imagery. This helps us get a clearer picture by reducing noise and variations.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//--------------------------- Sentinel 2 -------------------------</span>
<span class="hljs-comment">// Function to mask clouds and cirrus in Sentinel-2 imagery</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">maskS2clouds</span>(<span class="hljs-params">image</span>) </span>{
  <span class="hljs-keyword">var</span> qa = image.select(<span class="hljs-string">'QA60'</span>);
  <span class="hljs-keyword">var</span> cloudBitMask = <span class="hljs-number">1</span> &lt;&lt; <span class="hljs-number">10</span>;
  <span class="hljs-keyword">var</span> cirrusBitMask = <span class="hljs-number">1</span> &lt;&lt; <span class="hljs-number">11</span>;
  <span class="hljs-keyword">var</span> mask = qa.bitwiseAnd(cloudBitMask).eq(<span class="hljs-number">0</span>)
      .and(qa.bitwiseAnd(cirrusBitMask).eq(<span class="hljs-number">0</span>));
  <span class="hljs-keyword">return</span> image.updateMask(mask).divide(<span class="hljs-number">10000</span>);
}

<span class="hljs-comment">// Load Sentinel-2 imagery, filter by date and cloud cover, apply cloud masking, and clip to the ROI</span>
<span class="hljs-keyword">var</span> image = ee.ImageCollection(<span class="hljs-string">'COPERNICUS/S2_SR'</span>)
              .filterDate(<span class="hljs-string">'2022-05-19'</span>, <span class="hljs-string">'2022-05-22'</span>)
              .filter(ee.Filter.lt(<span class="hljs-string">'CLOUDY_PIXEL_PERCENTAGE'</span>,<span class="hljs-number">5</span>))
              .filterBounds(roi)
              .map(maskS2clouds)
              .map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">image</span>)</span>{<span class="hljs-keyword">return</span> image.clip(roi)});

<span class="hljs-comment">// Visualization parameters for displaying Sentinel-2 imagery</span>
<span class="hljs-keyword">var</span> vis = { <span class="hljs-attr">min</span>: <span class="hljs-number">0.0</span>, <span class="hljs-attr">max</span>: <span class="hljs-number">0.3</span>, <span class="hljs-attr">bands</span>: [<span class="hljs-string">'B4'</span>, <span class="hljs-string">'B3'</span>, <span class="hljs-string">'B2'</span>] };

<span class="hljs-comment">// Add Sentinel-2 imagery to the map</span>
<span class="hljs-built_in">Map</span>.addLayer(image, vis, <span class="hljs-string">"Sentinel2"</span>);

<span class="hljs-comment">// Get information about the Sentinel-2 imagery</span>
print(image, <span class="hljs-string">"Sentinel raw image"</span>);

<span class="hljs-comment">// Take the mean of the Sentinel-2 imagery</span>
<span class="hljs-keyword">var</span> image = image.mean();

<span class="hljs-comment">// Load additional Sentinel-2 imagery for a different date range</span>
<span class="hljs-keyword">var</span> s2BandNames = [<span class="hljs-string">'B2'</span>, <span class="hljs-string">'B3'</span>, <span class="hljs-string">'B4'</span>, <span class="hljs-string">'B7'</span>, <span class="hljs-string">'B8'</span>];
<span class="hljs-keyword">var</span> s2BandRename = [<span class="hljs-string">'blue'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'red_edge'</span>, <span class="hljs-string">'nir'</span>];
<span class="hljs-keyword">var</span> collections2 = ee.ImageCollection(<span class="hljs-string">'COPERNICUS/S2_SR'</span>)
              .filterDate(<span class="hljs-string">'2022-05-19'</span>, <span class="hljs-string">'2022-05-22'</span>)
              .filter(ee.Filter.lt(<span class="hljs-string">'CLOUDY_PIXEL_PERCENTAGE'</span>,<span class="hljs-number">05</span>))
              .select(s2BandNames, s2BandRename)
              .filterBounds(roi)
              .map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">image</span>)</span>{<span class="hljs-keyword">return</span> image.clip(roi)});

print(image, <span class="hljs-string">"Sentinel raw image"</span>);
<span class="hljs-keyword">var</span> image = collections2.mean();
</code></pre>
<p>After processing the imagery, we move on to calculate the Normalized Difference Vegetation Index (NDVI) from the Sentinel-2 data. NDVI is a key metric for assessing vegetation health and density. We'll use the Near Infrared (NIR) and Red bands to compute NDVI. Then, we'll create a composite image that includes all the Sentinel-2 bands along with the calculated NDVI.</p>
<p>To display these images, we add them as layers on the map. This allows us to visually inspect both the Sentinel-2 composite and the NDVI layer simultaneously, aiding in our analysis.</p>
<p>Now, let's center the map on our region of interest with a zoom level of 13. This gives us a closer look at the area we're studying, making it easier to interpret the results.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//---------------------------------- Calculate NDVI ------------------------------</span>
<span class="hljs-keyword">var</span> s2ndvi = image.normalizedDifference([<span class="hljs-string">'nir'</span>, <span class="hljs-string">'red'</span>]); 
<span class="hljs-keyword">var</span> comp = collections2.mean();
<span class="hljs-keyword">var</span> ndvi = comp.normalizedDifference([<span class="hljs-string">'nir'</span>, <span class="hljs-string">'red'</span>]).rename(<span class="hljs-string">'NDVI'</span>);
<span class="hljs-keyword">var</span> composite = ee.Image.cat(comp, ndvi);

<span class="hljs-built_in">Map</span>.centerObject(roi, <span class="hljs-number">13</span>);
</code></pre>
<p><strong>Create FeatureCollection representing different land cover types</strong></p>
<p>Now, let's delve into SAR Classification. We'll start by merging various feature collections representing different land cover types into one cohesive collection. This merged collection, named "newfc," will serve as our reference for training the classifier.</p>
<p>Next, we'll define the SAR (Synthetic Aperture Radar) bands to train the data. By combining the filtered SAR images (SARVV_filtered and SARVH_filtered) into one image called "final," we create a comprehensive dataset for classification. The selected bands for training are 'VH' and 'VV'.</p>
<p>To train our Random Forest classifier, we'll sample regions from the merged feature collection and assign random columns. These sampled regions are then split into training and validation datasets.</p>
<p>With the training data prepared, we proceeded to train the Random Forest classifier using the training dataset. This classifier is then applied to the SAR data to perform the classification. We'll visualize the classified SAR image on the map, showing different land cover types with distinct colors.</p>
<p>Additionally, we'll classify the validation data to evaluate the <strong>accuracy of our classification process.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">//----------------------------- SAR Classification ------------------------------</span>
<span class="hljs-keyword">var</span> newfc = wheat.merge(barley).merge(Uncultivate_land).merge(Road_airport).merge(bareland).merge(grassland);
<span class="hljs-keyword">var</span> final = ee.Image.cat(SARVV_filtered, SARVH_filtered);
<span class="hljs-keyword">var</span> bands = [<span class="hljs-string">'VH'</span>, <span class="hljs-string">'VV'</span>];
<span class="hljs-keyword">var</span> training_sar = final.select(bands).sampleRegions({ <span class="hljs-attr">collection</span>: newfc, <span class="hljs-attr">properties</span>: [<span class="hljs-string">'landcover'</span>], <span class="hljs-attr">scale</span>: <span class="hljs-number">10</span> }).randomColumn();
<span class="hljs-keyword">var</span> training_newfc1 = training_sar.filter(ee.Filter.lt(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> validation_newfc1 = training_sar.filter(ee.Filter.gte(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> classifier_sar = ee.Classifier.smileRandomForest(<span class="hljs-number">60</span>).train({ <span class="hljs-attr">features</span>: training_newfc1, <span class="hljs-attr">classProperty</span>: <span class="hljs-string">'landcover'</span>, <span class="hljs-attr">inputProperties</span>: bands });
<span class="hljs-keyword">var</span> classified_sar = final.select(bands).classify(classifier_sar);
print(classified_sar, <span class="hljs-string">'classified SAR'</span>);
<span class="hljs-built_in">Map</span>.addLayer(classified_sar, { <span class="hljs-attr">min</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">max</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">palette</span>: [<span class="hljs-string">'1667fa'</span>, <span class="hljs-string">'c9270d'</span>, <span class="hljs-string">'cf7b68'</span>, <span class="hljs-string">'ee9a1c'</span>, <span class="hljs-string">'146d0e'</span>, <span class="hljs-string">'04bd23'</span>, <span class="hljs-string">'37fe05'</span>] }, <span class="hljs-string">'SAR Classification'</span>);
<span class="hljs-keyword">var</span> validated_sar = validation_newfc1.classify(classifier_sar);
</code></pre>
<h3 id="heading-sentinel-2a-classification"><strong>Sentinel-2A Classification</strong></h3>
<p>Now, let's move on to Sentinel-2A Classification. We'll start by defining the bands to be used for classification. In addition to the spectral bands (blue, green, red, red_edge, and nir), we'll also include NDVI as a feature. This comprehensive set of features will help us effectively classify land cover types.</p>
<p>Next, we'll sample regions from the composite image based on the defined bands and land cover properties. These sampled regions will then be split into training and validation datasets to facilitate the classifier training process.</p>
<p>We'll train the Random Forest classifier using the training dataset, specifying the input features and the class property. Once trained, the classifier will be applied to the composite image to perform the classification.</p>
<p>To visualize the results, we'll add the classified Sentinel-2 image to the map, assigning distinct colors to different land cover types.</p>
<p>Additionally, we'll classify the validation data and print</p>
<p>the confusion matrix and accuracy metrics. This step helps us evaluate the performance of our classifier on unseen data.</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">//-------------------------------- Sentinel-2A Classification -------------------------------</span>
<span class="hljs-keyword">var</span> bandss2 = [<span class="hljs-string">'blue'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'red_edge'</span>, <span class="hljs-string">'nir'</span>];
<span class="hljs-keyword">var</span> trainings2 = composite.select(bandss2).sampleRegions({ <span class="hljs-attr">collection</span>: newfc, <span class="hljs-attr">properties</span>: [<span class="hljs-string">'landcover'</span>], <span class="hljs-attr">scale</span>: <span class="hljs-number">10</span> }).randomColumn();
<span class="hljs-keyword">var</span> training_newfc2 = trainings2.filter(ee.Filter.lt(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> validation_newfc2 = trainings2.filter(ee.Filter.gte(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> classifier_S2 = ee.Classifier.smileRandomForest(<span class="hljs-number">100</span>).train({ <span class="hljs-attr">features</span>: training_newfc2, <span class="hljs-attr">classProperty</span>: <span class="hljs-string">'landcover'</span>, <span class="hljs-attr">inputProperties</span>: bandss2 });
<span class="hljs-keyword">var</span> classified_S2 = composite.select(bandss2).classify(classifier_S2);
<span class="hljs-built_in">Map</span>.addLayer(classified_S2, { <span class="hljs-attr">min</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">max</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">palette</span>: [<span class="hljs-string">'1667fa'</span>, <span class="hljs-string">'c9270d'</span>, <span class="hljs-string">'cf7b68'</span>, <span class="hljs-string">'ee9a1c'</span>, <span class="hljs-string">'146d0e'</span>, <span class="hljs-string">'04bd23'</span>, <span class="hljs-string">'37fe05'</span>] }, <span class="hljs-string">'Optical Classification'</span>);
<span class="hljs-keyword">var</span> validated_s2 = validation_newfc2.classify(classifier_S2);
print(<span class="hljs-string">'RF S2 error matrix training: '</span>, classifier_S2.confusionMatrix());
print(<span class="hljs-string">'RF- S2 accuracy training: '</span>, classifier_S2.confusionMatrix().accuracy());
<span class="hljs-keyword">var</span> testAccuracy = validated_s2.errorMatrix(<span class="hljs-string">'landcover'</span>, <span class="hljs-string">'classification'</span>);
print(<span class="hljs-string">'RF S2 Validation error matrix: '</span>, testAccuracy);
print(<span class="hljs-string">'RF S2 Validation overall accuracy: '</span>, testAccuracy.accuracy());
</code></pre>
<h3 id="heading-combine-sar-and-sentinel-2-classification"><strong>Combine SAR and Sentinel-2 Classification</strong></h3>
<p>Let's now <strong>combine SAR and Sentinel-2 Classification</strong>. To achieve this, we'll define both SAR and optical bands to train the classifier. This includes bands from the optical imagery (blue, green, red, red_edge, nir, and NDVI) as well as SAR bands (VH and VV).</p>
<p>We'll sample regions from the merged feature collection using the defined bands and split them into training and validation datasets.</p>
<p>Once the training dataset is prepared, we'll train the Random Forest classifier using the training dataset, specifying the input features and the class property.</p>
<p>After training, the classifier will be applied to the combined optical and SAR image to perform the classification.</p>
<p>We'll visualize the combined classification on the map, masking out areas where either SAR or optical data is missing.</p>
<p>Finally, we'll classify the validation data and print the confusion matrix and accuracy metrics for both the training and validation datasets. This comprehensive evaluation will provide insights into the performance of our combined classification approach.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//----------------------------- Combine SAR and Sentinel 2 Classification ---------------------</span>
<span class="hljs-keyword">var</span> opt_sar = ee.Image.cat(composite, SARVV_filtered, SARVH_filtered);
<span class="hljs-keyword">var</span> bands_opt_sar = [<span class="hljs-string">'VH'</span>, <span class="hljs-string">'VV'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'red_edge'</span>, <span class="hljs-string">'nir'</span>, <span class="hljs-string">'NDVI'</span>];
<span class="hljs-keyword">var</span> training_opt_sar = opt_sar.select(bands_opt_sar).sampleRegions({ <span class="hljs-attr">collection</span>: newfc, <span class="hljs-attr">properties</span>: [<span class="hljs-string">'landcover'</span>], <span class="hljs-attr">scale</span>: <span class="hljs-number">10</span> }).randomColumn();
<span class="hljs-keyword">var</span> training_newfc3 = training_opt_sar.filter(ee.Filter.lt(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> validation_newfc3 = training_opt_sar.filter(ee.Filter.gte(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> classifier_opt_sar = ee.Classifier.smileRandomForest(<span class="hljs-number">100</span>).train({ <span class="hljs-attr">features</span>: training_newfc3, <span class="hljs-attr">classProperty</span>: <span class="hljs-string">'landcover'</span>, <span class="hljs-attr">inputProperties</span>: bands_opt_sar });
<span class="hljs-keyword">var</span> classifiedboth = opt_sar.select(bands_opt_sar).classify(classifier_opt_sar);
<span class="hljs-keyword">var</span> mask_o = composite.select(<span class="hljs-number">0</span>).neq(<span class="hljs-number">1000</span>);
<span class="hljs-keyword">var</span> mask_r = SARVV_filtered.neq(<span class="hljs-number">1000</span>);
<span class="hljs-keyword">var</span> mask = mask_r.updateMask(mask_o);
<span class="hljs-built_in">Map</span>.addLayer(classifiedboth.updateMask(mask), { <span class="hljs-attr">min</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">max</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">palette</span>: [<span class="hljs-string">'1667fa'</span>, <span class="hljs-string">'c9270d'</span>, <span class="hljs-string">'cf7b68'</span>, <span class="hljs-string">'ee9a1c'</span>, <span class="hljs-string">'146d0e'</span>, <span class="hljs-string">'04bd23'</span>, <span class="hljs-string">'37fe05'</span>] }, <span class="hljs-string">'Optical/SAR Classification'</span>);
<span class="hljs-keyword">var</span> validated_opt_sar = validation_newfc3.classify(classifier_opt_sar);
<span class="hljs-keyword">var</span> confusionMatrix = classifier_opt_sar.confusionMatrix();
print(<span class="hljs-string">'RF-Opt/SAR error matrix training: '</span>, classifier_opt_sar.confusionMatrix());
print(<span class="hljs-string">'RF-Opt/SAR accuracy training: '</span>, classifier_opt_sar.confusionMatrix().accuracy());
print(<span class="hljs-string">'RF-Opt/SAR Kappa training: '</span>, confusionMatrix.kappa());
print(<span class="hljs-string">'RF Training Consumer\'s accuracy (rows):'</span>, confusionMatrix.consumersAccuracy());
print(<span class="hljs-string">'RF Training Producer\'s accuracy (columns):'</span>, confusionMatrix.producersAccuracy());
print(<span class="hljs-string">'RF Training array :'</span>, confusionMatrix.array());
<span class="hljs-keyword">var</span> testAccuracy = validated_opt_sar.errorMatrix(<span class="hljs-string">'landcover'</span>, <span class="hljs-string">'classification'</span>);
print(<span class="hljs-string">'RF-Opt/SAR Validation error matrix: '</span>, testAccuracy);
print(<span class="hljs-string">'RF-Opt/SAR Validation overall accuracy: '</span>, testAccuracy.accuracy());
print(<span class="hljs-string">'RF-Opt/SAR Kappa Validation: '</span>, testAccuracy.kappa());
print(<span class="hljs-string">'RF Validation Consumer\'s accuracy (rows):'</span>, testAccuracy.consumersAccuracy());
print(<span class="hljs-string">'RF Validation Producer\'s accuracy (columns):'</span>, testAccuracy.producersAccuracy());
print(<span class="hljs-string">'RF Validation array :'</span>, testAccuracy.array());
</code></pre>
<h3 id="heading-export-the-results-to-google-drive"><strong>Export the results to Google Drive</strong></h3>
<p>To complete our analysis, let's <strong>export the results to Google Drive</strong>. We'll start by exporting the classified Sentinel-2 image as a GeoTIFF file.</p>
<p>This export operation includes several parameters such as the image to export, a description for the exported file, the spatial resolution (scale) in meters, the region of interest (roi), the folder in Google Drive to save the exported file, and the maximum number of pixels to export.</p>
<p>Once the export is initiated, Google Earth Engine will process the image and save it to the specified folder in your Google Drive account.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//----------------------------------- Export Results ----------------------------------------</span>
<span class="hljs-comment">// Export the classified Sentinel-2 image to Google Drive</span>
Export.image.toDrive({
    <span class="hljs-attr">image</span>: classified_S2, <span class="hljs-comment">// Classified Sentinel-2 image</span>
    <span class="hljs-attr">description</span>: <span class="hljs-string">'S2_RF_10m'</span>, <span class="hljs-comment">// Description</span>
    <span class="hljs-attr">scale</span>: <span class="hljs-number">10</span>, <span class="hljs-comment">// Spatial resolution</span>
    <span class="hljs-attr">region</span>: roi, <span class="hljs-comment">// Region of interest</span>
    <span class="hljs-attr">folder</span>: <span class="hljs-string">"M.Gaylan_Classification"</span>, <span class="hljs-comment">// Google Drive folder</span>
    <span class="hljs-attr">maxPixels</span>: <span class="hljs-number">1e13</span> <span class="hljs-comment">// Maximum number of pixels</span>
});
</code></pre>
<h3 id="heading-the-complete-code-is-as-follows">The complete code is as follows:</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">//The code is prepared by Dr. Azad Rasul: azad.rasul@soran.edu.iq</span>
<span class="hljs-comment">//---------------------------------------------------------------------------</span>
<span class="hljs-comment">// roi</span>
<span class="hljs-keyword">var</span> roi = ee.Geometry.Polygon(
  [[[<span class="hljs-number">44.253</span>, <span class="hljs-number">36.569</span>],
    [<span class="hljs-number">44.293</span>, <span class="hljs-number">36.596</span>],
    [<span class="hljs-number">44.367</span>, <span class="hljs-number">36.526</span>],
    [<span class="hljs-number">44.328</span>, <span class="hljs-number">36.5</span>]]], <span class="hljs-literal">null</span>, <span class="hljs-literal">false</span>);
<span class="hljs-comment">//----------------------------------- SAR -----------------------------------</span>
<span class="hljs-comment">// Load Sentinel-1 C-band SAR Ground Range collection (log scale, VV, descending)</span>
<span class="hljs-keyword">var</span> collectionVV = ee.ImageCollection(<span class="hljs-string">'COPERNICUS/S1_GRD'</span>)
  .filter(ee.Filter.eq(<span class="hljs-string">'instrumentMode'</span>, <span class="hljs-string">'IW'</span>))
  .filter(ee.Filter.listContains(<span class="hljs-string">'transmitterReceiverPolarisation'</span>, <span class="hljs-string">'VV'</span>))
  .filter(ee.Filter.eq(<span class="hljs-string">'orbitProperties_pass'</span>, <span class="hljs-string">'DESCENDING'</span>))
  .filterMetadata(<span class="hljs-string">'resolution_meters'</span>, <span class="hljs-string">'equals'</span> , <span class="hljs-number">10</span>)
  .filterBounds(roi)
  .map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">image</span>)</span>{<span class="hljs-keyword">return</span> image.clip(roi)})
  .select(<span class="hljs-string">'VV'</span>);
print(collectionVV, <span class="hljs-string">'Collection VV'</span>);

<span class="hljs-comment">// Load Sentinel-1 C-band SAR Ground Range collection (log scale, VH, descending)</span>
<span class="hljs-keyword">var</span> collectionVH = ee.ImageCollection(<span class="hljs-string">'COPERNICUS/S1_GRD'</span>)
  .filter(ee.Filter.eq(<span class="hljs-string">'instrumentMode'</span>, <span class="hljs-string">'IW'</span>))
  .filter(ee.Filter.listContains(<span class="hljs-string">'transmitterReceiverPolarisation'</span>, <span class="hljs-string">'VH'</span>))
  .filter(ee.Filter.eq(<span class="hljs-string">'orbitProperties_pass'</span>, <span class="hljs-string">'DESCENDING'</span>))
  .filterMetadata(<span class="hljs-string">'resolution_meters'</span>, <span class="hljs-string">'equals'</span> , <span class="hljs-number">10</span>)
  .filterBounds(roi)
  .map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">image</span>)</span>{<span class="hljs-keyword">return</span> image.clip(roi)})
  .select(<span class="hljs-string">'VH'</span>);
print(collectionVH, <span class="hljs-string">'Collection VH'</span>);

<span class="hljs-comment">// Filter SAR collections by date</span>
<span class="hljs-keyword">var</span> SARVV = collectionVV.filterDate(<span class="hljs-string">'2022-04-19'</span>, <span class="hljs-string">'2022-04-24'</span>).mosaic();
<span class="hljs-keyword">var</span> SARVH = collectionVH.filterDate(<span class="hljs-string">'2022-04-19'</span>, <span class="hljs-string">'2022-04-24'</span>).mosaic();

<span class="hljs-comment">// Add the SAR images to the map for visualization</span>
<span class="hljs-built_in">Map</span>.centerObject(roi, <span class="hljs-number">12</span>);
<span class="hljs-built_in">Map</span>.addLayer(SARVV, {<span class="hljs-attr">min</span>:<span class="hljs-number">-15</span>,<span class="hljs-attr">max</span>:<span class="hljs-number">0</span>}, <span class="hljs-string">'SAR VV'</span>, <span class="hljs-number">0</span>);
<span class="hljs-built_in">Map</span>.addLayer(SARVH, {<span class="hljs-attr">min</span>:<span class="hljs-number">-25</span>,<span class="hljs-attr">max</span>:<span class="hljs-number">0</span>}, <span class="hljs-string">'SAR VH'</span>, <span class="hljs-number">0</span>);

<span class="hljs-comment">// Apply filter to reduce speckle</span>
<span class="hljs-keyword">var</span> SMOOTHING_RADIUS = <span class="hljs-number">50</span>;
<span class="hljs-keyword">var</span> SARVV_filtered = SARVV.focal_mean(SMOOTHING_RADIUS, <span class="hljs-string">'circle'</span>, <span class="hljs-string">'meters'</span>);
<span class="hljs-keyword">var</span> SARVH_filtered = SARVH.focal_mean(SMOOTHING_RADIUS, <span class="hljs-string">'circle'</span>, <span class="hljs-string">'meters'</span>);

<span class="hljs-comment">// Display the filtered SAR images</span>
<span class="hljs-built_in">Map</span>.addLayer(SARVV_filtered, {<span class="hljs-attr">min</span>:<span class="hljs-number">-15</span>,<span class="hljs-attr">max</span>:<span class="hljs-number">0</span>}, <span class="hljs-string">'SAR VV Filtered'</span>,<span class="hljs-number">0</span>);
<span class="hljs-built_in">Map</span>.addLayer(SARVH_filtered, {<span class="hljs-attr">min</span>:<span class="hljs-number">-25</span>,<span class="hljs-attr">max</span>:<span class="hljs-number">0</span>}, <span class="hljs-string">'SAR VH Filtered'</span>,<span class="hljs-number">0</span>);

<span class="hljs-comment">//--------------------------- Sentinel 2 -------------------------</span>
<span class="hljs-comment">// Function to mask clouds and cirrus in Sentinel-2 imagery</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">maskS2clouds</span>(<span class="hljs-params">image</span>) </span>{
  <span class="hljs-keyword">var</span> qa = image.select(<span class="hljs-string">'QA60'</span>);
  <span class="hljs-keyword">var</span> cloudBitMask = <span class="hljs-number">1</span> &lt;&lt; <span class="hljs-number">10</span>;
  <span class="hljs-keyword">var</span> cirrusBitMask = <span class="hljs-number">1</span> &lt;&lt; <span class="hljs-number">11</span>;
  <span class="hljs-keyword">var</span> mask = qa.bitwiseAnd(cloudBitMask).eq(<span class="hljs-number">0</span>)
      .and(qa.bitwiseAnd(cirrusBitMask).eq(<span class="hljs-number">0</span>));
  <span class="hljs-keyword">return</span> image.updateMask(mask).divide(<span class="hljs-number">10000</span>);
}

<span class="hljs-comment">// Load Sentinel-2 imagery, filter by date and cloud cover, apply cloud masking, and clip to the ROI</span>
<span class="hljs-keyword">var</span> image = ee.ImageCollection(<span class="hljs-string">'COPERNICUS/S2_SR'</span>)
              .filterDate(<span class="hljs-string">'2022-05-19'</span>, <span class="hljs-string">'2022-05-22'</span>)
              .filter(ee.Filter.lt(<span class="hljs-string">'CLOUDY_PIXEL_PERCENTAGE'</span>,<span class="hljs-number">5</span>))
              .filterBounds(roi)
              .map(maskS2clouds)
              .map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">image</span>)</span>{<span class="hljs-keyword">return</span> image.clip(roi)});

<span class="hljs-comment">// Visualization parameters for displaying Sentinel-2 imagery</span>
<span class="hljs-keyword">var</span> vis = { <span class="hljs-attr">min</span>: <span class="hljs-number">0.0</span>, <span class="hljs-attr">max</span>: <span class="hljs-number">0.3</span>, <span class="hljs-attr">bands</span>: [<span class="hljs-string">'B4'</span>, <span class="hljs-string">'B3'</span>, <span class="hljs-string">'B2'</span>] };

<span class="hljs-comment">// Add Sentinel-2 imagery to the map</span>
<span class="hljs-built_in">Map</span>.addLayer(image, vis, <span class="hljs-string">"Sentinel2"</span>);

<span class="hljs-comment">// Get information about the Sentinel-2 imagery</span>
print(image, <span class="hljs-string">"Sentinel raw image"</span>);

<span class="hljs-comment">// Take the mean of the Sentinel-2 imagery</span>
<span class="hljs-keyword">var</span> image = image.mean();

<span class="hljs-comment">// Load additional Sentinel-2 imagery for a different date range</span>
<span class="hljs-keyword">var</span> s2BandNames = [<span class="hljs-string">'B2'</span>, <span class="hljs-string">'B3'</span>, <span class="hljs-string">'B4'</span>, <span class="hljs-string">'B7'</span>, <span class="hljs-string">'B8'</span>];
<span class="hljs-keyword">var</span> s2BandRename = [<span class="hljs-string">'blue'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'red_edge'</span>, <span class="hljs-string">'nir'</span>];
<span class="hljs-keyword">var</span> collections2 = ee.ImageCollection(<span class="hljs-string">'COPERNICUS/S2_SR'</span>)
              .filterDate(<span class="hljs-string">'2022-05-19'</span>, <span class="hljs-string">'2022-05-22'</span>)
              .filter(ee.Filter.lt(<span class="hljs-string">'CLOUDY_PIXEL_PERCENTAGE'</span>,<span class="hljs-number">05</span>))
              .select(s2BandNames, s2BandRename)
              .filterBounds(roi)
              .map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">image</span>)</span>{<span class="hljs-keyword">return</span> image.clip(roi)});

print(image, <span class="hljs-string">"Sentinel raw image"</span>);
<span class="hljs-keyword">var</span> image = collections2.mean();

<span class="hljs-comment">//---------------------------------- Calculate NDVI ------------------------------</span>
<span class="hljs-keyword">var</span> s2ndvi = image.normalizedDifference([<span class="hljs-string">'nir'</span>, <span class="hljs-string">'red'</span>]); 
<span class="hljs-keyword">var</span> comp = collections2.mean();
<span class="hljs-keyword">var</span> ndvi = comp.normalizedDifference([<span class="hljs-string">'nir'</span>, <span class="hljs-string">'red'</span>]).rename(<span class="hljs-string">'NDVI'</span>);
<span class="hljs-keyword">var</span> composite = ee.Image.cat(comp, ndvi);

<span class="hljs-built_in">Map</span>.centerObject(roi, <span class="hljs-number">13</span>);

<span class="hljs-comment">//----------------------------- SAR Classification ------------------------------</span>
<span class="hljs-keyword">var</span> newfc = wheat.merge(barley).merge(Uncultivate_land).merge(Road_airport).merge(bareland).merge(grassland);
<span class="hljs-keyword">var</span> final = ee.Image.cat(SARVV_filtered, SARVH_filtered);
<span class="hljs-keyword">var</span> bands = [<span class="hljs-string">'VH'</span>, <span class="hljs-string">'VV'</span>];
<span class="hljs-keyword">var</span> training_sar = final.select(bands).sampleRegions({ <span class="hljs-attr">collection</span>: newfc, <span class="hljs-attr">properties</span>: [<span class="hljs-string">'landcover'</span>], <span class="hljs-attr">scale</span>: <span class="hljs-number">10</span> }).randomColumn();
<span class="hljs-keyword">var</span> training_newfc1 = training_sar.filter(ee.Filter.lt(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> validation_newfc1 = training_sar.filter(ee.Filter.gte(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> classifier_sar = ee.Classifier.smileRandomForest(<span class="hljs-number">60</span>).train({ <span class="hljs-attr">features</span>: training_newfc1, <span class="hljs-attr">classProperty</span>: <span class="hljs-string">'landcover'</span>, <span class="hljs-attr">inputProperties</span>: bands });
<span class="hljs-keyword">var</span> classified_sar = final.select(bands).classify(classifier_sar);
print(classified_sar, <span class="hljs-string">'classified SAR'</span>);
<span class="hljs-built_in">Map</span>.addLayer(classified_sar, { <span class="hljs-attr">min</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">max</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">palette</span>: [<span class="hljs-string">'1667fa'</span>, <span class="hljs-string">'c9270d'</span>, <span class="hljs-string">'cf7b68'</span>, <span class="hljs-string">'ee9a1c'</span>, <span class="hljs-string">'146d0e'</span>, <span class="hljs-string">'04bd23'</span>, <span class="hljs-string">'37fe05'</span>] }, <span class="hljs-string">'SAR Classification'</span>);
<span class="hljs-keyword">var</span> validated_sar = validation_newfc1.classify(classifier_sar);

<span class="hljs-comment">//-------------------------------- Sentinel-2A Classification -------------------------------</span>
<span class="hljs-keyword">var</span> bandss2 = [<span class="hljs-string">'blue'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'red_edge'</span>, <span class="hljs-string">'nir'</span>];
<span class="hljs-keyword">var</span> trainings2 = composite.select(bandss2).sampleRegions({ <span class="hljs-attr">collection</span>: newfc, <span class="hljs-attr">properties</span>: [<span class="hljs-string">'landcover'</span>], <span class="hljs-attr">scale</span>: <span class="hljs-number">10</span> }).randomColumn();
<span class="hljs-keyword">var</span> training_newfc2 = trainings2.filter(ee.Filter.lt(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> validation_newfc2 = trainings2.filter(ee.Filter.gte(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> classifier_S2 = ee.Classifier.smileRandomForest(<span class="hljs-number">100</span>).train({ <span class="hljs-attr">features</span>: training_newfc2, <span class="hljs-attr">classProperty</span>: <span class="hljs-string">'landcover'</span>, <span class="hljs-attr">inputProperties</span>: bandss2 });
<span class="hljs-keyword">var</span> classified_S2 = composite.select(bandss2).classify(classifier_S2);
<span class="hljs-built_in">Map</span>.addLayer(classified_S2, { <span class="hljs-attr">min</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">max</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">palette</span>: [<span class="hljs-string">'1667fa'</span>, <span class="hljs-string">'c9270d'</span>, <span class="hljs-string">'cf7b68'</span>, <span class="hljs-string">'ee9a1c'</span>, <span class="hljs-string">'146d0e'</span>, <span class="hljs-string">'04bd23'</span>, <span class="hljs-string">'37fe05'</span>] }, <span class="hljs-string">'Optical Classification'</span>);
<span class="hljs-keyword">var</span> validated_s2 = validation_newfc2.classify(classifier_S2);
print(<span class="hljs-string">'RF S2 error matrix training: '</span>, classifier_S2.confusionMatrix());
print(<span class="hljs-string">'RF- S2 accuracy training: '</span>, classifier_S2.confusionMatrix().accuracy());
<span class="hljs-keyword">var</span> testAccuracy = validated_s2.errorMatrix(<span class="hljs-string">'landcover'</span>, <span class="hljs-string">'classification'</span>);
print(<span class="hljs-string">'RF S2 Validation error matrix: '</span>, testAccuracy);
print(<span class="hljs-string">'RF S2 Validation overall accuracy: '</span>, testAccuracy.accuracy());

<span class="hljs-comment">//----------------------------- Combine SAR and Sentinel 2 Classification ---------------------</span>
<span class="hljs-keyword">var</span> opt_sar = ee.Image.cat(composite, SARVV_filtered, SARVH_filtered);
<span class="hljs-keyword">var</span> bands_opt_sar = [<span class="hljs-string">'VH'</span>, <span class="hljs-string">'VV'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'red_edge'</span>, <span class="hljs-string">'nir'</span>, <span class="hljs-string">'NDVI'</span>];
<span class="hljs-keyword">var</span> training_opt_sar = opt_sar.select(bands_opt_sar).sampleRegions({ <span class="hljs-attr">collection</span>: newfc, <span class="hljs-attr">properties</span>: [<span class="hljs-string">'landcover'</span>], <span class="hljs-attr">scale</span>: <span class="hljs-number">10</span> }).randomColumn();
<span class="hljs-keyword">var</span> training_newfc3 = training_opt_sar.filter(ee.Filter.lt(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> validation_newfc3 = training_opt_sar.filter(ee.Filter.gte(<span class="hljs-string">'random'</span>, <span class="hljs-number">0.7</span>));
<span class="hljs-keyword">var</span> classifier_opt_sar = ee.Classifier.smileRandomForest(<span class="hljs-number">100</span>).train({ <span class="hljs-attr">features</span>: training_newfc3, <span class="hljs-attr">classProperty</span>: <span class="hljs-string">'landcover'</span>, <span class="hljs-attr">inputProperties</span>: bands_opt_sar });
<span class="hljs-keyword">var</span> classifiedboth = opt_sar.select(bands_opt_sar).classify(classifier_opt_sar);
<span class="hljs-keyword">var</span> mask_o = composite.select(<span class="hljs-number">0</span>).neq(<span class="hljs-number">1000</span>);
<span class="hljs-keyword">var</span> mask_r = SARVV_filtered.neq(<span class="hljs-number">1000</span>);
<span class="hljs-keyword">var</span> mask = mask_r.updateMask(mask_o);
<span class="hljs-built_in">Map</span>.addLayer(classifiedboth.updateMask(mask), { <span class="hljs-attr">min</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">max</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">palette</span>: [<span class="hljs-string">'1667fa'</span>, <span class="hljs-string">'c9270d'</span>, <span class="hljs-string">'cf7b68'</span>, <span class="hljs-string">'ee9a1c'</span>, <span class="hljs-string">'146d0e'</span>, <span class="hljs-string">'04bd23'</span>, <span class="hljs-string">'37fe05'</span>] }, <span class="hljs-string">'Optical/SAR Classification'</span>);
<span class="hljs-keyword">var</span> validated_opt_sar = validation_newfc3.classify(classifier_opt_sar);
<span class="hljs-keyword">var</span> confusionMatrix = classifier_opt_sar.confusionMatrix();
print(<span class="hljs-string">'RF-Opt/SAR error matrix training: '</span>, classifier_opt_sar.confusionMatrix());
print(<span class="hljs-string">'RF-Opt/SAR accuracy training: '</span>, classifier_opt_sar.confusionMatrix().accuracy());
print(<span class="hljs-string">'RF-Opt/SAR Kappa training: '</span>, confusionMatrix.kappa());
print(<span class="hljs-string">'RF Training Consumer\'s accuracy (rows):'</span>, confusionMatrix.consumersAccuracy());
print(<span class="hljs-string">'RF Training Producer\'s accuracy (columns):'</span>, confusionMatrix.producersAccuracy());
print(<span class="hljs-string">'RF Training array :'</span>, confusionMatrix.array());
<span class="hljs-keyword">var</span> testAccuracy = validated_opt_sar.errorMatrix(<span class="hljs-string">'landcover'</span>, <span class="hljs-string">'classification'</span>);
print(<span class="hljs-string">'RF-Opt/SAR Validation error matrix: '</span>, testAccuracy);
print(<span class="hljs-string">'RF-Opt/SAR Validation overall accuracy: '</span>, testAccuracy.accuracy());
print(<span class="hljs-string">'RF-Opt/SAR Kappa Validation: '</span>, testAccuracy.kappa());
print(<span class="hljs-string">'RF Validation Consumer\'s accuracy (rows):'</span>, testAccuracy.consumersAccuracy());
print(<span class="hljs-string">'RF Validation Producer\'s accuracy (columns):'</span>, testAccuracy.producersAccuracy());
print(<span class="hljs-string">'RF Validation array :'</span>, testAccuracy.array());

<span class="hljs-comment">//----------------------------------- Export Results ----------------------------------------</span>
<span class="hljs-comment">// Export the classified Sentinel-2 image to Google Drive</span>
Export.image.toDrive({
    <span class="hljs-attr">image</span>: classified_S2, <span class="hljs-comment">// Classified Sentinel-2 image</span>
    <span class="hljs-attr">description</span>: <span class="hljs-string">'S2_RF_10m'</span>, <span class="hljs-comment">// Description</span>
    <span class="hljs-attr">scale</span>: <span class="hljs-number">10</span>, <span class="hljs-comment">// Spatial resolution</span>
    <span class="hljs-attr">region</span>: roi, <span class="hljs-comment">// Region of interest</span>
    <span class="hljs-attr">folder</span>: <span class="hljs-string">"M.Gaylan_Classification"</span>, <span class="hljs-comment">// Google Drive folder</span>
    <span class="hljs-attr">maxPixels</span>: <span class="hljs-number">1e13</span> <span class="hljs-comment">// Maximum number of pixels</span>
});
</code></pre>
<p>I hope you found this tutorial helpful! If you did, don't forget to like and subscribe for more content. Until next time, happy coding!</p>
<p>Please consider subscribing to my <a target="_blank" href="https://www.youtube.com/channel/UCpbWlHEqBSnJb6i4UemXQpA?sub_confirmation=1"><strong>YouTube channel</strong></a> for future updates.</p>
<p>To access video tutorials and receive a certificate, enrol in my <a target="_blank" href="https://www.udemy.com/course/r-for-research/?referralCode=B6DCFDE343F0592EA61A"><strong>Udemy course</strong></a>.</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Deep Learning in R Programming]]></title><description><![CDATA[Hi everyone, today we're diving into some R programming with neural networks. First, we need to make sure we have all the tools we need, so we load up some…]]></description><link>https://smartrs.hashnode.dev/introduction-to-deep-learning-in-r-programming</link><guid isPermaLink="true">https://smartrs.hashnode.dev/introduction-to-deep-learning-in-r-programming</guid><category><![CDATA[/RProgramming]]></category><category><![CDATA[DeepLearning]]></category><category><![CDATA[Artificial Intelligence]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Fri, 03 May 2024 07:19:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724478147508/89a13172-9d4c-4982-8b99-fa88ed28508c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi everyone, today we're diving into some R programming with neural networks. First, we need to make sure we have all the tools we need, so we load up some <strong>libraries</strong> that help us with data and building neural networks. Then, we're going to work with a classic dataset called Iris.</p>
<pre><code class="language-r"># Install devtools
# install.packages("devtools")
# Install keras
# devtools::install_github("rstudio/keras")

# Load necessary libraries
library(tidyverse)   # For data manipulation
library(keras3)      # For building neural networks
library(tensorflow)  # Backend for Keras
library(datasets)    # Provides sample datasets
</code></pre>
<p>The <strong>Iris dataset</strong> has different types of flowers, and we want to teach our computer to recognize them based on their features. But computers like numbers, not flower names, so we convert the flower types into numbers.</p>
<p>Next, we <strong>split our dataset</strong> into two parts: one for teaching our computer (the training set) and one for testing how well it learned (the test set). We make sure both sets have a good mix of flower types.</p>
<pre><code class="language-r"># Load Iris dataset
data(iris)


# Convert class labels to numeric format (0, 1, 2)
iris[,5] &lt;- as.numeric(iris[,5]) - 1

# Convert iris dataframe to a matrix
iris &lt;- as.matrix(iris)

# Set dimension names to NULL
dimnames(iris) &lt;- NULL


# Determine sample size and split the dataset into training and test sets
ind &lt;- sample(2, nrow(iris), replace=TRUE, prob=c(0.67, 0.33))

# Select rows for training set where ind is 1
iris.training &lt;- iris[ind==1, 1:4]

# Select rows for test set where ind is 2
iris.test &lt;- iris[ind==2, 1:4]

# Split the class attribute for training set
iris.trainingtarget &lt;- iris[ind==1, 5]  # Select the class labels corresponding to the training set samples

# Split the class attribute for test set
iris.testtarget &lt;- iris[ind==2, 5]  # Select the class labels corresponding to the test set samples
</code></pre>
<p>Now, here's where things get interesting. We want our computer to understand the different flower types, but it's not as simple as saying 'this is a setosa' or 'this is a versicolor.' We need to speak the computer's language, which is 0s and 1s.</p>
<p>So, we do something called <strong>'one-hot encoding.'</strong> It's like translating flower names into a special code that the computer can understand. Each type of flower gets its own code, like a secret language.</p>
<pre><code class="language-r"># One hot encode training target values:
# Convert the class labels of the training set into a one-hot encoded format.
# One-hot encoding transforms categorical labels into a binary matrix where each column represents a unique class,
# and the column corresponding to the class label is marked as 1 while others are 0.
iris.trainLabels &lt;- to_categorical(iris.trainingtarget)

# One hot encode test target values:
# Similar to the above, convert the class labels of the test set into a one-hot encoded format.
iris.testLabels &lt;- to_categorical(iris.testtarget)
</code></pre>
<p>Just to be sure everything's going smoothly, we <strong>take a quick peek at our translated test</strong> set to make sure our codes look right.</p>
<pre><code class="language-r"># Print out the one-hot encoded test labels to double-check the result
print(iris.testLabels)
</code></pre>
<h2>Model 1</h2>
<p>Now, we're going to learn about building a neural network using R programming language. Let's start with Model 1.</p>
<p>First, we <strong>construct our model</strong>. Think of a model as a blueprint for our neural network. We <strong>initialize</strong> our model by creating an empty container for layers.</p>
<pre><code class="language-r">## Constructing the Model
# Initialize a sequential model
model &lt;- keras_model_sequential()
</code></pre>
<p>Then, we <strong>add layers</strong> to our model. Each layer processes data in a different way. In our first layer, we add what's called a dense layer. This layer has 8 units, which are like small processing units. We use an activation function called ReLU, which helps the network learn complex patterns in the data. Since this is our first layer, we also specify the input shape, which is the number of features in our data, in this case, 4 features from the Iris dataset.</p>
<p>Next, we add another dense layer. This time, it has 3 units. We use a different activation function called softmax. Softmax is handy for classification tasks because it gives us probabilities for each class.</p>
<pre><code class="language-r"># Add layers to the model
# Add a dense (fully connected) layer with 8 units/neurons, ReLU activation function, and input shape of (4,)
# The input shape (4,) corresponds to the number of features in the input data (4 features in Iris dataset)
# The ReLU activation function introduces non-linearity to the network
# The first layer requires specification of input shape since it's the first layer in the model
model %&gt;%
  layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %&gt;%
  # Add another dense layer with 3 units/neurons, softmax activation function
  # Softmax activation is commonly used for multi-class classification tasks
  # It ensures that the output values are between 0 and 1 and sum up to 1, representing class probabilities
  layer_dense(units = 3, activation = 'softmax')
</code></pre>
<p>Once our model is constructed, we check its <strong>summary</strong> to see its architecture, including the number of layers and parameters.</p>
<pre><code class="language-r"># Print a summary of the model architecture, including the number of layers,
# the type of layers, and the number of parameters in each layer.
summary(model)
</code></pre>
<p>After that, we <strong>compile our model</strong>. Compiling means configuring the model for training. We specify the loss function, optimizer, and metrics. The loss function tells the model how wrong it is during training. We use categorical crossentropy since we have multiple classes. The optimizer updates the model based on the data it sees and the loss function. We choose Adam optimizer, which is quite popular.</p>
<p>Lastly, we want to <strong>see how accurate our model</strong> is during training, so we use accuracy as our metric.</p>
<pre><code class="language-r"># Get model configuration
get_config(model)
# This line retrieves the configuration of the neural network model.
# It provides details about the architecture, such as the number of layers,
# the activation functions used, the number of units in each layer, etc.


# Get layer configuration
# Retrieve information about the first layer in the model
get_layer(model, index = 1)

# List the model's layers
model$layers  # This line lists all the layers in the model

# List the input tensors
model$inputs # This line retrieves the list of input tensors for the neural network model.

# List the output tensors
model$outputs # This line retrieves the list of output tensors for the neural network model
# Compile And Fit The Model:
# Compile the model
model %&gt;% compile(
  loss = 'categorical_crossentropy',  # Specify the loss function for categorical classification
  optimizer = 'adam',                  # Specify the optimizer algorithm (Adam)
  metrics = 'accuracy'                 # Specify the metric to evaluate model performance (accuracy)
)
</code></pre>
<p>Then, we <strong>train our model</strong> using the fit function. We provide it with our training data and labels, specify the number of epochs (training iterations), batch size (number of samples the model sees before updating), and a validation split (portion of training data used for validation).</p>
<p>We can <strong>visualize how our model</strong> learns over epochs by plotting its training history. We plot both the loss and accuracy for both training and validation data. This helps us understand if our model is improving over time.</p>
<pre><code class="language-r"># Store the fitting history in `history`
history &lt;- model %&gt;% fit(
  iris.training,           # Training data features (input)
  iris.trainLabels,        # Training data labels (output)
  epochs = 200,            # Number of training epochs (iterations over the entire dataset)
  batch_size = 5,          # Number of samples per gradient update
  validation_split = 0.2   # Fraction of the training data to be used as validation data
)


# Plot the history
plot(history) # Plotting the training history provides visual insights into the model's performance over each epoch.

# Visualize The Model Training History:
# Plot the model loss of the training data
plot(history$metrics$loss, main="Model Loss", xlab = "epoch", ylab="loss", col="blue", type="l")
# This command creates a plot of the model's loss on the training data over epochs.

# Plot the model loss of the test data
lines(history$metrics$val_loss, col="green")

# Add legend
legend("topright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

# Plot the accuracy of the training data
plot(history$metrics$acc, main="Model Accuracy", xlab = "epoch", ylab="accuracy", col="blue", type="l")

# Plot the accuracy of the validation data
lines(history$metrics$val_acc, col="green")

# Add Legend
legend("bottomright", c("train","test"), col=c("blue", "green"), lty=c(1,1))
</code></pre>
<p>Lastly, we <strong>evaluate our model</strong> on the test data to see how well it performs on unseen data. We <strong>print out</strong> the evaluation score to see its performance.</p>
<pre><code class="language-r"># Evaluate on test data and labels
score &lt;- model %&gt;% evaluate(iris.test, iris.testLabels, batch_size = 128)
# Print the score
print(score)
</code></pre>
<p>And that's Model 1! We've built our first neural network in R and trained it on the Iris dataset. In the next section, we'll explore more models and dive deeper into neural networks. Stay tuned!</p>
<h2>Model 2</h2>
<p>Now, we're going to <strong>improve our model</strong> by adding another hidden layer. Let's dive into it.</p>
<p>First, we <strong>initialize our sequential model</strong>, which is like a blank canvas waiting for us to add layers. We'll call it model2.</p>
<pre><code class="language-r"># Initialize the sequential model
model2 &lt;- keras_model_sequential()
</code></pre>
<p>Now, let's add layers to our model. We start by adding a dense layer with 8 units. Think of units as little computational blocks. We use the ReLU activation function, which helps the network learn complex patterns. Since this is our first layer, we need to specify the input shape, which is (4,). This means our data has 4 features.</p>
<p>Next, we add another dense layer, this time with 5 units and ReLU activation function. This layer automatically receives input from the previous one, so we don't need to specify the input shape again.</p>
<p>Finally, we add the output layer. This layer has 3 units because we have 3 classes in the Iris dataset. We use the softmax activation function here to get probabilities for each class.</p>
<pre><code class="language-r"># Add layers to model2:
# Add a dense layer with 8 units and ReLU activation function.
# Input shape is specified as (4,), indicating the input features.
# This layer connects to the input layer implicitly.
# Initialize the sequential model

model2 %&gt;%
  # Add a dense layer with 8 units and ReLU activation function.
  # Input shape is specified as (4,), indicating the input features.
  # This layer connects to the input layer implicitly.
  layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %&gt;%

  # Add another dense layer with 5 units and ReLU activation function.
  # This layer automatically receives input from the previous layer.
  layer_dense(units = 5, activation = 'relu') %&gt;%

  # Add the output layer with 3 units and softmax activation function.
  # This layer produces the final output probabilities for the three classes in the Iris dataset.
  layer_dense(units = 3, activation = 'softmax')
</code></pre>
<p>With our layers set, let's <strong>compile the model</strong>. We specify the loss function as categorical crossentropy, which is suitable for classification tasks. The optimizer we're using is Adam, a popular choice for training neural networks. We also want to track the accuracy metric during training.</p>
<pre><code class="language-r"># Compile the model
model2 %&gt;% compile(
  loss = 'categorical_crossentropy',
  optimizer = 'adam',
  metrics = 'accuracy'
)
</code></pre>
<p>Now, it's time to <strong>train our model</strong>. We fit it to our training data, specifying the number of epochs (how many times we go through the entire dataset) and the batch size (how many samples we use in each update).</p>
<pre><code class="language-r"># Fit the model to the data
model2 %&gt;% fit(
  iris.training, iris.trainLabels,
  epochs = 200, batch_size = 5,
  validation_split = 0.2
)
</code></pre>
<p>Once training is done, we <strong>evaluate our model</strong> on the test data to see how well it performs on unseen examples.</p>
<pre><code class="language-r"># Evaluate the model
score2 &lt;- model2 %&gt;% evaluate(iris.test, iris.testLabels, batch_size = 128)
</code></pre>
<p>And there we have it! Our model is trained and evaluated. Let's <strong>print out</strong> the evaluation score to see how well model2 performed.</p>
<pre><code class="language-r"># Print the score
print(score2)
</code></pre>
<h2>Model 3</h2>
<p>Alright, let's dive into <strong>building our third model</strong>, which we'll call "model3". Now, before we get into the nitty-gritty, let's understand what's going on. First off, we start by <strong>creating a sequential model</strong>. Think of it as a blueprint for our neural network. We're going to stack layers on top of each other, like building blocks.</p>
<pre><code class="language-r"># Hidden Units:
# Initialize a sequential model
model3 &lt;- keras_model_sequential()
</code></pre>
<p>Next, we <strong>add layers to our model</strong>. The first layer we add is what we call a "dense" layer. This layer has 28 hidden units. These units are like small computational hubs that process information. We use a "ReLU" activation function here, which helps introduce non-linearity into our model, allowing it to learn complex patterns from the data.</p>
<p>Moving on, we add another dense layer. This one has 3 units, which correspond to the 3 classes in our output. We use a "softmax" activation function here. This function gives us probabilities for each class, essentially telling us how confident our model is about its predictions.</p>
<pre><code class="language-r"># Add layers to the model
model3 %&gt;%
  # Add a dense layer with 28 units and ReLU activation function.
  layer_dense(units = 28, activation = 'relu', input_shape = c(4)) %&gt;%
  # Add another dense layer with 3 units (output classes) and softmax activation function.
  layer_dense(units = 3, activation = 'softmax')
</code></pre>
<p>Now, it's time to <strong>compile our model</strong>. Compiling is where we define some crucial settings for training, like what loss function to use (in our case, categorical crossentropy), which optimizer to use (Adam, a popular choice), and what metrics to track during training (accuracy, in our case).</p>
<pre><code class="language-r"># Compile the model
model3 %&gt;% compile(
  loss = 'categorical_crossentropy',
  optimizer = 'adam',
  metrics = 'accuracy'
)
</code></pre>
<p>With our model compiled, we train it using our <strong>training data</strong>. We'll train it for 200 epochs, which means we'll go through our entire dataset 200 times. Each time, we'll adjust our model's parameters to make it better at predicting.</p>
<pre><code class="language-r"># Fit the model to the data
model3 %&gt;% fit(
  iris.training, iris.trainLabels,
  epochs = 200, batch_size = 5,
  validation_split = 0.2
)
</code></pre>
<p>After training, it's <strong>evaluation time</strong>! We want to see how well our model performs on data it hasn't seen before (our test data). We calculate a score that tells us how accurate our model is.</p>
<pre><code class="language-r"># Evaluate the model
score3 &lt;- model3 %&gt;% evaluate(iris.test, iris.testLabels, batch_size = 128)
</code></pre>
<p>And there you have it! We've built, trained, and evaluated our third model. Now, let's see how well it did by <strong>printing out</strong> its score. Ready? Let's go!</p>
<pre><code class="language-r"># Print the score
print(score3)
</code></pre>
<h2>The entire code together:</h2>
<pre><code class="language-r"># Install devtools
# install.packages("devtools")
# Install keras
# devtools::install_github("rstudio/keras")

# Load necessary libraries
library(tidyverse)   # For data manipulation
library(keras3)      # For building neural networks
library(tensorflow)  # Backend for Keras
library(datasets)    # Provides sample datasets


# Load Iris dataset
data(iris)


# Convert class labels to numeric format (0, 1, 2)
iris[,5] &lt;- as.numeric(iris[,5]) - 1

# Convert iris dataframe to a matrix
iris &lt;- as.matrix(iris)

# Set dimension names to NULL
dimnames(iris) &lt;- NULL


# Determine sample size and split the dataset into training and test sets
ind &lt;- sample(2, nrow(iris), replace=TRUE, prob=c(0.67, 0.33))

# Select rows for training set where ind is 1
iris.training &lt;- iris[ind==1, 1:4]

# Select rows for test set where ind is 2
iris.test &lt;- iris[ind==2, 1:4]

# Split the class attribute for training set
iris.trainingtarget &lt;- iris[ind==1, 5]  # Select the class labels corresponding to the training set samples

# Split the class attribute for test set
iris.testtarget &lt;- iris[ind==2, 5]  # Select the class labels corresponding to the test set samples


# One hot encode training target values:
# Convert the class labels of the training set into a one-hot encoded format.
# One-hot encoding transforms categorical labels into a binary matrix where each column represents a unique class,
# and the column corresponding to the class label is marked as 1 while others are 0.
iris.trainLabels &lt;- to_categorical(iris.trainingtarget)

# One hot encode test target values:
# Similar to the above, convert the class labels of the test set into a one-hot encoded format.
iris.testLabels &lt;- to_categorical(iris.testtarget)


# Print out the one-hot encoded test labels to double-check the result
print(iris.testLabels)
#--------------------------------------- model 1 ----------------------------------------
## Constructing the Model
# Initialize a sequential model
model &lt;- keras_model_sequential()

# Add layers to the model
# Add a dense (fully connected) layer with 8 units/neurons, ReLU activation function, and input shape of (4,)
# The input shape (4,) corresponds to the number of features in the input data (4 features in Iris dataset)
# The ReLU activation function introduces non-linearity to the network
# The first layer requires specification of input shape since it's the first layer in the model
model %&gt;%
  layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %&gt;%
  # Add another dense layer with 3 units/neurons, softmax activation function
  # Softmax activation is commonly used for multi-class classification tasks
  # It ensures that the output values are between 0 and 1 and sum up to 1, representing class probabilities
  layer_dense(units = 3, activation = 'softmax')

# Print a summary of the model architecture, including the number of layers,
# the type of layers, and the number of parameters in each layer.
summary(model)


# Get model configuration
get_config(model)
# This line retrieves the configuration of the neural network model.
# It provides details about the architecture, such as the number of layers,
# the activation functions used, the number of units in each layer, etc.


# Get layer configuration
# Retrieve information about the first layer in the model
get_layer(model, index = 1)

# List the model's layers
model$layers  # This line lists all the layers in the model

# List the input tensors
model$inputs # This line retrieves the list of input tensors for the neural network model.

# List the output tensors
model$outputs # This line retrieves the list of output tensors for the neural network model

# Compile And Fit The Model:
# Compile the model
model %&gt;% compile(
  loss = 'categorical_crossentropy',  # Specify the loss function for categorical classification
  optimizer = 'adam',                  # Specify the optimizer algorithm (Adam)
  metrics = 'accuracy'                 # Specify the metric to evaluate model performance (accuracy)
)


# Store the fitting history in `history`
history &lt;- model %&gt;% fit(
  iris.training,           # Training data features (input)
  iris.trainLabels,        # Training data labels (output)
  epochs = 200,            # Number of training epochs (iterations over the entire dataset)
  batch_size = 5,          # Number of samples per gradient update
  validation_split = 0.2   # Fraction of the training data to be used as validation data
)


# Plot the history
plot(history) # Plotting the training history provides visual insights into the model's performance over each epoch.

# Visualize The Model Training History:
# Plot the model loss of the training data
plot(history$metrics$loss, main="Model Loss", xlab = "epoch", ylab="loss", col="blue", type="l")
# This command creates a plot of the model's loss on the training data over epochs.

# Plot the model loss of the test data
lines(history$metrics$val_loss, col="green")

# Add legend
legend("topright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

# Plot the accuracy of the training data
plot(history$metrics$acc, main="Model Accuracy", xlab = "epoch", ylab="accuracy", col="blue", type="l")

# Plot the accuracy of the validation data
lines(history$metrics$val_acc, col="green")

# Add Legend
legend("bottomright", c("train","test"), col=c("blue", "green"), lty=c(1,1))

# Evaluate on test data and labels
score &lt;- model %&gt;% evaluate(iris.test, iris.testLabels, batch_size = 128)

# Print the score
print(score)
#------------------------------------ model 2 ----------------------------
# Fine-tuning Your Model:
# Adding Layers

# Initialize the sequential model
model2 &lt;- keras_model_sequential()


# Add layers to model2:
# Add a dense layer with 8 units and ReLU activation function.
# Input shape is specified as (4,), indicating the input features.
# This layer connects to the input layer implicitly.
# Initialize the sequential model

model2 %&gt;%
  # Add a dense layer with 8 units and ReLU activation function.
  # Input shape is specified as (4,), indicating the input features.
  # This layer connects to the input layer implicitly.
  layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %&gt;%

  # Add another dense layer with 5 units and ReLU activation function.
  # This layer automatically receives input from the previous layer.
  layer_dense(units = 5, activation = 'relu') %&gt;%

  # Add the output layer with 3 units and softmax activation function.
  # This layer produces the final output probabilities for the three classes in the Iris dataset.
  layer_dense(units = 3, activation = 'softmax')



# Compile the model
model2 %&gt;% compile(
  loss = 'categorical_crossentropy',
  optimizer = 'adam',
  metrics = 'accuracy'
)


# Fit the model to the data
model2 %&gt;% fit(
  iris.training, iris.trainLabels,
  epochs = 200, batch_size = 5,
  validation_split = 0.2
)

# Evaluate the model
score2 &lt;- model2 %&gt;% evaluate(iris.test, iris.testLabels, batch_size = 128)

# Print the score
print(score2)
#-------------------------------model 3 -------------------------------
# Hidden Units:
# Initialize a sequential model
model3 &lt;- keras_model_sequential()

# Add layers to the model
model3 %&gt;%
  # Add a dense layer with 28 units and ReLU activation function.
  layer_dense(units = 28, activation = 'relu', input_shape = c(4)) %&gt;%
  # Add another dense layer with 3 units (output classes) and softmax activation function.
  layer_dense(units = 3, activation = 'softmax')


# Compile the model
model3 %&gt;% compile(
  loss = 'categorical_crossentropy',
  optimizer = 'adam',
  metrics = 'accuracy'
)

# Fit the model to the data
model3 %&gt;% fit(
  iris.training, iris.trainLabels,
  epochs = 200, batch_size = 5,
  validation_split = 0.2
)

# Evaluate the model
score3 &lt;- model3 %&gt;% evaluate(iris.test, iris.testLabels, batch_size = 128)

# Print the score
print(score3)
# Source of the code: https://rpubs.com/Nilafhiosagam/541333
</code></pre>
<h4>Source of the code (adapted): <a href="https://rpubs.com/Nilafhiosagam/541333">https://rpubs.com/Nilafhiosagam/541333</a></h4>
]]></content:encoded></item><item><title><![CDATA[Create a basic chatbot in Python]]></title><description><![CDATA[Source of the code: this tutorial is based on Matthew Inkawhich's PyTorch chatbot tutorial. In this tutorial, we will explore an engaging application of…]]></description><link>https://smartrs.hashnode.dev/create-a-basic-chatbot-in-python</link><guid isPermaLink="true">https://smartrs.hashnode.dev/create-a-basic-chatbot-in-python</guid><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[chatbot]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Mon, 01 Apr 2024 09:55:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724479900753/94fd7adb-bb56-403a-8171-9f774d095bda.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Source of the code:</strong> this tutorial is based on <a href="https://github.com/MatthewInkawhich/pytorch-chatbot">Matthew Inkawhich's PyTorch chatbot tutorial</a>.</p>
<p>In this tutorial, we will explore an engaging application of recurrent sequence-to-sequence models. Our goal is to create a basic chatbot using movie scripts from the Cornell Movie-Dialogs Corpus.</p>
<p>Conversational models are currently a popular area of research in artificial intelligence. Chatbots are used in many scenarios, such as customer service platforms and online helpdesks. These bots typically rely on retrieval-based models, which provide predefined responses to specific types of questions. While these models may suffice in narrow domains like a company's IT helpdesk, they are not robust enough for broader applications. The challenge of teaching a machine to engage in meaningful conversations across different domains remains unsolved. The recent surge in deep learning has led to the development of powerful generative models such as Google's Neural Conversational Model, which represents a significant advancement in multi-domain generative conversational models. In this tutorial, we will demonstrate how to implement a similar model in PyTorch.</p>
<p>Download the <a href="https://github.com/MatthewInkawhich/pytorch-chatbot/tree/c584736728730af8fc47c471685bf286425f6d84/data/cornell%20movie-dialogs%20corpus">data</a></p>
<pre><code class="language-python">import os

# Get the current working directory
os.getcwd()


%matplotlib inline

# import modules and libraries
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import torch
from torch.jit import script, trace
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
import csv
import random
import re
import os
import unicodedata
import codecs
from io import open
import itertools
import math

# Define the name of the corpus
corpus_name = "movie-corpus"

# Specify the path to the corpus directory
corpus = os.path.join("data", corpus_name)


def printLines(file, n=10):
    # Open the file in binary mode to read
    with open(file, 'rb') as datafile:
        # Read all lines from the file
        lines = datafile.readlines()

    # Print the first n lines
    for line in lines[:n]:
        print(line)
# Call the function
printLines(os.path.join(corpus, "movie_lines.txt"))

# Splits each line of the file into a dictionary of fields
def loadLines(fileName, fields):
    lines = {}
    with open(fileName, 'r', encoding='iso-8859-1') as f:
        for line in f:
            values = line.split(" +++$+++ ")
            # Extract fields
            lineObj = {}
            for i, field in enumerate(fields):
                lineObj[field] = values[i]
            lines[lineObj['lineID']] = lineObj
    return lines

# Groups fields of lines from `loadLines` into conversations based on *movie_conversations.txt*
def loadConversations(fileName, lines, fields):
    conversations = []
    with open(fileName, 'r', encoding='iso-8859-1') as f:
        for line in f:
            values = line.split(" +++$+++ ")
            # Extract fields
            convObj = {}
            for i, field in enumerate(fields):
                convObj[field] = values[i]
            # Convert string to list (convObj["utteranceIDs"] == "['L598485', 'L598486', ...]")
            lineIds = eval(convObj["utteranceIDs"])
            # Reassemble lines
            convObj["lines"] = []
            for lineId in lineIds:
                convObj["lines"].append(lines[lineId])
            conversations.append(convObj)
    return conversations

# Extracts pairs of sentences from conversations
def extractSentencePairs(conversations):
    qa_pairs = []
    for conversation in conversations:
        # Iterate over all the lines of the conversation
        for i in range(len(conversation["lines"]) - 1):  # We ignore the last line (no answer for it)
            inputLine = conversation["lines"][i]["text"].strip()
            targetLine = conversation["lines"][i+1]["text"].strip()
            # Filter wrong samples (if one of the lists is empty)
            if inputLine and targetLine:
                qa_pairs.append([inputLine, targetLine])
    return qa_pairs

# Define path to new file
datafile = os.path.join(corpus, "formatted_movie_lines.txt")

delimiter = '\t'
# Unescape the delimiter
delimiter = str(codecs.decode(delimiter, "unicode_escape"))

# Initialize lines dict, conversations list, and field ids
lines = {}
conversations = []
MOVIE_LINES_FIELDS = ["lineID", "characterID", "movieID", "character", "text"]
MOVIE_CONVERSATIONS_FIELDS = ["character1ID", "character2ID", "movieID", "utteranceIDs"]

# Load lines and process conversations
print("\nProcessing corpus...")
lines = loadLines(os.path.join(corpus, "movie_lines.txt"), MOVIE_LINES_FIELDS)
print("\nLoading conversations...")
conversations = loadConversations(os.path.join(corpus, "movie_conversations.txt"),
                                  lines, MOVIE_CONVERSATIONS_FIELDS)

# Write new csv file
print("\nWriting newly formatted file...")
with open(datafile, 'w', encoding='utf-8') as outputfile:
    writer = csv.writer(outputfile, delimiter=delimiter, lineterminator='\n')
    for pair in extractSentencePairs(conversations):
        writer.writerow(pair)

# Print a sample of lines
print("\nSample lines from file:")
printLines(datafile)

# Default word tokens
PAD_token = 0  # Used for padding short sentences
SOS_token = 1  # Start-of-sentence token
EOS_token = 2  # End-of-sentence token

class Voc:
    def __init__(self, name):
        self.name = name
        self.trimmed = False
        self.word2index = {}
        self.word2count = {}
        self.index2word = {PAD_token: "PAD", SOS_token: "SOS", EOS_token: "EOS"}
        self.num_words = 3  # Count SOS, EOS, PAD

    def addSentence(self, sentence):
        for word in sentence.split(' '):
            self.addWord(word)

    def addWord(self, word):
        if word not in self.word2index:
            self.word2index[word] = self.num_words
            self.word2count[word] = 1
            self.index2word[self.num_words] = word
            self.num_words += 1
        else:
            self.word2count[word] += 1

    # Remove words below a certain count threshold
    def trim(self, min_count):
        if self.trimmed:
            return
        self.trimmed = True

        keep_words = []

        for k, v in self.word2count.items():
            if v &gt;= min_count:
                keep_words.append(k)

        print('keep_words {} / {} = {:.4f}'.format(
            len(keep_words), len(self.word2index), len(keep_words) / len(self.word2index)
        ))

        # Reinitialize dictionaries
        self.word2index = {}
        self.word2count = {}
        self.index2word = {PAD_token: "PAD", SOS_token: "SOS", EOS_token: "EOS"}
        self.num_words = 3 # Count default tokens

        for word in keep_words:
            self.addWord(word)

MAX_LENGTH = 10  # Maximum sentence length to consider

# Turn a Unicode string to plain ASCII, thanks to
# https://stackoverflow.com/a/518232/2809427
def unicodeToAscii(s):
    return ''.join(
        c for c in unicodedata.normalize('NFD', s)
        if unicodedata.category(c) != 'Mn'
    )

# Lowercase, trim, and remove non-letter characters
def normalizeString(s):
    s = unicodeToAscii(s.lower().strip())
    s = re.sub(r"([.!?])", r" \1", s)
    s = re.sub(r"[^a-zA-Z.!?]+", r" ", s)
    s = re.sub(r"\s+", r" ", s).strip()
    return s

# Read query/response pairs and return a voc object
def readVocs(datafile, corpus_name):
    print("Reading lines...")
    # Read the file and split into lines
    lines = open(datafile, encoding='utf-8').\
        read().strip().split('\n')
    # Split every line into pairs and normalize
    pairs = [[normalizeString(s) for s in l.split('\t')] for l in lines]
    voc = Voc(corpus_name)
    return voc, pairs

# Returns True iff both sentences in a pair 'p' are under the MAX_LENGTH threshold
def filterPair(p):
    # Input sequences need to preserve the last word for EOS token
    return len(p[0].split(' ')) &lt; MAX_LENGTH and len(p[1].split(' ')) &lt; MAX_LENGTH

# Filter pairs using filterPair condition
def filterPairs(pairs):
    return [pair for pair in pairs if filterPair(pair)]

# Using the functions defined above, return a populated voc object and pairs list
def loadPrepareData(corpus, corpus_name, datafile, save_dir):
    print("Start preparing training data ...")
    voc, pairs = readVocs(datafile, corpus_name)
    print("Read {!s} sentence pairs".format(len(pairs)))
    pairs = filterPairs(pairs)
    print("Trimmed to {!s} sentence pairs".format(len(pairs)))
    print("Counting words...")
    for pair in pairs:
        voc.addSentence(pair[0])
        voc.addSentence(pair[1])
    print("Counted words:", voc.num_words)
    return voc, pairs


# Load/Assemble voc and pairs
save_dir = os.path.join("data", "save")
voc, pairs = loadPrepareData(corpus, corpus_name, datafile, save_dir)
# Print some pairs to validate
print("\npairs:")
for pair in pairs[:10]:
    print(pair)

MIN_COUNT = 3    # Minimum word count threshold for trimming

def trimRareWords(voc, pairs, MIN_COUNT):
    # Trim words used under the MIN_COUNT from the voc
    voc.trim(MIN_COUNT)
    # Filter out pairs with trimmed words
    keep_pairs = []
    for pair in pairs:
        input_sentence = pair[0]
        output_sentence = pair[1]
        keep_input = True
        keep_output = True
        # Check input sentence
        for word in input_sentence.split(' '):
            if word not in voc.word2index:
                keep_input = False
                break
        # Check output sentence
        for word in output_sentence.split(' '):
            if word not in voc.word2index:
                keep_output = False
                break

        # Only keep pairs that do not contain trimmed word(s) in their input or output sentence
        if keep_input and keep_output:
            keep_pairs.append(pair)

    print("Trimmed from {} pairs to {}, {:.4f} of total".format(len(pairs), len(keep_pairs), len(keep_pairs) / len(pairs)))
    return keep_pairs


# Trim voc and pairs
pairs = trimRareWords(voc, pairs, MIN_COUNT)

def indexesFromSentence(voc, sentence):
    return [voc.word2index[word] for word in sentence.split(' ')] + [EOS_token]


def zeroPadding(l, fillvalue=PAD_token):
    return list(itertools.zip_longest(*l, fillvalue=fillvalue))

def binaryMatrix(l, value=PAD_token):
    m = []
    for i, seq in enumerate(l):
        m.append([])
        for token in seq:
            if token == PAD_token:
                m[i].append(0)
            else:
                m[i].append(1)
    return m

# Returns padded input sequence tensor and lengths
def inputVar(l, voc):
    indexes_batch = [indexesFromSentence(voc, sentence) for sentence in l]
    lengths = torch.tensor([len(indexes) for indexes in indexes_batch])
    padList = zeroPadding(indexes_batch)
    padVar = torch.LongTensor(padList)
    return padVar, lengths

# Returns padded target sequence tensor, padding mask, and max target length
def outputVar(l, voc):
    indexes_batch = [indexesFromSentence(voc, sentence) for sentence in l]
    max_target_len = max([len(indexes) for indexes in indexes_batch])
    padList = zeroPadding(indexes_batch)
    mask = binaryMatrix(padList)
    mask = torch.ByteTensor(mask)
    padVar = torch.LongTensor(padList)
    return padVar, mask, max_target_len

# Returns all items for a given batch of pairs
def batch2TrainData(voc, pair_batch):
    pair_batch.sort(key=lambda x: len(x[0].split(" ")), reverse=True)
    input_batch, output_batch = [], []
    for pair in pair_batch:
        input_batch.append(pair[0])
        output_batch.append(pair[1])
    inp, lengths = inputVar(input_batch, voc)
    output, mask, max_target_len = outputVar(output_batch, voc)
    return inp, lengths, output, mask, max_target_len


# Example for validation
small_batch_size = 5
batches = batch2TrainData(voc, [random.choice(pairs) for _ in range(small_batch_size)])
input_variable, lengths, target_variable, mask, max_target_len = batches

print("input_variable:", input_variable)
print("lengths:", lengths)
print("target_variable:", target_variable)
print("mask:", mask)
print("max_target_len:", max_target_len)

class EncoderRNN(nn.Module):
    def __init__(self, hidden_size, embedding, n_layers=1, dropout=0):
        super(EncoderRNN, self).__init__()
        self.n_layers = n_layers
        self.hidden_size = hidden_size
        self.embedding = embedding

        # Initialize GRU; the input_size and hidden_size params are both set to 'hidden_size'
        #   because our input size is a word embedding with number of features == hidden_size
        self.gru = nn.GRU(hidden_size, hidden_size, n_layers,
                          dropout=(0 if n_layers == 1 else dropout), bidirectional=True)

    def forward(self, input_seq, input_lengths, hidden=None):
        # Convert word indexes to embeddings
        embedded = self.embedding(input_seq)
        # Pack padded batch of sequences for RNN module
        packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths)
        # Forward pass through GRU
        outputs, hidden = self.gru(packed, hidden)
        # Unpack padding
        outputs, _ = torch.nn.utils.rnn.pad_packed_sequence(outputs)
        # Sum bidirectional GRU outputs
        outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:]
        # Return output and final hidden state
        return outputs, hidden

# Luong attention layer
class Attn(torch.nn.Module):
    def __init__(self, method, hidden_size):
        super(Attn, self).__init__()
        self.method = method
        if self.method not in ['dot', 'general', 'concat']:
            raise ValueError(self.method, "is not an appropriate attention method.")
        self.hidden_size = hidden_size
        if self.method == 'general':
            self.attn = torch.nn.Linear(self.hidden_size, hidden_size)
        elif self.method == 'concat':
            self.attn = torch.nn.Linear(self.hidden_size * 2, hidden_size)
            self.v = torch.nn.Parameter(torch.FloatTensor(hidden_size))

    def dot_score(self, hidden, encoder_output):
        return torch.sum(hidden * encoder_output, dim=2)

    def general_score(self, hidden, encoder_output):
        energy = self.attn(encoder_output)
        return torch.sum(hidden * energy, dim=2)

    def concat_score(self, hidden, encoder_output):
        energy = self.attn(torch.cat((hidden.expand(encoder_output.size(0), -1, -1), encoder_output), 2)).tanh()
        return torch.sum(self.v * energy, dim=2)

    def forward(self, hidden, encoder_outputs):
        # Calculate the attention weights (energies) based on the given method
        if self.method == 'general':
            attn_energies = self.general_score(hidden, encoder_outputs)
        elif self.method == 'concat':
            attn_energies = self.concat_score(hidden, encoder_outputs)
        elif self.method == 'dot':
            attn_energies = self.dot_score(hidden, encoder_outputs)

        # Transpose max_length and batch_size dimensions
        attn_energies = attn_energies.t()

        # Return the softmax normalized probability scores (with added dimension)
        return F.softmax(attn_energies, dim=1).unsqueeze(1)

class LuongAttnDecoderRNN(nn.Module):
    def __init__(self, attn_model, embedding, hidden_size, output_size, n_layers=1, dropout=0.1):
        super(LuongAttnDecoderRNN, self).__init__()

        # Keep for reference
        self.attn_model = attn_model
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.n_layers = n_layers
        self.dropout = dropout

        # Define layers
        self.embedding = embedding
        self.embedding_dropout = nn.Dropout(dropout)
        self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=(0 if n_layers == 1 else dropout))
        self.concat = nn.Linear(hidden_size * 2, hidden_size)
        self.out = nn.Linear(hidden_size, output_size)

        self.attn = Attn(attn_model, hidden_size)

    def forward(self, input_step, last_hidden, encoder_outputs):
        # Note: we run this one step (word) at a time
        # Get embedding of current input word
        embedded = self.embedding(input_step)
        embedded = self.embedding_dropout(embedded)
        # Forward through unidirectional GRU
        rnn_output, hidden = self.gru(embedded, last_hidden)
        # Calculate attention weights from the current GRU output
        attn_weights = self.attn(rnn_output, encoder_outputs)
        # Multiply attention weights to encoder outputs to get new "weighted sum" context vector
        context = attn_weights.bmm(encoder_outputs.transpose(0, 1))
        # Concatenate weighted context vector and GRU output using Luong eq. 5
        rnn_output = rnn_output.squeeze(0)
        context = context.squeeze(1)
        concat_input = torch.cat((rnn_output, context), 1)
        concat_output = torch.tanh(self.concat(concat_input))
        # Predict next word using Luong eq. 6
        output = self.out(concat_output)
        output = F.softmax(output, dim=1)
        # Return output and final hidden state
        return output, hidden

def maskNLLLoss(inp, target, mask):
    nTotal = mask.sum()
    crossEntropy = -torch.log(torch.gather(inp, 1, target.view(-1, 1)).squeeze(1))
    mask = mask.type(torch.BoolTensor)  # Convert mask to BoolTensor
    loss = crossEntropy.masked_select(mask).mean()
    loss = loss.to(device)
    return loss, nTotal.item()

def train(input_variable, lengths, target_variable, mask, max_target_len, encoder, decoder, embedding,
          encoder_optimizer, decoder_optimizer, batch_size, clip, max_length=MAX_LENGTH):

    # Zero gradients
    encoder_optimizer.zero_grad()
    decoder_optimizer.zero_grad()

    # Set device options
    input_variable = input_variable.to(device)
    lengths = lengths.to(device)
    target_variable = target_variable.to(device)
    mask = mask.to(device)

    # Initialize variables
    loss = 0
    print_losses = []
    n_totals = 0

    # Forward pass through encoder
    encoder_outputs, encoder_hidden = encoder(input_variable, lengths)

    # Create initial decoder input (start with SOS tokens for each sentence)
    decoder_input = torch.LongTensor([[SOS_token for _ in range(batch_size)]])
    decoder_input = decoder_input.to(device)

    # Set initial decoder hidden state to the encoder's final hidden state
    decoder_hidden = encoder_hidden[:decoder.n_layers]

    # Determine if we are using teacher forcing this iteration
    use_teacher_forcing = True if random.random() &lt; teacher_forcing_ratio else False

    # Forward batch of sequences through decoder one time step at a time
    if use_teacher_forcing:
        for t in range(max_target_len):
            decoder_output, decoder_hidden = decoder(
                decoder_input, decoder_hidden, encoder_outputs
            )
            # Teacher forcing: next input is current target
            decoder_input = target_variable[t].view(1, -1)
            # Calculate and accumulate loss
            mask_loss, nTotal = maskNLLLoss(decoder_output, target_variable[t], mask[t])
            loss += mask_loss
            print_losses.append(mask_loss.item() * nTotal)
            n_totals += nTotal
    else:
        for t in range(max_target_len):
            decoder_output, decoder_hidden = decoder(
                decoder_input, decoder_hidden, encoder_outputs
            )
            # No teacher forcing: next input is decoder's own current output
            _, topi = decoder_output.topk(1)
            decoder_input = torch.LongTensor([[topi[i][0] for i in range(batch_size)]])
            decoder_input = decoder_input.to(device)
            # Calculate and accumulate loss
            mask_loss, nTotal = maskNLLLoss(decoder_output, target_variable[t], mask[t])
            loss += mask_loss
            print_losses.append(mask_loss.item() * nTotal)
            n_totals += nTotal

    # Perform backpropatation
    loss.backward()

    # Clip gradients: gradients are modified in place
    _ = torch.nn.utils.clip_grad_norm_(encoder.parameters(), clip)
    _ = torch.nn.utils.clip_grad_norm_(decoder.parameters(), clip)

    # Adjust model weights
    encoder_optimizer.step()
    decoder_optimizer.step()

    return sum(print_losses) / n_totals

def trainIters(model_name, voc, pairs, encoder, decoder, encoder_optimizer, decoder_optimizer, embedding, encoder_n_layers, decoder_n_layers, save_dir, n_iteration, batch_size, print_every, save_every, clip, corpus_name, loadFilename):

    # Load batches for each iteration
    training_batches = [batch2TrainData(voc, [random.choice(pairs) for _ in range(batch_size)])
                      for _ in range(n_iteration)]

    # Initializations
    print('Initializing ...')
    start_iteration = 1
    print_loss = 0
    if loadFilename:
        start_iteration = checkpoint['iteration'] + 1

    # Training loop
    print("Training...")
    for iteration in range(start_iteration, n_iteration + 1):
        training_batch = training_batches[iteration - 1]
        # Extract fields from batch
        input_variable, lengths, target_variable, mask, max_target_len = training_batch

        # Run a training iteration with batch
        loss = train(input_variable, lengths, target_variable, mask, max_target_len, encoder,
                     decoder, embedding, encoder_optimizer, decoder_optimizer, batch_size, clip)
        print_loss += loss

        # Print progress
        if iteration % print_every == 0:
            print_loss_avg = print_loss / print_every
            print("Iteration: {}; Percent complete: {:.1f}%; Average loss: {:.4f}".format(iteration, iteration / n_iteration * 100, print_loss_avg))
            print_loss = 0

        # Save checkpoint
        if (iteration % save_every == 0):
            directory = os.path.join(save_dir, model_name, corpus_name, '{}-{}_{}'.format(encoder_n_layers, decoder_n_layers, hidden_size))
            if not os.path.exists(directory):
                os.makedirs(directory)
            torch.save({
                'iteration': iteration,
                'en': encoder.state_dict(),
                'de': decoder.state_dict(),
                'en_opt': encoder_optimizer.state_dict(),
                'de_opt': decoder_optimizer.state_dict(),
                'loss': loss,
                'voc_dict': voc.__dict__,
                'embedding': embedding.state_dict()
            }, os.path.join(directory, '{}_{}.tar'.format(iteration, 'checkpoint')))

class GreedySearchDecoder(nn.Module):
    def __init__(self, encoder, decoder):
        super(GreedySearchDecoder, self).__init__()
        self.encoder = encoder
        self.decoder = decoder

    def forward(self, input_seq, input_length, max_length):
        # Forward input through encoder model
        encoder_outputs, encoder_hidden = self.encoder(input_seq, input_length)
        # Prepare encoder's final hidden layer to be first hidden input to the decoder
        decoder_hidden = encoder_hidden[:decoder.n_layers]
        # Initialize decoder input with SOS_token
        decoder_input = torch.ones(1, 1, device=device, dtype=torch.long) * SOS_token
        # Initialize tensors to append decoded words to
        all_tokens = torch.zeros([0], device=device, dtype=torch.long)
        all_scores = torch.zeros([0], device=device)
        # Iteratively decode one word token at a time
        for _ in range(max_length):
            # Forward pass through decoder
            decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden, encoder_outputs)
            # Obtain most likely word token and its softmax score
            decoder_scores, decoder_input = torch.max(decoder_output, dim=1)
            # Record token and score
            all_tokens = torch.cat((all_tokens, decoder_input), dim=0)
            all_scores = torch.cat((all_scores, decoder_scores), dim=0)
            # Prepare current token to be next decoder input (add a dimension)
            decoder_input = torch.unsqueeze(decoder_input, 0)
        # Return collections of word tokens and scores
        return all_tokens, all_scores

def evaluate(encoder, decoder, searcher, voc, sentence, max_length=MAX_LENGTH):
    ### Format input sentence as a batch
    # words -&gt; indexes
    indexes_batch = [indexesFromSentence(voc, sentence)]
    # Create lengths tensor
    lengths = torch.tensor([len(indexes) for indexes in indexes_batch])
    # Transpose dimensions of batch to match models' expectations
    input_batch = torch.LongTensor(indexes_batch).transpose(0, 1)
    # Use appropriate device
    input_batch = input_batch.to(device)
    lengths = lengths.to(device)
    # Decode sentence with searcher
    tokens, scores = searcher(input_batch, lengths, max_length)
    # indexes -&gt; words
    decoded_words = [voc.index2word[token.item()] for token in tokens]
    return decoded_words


def evaluateInput(encoder, decoder, searcher, voc):
    input_sentence = ''
    while(1):
        try:
            # Get input sentence
            input_sentence = input('&gt; ')
            # Check if it is quit case
            if input_sentence == 'q' or input_sentence == 'quit': break
            # Normalize sentence
            input_sentence = normalizeString(input_sentence)
            # Evaluate sentence
            output_words = evaluate(encoder, decoder, searcher, voc, input_sentence)
            # Format and print response sentence
            output_words[:] = [x for x in output_words if not (x == 'EOS' or x == 'PAD')]
            print('Bot:', ' '.join(output_words))

        except KeyError:
            print("Error: Encountered unknown word.")

# Configure models
model_name = 'cb_model'
attn_model = 'dot'
#attn_model = 'general'
#attn_model = 'concat'
hidden_size = 500
encoder_n_layers = 2
decoder_n_layers = 2
dropout = 0.1
batch_size = 64

# Set checkpoint to load from; set to None if starting from scratch
loadFilename = None
checkpoint_iter = 4000

# Load model if a loadFilename is provided
if loadFilename:
    # If loading on same machine the model was trained on
    checkpoint = torch.load(loadFilename)
    # If loading a model trained on GPU to CPU
    #checkpoint = torch.load(loadFilename, map_location=torch.device('cpu'))
    encoder_sd = checkpoint['en']
    decoder_sd = checkpoint['de']
    encoder_optimizer_sd = checkpoint['en_opt']
    decoder_optimizer_sd = checkpoint['de_opt']
    embedding_sd = checkpoint['embedding']
    voc.__dict__ = checkpoint['voc_dict']

print('Building encoder and decoder ...')
# Initialize word embeddings
embedding = nn.Embedding(voc.num_words, hidden_size)
if loadFilename:
    embedding.load_state_dict(embedding_sd)
# Initialize encoder &amp; decoder models
encoder = EncoderRNN(hidden_size, embedding, encoder_n_layers, dropout)
decoder = LuongAttnDecoderRNN(attn_model, embedding, hidden_size, voc.num_words, decoder_n_layers, dropout)
if loadFilename:
    encoder.load_state_dict(encoder_sd)
    decoder.load_state_dict(decoder_sd)
# Use appropriate device
encoder = encoder.to(device)
decoder = decoder.to(device)
print('Models built and ready to go!')

# Configure training/optimization
clip = 50.0
teacher_forcing_ratio = 1.0
learning_rate = 0.0001
decoder_learning_ratio = 5.0
n_iteration = 4000
print_every = 1
save_every = 500

# Ensure dropout layers are in train mode
encoder.train()
decoder.train()

# Initialize optimizers
print('Building optimizers ...')
encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)
decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate * decoder_learning_ratio)
if loadFilename:
    encoder_optimizer.load_state_dict(encoder_optimizer_sd)
    decoder_optimizer.load_state_dict(decoder_optimizer_sd)

# Run training iterations
print("Starting Training!")
trainIters(model_name, voc, pairs, encoder, decoder, encoder_optimizer, decoder_optimizer,
           embedding, encoder_n_layers, decoder_n_layers, save_dir, n_iteration, batch_size,
           print_every, save_every, clip, corpus_name, loadFilename)

# Set dropout layers to eval mode
encoder.eval()
decoder.eval()

# Initialize search module
searcher = GreedySearchDecoder(encoder, decoder)

# Begin chatting (run the following line to begin)
evaluateInput(encoder, decoder, searcher, voc)
</code></pre>
]]></content:encoded></item><item><title><![CDATA[17- Wind Rose Plots for Different Time Periods]]></title><description><![CDATA[This code showcases the creation of wind rose plots for different time periods, using worldmet and openair packages, including wind rose plots for the…]]></description><link>https://smartrs.hashnode.dev/17-wind-rose-plots-for-different-time-periods</link><guid isPermaLink="true">https://smartrs.hashnode.dev/17-wind-rose-plots-for-different-time-periods</guid><category><![CDATA[#windrose]]></category><category><![CDATA[#openair]]></category><category><![CDATA[#worldmet]]></category><category><![CDATA[R Language]]></category><category><![CDATA[#Plots]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Fri, 16 Feb 2024 21:13:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1708117774184/82b93611-bbbf-44e3-8961-1f7f76fe443d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This code showcases the creation of wind rose plots for different time periods, using worldmet and openair packages, including wind rose plots for the entire period, specific months, and seasonal wind rose plots. Each section demonstrates a different approach to generating wind rose plots based on the specified time frame.</p>
<hr />
<h3>1. Wind Rose Plot for the Period 2014 to 2023</h3>
<pre><code class="language-r">library(openair)
library(worldmet)
# Define the start and end years for the period
start_year &lt;- 2014
end_year &lt;- 2023

# Initialize an empty list to store data for all years
all_years_data &lt;- data.frame()

# Loop through the years 2014 to 2023
for (year in start_year:end_year) {
  # Import NOAA data for the specific station and year
  met_data &lt;- importNOAA(code = "406356-99999", year = year)

  # Append the data for the current year to the list
  all_years_data &lt;- rbind(all_years_data, met_data)
}

# Create a wind rose plot for the aggregated data
windrose &lt;- windRose(all_years_data)

# Print the wind rose plot
print(windrose)

# Save the wind rose plot as a PNG file with specified width and height (600x600 pixels)
png("wind_rose_plot_Erbil_2014_2023.png", width = 600, height = 600)
print(windrose)
dev.off()
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708117651003/e92b0294-7ef1-49dd-95b1-a612f4e2e8b0.png" alt="" style="display:block;margin:0 auto" />

<h3>2. Wind Rose Plots for Specific Months from 2014 to 2023</h3>
<pre><code class="language-r"># Define the start and end years for the period
start_year &lt;- 2020
end_year &lt;- 2022

# Initialize an empty list to store wind rose plots for each month
windrose_plots &lt;- list()

# Function to check and add missing columns as NA columns
add_missing_columns &lt;- function(data, ref_cols) {
  missing_cols &lt;- setdiff(ref_cols, colnames(data))
  for (col in missing_cols) {
    data[[col]] &lt;- NA
  }
  return(data)
}

# Loop through the months
for (month in 1:12) {
  # Initialize an empty data frame to store aggregated data for the month
  aggregated_data &lt;- data.frame()

  # Loop through the years in the period
  for (year in start_year:end_year) {
    # Import NOAA data for the specific station and year
    met_data &lt;- importNOAA(code = "406356-99999", year = year)

    # Filter data for the specific month and year
    met_data &lt;- subset(met_data, format(date, "%m") == sprintf("%02d", month))

    # Append the filtered data to the aggregated data frame
    if (nrow(met_data) &gt; 0) {
      if (nrow(aggregated_data) == 0) {
        aggregated_data &lt;- met_data
      } else {
        # Ensure all data frames have the same structure before combining them
        aggregated_data &lt;- rbind(aggregated_data, add_missing_columns(met_data, colnames(aggregated_data)))
      }
    }
  }

  # Create a wind rose plot for the aggregated data
  windrose &lt;- windRose(aggregated_data)

  # Store the wind rose plot in the list
  windrose_plots[[month]] &lt;- windrose
}

# Save the wind rose plots as PNG files
for (month in 1:12) {
  png(paste("Erbil_for_period_wind_rose_plot_month_", month, ".png", sep = ""), width = 600, height = 600)
  print(windrose_plots[[month]])
  dev.off()
}
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708117691883/fb3aa867-caac-4c82-89ba-923f7e32198e.png" alt="" style="display:block;margin:0 auto" />

<h3>3. Seasonal Wind Rose Plots for the Period 2014 to 2023</h3>
<pre><code class="language-r"># Load necessary packages
library(openair)   # Package for air quality data analysis and visualization
library(worldmet)

# Define the start and end years for the period
start_year &lt;- 2020
end_year &lt;- 2022

# Define the start and end months for each season
seasons &lt;- list(
  Spring = c(3, 4, 5),
  Summer = c(6, 7, 8),
  Autumn = c(9, 10, 11),
  Winter = c(12, 1, 2)  # December of the current year and January and February of the next year
)

# Initialize an empty list to store wind rose plots for each season
windrose_seasonal_plots &lt;- list()

# Loop through the seasons
for (season_name in names(seasons)) {
  # Initialize an empty data frame to store aggregated data for the season
  aggregated_seasonal_data &lt;- NULL

  # Extract start and end months for the current season
  season_months &lt;- seasons[[season_name]]

  # Loop through the years in the period
  for (year in start_year:end_year) {
    # Import NOAA data for the specific station and year
    met_data &lt;- importNOAA(code = "406356-99999", year = year)

    # Filter data for the specific months of the current season
    met_data_season &lt;- subset(met_data, format(date, "%m") %in% sprintf("%02d", season_months))

    # Append the filtered data to the aggregated data frame for the current season
    if (nrow(met_data_season) &gt; 0) {
      if (is.null(aggregated_seasonal_data)) {
        aggregated_seasonal_data &lt;- met_data_season
      } else {
        # Ensure all data frames have the same structure before combining them
        if (identical(names(aggregated_seasonal_data), names(met_data_season))) {
          aggregated_seasonal_data &lt;- rbind(aggregated_seasonal_data, met_data_season)
        } else {
          warning("Data frame structure mismatch. Skipping...")
        }
      }
    }
  }

  # Print the structure of the aggregated data frame
  print(str(aggregated_seasonal_data))

  # Create a wind rose plot for the aggregated seasonal data
  windrose_seasonal &lt;- windRose(aggregated_seasonal_data)

  # Store the wind rose plot in the list
  windrose_seasonal_plots[[season_name]] &lt;- windrose_seasonal
}

# Save the wind rose plots for each season as PNG files
for (season_name in names(seasons)) {
  png(paste("Erbil_for_period_wind_rose_plot_", season_name, ".png", sep = ""), width = 600, height = 600)
  print(windrose_seasonal_plots[[season_name]])
  dev.off()
}
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708117729725/c1da120a-22a8-440b-ab7f-d591a0e05e35.png" alt="" style="display:block;margin:0 auto" />

<p>In this blog post, we explored how to create wind rose plots using the <code>openair</code> and <code>worldmet</code> packages in R. Wind rose plots are valuable tools for visualizing wind patterns over a specified period. We demonstrated how to generate wind rose plots for different time periods, including yearly, monthly, and seasonal aggregations, using historical weather data from NOAA. By following these examples, researchers and weather enthusiasts can gain insights into the prevailing wind directions and speeds, which can be useful for various applications such as climate studies, urban planning, and renewable energy assessments. With the flexibility of R and the comprehensive data provided by NOAA, creating informative wind rose plots has never been easier.</p>
]]></content:encoded></item><item><title><![CDATA[16- Analyzing Annual Weather Data with R]]></title><description><![CDATA[In this blog post, we'll explore how to import and analyze annual weather data using R programming. The focus will be on a specific weather station with…]]></description><link>https://smartrs.hashnode.dev/16-analyzing-annual-weather-data-with-r</link><guid isPermaLink="true">https://smartrs.hashnode.dev/16-analyzing-annual-weather-data-with-r</guid><category><![CDATA[R Language]]></category><category><![CDATA[weather]]></category><category><![CDATA[functions]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sun, 04 Feb 2024 15:47:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1707124207947/6ea665f8-ec6a-4697-9358-dd28db34e9bf.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog post, we'll explore how to import and analyze annual weather data using R programming. The focus will be on a specific weather station with the code "406210-99999" in Kirkuk. We'll calculate annual means (or sums, e.g. for precipitation) for various weather variables and visualize the results. Let's dive into the code step by step.</p>
<h2>Load Necessary Packages</h2>
<pre><code class="language-R"># Load necessary packages
library(worldmet)  # Package for importing NOAA weather data
library(dplyr)      # Package for data manipulation
library(lubridate)  # For handling dates
</code></pre>
<h2>Define the Import and Analysis Function</h2>
<pre><code class="language-r"># Function to import NOAA data and calculate annual means (or sums)
import_and_calculate_means &lt;- function(year) {
  # Import weather data for a specific station and a given year
  data &lt;- importNOAA(code = "406210-99999", year = year)

  # Convert the date column to a Date type if it's not already in that format
  data$date &lt;- as.Date(data$date)

  # Extract year from the date column using lubridate package
  data$year &lt;- year(data$date)

  # Select only numeric columns for summarization
  numeric_data &lt;- data %&gt;% select_if(is.numeric)

  # Group by year and calculate annual means (or sums) for each numeric variable
  annual_data &lt;- numeric_data %&gt;%
    group_by(year) %&gt;%
    #summarize(across(everything(), sum, na.rm = TRUE))
    summarize(across(everything(), mean, na.rm = TRUE))

  # Show the resulting annual aggregated data
  print(annual_data)

  # Write the data to a CSV file with a filename indicating the station code and the year
  #write.csv(annual_data, paste("Kirkuk_Weather_data_annual_sum_", year, ".csv", sep = ""), row.names = TRUE)
  write.csv(annual_data, paste("Kirkuk_Weather_data_annual_average_", year, ".csv", sep = ""), row.names = TRUE)
}
</code></pre>
<h2>Loop Through the Years and Execute the Function</h2>
<pre><code class="language-r"># Loop through the years 2014 to 2023 and apply the import_and_calculate_means function
for (year in 2014:2023) {
  import_and_calculate_means(year)
  #import_and_calculate_sums(year)
}
</code></pre>
<p>Feel free to run this code in your R environment, and don't forget to share your findings and visualizations based on the annual weather data. Happy coding!</p>
<h2>Here's the entire R code</h2>
<pre><code class="language-r"># Load necessary packages
library(worldmet)  # Package for importing NOAA weather data
library(dplyr)      # Package for data manipulation
library(lubridate)  # For handling dates

# Function to import NOAA data and calculate annual means
import_and_calculate_means &lt;- function(year) {
  # Import weather data for a specific station and a given year
  data &lt;- importNOAA(code = "406210-99999", year = year)

  # Convert the date column to a Date type if it's not already in that format
  data$date &lt;- as.Date(data$date)

  # Extract year from the date column using lubridate package
  data$year &lt;- year(data$date)

  # Select only numeric columns for summarization
  numeric_data &lt;- data %&gt;% select_if(is.numeric)

  # Group by year and calculate annual means for each numeric variable
  annual_data &lt;- numeric_data %&gt;%
    group_by(year) %&gt;%
    summarize(across(everything(), mean, na.rm = TRUE))

  # Show the resulting annual aggregated data
  print(annual_data)

  # Write the data to a CSV file with a filename indicating the station code and the year
  write.csv(annual_data, paste("Kirkuk_Weather_data_annual_sum_", year, ".csv", sep = ""), row.names = TRUE)
}

# Loop through the years 2014 to 2023 and apply the import_and_calculate_means function
for (year in 2014:2023) {
  import_and_calculate_means(year)
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[5- 🌟Let's Package Python!🌟]]></title><description><![CDATA[🐍📦 Hey there, future Python wizards! Ready to share your code with the world? Let's make it happen step by step! 🌟 Creating Your Project Structure: 📁…]]></description><link>https://smartrs.hashnode.dev/5-lets-package-python</link><guid isPermaLink="true">https://smartrs.hashnode.dev/5-lets-package-python</guid><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[python beginner]]></category><category><![CDATA[package]]></category><category><![CDATA[Kids]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Tue, 02 Jan 2024 19:25:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704223145917/172798ed-cf24-40eb-9f88-b0f6cbbd5791.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>🐍📦</strong> Hey there, future Python wizards! Ready to share your code with the world? Let's make it happen step by step! 🌟</p>
<p><strong>Creating Your Project Structure:</strong></p>
<p>📁 Create a folder named <code>packaging</code>. 📁 Inside <code>packaging</code>, add another folder named <code>src</code>. 📁 Within <code>src</code>, craft a folder with your project name, let's say <code>smartrs</code>. 📄 Pop in an empty <code>__init__.py</code> file and an awesome <code>example.py</code> file with cool code! 💻</p>
<p><strong>Configuring Your Files:</strong></p>
<p>📄 In the main <code>packaging</code> folder, add essential files like <code>LICENSE</code>, <code>pyproject.toml</code>, and <code>README.md</code>. 📁 Don't forget to create an empty <code>tests/</code> directory for later testing.</p>
<p><strong>Setting Up the</strong> <code>pyproject.toml</code> <strong>File:</strong></p>
<p>🛠️ Open <code>pyproject.toml</code> and paste the special incantation to set up your project. 🪄</p>
<p><strong>Crafting README &amp; License:</strong></p>
<p>📜 Fill your <code>README.md</code> with all the fun details about your package! Use Markdown for extra pizzazz! ✨ 📜 Don't skip the <code>LICENSE</code> file! Use a cool license like MIT to make your project legit! 🕶️</p>
<p><strong>Creating Distribution Packages:</strong></p>
<p>💾 Now, it's time to create packages for your project using commands! Follow along for the mastery! ✨</p>
<p><strong>Uploading to PyPI:</strong></p>
<p>🌐 Get ready to share your creation on PyPI! Create an account and install Twine with a simple command. 🎉</p>
<p>📦 Upload your package to PyPI using Twine! You'll need your PyPI account credentials for this. 🌟</p>
<p><strong>Checking Your Awesome Work:</strong></p>
<p>✅ Your package is now live on PyPI! 🎈 Install it using <code>pip install smartrs==0.0.1</code> to test its superpowers! 💪</p>
<p><strong>Hooray! You Did It! 🎉</strong></p>
<p>That's it, young coders! You've packaged your Python project like a pro! Keep coding, sharing, and exploring new tricks! For more details, check out the links below! Happy coding!</p>
<p>📚 Learn More:</p>
<ul>
<li><p><a href="https://smartrs.hashnode.dev/step-by-step-guide-to-packaging-and-publishing-python-projects-on-pypi">Step-by-Step Guide to Packaging and Publishing Python Projects on PyPI</a></p>
</li>
<li><p><a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/">Packaging Python Projects</a></p>
</li>
<li><p><a href="https://www.tutorialsteacher.com/python/python-package">Python Packages Tutorial</a></p>
</li>
<li><p><a href="https://www.youtube.com/watch?v=EIwLZiTuYoA">Create &amp; Publish Python Packages on PyPI in 5 Minutes! 🎬</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[4- 🌟 Pykid Modules 🌟]]></title><description><![CDATA[Ready for an awesome Python adventure? Let's dive into a world of fun with code, where we can make computers do amazing things! ✨ First up, let's learn how…]]></description><link>https://smartrs.hashnode.dev/4-pykid-modules</link><guid isPermaLink="true">https://smartrs.hashnode.dev/4-pykid-modules</guid><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[python beginner]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Tue, 02 Jan 2024 15:45:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704210244381/522d69e2-82b5-43c6-a492-107611149ae4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>Hey there, coding explorers!</h3>
<p>Ready for an awesome Python adventure? Let's dive into a world of fun with code, where we can make computers do amazing things! ✨</p>
<p>First up, let's learn how to add numbers and words together by creating a simple module! 🪄</p>
<p>Imagine we have a super-special treasure chest called <code>my_module.py</code>. Inside, we'll store a function ✨ called <code>add</code> that can add numbers or join words!</p>
<p><strong>Here's how it looks:</strong></p>
<pre><code class="language-python">def add(a, b):  # This line says: "Hey, here's a function named 'add' that takes two things!"
  return a + b  # This line says: "Take those two things and add them together!"
</code></pre>
<p>For example, if you use Jupyter Notebook, create a new text file, write the code in it, and save it as <code>my_module.py</code> in your working directory.</p>
<p>To use our fun <code>add</code> function, we'll open the treasure chest like this:</p>
<pre><code class="language-python">import my_module  # This line says: "Hey, let's bring in the 'my_module' treasure chest!"
from my_module import add  # This line says: "And let's take out the 'add' function from the chest!"
</code></pre>
<p>Now, let's test it out!</p>
<ul>
<li>Adding numbers:</li>
</ul>
<pre><code class="language-python">add(2023, 2024)  # This line says: "Use the 'add' function to add 2023 and 2024!"
# Output: 4047
</code></pre>
<ul>
<li>Adding words:</li>
</ul>
<pre><code class="language-python">add("Python", " is fun!")  # This line says: "Add 'Python' and ' is fun!' together!"
# Output: Python is fun!
</code></pre>
<p>Wait, there's more! Let's make some animal sounds!</p>
<p>We'll use the <code>playsound</code> module from the <strong>playsound</strong> library (install it with <code>pip install playsound</code>) and create another fun function ✨ called <code>sound</code>!</p>
<p><strong>Here's how it works:</strong></p>
<pre><code class="language-python">from playsound import playsound  # This line says: "Bring in the 'playsound' module!"

def sound(animal): # This line says: "Here's a function named 'sound' that takes the name of an animal!"
    if animal == 'cat':
        playsound('https://www.myinstants.com/media/sounds/meow_3.mp3')
    elif animal == 'dog':
        playsound('https://www.myinstants.com/media/sounds/dog-barking-sound-effect.mp3')
    elif animal == 'cow':
        playsound('https://www.myinstants.com/media/sounds/cow1.mp3')
    elif animal == 'duck':
        playsound('https://www.myinstants.com/media/sounds/duck.mp3')
    else:
        print("Sorry, I don't know that animal's sound!") # Oops!
</code></pre>
<p>Save these fun sounds in a treasure chest called <code>module_sound.py</code>! ✨ Then import it with <code>from module_sound import sound</code>.</p>
<p>Now, let's hear some animals! Try 'cat', 'dog', 'duck', or 'cow'!</p>
<pre><code class="language-python">sound("cat")
sound("dog")
sound("duck")
sound("cow")
sound("lion") # Output: Sorry, I don't know that animal's sound!
</code></pre>
<p>Built-in modules</p>
<p>Python comes with several built-in modules that we can import and use in our programs.</p>
<p>We can even ask the computer what kind of system it is!</p>
<pre><code class="language-python">import platform
print("Your platform system is:", platform.system())  # This line says: "Tell me what kind of computer you are!"
# Output: Your platform system is: Windows 🪟
</code></pre>
<p>Stay tuned for more exciting coding adventures!</p>
]]></content:encoded></item><item><title><![CDATA[3- 🌟 Pykid Functions 🌟]]></title><description><![CDATA[Think of a function as a super-cool gadget that can do a special job for you, just like a robot helper! Let's create a gadget called "my_function": Now, we…]]></description><link>https://smartrs.hashnode.dev/3-pykid-functions</link><guid isPermaLink="true">https://smartrs.hashnode.dev/3-pykid-functions</guid><category><![CDATA[Functional Programming]]></category><category><![CDATA[functions]]></category><category><![CDATA[Python]]></category><category><![CDATA[Kids]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Mon, 01 Jan 2024 10:47:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704112647030/a5147f48-3557-473f-9678-ee8552431a83.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Think of a function as a super-cool gadget that can do a special job for you, just like a robot helper!</p>
<p>Let's create a gadget called "my_function":</p>
<pre><code class="language-python">def my_function(): # Inside the gadget, we write the instructions for its job:
     print("👋 Hello from Pykid!")
</code></pre>
<p>Now, we can use the gadget by calling its name, like pressing a button:</p>
<pre><code class="language-python">my_function() # This makes the gadget do its job, and we see the message!
# Output: 👋 Hello from Pykid!
</code></pre>
<p>We can make our gadgets even more awesome by giving them special tools to work with!</p>
<p>For example, let's give a gadget a name to use in a greeting:</p>
<pre><code class="language-python">def greet_friend(name): # Now the gadget knows to use the name we give it:
     print(f" Hello, {name}! How are you today?")
</code></pre>
<p>Let's try it out!</p>
<pre><code class="language-python">greet_friend("Aisha")
# Output: Hello, Aisha! How are you today?
greet_friend("Anas")
# Output: Hello, Anas! How are you today?
</code></pre>
<p>Cool, right? The gadget can do different things depending on the tools we give it! It's like having a whole toolbox of gadgets!</p>
<p>Remember, functions are like our trusty robot helpers in coding, making our programs easier and more fun to build!</p>
<p><strong>Creating a Function to Introduce Animals:</strong></p>
<ul>
<li><p>Imagine a special machine called "animal_sounds" that knows about different animals and their sounds.</p>
</li>
<li><p>This machine takes the name of an animal as its input.</p>
</li>
<li><p>It has a set of instructions for each animal it knows:</p>
<ul>
<li><p>If you tell it "cat", it prints "🐱 A cat says: Meow!"</p>
</li>
<li><p>If you tell it "dog", it prints "🐶 A dog says: Woof!"</p>
</li>
<li><p>And so on for cows, ducks, and more!</p>
</li>
</ul>
</li>
<li><p>If you give it an animal it doesn't know, it politely says "Sorry, I don't know that animal!"</p>
</li>
</ul>
<pre><code class="language-python">def animal_sounds(animal):
    if animal == 'cat':
        print("🐱 A cat says: Meow!")
    elif animal == 'dog':
        print("🐶 A dog says: Woof!")
    elif animal == 'cow':
        print("🐮 A cow says: Moo!")
    elif animal == 'duck':
        print("🦆 A duck says: Quack!")
    else:
        print("Sorry, I don't know that animal!")

# Introducing different animals and their sounds
animal_sounds('cat')
# Output: 🐱 A cat says: Meow!

animal_sounds('dog')
# Output: 🐶 A dog says: Woof!

animal_sounds('cow')
# Output: 🐮 A cow says: Moo!

animal_sounds('duck')
# Output: 🦆 A duck says: Quack!

animal_sounds('elephant')
# Output: Sorry, I don't know that animal!
</code></pre>
<p><strong>Playing Animal Sounds:</strong></p>
<ul>
<li>We can make this machine even cooler by giving it the ability to play real animal sounds!</li>
<li>We import a special tool called "playsound" that can play audio files.</li>
<li>Now, instead of just printing the sound, the machine can play it out loud!</li>
<li>We give it the location of each sound file, like a map that helps the machine find the right sound.</li>
</ul>
<p><strong>Calling the Function:</strong></p>
<ul>
<li>To use the machine, we call it by its name, "animal_sounds", and give it the name of the animal we want to hear.</li>
<li>For example, <code>animal_sounds('cat')</code> plays the cat's meow.</li>
<li>We can call it many times to hear different animals!</li>
</ul>
<p>Note: install the tool first with <code>pip install playsound</code>.</p>
<pre><code class="language-python">from playsound import playsound

# Function to play animal sounds
def animal_sounds(animal):
    if animal == 'cat':
        playsound('https://www.myinstants.com/media/sounds/meow_3.mp3')
    elif animal == 'dog':
        playsound('https://www.myinstants.com/media/sounds/dog-barking-sound-effect.mp3')
    elif animal == 'cow':
        playsound('https://www.myinstants.com/media/sounds/cow1.mp3')
    elif animal == 'duck':
        playsound('https://www.myinstants.com/media/sounds/duck.mp3')
    else:
        print("Sorry, I don't know that animal's sound!")

# Calling the function to play animal sounds
animal_sounds('cat')
animal_sounds('dog')
animal_sounds('duck')
animal_sounds('cow')
</code></pre>
<p><strong>Handling Unknown Animals:</strong></p>
<pre><code class="language-python">animal_sounds('elephant')
# Output: Sorry, I don't know that animal's sound!
</code></pre>
]]></content:encoded></item><item><title><![CDATA[2- 🌟Pykid Control Flow🌟]]></title><description><![CDATA[Get set to explore Python, a language that's as exciting as playing with toys or creating your very own adventures! Here's your guide to making Python do…]]></description><link>https://smartrs.hashnode.dev/2-pykid-control-flow</link><guid isPermaLink="true">https://smartrs.hashnode.dev/2-pykid-control-flow</guid><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[Functional Programming]]></category><category><![CDATA[Kids]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sun, 31 Dec 2023 07:28:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704013564424/ac52d4b0-d85d-4ee2-ad37-ead7280b4f91.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3><strong>Welcome to Python's Playhouse! 🎉</strong></h3>
<p>Get set to explore Python, a language that's as exciting as playing with toys or creating your very own adventures!</p>
<p>Here's your guide to making Python do incredible things:</p>
<h3><strong>If...Else: The Decision Wizard!</strong></h3>
<p>Imagine Python as a magical genie granting wishes! It uses "if" and "else" to make choices, just like picking between pizza or pancakes. Example: Let's decide which animal is louder!</p>
<pre><code class="language-python">lion_roar = 100  # Imagine a lion's roar at 100 decibels!
bird_tweet = 80  # Imagine a chirping bird at 80 decibels!

if lion_roar &gt; bird_tweet:
    print("The lion roars louder! 🦁🔊")  # The king of the jungle is the loudest!
else:
    print("The bird's tweet is sweet! 🐦🎶")  # Birds sing, but lions roar louder!
</code></pre>
<h3><strong>While Loops: The Repeat Machine!</strong></h3>
<p>Python's "while" loop is like a magic trick that keeps going until it's time to stop! It repeats a fun action until a special condition is reached.</p>
<p>Example: Count the stars in the sky!</p>
<pre><code class="language-python">stars = 10  # Starting with 100 shiny stars!

while stars &gt; 0:
    print("I see a star! Total:", stars, "⭐️" * stars)  # Printing star emojis based on the number
    stars -= 1  # Wishing upon each star!

print("All stars wished upon! Make way for new wishes!")  # Time for new wishes to come true! 🌟✨
</code></pre>
<h3><strong>For Loops: The Word Explorer!</strong></h3>
<p>"For" loops are like taking a magnifying glass and examining one thing at a time! They help Python explore groups of stuff, like the letters in a word or toys in a toy chest. Example: Spell out your favorite animal—G-I-R-A-F-F-E!</p>
<pre><code class="language-python">animal = "GIRAFFE"

for letter in animal:  # Let's explore each letter in "GIRAFFE"
    print(letter, "🦒")  # Display each letter, one at a time!
</code></pre>
]]></content:encoded></item><item><title><![CDATA[17- Python-Based Kriging for Rainfall Interpolation in Erbil]]></title><description><![CDATA[This code performs spatial interpolation of rain data using kriging, enabling the estimation of rain values at unmeasured locations within the Erbil…]]></description><link>https://smartrs.hashnode.dev/17-python-based-kriging-for-rainfall-interpolation-in-erbil</link><guid isPermaLink="true">https://smartrs.hashnode.dev/17-python-based-kriging-for-rainfall-interpolation-in-erbil</guid><category><![CDATA[kriging]]></category><category><![CDATA[pykrige]]></category><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[research]]></category><category><![CDATA[Interpretation]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sat, 30 Dec 2023 19:26:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703965061399/c568e814-2814-4c7c-823f-9d20c48c4533.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This code performs spatial interpolation of rain data using kriging, enabling the estimation of rain values at unmeasured locations within the Erbil Governorate, based on the available data.</p>
<p><strong>1. Importing Necessary Libraries:</strong></p>
<ul>
<li><p><strong>pandas:</strong> Used for loading and manipulating tabular data, like the CSV file.</p>
</li>
<li><p><strong>numpy:</strong> Provides efficient array operations for numerical computations.</p>
</li>
<li><p><strong>pykrige.ok:</strong> Offers the OrdinaryKriging class for performing kriging interpolation.</p>
</li>
<li><p><strong>matplotlib.pyplot:</strong> Used to visualize data and create plots.</p>
</li>
</ul>
<p><strong>2. Loading Data:</strong></p>
<ul>
<li><code>data =</code> <code>pd.read_csv("Erbil_Rain.csv")</code>: Reads rain data from a CSV file named "Erbil_Rain.csv" into a pandas DataFrame.</li>
</ul>
<table>
<thead>
<tr>
<th>station</th>
<th>rain</th>
<th>x</th>
<th>y</th>
</tr>
</thead>
<tbody><tr>
<td>Qushtapa</td>
<td>350</td>
<td>44.0319</td>
<td>36.0039</td>
</tr>
<tr>
<td>Ainkwawa</td>
<td>414</td>
<td>44.0119</td>
<td>36.2206</td>
</tr>
<tr>
<td>Khabat</td>
<td>339</td>
<td>43.67039</td>
<td>36.2758</td>
</tr>
<tr>
<td>Bnaslawa</td>
<td>381</td>
<td>44.1124</td>
<td>36.15444</td>
</tr>
<tr>
<td>Shorsh</td>
<td>566</td>
<td>44.386</td>
<td>36.1786</td>
</tr>
<tr>
<td>Shaqlawa</td>
<td>810</td>
<td>44.3214</td>
<td>36.4056</td>
</tr>
<tr>
<td>Harir</td>
<td>591</td>
<td>44.355</td>
<td>36.5475</td>
</tr>
<tr>
<td>Khalifan</td>
<td>768</td>
<td>44.4006</td>
<td>36.6039</td>
</tr>
<tr>
<td>Soran</td>
<td>701</td>
<td>44.5428</td>
<td>36.6581</td>
</tr>
<tr>
<td>Rwandz</td>
<td>736</td>
<td>44.5339</td>
<td>36.6169</td>
</tr>
<tr>
<td>Choman</td>
<td>796</td>
<td>44.8808</td>
<td>36.6278</td>
</tr>
<tr>
<td>Sidakan</td>
<td>824</td>
<td>44.6711</td>
<td>36.7983</td>
</tr>
<tr>
<td>Mergasor</td>
<td>1384</td>
<td>44.3008</td>
<td>36.84</td>
</tr>
<tr>
<td>Makhmwr</td>
<td>257</td>
<td>43.57887</td>
<td>35.77511</td>
</tr>
<tr>
<td>Bastora</td>
<td>457</td>
<td>44.16148</td>
<td>36.33709</td>
</tr>
<tr>
<td>Dibaga</td>
<td>299</td>
<td>43.808</td>
<td>35.8747</td>
</tr>
<tr>
<td>Gwer</td>
<td>269</td>
<td>43.499</td>
<td>36.048</td>
</tr>
<tr>
<td>Barzewa</td>
<td>700</td>
<td>44.611</td>
<td>36.626</td>
</tr>
<tr>
<td>Koya</td>
<td>622</td>
<td>44.617</td>
<td>36.083</td>
</tr>
</tbody></table>
<p><strong>3. Extracting Data:</strong></p>
<ul>
<li><p><code>x = data['x']</code></p>
</li>
<li><p><code>y = data['y']</code></p>
</li>
<li><p><code>rain = data['rain']</code>: Extracts the x-coordinates, y-coordinates, and rain values from the DataFrame.</p>
</li>
</ul>
<p><strong>4. Creating a Kriging Object:</strong></p>
<ul>
<li><code>ok = OrdinaryKriging(x, y, rain, variogram_model='linear', verbose=False)</code>: Creates an instance of OrdinaryKriging for spatial interpolation, using a linear variogram model.</li>
</ul>
<p><strong>5. Defining a Grid for Interpolation:</strong></p>
<ul>
<li><p><code>grid_x = np.linspace(min(x), max(x), 100)</code></p>
</li>
<li><p><code>grid_y = np.linspace(min(y), max(y), 100)</code>: Creates evenly spaced grid points in the x and y directions, covering the spatial extent of the data.</p>
</li>
</ul>
<p><strong>6. Performing Kriging Interpolation:</strong></p>
<ul>
<li><code>z, ss = ok.execute('grid', grid_x, grid_y)</code>: Performs kriging interpolation on the defined grid, estimating rain values at each grid point and providing associated kriging variance (or squared standard deviation).</li>
</ul>
<p><strong>7. Plotting Original Data Points:</strong></p>
<ul>
<li><code>plt.scatter(x, y, c=rain, cmap='viridis', label='Original Data')</code>: Creates a scatter plot of the original data points, with colors representing rain values.</li>
</ul>
<p><strong>8. Plotting Interpolated Surface:</strong></p>
<ul>
<li><code>plt.contourf(grid_x, grid_y, z, cmap='viridis', levels=50)</code>: Creates a contour plot of the interpolated rain surface, smoothly visualizing the predicted rain values across the entire grid.</li>
</ul>
<p><strong>9. Displaying Plots:</strong></p>
<ul>
<li><code>plt.show()</code>: Shows both plots to visualize the original data and the interpolated surface.</li>
</ul>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703965027195/86705c89-ae08-4726-9af9-361206023565.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703965179020/dde4bdbd-0b53-42db-9a7a-b7f693714095.png" alt="" style="display:block;margin:0 auto" />

<p><strong>The full code is presented below:</strong></p>
<pre><code class="language-python">import pandas as pd
import numpy as np
from pykrige.ok import OrdinaryKriging
import matplotlib.pyplot as plt

# Load data from CSV
data = pd.read_csv("Erbil_Rain.csv")

# Assuming the columns are named station, rain, x, and y
x = data['x']
y = data['y']
rain = data['rain']

# Create an instance of OrdinaryKriging
ok = OrdinaryKriging(x, y, rain, variogram_model='linear', verbose=False)

# Define a grid to interpolate
grid_x = np.linspace(min(x), max(x), 100)  # Adjust the number of points as needed
grid_y = np.linspace(min(y), max(y), 100)  # Adjust the number of points as needed

# Perform kriging interpolation on the defined grid
z, ss = ok.execute('grid', grid_x, grid_y)

# Plotting original data points
plt.figure(figsize=(10, 6))

# Plot original data points
plt.scatter(x, y, c=rain, cmap='viridis', label='Original Data')
plt.colorbar(label='Rain (mm)')
plt.title('Original Data Points')
plt.xlabel('X')
plt.ylabel('Y')

# Contour plot of the interpolated surface
plt.figure(figsize=(10, 6))
plt.contourf(grid_x, grid_y, z, cmap='viridis', levels=50)
plt.colorbar(label='Interpolated rain (mm)')
plt.title('Kriging Interpolated Rain')
plt.xlabel('X')
plt.ylabel('Y')

plt.tight_layout()
plt.show()
</code></pre>
]]></content:encoded></item><item><title><![CDATA[1- 🌟Welcome and variables🌟]]></title><description><![CDATA[Welcome message print("👋 Hello, Anas! Let's dive into Python together!") Excitement for Python print("🐍 I'm super excited to learn Python!") Variables…]]></description><link>https://smartrs.hashnode.dev/1-welcome-and-variables</link><guid isPermaLink="true">https://smartrs.hashnode.dev/1-welcome-and-variables</guid><category><![CDATA[Python]]></category><category><![CDATA[Kids]]></category><category><![CDATA[coding]]></category><category><![CDATA[introduction]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sat, 30 Dec 2023 09:51:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704013243975/dcdb873b-d7c8-4ed0-a17f-4869363ecb48.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>Welcome message</h3>
<pre><code class="language-python">print("👋 Hello, Anas! Let's dive into Python together!")
</code></pre>
<h3>Excitement for Python</h3>
<pre><code class="language-python">print("🐍 I'm super excited to learn Python!")
</code></pre>
<h3>Variables with names</h3>
<pre><code class="language-python">author = "Anas"
reader = "Aviar"
</code></pre>
<h3>Print reader's name</h3>
<pre><code class="language-python">print("📚 Reader's name:", reader)
</code></pre>
<h3>Update reader's name</h3>
<pre><code class="language-python">reader = "Muhammad"
</code></pre>
<h3>Print updated reader's name</h3>
<pre><code class="language-python">print("📖 Updated reader's name:", reader)
</code></pre>
<h3>Variables with favorite things</h3>
<pre><code class="language-python">favorite_color = "green"
mood = "happy"
age = 10
school = "Kar"
favorite_food = "Briani"
</code></pre>
<h3>Printing favorite food using comma separation</h3>
<pre><code class="language-python">print("🍛 I love", favorite_food + "!")
</code></pre>
<h3>Printing favorite color using comma separation</h3>
<pre><code class="language-python">print("🎨 My favorite color is", favorite_color + "!")
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Python for Scientific Research: From Beginner to Advanced]]></title><description><![CDATA[This course is a comprehensive introduction to Python for scientific research. It covers all the essential topics you need to know to get started with…]]></description><link>https://smartrs.hashnode.dev/python-for-scientific-research-from-beginner-to-advanced</link><guid isPermaLink="true">https://smartrs.hashnode.dev/python-for-scientific-research-from-beginner-to-advanced</guid><category><![CDATA[Python]]></category><category><![CDATA[research]]></category><category><![CDATA[udemy]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Sun, 10 Sep 2023 21:35:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724480086814/35d81fd9-b2bb-422d-93a0-798de224586d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7">This course</a> is a comprehensive introduction to Python for scientific research. It covers all the essential topics you need to know to get started with Python, including:</p>
<ul>
<li><p>Installing Python and creating an environment</p>
</li>
<li><p>Python programming fundamentals, such as variables, data types, control flow, and functions</p>
</li>
<li><p>File handling</p>
</li>
<li><p>Statistics and scientific computation using NumPy and SciPy</p>
</li>
<li><p>Plotting in Python using Matplotlib</p>
</li>
<li><p>Case studies using Python for scientific research</p>
</li>
</ul>
<p><a target="_blank" href="https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7">The course</a> is designed for beginners who have no prior experience with Python. It is also a great refresher for those who have some experience with Python but want to learn more about its scientific capabilities.</p>
<p>The course is divided into six sections:</p>
<ul>
<li><p><strong>Section 1: Install Python and create environment</strong></p>
<ul>
<li>This section teaches you how to install Python and create a virtual environment for your projects.</li>
</ul>
</li>
<li><p><strong>Section 2: Python Programming Fundamentals</strong></p>
<ul>
<li>This section covers the basics of Python programming, such as variables, data types, control flow, and functions.</li>
</ul>
</li>
<li><p><strong>Section 3: File handling</strong></p>
<ul>
<li>This section teaches you how to read and write files in Python.</li>
</ul>
</li>
<li><p><strong>Section 4: Statistics and scientific computation</strong></p>
<ul>
<li>This section introduces you to the NumPy and SciPy libraries, which are used for scientific computation in Python.</li>
</ul>
</li>
<li><p><strong>Section 5: Plotting in Python</strong></p>
<ul>
<li>This section teaches you how to create plots in Python using the Matplotlib library.</li>
</ul>
</li>
<li><p><strong>Section 6: Case studies</strong></p>
<ul>
<li>This section presents two case studies that demonstrate how Python can be used for scientific research.</li>
</ul>
</li>
</ul>
<p>The course includes video lectures, quizzes, and coding exercises to help you learn the material. The course also has a forum where you can ask questions and get help from the instructor and other students.</p>
<p>If you are interested in learning Python for scientific research, <a target="_blank" href="https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7">this course</a> is a great place to start. It is comprehensive, well-organized, and easy to follow.</p>
<p>Here are some of the benefits of taking this course:</p>
<ul>
<li><p>You will learn the essential skills you need to use Python for scientific research.</p>
</li>
<li><p>You will be able to read and write Python code.</p>
</li>
<li><p>You will be able to use Python for data analysis, statistics, and plotting.</p>
</li>
<li><p>You will be able to apply Python to your own research projects.</p>
</li>
</ul>
<p>If you are ready to learn <a target="_blank" href="https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7">Python for scientific research</a>, I encourage you to enroll in this course. I am confident that you will find it informative and helpful.</p>
]]></content:encoded></item><item><title><![CDATA[Step-by-Step Guide to Packaging and Publishing Python Projects on PyPI]]></title><description><![CDATA[Are you looking for a step-by-step guide to packaging and publishing your Python projects on PyPI? Look no further! This comprehensive guide will walk you…]]></description><link>https://smartrs.hashnode.dev/step-by-step-guide-to-packaging-and-publishing-python-projects-on-pypi</link><guid isPermaLink="true">https://smartrs.hashnode.dev/step-by-step-guide-to-packaging-and-publishing-python-projects-on-pypi</guid><category><![CDATA[Python]]></category><category><![CDATA[package]]></category><category><![CDATA[pypi]]></category><dc:creator><![CDATA[Azad Rasul]]></dc:creator><pubDate>Mon, 13 Mar 2023 23:13:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704217863699/c3d513ed-4846-4008-92b6-6e92815ad856.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Are you looking for a step-by-step guide to packaging and publishing your Python projects on PyPI? Look no further! This comprehensive guide will walk you through everything you need to know, from organizing your files and creating a package to uploading it to PyPI for easy installation using pip. With clear instructions and helpful examples, you'll be able to share your Python projects with the world in no time.</p>
<p>In this guide, we use a simple project called "smartrs". Replace it with your own unique name so that your package doesn't clash with packages uploaded by other people following this tutorial.</p>
<p><strong>Step 1: Organizing Your Project Files:</strong></p>
<p>Create the following structure of files and folders on your computer:</p>
<pre><code class="language-python">packaging/
└── src/
    └── smartrs/
        ├── __init__.py
        └── example.py
</code></pre>
<p>It's recommended that the name of the directory holding the Python files matches the project name. This makes configuration easier and clearer for package users. To import the directory as a package, an empty init.py file is necessary. An example.py module within the package can contain the package's logic such as functions, classes, and constants. You can add the necessary content to the example.py file:</p>
<pre><code class="language-python">def add_ten(number):
     return number + 10
</code></pre>
<p><strong>Step 2: Generating Necessary Files:</strong></p>
<p>To prepare the project for distribution, you need to include certain files in the package. Once you've completed this step, the structure of the project will resemble the following:</p>
<pre><code class="language-python">packaging/
├── LICENSE
├── pyproject.toml
├── README.md
├── src/
│   └── smartrs/
│       ├── __init__.py
│       └── example.py
└── tests/
</code></pre>
<p>To set up a directory for testing purposes, create a folder called "<strong>tests/</strong>" and leave it empty for the time being.</p>
<p>To specify which "backend" tool to use for creating distribution packages for your project, you need to create a file called "<strong>pyproject.toml</strong>". This file is used by "frontend" build tools like pip and build to identify the appropriate "backend" tool.</p>
<p>Open <code>pyproject.toml</code> and enter:</p>
<pre><code class="language-toml">[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
</code></pre>
<p>Then add the following content below it. Change the <code>name</code> to the name of your package:</p>
<pre><code class="language-toml">[project]
name = "smartrs"
version = "0.0.1"
authors = [
  { name="Example Author", email="author@example.com" },
]
description = "A small example package"
readme = "README.md"
requires-python = "&gt;=3.7"
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
]

[project.urls]
"Homepage" = "https://github.com/pypa/sampleproject"
"Bug Tracker" = "https://github.com/pypa/sampleproject/issues"
</code></pre>
<p><strong>Step 3: Preparing README and License:</strong></p>
<p><strong>Prepare README.md:</strong></p>
<p>Open the <code>README.md</code> file and enter the following content:</p>
<pre><code class="language-markdown"># Example Package

This is a simple example package. You can use
[Github-flavored Markdown](https://guides.github.com/features/mastering-markdown/)
to write your content.
</code></pre>
<p><strong>Prepare a LICENSE:</strong></p>
<p>Including a license is a crucial requirement for every package uploaded to the Python Package Index. To add a license, you can open the LICENSE file and input the text of your chosen license. A commonly used license is the MIT license:</p>
<pre><code class="language-text">Copyright (c) 2018 The Python Packaging Authority

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</code></pre>
<p><strong>Step 4: Creating Distribution Archives:</strong></p>
<p>The next step is to create distribution packages for your project. These archives are produced and then uploaded to the Python Package Index, where they can be installed using pip.</p>
<p>Execute this command in the directory where the <strong>pyproject.toml</strong> file is located, (the "packaging" folder). On Windows, you can Shift + right-click inside the folder and choose "Git Bash Here":</p>
<pre><code class="language-python">python -m build
</code></pre>
<p>This command prints a lot of output. When it finishes, it creates two files in the <code>dist</code> directory.</p>
<pre><code class="language-python">dist/
├── smartrs-0.0.1-py3-none-any.whl
└── smartrs-0.0.1.tar.gz
</code></pre>
<p>The <code>tar.gz</code> file is a <a href="https://packaging.python.org/en/latest/glossary/#term-Source-Distribution-or-sdist">source distribution</a> whereas the <code>.whl</code> file is a <a href="https://packaging.python.org/en/latest/glossary/#term-Built-Distribution">built distribution</a>.</p>
<p><strong>Step 5: Uploading to PyPI:</strong></p>
<p>First, create an account on PyPI.</p>
<p>After registering, you can use Twine to upload distribution packages. Install Twine:</p>
<pre><code class="language-python">pip install --upgrade twine
</code></pre>
<p>Then run Twine to upload all the files in the <code>dist</code> folder:</p>
<pre><code class="language-python">twine upload --verbose dist/*
# username: __token__
# password: pypi-AgEIcHlwaS5vcmc..... (your token)
</code></pre>
<p>You will be asked for your PyPI credentials. PyPI no longer accepts account passwords for uploads, so create an API token in your PyPI account settings and use it:</p>
<p>To use an API token:</p>
<ul>
<li><p>Set your username to <code>__token__</code></p>
</li>
<li><p>Set your password to the token value, including the <code>pypi-</code> prefix</p>
</li>
</ul>
<p>Once uploaded, your package should be viewable on PyPI; for example:</p>
<p><a href="https://pypi.org/project/smartrs/0.0.1/">https://pypi.org/project/smartrs/0.0.1/</a></p>
<p>To install the package you uploaded and check that it works, use pip:</p>
<pre><code class="language-python">pip install smartrs==0.0.1
</code></pre>
<pre><code class="language-python">Successfully built smartrs
Installing collected packages: smartrs
Successfully installed smartrs-0.0.1
</code></pre>
<p><strong>Step 6: Verifying Installation:</strong></p>
<p>One way to verify that the package was installed properly is by importing it and running a test.</p>
<pre><code class="language-python">from smartrs import example
example.add_ten(5)
</code></pre>
<p>Well done, you have successfully packaged and shared a Python project!</p>
<p>In conclusion, publishing a Python project on PyPI is the standard way to share your code with the world. With the help of this step-by-step guide, you can easily organize your files, create a package, and upload it to PyPI for easy installation using pip. By following the instructions provided and using tools like Twine, you can successfully publish your Python projects and make them accessible to others. Remember to include a license and a README file to provide important information about your project, and don't hesitate to consult additional resources for more information and guidance.</p>
<p>For more information, visit:</p>
<ul>
<li><p><a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/">Packaging Python Projects</a></p>
</li>
<li><p><a href="https://www.tutorialsteacher.com/python/python-package">Python Packages</a></p>
</li>
<li><p><a href="https://www.youtube.com/watch?v=EIwLZiTuYoA">How to create a Python package and publish it on PyPI in 5 minutes</a></p>
</li>
</ul>
]]></content:encoded></item></channel></rss>