<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fatih Karahan on Medium]]></title>
        <description><![CDATA[Stories by Fatih Karahan on Medium]]></description>
        <link>https://medium.com/@sekanti02?source=rss-a249afbb20fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AR6TOUlwr__FKnhjE7TG4A.jpeg</url>
            <title>Stories by Fatih Karahan on Medium</title>
            <link>https://medium.com/@sekanti02?source=rss-a249afbb20fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:23:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sekanti02/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Talk Like a Local: 10 Creative ChatGPT Prompts for Language Learners]]></title>
            <link>https://medium.com/@sekanti02/talk-like-a-local-10-creative-chatgpt-prompts-for-language-learners-8745e7f4b0c6?source=rss-a249afbb20fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8745e7f4b0c6</guid>
            <category><![CDATA[language-learning]]></category>
            <category><![CDATA[language-translation]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[community]]></category>
            <category><![CDATA[culture]]></category>
            <dc:creator><![CDATA[Fatih Karahan]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 16:47:19 GMT</pubDate>
            <atom:updated>2024-12-10T19:59:28.627Z</atom:updated>
            <content:encoded><![CDATA[<h3>Speak Like a Local: 7 Creative ChatGPT Prompts for Language Learners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mowOm6IdOQHJ80OMuMOrQ.png" /></figure><p><strong>Imagine having a personal language tutor available 24/7 — one that adapts to your needs, answers every question, and never tires.</strong></p><p><strong>That’s what ChatGPT can be for language learners.</strong></p><p><strong>Whether it’s mastering grammar, expanding vocabulary, or practicing real-life scenarios, ChatGPT is your customizable language-learning assistant.</strong></p><p>Hi, I’m Fatih, and I want to share a bit about myself before diving in. I recently moved to Germany to start my master’s program, and yes, as you might have guessed — people here speak German (shocking, right? 😄). Since then, learning the language has been an adventure, filled with funny moments, small victories, and plenty of questions along the way.</p><p>The techniques I’m sharing with you today aren’t just theoretical. They come straight from my own experience, tried and proven through daily practice. From cracking tricky grammar rules to simulating real-life conversations, ChatGPT has been my secret weapon in navigating this linguistic journey.</p><p>Here are 7 creative ways I’ve used ChatGPT to level up my German, and I promise, they’ll work for you too!</p><h3>1. Master Grammar with Real-Life Examples</h3><p>Grammar can feel daunting, but ChatGPT makes it easier to grasp. Let me share a personal example:</p><p>One day, I was trying to use the sentence <strong>“Ich gehe zur Mensa”</strong> (I’m going to the cafeteria). The phrase confused me because I realized the word <em>“Mensa”</em> had taken on the dative case and turned into <em>“der Mensa.”</em> I wasn’t sure why, and the moment the question popped into my head, I opened my phone and asked ChatGPT, my go-to tutor.</p><p>Within seconds, it explained the nuances of prepositions like <em>“zu”</em> and their connection to dative cases, breaking it down with examples. ChatGPT didn’t just clarify the grammar — it also gave me context on when and why such changes occur, making the concept stick.</p><ul><li><strong>Prompt Idea:</strong> “Explain why <em>‘Ich gehe zur Mensa’</em> uses the dative case and provide similar examples.”</li><li><strong>Practice Activity:</strong> Use ChatGPT to create a list of prepositions that trigger the dative case and build sentences for practice.</li></ul><p><strong>Why it Works:</strong> With ChatGPT, your questions don’t have to wait for a formal study session. Whenever confusion strikes, you have the possibility of solving it instantly, wherever you are. This immediacy turns moments of doubt into powerful learning opportunities.</p><h3>2. Improve Pronunciation with Feedback</h3><p>Speaking confidently starts with nailing pronunciation. For me, German words like <em>“Eichhörnchen”</em> (squirrel) were a mouthful at first. I’d ask ChatGPT, <em>“How do I pronounce this?”</em> and it would break the word into syllables, offering tips for articulation.</p><p>But here’s the game-changer: Instead of just practicing isolated words, I worked on my pronunciation within conversations. After asking or answering a question, I’d follow up with, <em>“How was my pronunciation?”</em> ChatGPT would point out areas to refine, making the practice seamless and natural.</p><ul><li><strong>Prompt Idea:</strong> “Help me pronounce tricky words like *‘Rindfleisch.’ Break it down step by step.”</li></ul><p><strong>Why it Works:</strong> You’re practicing pronunciation in context, so it feels less mechanical and more connected to real-life communication.</p><h3>3. Build Vocabulary in Context</h3><p>Living in Germany has taught me that real-life situations often catch you off guard. Picture this: you’re at the supermarket trying to ask where the milk is, but instead, you awkwardly blurt out <em>“Sprechen Sie Englisch?”</em> (Do you speak English?) with a nervous smile. Been there, done that!</p><p>To avoid these moments, I started practicing everyday scenarios with ChatGPT. For example, I’d ask it to role-play a conversation where I’m buying groceries. It would teach me key phrases like <em>“Wo finde ich die Milch?”</em> (Where can I find the milk?) or <em>“Kann ich mit Karte bezahlen?”</em> (Can I pay by card?).</p><p>The goal isn’t to memorize every single word but to build a foundational vocabulary for these contexts. By practicing again and again, you naturally start to feel more confident.</p><ul><li><strong>Prompt Idea:</strong> “Create a role-play conversation at a German supermarket where I ask about items and payment methods.”</li><li><strong>Practice Tip:</strong> Work through scenarios like ordering food, buying a train ticket, or asking for directions.</li></ul><p><strong>Why it Works:</strong> You’re not aiming for perfection, just consistent practice to familiarize yourself with phrases and build confidence for real-life conversations.</p><h3>4. Practice Real-Life Conversations</h3><p>After building vocabulary for specific contexts, the next logical step is to simulate real-life conversations. For example, I often asked ChatGPT to pretend to be a train conductor, helping me practice scenarios like <em>“Wann fährt der nächste Zug nach München?”</em> (When does the next train to Munich leave?) or <em>“Wie viel kostet ein Ticket?”</em> (How much is a ticket?).</p><p>The beauty of these role-plays is their practicality. There’s a high likelihood you’ll encounter these situations in real life, and the more you practice, the easier they become.</p><ul><li><strong>Prompt Idea:</strong> “Pretend you’re a waiter in a German restaurant. I’ll order food, and you respond naturally.”</li></ul><p><strong>Why it Works:</strong> Familiarizing yourself with these interactions reduces stress and boosts confidence when it’s time to speak for real.</p><h3>5. Correct Your Mistakes for Better Learning</h3><p>Writing in a new language can feel intimidating, especially when you’re unsure if your sentences are correct. For example, when preparing for a presentation in German, I’d draft my script and ask ChatGPT to correct it. Not only would it flag errors, but it would also explain the fixes, like why a verb needed to be conjugated differently or why the word order was incorrect.</p><p>This feature is also incredibly useful for structured tasks, like writing practice for language exams. Exams often expect specific structures and formalities, and ChatGPT can help you tailor your writing to meet those requirements. You can even challenge yourself by asking ChatGPT to include deliberate mistakes for you to spot and correct — turning practice into an engaging learning activity.</p><ul><li><strong>Prompt Idea:</strong> “Correct this essay I wrote for a German B1 exam. Highlight grammatical issues and suggest improvements.”</li><li><strong>Bonus Activity:</strong> Draft your class presentation, focusing on a grammar point you’re studying, and have ChatGPT refine it.</li></ul><p><strong>Why it Works:</strong> Active correction strengthens your understanding of grammar, improves your writing skills, and boosts your confidence for exams and real-world tasks.</p><h3>6. Comprehend and Discuss What You Learn</h3><p>One of my favorite ways to use ChatGPT is combining passive and active learning in a single session. Here’s how it works: I’d spend about 50 minutes reading a German story, article, or even a textbook chapter. Afterward, I’d upload key parts of what I read into ChatGPT to deepen my comprehension.</p><p>I’d ask ChatGPT to quiz me on the story, explain words I didn’t know, or even discuss the plot with me. For instance, I’d say, <em>“Ask me 5 questions about this story to check if I understood it correctly,”</em> or <em>“Help me practice using the word ‘schüchtern’ in a sentence.”</em></p><p>This approach doesn’t just stop at reading comprehension — it also pushes you into active learning by discussing and practicing what you’ve learned.</p><ul><li><strong>Prompt Idea:</strong> “Here’s a paragraph I read. Ask me questions to test my understanding and help me use 3 new words in sentences.”</li></ul><p><strong>Why it Works:</strong> This method strengthens your understanding of new material and reinforces vocabulary while blending passive reading with active speaking practice. It’s a perfect recipe for balanced language learning.</p><h3>7. Connect Words with Keywords and Context</h3><p>One of the most effective techniques I’ve used to solidify vocabulary is creating keyword pairs or groups. For example, I might give ChatGPT a set of words — nouns, verbs, adjectives — and ask it to test me on synonyms, antonyms, or even related contexts.</p><p>For instance, I’d provide words like <em>“heiß” (hot)</em> and <em>“kalt” (cold)</em> and ask, <em>“Give me a sentence using these words together,”</em> or, <em>“Ask me for antonyms of these words.”</em> Sometimes, I’d go beyond synonyms and antonyms to explore contexts, like <em>“What comes to mind when you think of ‘Sommer’ (summer) and ‘Winter’ (winter)?”</em></p><p>This technique creates a web of connections in your mind, linking words together and helping you recall them more easily.</p><ul><li><strong>Prompt Idea:</strong> “Test me on these 5 words by asking for synonyms, antonyms, or related contexts: ‘warm,’ ‘langsam,’ ‘glücklich,’ ‘dunkel,’ ‘leicht.’”</li><li><strong>Why it Works:</strong> This method deepens your understanding of vocabulary by embedding words in a network of meanings, making them more memorable and useful in conversation.</li></ul><h3>Conclusion</h3><p>Language learning is a journey, and with ChatGPT as your partner, it becomes a lot more engaging, accessible, and fun. From mastering grammar to building vocabulary and practicing conversations, ChatGPT adapts to your needs, making it the perfect tool for both structured and spontaneous learning.</p><p>Every method I’ve shared here comes from my own experience of living in Germany and immersing myself in the language. These techniques helped me navigate real-life situations, understand complex grammar rules, and grow my confidence — all by practicing consistently and creatively.</p><p>If you’re someone who’s looking for extra guidance or just needs a friendly hand to explore new methods, I’d love to help. While I’m not a professional language coach, I’m passionate about sharing what I’ve learned and finding ways to make language learning enjoyable for everyone.</p><p><strong>Feel free to email me at sekanti02@gmail.com to schedule a free appointment. We can discuss your language learning goals, exchange ideas, and explore ways to make the process easier and more effective for you. Let’s make language learning a fun and rewarding journey together!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8745e7f4b0c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning for Beginners: Mastering Linear Regression and Beyond]]></title>
            <link>https://medium.com/@sekanti02/supervised-learning-for-beginners-linear-regression-and-beyond-61a2c4280360?source=rss-a249afbb20fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/61a2c4280360</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fatih Karahan]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 15:38:19 GMT</pubDate>
            <atom:updated>2024-12-09T16:41:04.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KD8eDC920cLurPFfQAmSeA.png" /></figure><p>Machine learning might sound complex, but what if I told you it’s not as intimidating as it seems?</p><p>By breaking it into bite-sized pieces, even the most abstract concepts start to make sense.</p><p>In this article, we’ll take a beginner-friendly journey into the world of supervised learning, focusing on <strong>linear regression</strong> — one of the simplest yet most powerful algorithms in machine learning.</p><p>But we won’t stop there. You’ll also discover:</p><ul><li>How machines learn to make predictions from labeled data.</li><li>Why concepts like <strong>loss functions</strong> and <strong>gradient descent</strong> are essential.</li><li>Hands-on Python code to visualize these ideas and experiment on your own.</li></ul><p>By the end, you’ll not only understand the math but also have the tools to bring these concepts to life. Ready to dive in? Let’s get started!</p><h3>What is Supervised Learning?</h3><p>In supervised learning, we teach a machine-learning model by providing it with labeled data. This means each input has a corresponding output, and the model learns to map inputs to outputs.</p><h3>Supervised vs. Unsupervised Learning</h3><ul><li><strong>Supervised Learning</strong>: Data comes with labels. Example: Predicting house prices based on square footage and location.</li><li><strong>Unsupervised Learning</strong>: Data has no labels. Example: Clustering customers into groups based on their purchasing behavior.</li></ul><p><strong>Visual Suggestion</strong>: Add an image comparing supervised and unsupervised learning. A table or diagram illustrating labeled vs. unlabeled data could work well.</p><h3>Linear Regression: The Simplest Supervised Model</h3><p>Linear regression is often the first algorithm to learn because it’s simple yet powerful. It’s based on the equation of a straight line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*oBelWpF8T9HyYFCd_wK9Lw.jpeg" /></figure><p>where:</p><ul><li>w: Weight (slope)</li><li>b: Bias (intercept)</li></ul><p>The goal of linear regression is to find the best w and b such that the predicted values align closely with the actual data points.</p><h3>Why Does It Make Sense?</h3><p>Linear regression assumes a linear relationship between the input (x) and the output (y). Let’s visualize this with some Python code:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Generate random data<br>np.random.seed(42)<br>x = np.linspace(0, 10, 5p0)<br>y = 2 * x + 1 + np.random.normal(0, 1, size=x.shape)<br><br># Plot data points<br>plt.scatter(x, y, label=&quot;Data Points&quot;)<br>plt.xlabel(&quot;x&quot;)<br>plt.ylabel(&quot;y&quot;)<br>plt.title(&quot;Linear Relationship&quot;)<br>plt.legend()<br>plt.show()</pre><p><strong>Visual Suggestion</strong>: Include a plot showing scattered data points and a fitted line for context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*bxO4C6EbRjKiaIptixPEag.png" /></figure><h3>Fitting the Line: Loss Functions and Optimization</h3><p>To find the best-fit line, we need to minimize the error. This is where <strong>loss functions</strong> come into play.</p><h3>Loss Functions in Linear Regression</h3><ol><li><strong>L2 Loss (Mean Squared Error)</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*acd2GrsoRSQMtxhtHWDHvg.png" /></figure><ul><li>Penalizes large errors more heavily.</li><li>Creates a convex function, making optimization easier.</li></ul><p><strong>2. L1 Loss (Mean Absolute Error)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*vNF_tYAxFh-01wDzq1wU9Q.png" /></figure><ul><li>Less sensitive to outliers than L2.</li></ul><p><strong>When to Use</strong>:</p><ul><li><strong>L2</strong>: For tasks where large deviations need to be penalized (e.g., regression tasks with fewer outliers).</li><li><strong>L1</strong>: When data contains significant outliers.</li></ul><p><strong>Python Code to Compare</strong>:</p><pre># Define L2 and L1 loss functions<br>def l2_loss(y_true, y_pred):<br>    return np.mean((y_true - y_pred) ** 2)<br><br>def l1_loss(y_true, y_pred):<br>    return np.mean(np.abs(y_true - y_pred))<br><br># Example usage<br>y_pred = 2 * x + 1<br>print(&quot;L2 Loss:&quot;, l2_loss(y, y_pred))<br>print(&quot;L1 Loss:&quot;, l1_loss(y, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*XZK6QxY51ykx91WeNOwHAA.png" /></figure><p>Final weight (w): 2.0103451449558656<br>Final bias (b): 0.6077147245753991</p><h3>Why Do We Use Squared Errors?</h3><p>Using squared errors in L2 loss has key advantages:</p><ul><li><strong>Convexity</strong>: Makes the optimization landscape smooth and easier to navigate with algorithms like gradient descent.</li><li><strong>All Positive</strong>: Ensures the errors don’t cancel each other out.</li></ul><h3>Gradient Descent: Optimizing the Parameters</h3><p>Gradient descent is an iterative method to minimize the loss function. It updates the weights and biases based on the gradient of the loss.</p><h3>Gradient Descent Formula:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*DjtZxK386igRBPhhfkhyGg.png" /></figure><p>where:</p><ul><li>n: Learning rate (controls the step size).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/1*XkfZ_fKY_5AK_MQjwFaSSw.png" /></figure><ul><li>Gradient with respect to w.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/37/1*1EFLPAuaRSO2enWHOa4ikQ.png" /></figure><ul><li>Gradient with respect to b</li></ul><h3>Step-by-Step Visualization:</h3><p>Here’s a Python implementation to show gradient descent in action:</p><pre># Gradient Descent for Linear Regression<br>w, b = 0.0, 0.0  # Initialize weights and bias<br>learning_rate = 0.01<br>epochs = 100<br><br>losses = []<br><br>for _ in range(epochs):<br>    # Predictions<br>    y_pred = w * x + b<br>    <br>    # Calculate gradients<br>    dw = -2 * np.mean(x * (y - y_pred))<br>    db = -2 * np.mean(y - y_pred)<br>    <br>    # Update parameters<br>    w -= learning_rate * dw<br>    b -= learning_rate * db<br>    <br>    # Compute loss and store it<br>    losses.append(l2_loss(y, y_pred))<br><br># Plot the results<br>plt.plot(range(epochs), losses, label=&quot;Loss over Epochs&quot;)<br>plt.xlabel(&quot;Epochs&quot;)<br>plt.ylabel(&quot;Loss&quot;)<br>plt.title(&quot;Gradient Descent Progress&quot;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*6jIwtCMTt7vVNmkBSFsMmQ.png" /></figure><h3>Visualize Gradient Descent:</h3><ol><li>Start with a random line and high loss.</li><li>Show intermediate steps as the line adjusts.</li><li>End with the best-fit line and minimal loss.</li></ol><p><strong>Visual Suggestion</strong>: Create 3 plots showing different stages of gradient descent:</p><ol><li>Initial line and high loss.</li><li>Intermediate step with reduced loss.</li><li>Final fit with minimized loss.</li></ol><h3>Summary</h3><p>Linear regression is a gateway to understanding machine learning. By exploring:</p><ul><li><strong>Supervised learning basics</strong>,</li><li><strong>The math and intuition of linear regression</strong>, and</li><li><strong>Key optimization techniques like gradient descent</strong>,</li></ul><p>you’ve taken the first step toward mastering ML fundamentals. Don’t stop here — experiment with the Python code provided and explore how these concepts apply to real-world problems!</p><p><strong>Call to Action</strong>: If you enjoyed this guide, consider implementing it on your own dataset or exploring how other models like logistic regression work!</p><h3>Experimental Questions for Hands-On Learning</h3><p>Understanding the concepts is great, but experimenting with them will deepen your understanding. Here are a few questions to try on your own using the provided Python code:</p><h4>1. Learning Rate</h4><ul><li>Modify the learning_rate parameter in the code. Try values like <strong>0.001</strong>, <strong>0.01</strong>, or <strong>0.1</strong>.</li><li><strong>What to observe</strong>: How does the learning rate impact the loss reduction? Does the model converge faster, slower, or fail to converge?</li></ul><h4>2. Noise in Data</h4><ul><li>Adjust the amount of random noise added to the dataset. You can do this by modifying the np.random.normal function in the data generation step.</li><li><strong>What to observe</strong>: How does increased noise affect the fitted line? Does it result in a higher loss? Is the line still accurate for the noisy data?</li></ul><h4>3. Number of Epochs</h4><ul><li>Change the number of epochs in the code. For example, reduce it to <strong>10</strong> or increase it to <strong>500</strong>.</li><li><strong>What to observe</strong>: How does the number of epochs affect the final weight, bias, or loss? Do you notice underfitting or overfitting behavior?</li></ul><h4>4. L1 Loss</h4><ul><li>Modify the gradient descent function in the code to use <strong>L1 Loss</strong> (Mean Absolute Error) instead of <strong>L2 Loss</strong> (Mean Squared Error).</li><li><strong>What to observe</strong>: Compare the results. How does the fitted line differ? Which loss function seems more robust to outliers in the data?</li></ul><h3>Explore the Code and Experiment!</h3><p>To experiment with these questions, clone the GitHub repository that contains all the code used in this article:</p><p><a href="https://github.com/Fatih0234/ml_work/tree/main/my_work/linear_regression"><strong>GitHub Repository: Linear Regression Experiments</strong></a></p><p>The repository includes the Python code, instructions, and everything you need to get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61a2c4280360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Gradient Descent: Batch, Stochastic, and Mini-Batch Explained]]></title>
            <link>https://medium.com/@sekanti02/mastering-gradient-descent-batch-stochastic-and-mini-batch-explained-3b8f4f73bba4?source=rss-a249afbb20fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b8f4f73bba4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Fatih Karahan]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 13:31:10 GMT</pubDate>
            <atom:updated>2024-12-08T13:31:10.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*Tkwy7773VNSRHVen.jpeg" /></figure><p>Imagine you’re at the top of a hill, trying to find your way to the lowest valley. Instead of blindly stumbling down, you carefully calculate the steepest path forward. This is the essence of <strong>Gradient Descent</strong>, a cornerstone algorithm in machine learning. It helps us find the “minimum” of a function, much like finding the bottom of that valley.</p><p>But here’s the twist: there isn’t just one way to get there. Depending on the size of your “hill” (or dataset), you can choose between three distinct paths:</p><ul><li><strong>Batch Gradient Descent (BGD)</strong> — slow but steady.</li><li><strong>Stochastic Gradient Descent (SGD)</strong> — fast but chaotic.</li><li><strong>Mini-Batch Gradient Descent</strong> — the perfect middle ground.</li></ul><p>In this article, we’ll explore these three methods in detail, break down their pros and cons, and even compare them with a practical Python implementation. Whether you’re new to machine learning or brushing up on the basics, this guide will equip you with the knowledge to pick the right gradient descent approach for your next project.</p><h3>1. Batch Gradient Descent (BGD)</h3><h3>What is Batch Gradient Descent?</h3><p>Batch Gradient Descent processes the <strong>entire dataset</strong> at once to compute the gradient of the loss function and update the model parameters. It calculates the average gradient for all data points in each iteration.</p><h3>Advantages</h3><ul><li><strong>Guaranteed convergence</strong> to the global minimum for convex problems.</li><li><strong>Stable updates</strong>, as the gradient is averaged over the entire dataset.</li></ul><h3>Disadvantages</h3><ul><li><strong>Computationally expensive</strong> for large datasets, as it processes all data points at each step.</li><li>May be <strong>slow</strong> due to the heavy computational load.</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Generating synthetic data<br>np.random.seed(42)<br>x = np.random.randn(100, 1)  # 100 data points<br>y = 5 * x + np.random.randn(100, 1)  # Linear relation with noise<br><br># Parameters<br>w, b = 1000, 0.0  # Initialize weight and bias<br>learning_rate = 0.01<br>batch_size = 10  # Mini-batch size for Mini-Batch GD<br><br># Batch Gradient Descent Function<br>def batch_descent(x, y, w, b, learning_rate):<br>    yhat = w * x + b<br>    loss = np.mean((y - yhat)**2)<br>    dw = -2 * np.mean(x * (y - yhat))<br>    db = -2 * np.mean(y - yhat)<br>    w -= learning_rate * dw<br>    b -= learning_rate * db<br>    return w, b, loss</pre><h3>2. Stochastic Gradient Descent (SGD)</h3><h3>What is Stochastic Gradient Descent?</h3><p>In SGD, the model parameters are updated after computing the gradient for a <strong>single randomly chosen training sample</strong>. This leads to more frequent updates and faster iterations.</p><h3>Advantages</h3><ul><li>Faster updates allow it to handle <strong>large datasets</strong> effectively.</li><li>The inherent noise in updates can help <strong>escape local minima</strong>.</li></ul><h3>Disadvantages</h3><ul><li>Updates are <strong>noisy</strong>, leading to a less smooth path towards the minimum.</li><li>It may <strong>oscillate around the global minimum</strong>, preventing convergence.</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Generating synthetic data<br>np.random.seed(42)<br>x = np.random.randn(100, 1)  # 100 data points<br>y = 5 * x + np.random.randn(100, 1)  # Linear relation with noise<br><br># Parameters<br>w, b = 1000, 0.0  # Initialize weight and bias<br>learning_rate = 0.01<br>batch_size = 10  # Mini-batch size for Mini-Batch GD<br><br><br># Stochastic Gradient Descent Function<br>def stochastic_descent(x, y, w, b, learning_rate):<br>    idx = np.random.randint(0, len(x))  # Random index<br>    xi, yi = x[idx:idx+1], y[idx:idx+1]<br>    yhat = w * xi + b<br>    loss = (yi - yhat)**2<br>    dw = -2 * xi * (yi - yhat)<br>    db = -2 * (yi - yhat)<br>    w -= learning_rate * dw<br>    b -= learning_rate * db<br>    return w, b, loss</pre><h3>3. Mini-Batch Gradient Descent</h3><h3>What is Mini-Batch Gradient Descent?</h3><p>Mini-Batch Gradient Descent is a middle ground between BGD and SGD. The dataset is split into <strong>small batches</strong> (mini-batches), and the gradient is computed for each batch.</p><h3>Advantages</h3><ul><li><strong>Faster convergence</strong> than BGD.</li><li><strong>More stable updates</strong> compared to SGD due to the averaging effect of batches.</li><li>Can leverage <strong>vectorized operations</strong> on modern hardware like GPUs.</li></ul><h3>Disadvantages</h3><ul><li>Requires careful tuning of the <strong>mini-batch size</strong> for optimal performance.</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Generating synthetic data<br>np.random.seed(42)<br>x = np.random.randn(100, 1)  # 100 data points<br>y = 5 * x + np.random.randn(100, 1)  # Linear relation with noise<br><br># Parameters<br>w, b = 1000, 0.0  # Initialize weight and bias<br>learning_rate = 0.01<br>batch_size = 10  # Mini-batch size for Mini-Batch GD<br><br><br># Mini-Batch Gradient Descent Function<br>def mini_batch_descent(x, y, w, b, learning_rate, batch_size):<br>    idx = np.random.choice(len(x), batch_size, replace=False)  # Random mini-batch<br>    xi, yi = x[idx], y[idx]<br>    yhat = w * xi + b<br>    loss = np.mean((yi - yhat)**2)<br>    dw = -2 * np.mean(xi * (yi - yhat))<br>    db = -2 * np.mean(yi - yhat)<br>    w -= learning_rate * dw<br>    b -= learning_rate * db<br>    return w, b, loss</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*vYBVnGM_xFZVMS6NCFGwHw.png" /></figure><h3>Interpreting the Loss Comparison Plot for Gradient Descent Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*VNlQjiy4wX52Odta728etA.png" /></figure><p>The loss comparison plot vividly highlights the differences in the behavior of the three gradient descent methods: <strong>Batch Gradient Descent (BGD)</strong>, <strong>Stochastic Gradient Descent (SGD)</strong>, and <strong>Mini-Batch Gradient Descent</strong>. Here’s an interpretation of what we observe:</p><h3>Key Insights</h3><ul><li><strong>SGD’s Noisiness:</strong> As seen in the plot, the orange curve shows erratic oscillations before stabilizing, demonstrating the noisy updates inherent to SGD.</li><li><strong>BGD’s Stability:</strong> The blue curve highlights the smooth convergence of BGD, but it progresses slowly at first compared to the other methods.</li><li><strong>Mini-Batch’s Balance:</strong> The green curve captures the “middle-ground” behavior, with faster convergence than BGD and less noise than SGD, making it a popular choice in modern machine learning workflows.</li></ul><h3>Conclusion</h3><ul><li><strong>When to use BGD?</strong> Best suited for small datasets where computational cost is not a concern, and stability is paramount.</li><li><strong>When to use SGD?</strong> Ideal for very large datasets or scenarios requiring quick initial convergence. It’s often used in online learning systems.</li><li><strong>When to use Mini-Batch GD?</strong> The most practical and commonly used method for real-world applications, balancing speed, stability, and scalability.</li></ul><p>The choice of gradient descent method ultimately depends on the size of your dataset, available computational resources, and your application’s requirements for speed and precision.</p><h3>Final Thoughts and Call-to-Action</h3><p>The choice between <strong>Batch Gradient Descent (BGD)</strong>, <strong>Stochastic Gradient Descent (SGD)</strong>, and <strong>Mini-Batch Gradient Descent</strong> depends on your specific dataset, computational resources, and learning objectives. But theory alone isn’t enough — experimenting with these methods will give you a much deeper understanding of how they work.</p><h4>Interactive Challenges: Try It Yourself!</h4><p>To truly grasp the nuances of gradient descent, I’ve prepared <strong>7 hands-on challenges</strong> in the GitHub repository. These include tasks like experimenting with learning rates, exploring mini-batch sizes, and even tweaking the dataset for non-linear relationships.</p><p>Here’s what you’ll gain:</p><ul><li>A better intuition for how gradient descent converges to a minimum.</li><li>Insights into why SGD is noisy and why Mini-Batch GD is the sweet spot.</li><li>The chance to fork the code, modify it, and truly <em>own</em> your learning.</li></ul><h3>Explore the Repo!</h3><p>Check out the <a href="https://github.com/Fatih0234/ml_work/tree/main/my_work/supervised_ml"><strong>GitHub repository</strong></a> to access the full Python code, detailed documentation, and step-by-step experimentation challenges.</p><ul><li>Fork the repository and experiment with the code.</li><li>Share your results or questions on my <a href="https://www.linkedin.com/in/fatih-karahan-717931193/"><strong>LinkedIn</strong></a> or <a href="https://portfolio-app-fatihkarahan.streamlit.app/"><strong>personal website</strong> </a>— I’d love to hear from you!</li></ul><p>Take on the challenges, and let’s make gradient descent a tool you understand inside and out. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b8f4f73bba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-end Machine Learning Project, Predicting a League of Legends Game Winner]]></title>
            <link>https://medium.com/@sekanti02/end-to-end-machine-learning-project-predicting-a-league-of-legends-game-winner-e9437456d63b?source=rss-a249afbb20fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9437456d63b</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Fatih Karahan]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 17:15:29 GMT</pubDate>
            <atom:updated>2023-03-11T17:15:29.910Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>League of Legends is a popular multiplayer online battle arena (MOBA) game, where two teams of players compete against each other to destroy the enemy team’s base. With millions of players worldwide, League of Legends has become a global phenomenon, with professional leagues and tournaments offering significant prizes to the winners.</p><p>In this article, we will explore the process of building a machine learning model to predict the winner of a League of Legends(LoL) game. We will start by performing exploratory data analysis (EDA) on a dataset of League of Legends games, to understand the key features and their relationships with the target variable. We will then preprocess the data by encoding categorical features and splitting it into training and testing sets.</p><p>Next, we will train two machine learning models on the data, decision trees and Gradient Boosting. We will use hyperparameter tuning techniques to optimize the performance of each model and compare their accuracy and performance.</p><p>Finally, we will select the best-performing model and evaluate its performance on the testing set, using metrics such as accuracy, precision, and cross-validation score. We will also discuss the strengths and limitations of the model and suggest possible directions for future research.</p><p>Overall, this project demonstrates the application of machine learning techniques to a real-world problem and highlights the importance of data preprocessing, feature selection, model selection, and evaluation in building accurate and reliable predictive models.</p><h4>If you want to follow along with me, you can check out the GitHub repo and find out the dataset and jupyter notebook =&gt; <a href="https://github.com/Fatih0234/LoL_ML_prediction">https://github.com/Fatih0234/LoL_ML_prediction</a></h4><p>Throughout this article we will be following these steps;</p><p>1. Frame the problem and look at the big picture.</p><p>2. Get the data.</p><p>3. Explore the data to gain insights.</p><p>4. Prepare the data to better expose the underlying data patterns to machine learning algorithms.</p><p>5. Explore many different models and shortlist the best ones.</p><p>6. Fine-tune your models and combine them into a great solution.</p><h3>1. Frame the problem and look at the big picture.</h3><p>Can you guess the result of a LoL game with supervised-machine learning techniques?</p><h3>2. Get the data.</h3><pre>df = pd.read_csv(&#39;games.csv&#39;) # main games dataframe<br>jDict = pd.read_json(&#39;champion_info_2.json&#39;)<br>champInfo = pd.read_json((jDict[&#39;data&#39;]).to_json(), orient=&#39;index&#39;)<br># each champion&#39;s dataframe.</pre><h3>General Info on Dataset</h3><p>This is a collection of over 50,000 ranked EUW games from the game League of Legends, as well as json files containing a way to convert between champion and summoner spell IDs and their names. For each game, there are fields for:</p><ul><li>Game ID</li><li>Creation Time (in Epoch format)</li><li>Game Duration (in seconds)</li><li>Season ID</li><li>Winner (1 = team1, 2 = team2)</li><li>First Baron, dragon, tower, blood, inhibitor and Rift Herald (1 = team1, 2 = team2, 0 = none)</li><li>Champions and summoner spells for each team (Stored as Riot’s champion and summoner spell IDs)</li><li>The number of tower, inhibitor, Baron, dragon and Rift Herald kills each team has</li><li>The 5 bans of each team (Again, champion IDs are used)</li></ul><h3>3. Explore the data to gain insights.</h3><pre>df_exp = df.copy() # we have created a clean df for exploration</pre><pre>df_exp.shape  =&gt; (51490, 60)</pre><p>Since we have 60 rows, it will be challenging to show every code snippet’s result. So, as indicated in the beginning, you can go through this project by following the Jupiter notebook shared at the beginning of this article.</p><pre>df_exp.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*97yCa2cxN1nd9gLQvzYqWg.png" /><figcaption>info function</figcaption></figure><p>There are columns that are not shown here in this figure however as indicated on the bottom side dtypes: int64(60), 60 columns are all int64.</p><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*4K8sZ23mJEnjloIfOCzzhw.png" /></figure><p>We don’t have any null values which is good news.</p><pre>df_exp.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*AZUt76lGml-Lh4mD8h6SUA.png" /></figure><h4>Champions dataframe (our another data frame)</h4><pre>champInfo.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*w2Y9AtgY6rqSfWx20lhHpg.png" /></figure><h4>For understanding the columns better, a quick summary of LoL</h4><p>If you know the game, simply skip this section. League of legends ranked games are played with two teams each with 5 members. When you get into the champion pick section. You choose your summaries ( there are two). Summaries are basically special features you can use throughout the game. You pick a hero and ban a hero. There is a map and lanes. Every lane has its own unique features and there are different type of champions that has unique features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*UYpFVha7UPbbieqBknjCAw.png" /></figure><pre>champsid_only = [&quot;t1_champ1id&quot;,&quot;t1_champ2id&quot;, &quot;t1_champ3id&quot;, &quot;t1_champ4id&quot;, &quot;t1_champ5id&quot;, &quot;t2_champ1id&quot;, &quot;t2_champ2id&quot;, &quot;t2_champ3id&quot;, &quot;t2_champ4id&quot;, &quot;t2_champ5id&quot;]<br>df_exp[champsid_only].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*IcE8KSFcXHAYqWhSjk4maA.png" /></figure><p>There are 10 columns in this particular dataframe and 5 of them for team1 and 5 of the others for team2. So, you see a lot of numbers whar are they? They are the id’s of champions. We will reach the actual champions name in the future by joining our champInfo and df dataframes.</p><h4>So far so good hıh?</h4><p>Let’s ask some questions</p><p>What are the top 10 champions that are picked?</p><pre>champsid_only = [&quot;t1_champ1id&quot;,&quot;t1_champ2id&quot;, &quot;t1_champ3id&quot;, &quot;t1_champ4id&quot;, &quot;t1_champ5id&quot;, &quot;t2_champ1id&quot;, &quot;t2_champ2id&quot;, &quot;t2_champ3id&quot;, &quot;t2_champ4id&quot;, &quot;t2_champ5id&quot;]<br><br># let&#39;s add all the picks of the teams<br>most_picked_champs = df_exp[champsid_only].stack().value_counts()<br>most_picked_champs.nlargest(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*eO-p6sOvl4_SddO34Xv_Tw.png" /></figure><p>It seems the champion with 412 id has been picked mostly. Let’s make this more clear and more visually pleasant</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*geYaeoQWfu3lQhaIKqao4Q.png" /><figcaption>Here I just converted the pandas Series object to DataFrame for ease-use purposes.</figcaption></figure><pre>merged_most_picked = pd.merge(most_picked_champs, champInfo, on=&#39;id&#39;)<br>merged_most_picked</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*qJsdLgzntTFdu7ifoxvjIw.png" /></figure><p>Now we have name of the champ, tags and title. So, title and key columns won’t be useful so let’s drop them immediately</p><pre>merged_most_picked.drop([&quot;title&quot;, &quot;key&quot;], inplace=True, axis=1)</pre><p>Let’s make a bar graph by using the seaborn package.</p><pre>plt.figure(figsize=(10,5))<br>sns.barplot(x=&quot;name&quot;, y=&quot;count&quot;, data=merged_most_picked.nlargest(10, &quot;count&quot;))<br>sns.set_style(&quot;darkgrid&quot;)<br>plt.title(&quot;10-Most Picked Champions&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*wz3lGRxKBWKMsz7VyobsLw.png" /></figure><p>It seems Thresh and Tristana are the most picked champions, interesting innit?</p><h4>We have looked at the most picked, what about the most banned 10 champions?</h4><p>It has pretty same way of doing most picked champs, let’s do it.</p><pre># which champs are the most banned?<br>banned_champ = [&quot;t1_ban1&quot;, &quot;t1_ban2&quot;, &quot;t1_ban3&quot;, &quot;t1_ban4&quot;, &quot;t1_ban5&quot;, &quot;t2_ban1&quot;, &quot;t2_ban2&quot;, &quot;t2_ban3&quot;, &quot;t2_ban4&quot;, &quot;t2_ban5&quot;]<br><br>most_banned_champs = df_exp[banned_champ].stack().value_counts()<br><br># let&#39;s concat the most banned champs with the champInfo dataframe<br># however let&#39;s first reset the index in order to make the merge easier<br>most_banned_champs = most_banned_champs.to_frame().reset_index()<br>most_banned_champs.rename(columns={&quot;index&quot;: &quot;id&quot;, 0: &quot;count&quot;}, inplace=True)<br><br>most_banned_champs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*-QuYWja6IzE93RxTnsLdtQ.png" /></figure><p>Again, we don’t really understand from champ ids, so let’s join our two dataframes.</p><pre># let&#39;s merge the two dataframes<br>most_banned_champs = most_banned_champs.merge(champInfo, on=&quot;id&quot;, how=&quot;left&quot;)<br>most_banned_champs.drop([&quot;title&quot;, &quot;key&quot;], inplace=True, axis=1)<br>most_banned_champs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*eTXIKKbpuQSOGShKUX1K8A.png" /></figure><p>Again we have left-joined two dataframes and dropped the title and key columns.</p><p>It is time to graph this.</p><pre># Let&#39;s draw a barplot<br>plt.figure(figsize=(10,5))<br>ax = sns.barplot(x=&quot;name&quot;, y=&quot;count&quot;, data=most_banned_champs.nlargest(10, &quot;count&quot;))<br>ax.bar_label(ax.containers[0], fmt=&#39;%.0f&#39;, padding=3)<br>plt.title(&quot;10-Most Banned Champions&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*U_LduoYCwxmt_M_RHMe6dA.png" /></figure><p>Apparently, Yasuo, zed, cho’gath and Dariues are the champions most people don’t like.</p><h4>What are the win-loose portion between team1(blue) and team2(red)?</h4><p>It is a pretty straight-forward task.</p><pre>winner_portion =  df_exp[&quot;winner&quot;].value_counts().reset_index()<br>winner_portion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*r6DWkzSYqLRaNVmEfUC_2Q.png" /></figure><pre>winner_portion[&quot;index&quot;] =  winner_portion[&quot;index&quot;].map({1: &quot;Blue&quot;, 2: &quot;Red&quot;})<br>winner_portion.rename(columns={&quot;index&quot;: &quot;Team&quot;, &quot;winner&quot;: &quot;Count&quot;}, inplace=True)<br>winner_portion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*CQZXvnyo8cMPbqan3p437g.png" /></figure><p>So, we are getting there slowly. In order to have a portion of the whole, we need to divide each part by the whole.</p><pre>winner_portion[&quot;Count&quot;] = round(winner_portion[&quot;Count&quot;]/winner_portion[&quot;Count&quot;].sum() * 100,1)<br>winner_portion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*71mFyK-IYVGnlPGH-PjA9g.png" /></figure><p>It ‘s reay, let’s graph this.</p><pre>ax = sns.barplot(x=&quot;Team&quot;, y=&quot;Count&quot;, data=winner_portion, palette=&quot;Set2&quot;)<br><br>ax.set_title(&quot;Win Percentage of the Teams&quot;)<br>ax.set_xlabel(&quot;Team&quot;)<br>ax.set_ylabel(&quot;Win Percentage&quot;)<br>ax.bar_label(ax.containers[0], fmt=&#39;%.1f%%&#39;, padding=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*2gLMuuPRLAGW8fXjAjQsYQ.png" /></figure><p>It seems that each team’s win is even which is pretty expected actually if you take into account that we are observing more than 50k games. However, there is a slightly difference. Blue’s team has a slightly advantage. Does it have to do with the blue team’s base closeness to the target creatures on the map? I don’t know you tell me :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*vvqlgd6pA7SjMP1wyelZxA.png" /><figcaption>League of Legend’s game map.</figcaption></figure><p>We have a column that indicates the game duration in term’s of seconds. So, let’s look at its distribution with a team filter.</p><p>First let’s convert it to minutes since it will be easier to work with.</p><pre>df_exp[&quot;game_duration_min&quot;] = round(df_exp[&quot;gameDuration&quot;] / 60)<br>df_exp[&quot;game_duration_min&quot;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*lcEeY9nGtz2yIe4A2uIYGA.png" /></figure><pre>plt.figure(figsize=(10,5))<br>sns.kdeplot(x = &quot;game_duration_min&quot;,data=df_exp ,hue=&quot;winner&quot;, palette=&quot;Set2&quot;)<br>plt.title(&quot;Game Duration Distribution&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*KvZHYMotmJpm37pZ0AenqA.png" /></figure><p>So, actually we see a almost identical distribution for both sides which is pretty impressive. We have a normal distribution even though we have slightly weird movements on the left side. That’s because one of the team members left the game in the beginning of the game, that team has the chance to surrender the game and they don’t loose any ranked points whatsoever. So, those games are actually our outliers, let’s drop those rows from our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*htmWIxg-l2gJFsfJLhzKyw.png" /></figure><p>I have made the choice of 15 for my threshold, So I will be counting the games finished under 15 minutes as games with a team that has an afk(away from keyboard) player. Let’s drop those from our dataset.</p><pre>index =  df_exp[df_exp[&quot;game_duration_min&quot;]&lt;15].index<br>df_exp.drop(index, inplace=True)<br>df_exp</pre><p>Afte deleting the outliers, let’s check the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*T9syE4BzuTRAFGrGvbTUYQ.png" /></figure><p>Now it is better, it still has outliers and it is pretty left-skewed.</p><p>Our EDA section is done, there could have been done a lot of things however, let us dive into modelling stage.</p><h4>4. Prepare the data to better expose the underlying data patterns to machine learning algorithms.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*M0Ydb4e79SNmJ-SOcVARTg.png" /></figure><p>Here you can see we have tags column that is the feature of each champion. So, I thought this could be a good way of making encoding. Let’s dive in.</p><pre># from id to name<br><br>def id_to_tags(id):<br>    return champInfo.loc[id][&quot;tags&quot;]<br><br>df[&quot;t1_champ1id&quot;].apply(id_to_tags)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*i9j6VDFgSOc88oyFThm_CQ.png" /></figure><p>I have tested out the id_to_tags section to the t1_champ1id column and it works as expected.</p><pre>champ_picks = [&quot;t1_champ1id&quot;, &quot;t1_champ2id&quot;, &quot;t1_champ3id&quot;, &quot;t1_champ4id&quot;, &quot;t1_champ5id&quot;, &quot;t2_champ1id&quot;, &quot;t2_champ2id&quot;, &quot;t2_champ3id&quot;, &quot;t2_champ4id&quot;, &quot;t2_champ5id&quot;]<br><br>df_mdl_tags = df_mdl[champ_picks].applymap(id_to_tags)<br>df_mdl_tgs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*7_SsivFfmkipY1PCeJnIfQ.png" /></figure><p>Here again we have excluded all the 10 champion pick’s into a different dataframe and applied the id-to-tags function all of them in one go.</p><pre>df_mdl_tags_t1 = df_mdl_tags.iloc[:, :5]<br>df_mdl_tags_t2 = df_mdl_tags.iloc[:, 5:]</pre><p>there we go, now we have two dataframe that includes each team’s champ picks.</p><pre><br><br># Create a function to count the occurrences of each value in a list<br>def count_values(lst, value):<br>    return lst.count(value)<br><br><br><br><br><br>def tags_encoding(df, team):<br>    # we have concatenate all the lists in a row<br>    df = df.sum(axis=1)<br>    #let&#39;s convert it into a df because in the summation part it got series type<br>    df = pd.DataFrame(df)<br>    df.columns = [f&quot;{team}tags&quot;]<br>    <br>    # Create a list of unique values from all the lists in the column<br>    unique_values = list(set([value for sublist in df[f&quot;{team}tags&quot;] for value in sublist]))<br><br>    # Create new columns based on the unique values<br>    for value in unique_values:<br>        df[team+value] = df[f&quot;{team}tags&quot;].apply(count_values, args=(value,))<br>        <br>    return df<br><br>df_t1_encoded = tags_encoding(df_mdl_tags_t1, &quot;t1&quot;)<br>df_t2_encoded = tags_encoding(df_mdl_tags_t2, &quot;t2&quot;)</pre><p>Here in this tags_encoding function might look intimidating which is actually. I don’t really understand some parts of it actually. But what does this function do is that it gets the dataframe and add’s all the taggs into one big list and encodes them according to each tag’s total number. I think you will understand more when I show it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*MsBqsCgX7aMBKJhQq743Lg.png" /></figure><p>it has encoded from this to this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*ry522jyLOk5g66a7foFV6g.png" /></figure><p>We have implied the same for df_t2_encoded as well.</p><p>Let’s concatenate those two teams again into one dataframe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*0FacWJlKrQN7R403nwqP2Q.png" /></figure><p>Here in this dataframe we have t1tags and t2tags which are no longer useful so, let’s drop them</p><pre>df_teams_encoded.drop([&quot;t1tags&quot;, &quot;t2tags&quot;], inplace=True, axis=1)</pre><p>And finally, let’s concatenate this encoded dataframe with out original dataframe.</p><pre><br>df_mdl = pd.concat([df_mdl, df_teams_encoded], axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*qYSv9Skp6B5QDqBQYF8S1Q.png" /></figure><p>As you can see we have added a bunch of other columns via feature engineering.</p><h4>Let’s encode the creation time to a categorical variable day of the week</h4><pre># One hot encoding the time of the game<br>from sklearn.preprocessing import OneHotEncoder<br><br># initialize the OneHotEncoder<br>encoder = OneHotEncoder(handle_unknown=&#39;ignore&#39;)<br><br># we have created an encoded df<br>one_hot_encoded = pd.DataFrame(encoder.fit_transform(df_mdl[[&quot;day_of_week&quot;]]).toarray())<br><br># giving the correct column names<br>one_hot_encoded.columns = encoder.get_feature_names_out([&quot;day_of_week&quot;])<br><br># finally concatenating them with the original df_mdl<br>df_mdl = df_mdl.join(one_hot_encoded)<br>df_mdl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*kRdCxO9TXERESoB44UuNQA.png" /></figure><p>Here we simply converted the creatime to datetime object and we extracted the day of the week and we have implemented OneHotEncoding, that’s it. Again we have added 7 more columns to our model dataset.</p><p>We have some unnecessary columns, so let’s delete them</p><pre># let&#39;s drop the day_of_week column since we don&#39;t need it anymore<br># and drop the other useless columns<br><br>df_mdl.drop([&quot;creationTime&quot;, &quot;gameId&quot;, &quot;day_of_week&quot;], inplace=True, axis=1)<br>df_mdl</pre><p>We have come to the end of this section, I hope it was fun!</p><h4>5. Explore many different models and shortlist the best ones.</h4><h4>6. Fine-tune your models and combine them into a great solution.</h4><p>We will be going through those two steps in one-go.</p><h4>Decision Tree Classifier</h4><pre># let&#39;s implement Decision Tree Classifier<br> <br>from sklearn.tree import DecisionTreeClassifier<br><br>dtc = DecisionTreeClassifier()<br>dtc.fit(X_train, y_train)<br><br>print(&quot;Score on test data&quot;)<br>print(dtc.score(X_test, y_test))<br>print(&quot;Score on train data &quot;)<br>print(dtc.score(X_train, y_train))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*sjwF3NstNxn_skh5Srl_rA.png" /></figure><p>So, our data has full accuracy on training data whereas it has 95% accuracy on test data. This might mean our data overfitting so let’s go through both cross_val_score and hyperparameter tunning in one go.</p><pre># hyperparameter tunning method for decision tree classifier<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import GridSearchCV, cross_val_score<br><br><br># Define the hyperparameters to tune<br>param_grid = {<br>    &#39;max_depth&#39;: [2, 3, 4, 5],<br>    &#39;min_samples_split&#39;: [2, 3, 4],<br>    &#39;min_samples_leaf&#39;: [1, 2, 3]<br>}<br><br># Create the decision tree classifier object<br>dt = DecisionTreeClassifier()<br><br># Create the GridSearchCV object<br>grid_search = GridSearchCV(dt, param_grid, cv=5)<br><br># Fit the GridSearchCV object to the data<br>grid_search.fit(X_train, y_train)<br><br># Get the best hyperparameters and the corresponding score<br>best_params = grid_search.best_params_<br>best_score = grid_search.best_score_<br><br># Create the decision tree classifier object with the best hyperparameters<br>dt_best = DecisionTreeClassifier(**best_params)<br><br># Calculate the cross-validation score<br>cv_score = cross_val_score(dt_best, X_train, y_train, cv=5)<br><br># Print the results<br>print(f&#39;Best hyperparameters: {best_params}&#39;)<br>print(f&#39;Best score: {best_score:.2f}&#39;)<br>print(f&#39;Cross-validation score: {cv_score.mean():.2f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*XGCaOJKYMfJ0XLRlKLICMg.png" /></figure><p>Our best score has gone up to 96% which is pretty impressive.</p><h4>Our last model Gradient Boosting Classifier</h4><pre># let&#39;s try the gradient boosting classifier<br>from sklearn.ensemble import GradientBoostingClassifier<br><br>gbc = GradientBoostingClassifier()<br><br>gbc.fit(X_train, y_train)<br><br>print(&quot;Score on test data&quot;)<br>print(gbc.score(X_test, y_test))<br>print(&quot;Score on train data &quot;)<br>print(gbc.score(X_train, y_train))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*-H0ZpyXuv_Vs66lHiChH9g.png" /></figure><p>So, actually gradient boosting classifier has a more robust evaluation because of its depth. So, our training data score and test data score are pretty close which is a good sign.</p><p>Let’s hyperparameter tune and cross_val_score</p><pre># hyperparameter tunning<br><br>from sklearn.ensemble import GradientBoostingClassifier<br>from sklearn.model_selection import GridSearchCV, cross_val_score<br>from sklearn.metrics import accuracy_score<br><br># Define the parameter grid to search<br>param_grid = {<br>    &#39;learning_rate&#39;: [0.05, 0.1, 0.2],<br>    &#39;max_depth&#39;: [3, 4, 5],<br>    &#39;n_estimators&#39;: [50, 100, 200]<br>}<br><br># Create a GradientBoostingClassifier<br>gb = GradientBoostingClassifier()<br><br># Create a GridSearchCV object<br>grid_search = GridSearchCV(<br>    estimator=gb,<br>    param_grid=param_grid,<br>    cv=5,<br>    scoring=&#39;accuracy&#39;,<br>    n_jobs=-1<br>)<br><br># Fit the GridSearchCV object to the data<br>grid_search.fit(X_train, y_train)<br><br># Print the best hyperparameters<br>print(grid_search.best_params_)<br><br># Create a GradientBoostingClassifier with the best hyperparameters<br>best_gb = GradientBoostingClassifier(**grid_search.best_params_)<br><br># Evaluate the best GradientBoostingClassifier with cross_val_score<br>scores = cross_val_score(<br>    estimator=best_gb,<br>    X=X_train,<br>    y=y_train,<br>    cv=5,<br>    scoring=&#39;accuracy&#39;,<br>    n_jobs=-1<br>)<br><br># Print the mean accuracy score and standard deviation<br>print(&quot;Accuracy: {:.4f} (+/- {:.4f})&quot;.format(scores.mean(), scores.std()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*0RQuOPXInbRdL9e3XIZjNw.png" /></figure><p>Our accuracy is 97% with a 0.0018 standard deviation for Gradient Boosting which is pretty impressive.</p><p>Those two ML models are pretty good for binary classification however you can also try Super vector machine and Logistic Regression. I would love to see the results of those models on the comment section .</p><p>So this is the end of this article, I hope you have learned a lot and enjoyed it. In conclusion, we now have the ability to predict the winner of the game in a game. So, this is really great.</p><p>I am open to your discussion and critics. You can reach me via LinkedIn</p><p>LinkedIn =&gt; <a href="http://www.linkedin.com/in/fatih-karahan-717931193/">www.linkedin.com/in/fatih-karahan-717931193/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9437456d63b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full edged End-to-End Machine Learning Project- Hotel Reservations Canceled? or not?]]></title>
            <link>https://medium.com/@sekanti02/full-edged-end-to-end-machine-learning-project-hotel-reservations-canceled-or-not-d17829940237?source=rss-a249afbb20fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d17829940237</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Fatih Karahan]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 16:14:03 GMT</pubDate>
            <atom:updated>2023-03-01T16:14:03.032Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-End Machine Learning Project- Hotel Reservation Canceled? or not?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*RRskON55j3p9eZSqWROmfQ.png" /></figure><p>Hotel reservation cancellations can be a headache for both travelers and hoteliers. But what if there was a way to predict them before they occur? Machine learning can help. In this article, we’ll take a deep dive into an end-to-end machine-learning project that uses historical hotel reservation data to predict whether a reservation will be canceled or not.</p><p>First, we’ll frame the problem and look at the big picture, discussing why predicting cancellations is important and how machine learning can help. Then, we’ll explore how to get the data, including what sources to use and how to clean it.</p><p>Next, we’ll explore the data to gain insights and prepare it to better expose the underlying data patterns to machine learning algorithms. This will involve data preprocessing techniques such as feature engineering, normalization, and encoding.</p><p>After that, we’ll explore many different models and shortlist the best ones. We’ll cover a variety of machine-learning algorithms, including logistic regression, decision trees classifier, Random-Forest-Classifier, and a few more. We’ll also discuss how to evaluate the models and choose the best one for our problem.</p><p>Once we’ve selected our model, we’ll fine-tune it and combine it with other models to create a great solution. We’ll discuss techniques such as hyperparameter tuning and cross-validation</p><p>Join us as we take you through the 6 of an end-to-end machine learning project, showing you how to use data to solve real-world problems in the hotel industry.</p><p>I want you to grab your coffee and if you can grab your laptop and go through this project. You can find the datasets and code snippets in the link below in my GitHub repo.</p><p><a href="https://github.com/Fatih0234/hotel-reservation">https://github.com/Fatih0234/hotel-reservation</a></p><h3><strong>1. Frame the problem and look at the big picture.</strong></h3><p>Can you predict if the customer is going to honor the reservation or cancel it?</p><h3>2. Get the data.</h3><pre>df = pd.read_csv(&#39;Hotel Reservations.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*JgQK2JDhi8iL17-xAYz1GA.png" /></figure><h3>3. Explore the data to gain insights.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*6h6Wd8jHpqCt8cFOhFdp6A.png" /></figure><p>We got 36275 rows and 19 columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*6fnWDU7ttrQHSbQ8-v0CTg.png" /><figcaption>info function</figcaption></figure><p>I love info function in pandas because it really gives a lot of info about the dataset. Here, we can see the indexes, null values, data dtypes and also things like memory usage which is pretty handy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*2-pOD1rO-ziwPBuIfzpQDw.png" /></figure><p>We don’t have any null values in our dataset.</p><pre># let&#39;s switch to a new dataframe to have a clean copy <br># of the original data to explore the data.<br><br>df_exp = df.copy()<br><br># Since Booking ID won&#39;t attribute to the analysis, we can drop it.<br>df_exp = df_exp.drop([&quot;Booking_ID&quot;], axis=1)</pre><h4>Let’s now look at a few distributions and columns relations</h4><pre>sns.pairplot(df_exp[[&quot;no_of_weekend_nights&quot;,<br>                     &quot;no_of_week_nights&quot;,<br>                     &quot;lead_time&quot;,<br>                     &quot;arrival_month&quot;,<br>                     &quot;avg_price_per_room&quot;,<br>                     &quot;no_special_requests&quot;<br>                    ]], kind=&quot;reg&quot;, diag_kind=&quot;kde&quot;, hue=&quot;booking_status&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xW3XI5md3w9AWCR5orenjQ.png" /></figure><p>As customers have more no_of_special_requests, they tend to not cancel their bookings which is a good signal for our machine learning model. Moreover, as special requests increase, avg_price increases which makes sense.</p><pre>df_exp[[<br>   &#39;no_of_adults&#39;, &#39;no_of_children&#39;, <br>        &#39;no_of_weekend_nights&#39;,<br>       &#39;no_of_week_nights&#39;, <br>      #  &#39;type_of_meal_plan&#39;, <br>    #    &#39;required_car_parking_space&#39;,<br>    #    &#39;room_type_reserved&#39;, <br>       &#39;lead_time&#39;, <br>    #    &#39;arrival_year&#39;, <br>       &#39;arrival_month&#39;,<br>    #    &#39;arrival_date&#39;, &#39;market_segment_type&#39;, &#39;repeated_guest&#39;,<br>       &#39;no_of_previous_cancellations&#39;, &#39;no_of_previous_bookings_not_canceled&#39;,<br>       &#39;avg_price_per_room&#39;, &#39;no_of_special_requests&#39;,<br>    #    &#39;booking_status&#39;<br>       ]].hist(figsize=(20,20), bins=20, xlabelsize=10, ylabelsize=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*OraifR5_An87TZZhIMtRqA.png" /></figure><p>Here we see gaussian/standard distributions in avg_price, no of week nights, no of adults columns, and power-law(80–20 rule) distribution in no_of_special requests and lead_time columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*sXDS67Q5QonN38Y93xBBNA.png" /></figure><p>Here in this analysis, we can see that roughly 2/3 of our customers don’t cancel and the rest cancels.</p><p>Now I want to make some analysis on repeated guests. For this, let’s filter out our dataset.</p><pre># let&#39;s look at the case where first filter out the repeated guest =1<br><br>df_repeated = df_exp[df_exp[&quot;repeated_guest&quot;]==1]<br>df_repeated</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*yUlB_li8KIpdd2zVw6ZvtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*JlZKY2Wnu8Bsnb6rLVjrPw.png" /></figure><p>From analysis, we can say that only 1.75% of our repeated customers cancel which is a really strong argument for us.</p><h4>Let’s now look at this in a different way.</h4><pre>count_of_canceled = df_repeated.groupby(&quot;no_of_previous_cancellations&quot;).size().to_frame().reset_index().rename(columns={0:&quot;count&quot;})<br><br>count_of_canceled.sort_values(by=&quot;count&quot;, ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*HPwJSPaDyLUrgqB22emRtA.png" /></figure><p>Let’s put this on a barplot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*EM4qdxxgNMLv6Y_5CVCbrA.png" /></figure><p>2/3 of our repeated guests never made any cancelations before which is really impressive signal for our model.</p><p>Let’s now look at our date columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*74lJyTgOxT5L94nxRa8Lmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*D6cYgZpEzx60R4nzSYkZGA.png" /></figure><p>Our historic hotel reservations dataset starts from 7th month of 2017 to end of 2018.</p><p>Let’s look at our columns correlations to each other</p><pre># LEt&#39;s make correlation analysis.<br>corr = df_exp.corr()<br>plt.figure(figsize=(15,15))<br>sns.heatmap(corr, annot=True, cmap=&quot;coolwarm&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*PwTB9dbkDU2RXR-SLLwS6w.png" /></figure><p>Here we see that there is a 0.54 correlation between not cancellations and repeated guests which we have discovered actually before this relation. Other than this we can’t really any worth-noting thing out of this heatmap.</p><h3>4. Prepare the data to better expose the underlying data patterns to machine learning algorithms.</h3><h4>Let’s categorize the arrival time into just days like Monday, Tuesday etc.</h4><p>I want to use my date column by converting it into categorical data. How will I do this is that first I will take my year, month and day columns together in a string column as a date then I will convert this to datetime type, afterwards I will be able to extract the exact day of that arrival day.</p><p>If you want you can give this problem a try on your own, it is great opportunity to see how you do this challenge on your own.</p><pre>df_exp[&quot;date&quot;] = df_exp[&quot;arrival_year&quot;].astype(&quot;str&quot;) +&quot;-&quot;+ df_exp[&quot;arrival_month&quot;].astype(&quot;str&quot;) + &quot;-&quot;+ df_exp[&quot;arrival_date&quot;].astype(&quot;str&quot;) <br>df_exp.dtypes<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*AXnNAtlPkAwnFzhQbQzKSQ.png" /></figure><h4><em>there are some problems with our data as we have 2018–02–29 which is not possible, we will convert those into 2018–02–28</em></h4><pre>df_exp[(df_exp[&quot;arrival_month&quot;] == 2) &amp; (df_exp[&quot;arrival_date&quot;] == 29)] = df_exp[(df_exp[&quot;arrival_month&quot;] == 2) &amp; (df_exp[&quot;arrival_date&quot;] == 29)].replace(29,28)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*SPoKbzDjqIows02TOKpt6g.png" /></figure><p>Now we have a date column where we have datetime dtype values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*AZ4Ss1wPS6JsnTmOOOQZDA.png" /></figure><p>In those two cells, we have created a column where we have day of the week but in numbers format. 0 means Monday, 1 means Tuesday etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*GWyalZ9l9TB68kjUYLOmxQ.png" /></figure><p>Here we have mapped those values as Weekday and Weekend. Now we got what we want. We are doing pretty good, let’s keep going.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*Ofo1MtZ6MOZt1b91Vk8x6A.png" /></figure><p>2/3 of our customer’s arrival date is in weekdays and the rest is in weekend.</p><p>Exploration part is done, we have done great exploration so far. Let’s get going to modeling stage slowly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*LN-tfnr9ui_xIkfk1agvAg.png" /></figure><p>For ML models, we need only numerical models. We will be working on it in thid df_mdl dataframe.</p><p>We have dropped the date-related columns except for our dayofweek column.</p><h4>Let’s take care of categorical data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*R8ZTuzbsCZUi4RQIX9wq2w.png" /></figure><p>We have started with our target value. if it is canceled it is 1 else 0, simple haa!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*cmK9nSfgt01ndh3egf-08g.png" /></figure><p>Those are the rest of the categorical columns in our dataset. We will be implementing OneHotEncoding to them.</p><h4>What is OneHotEncoding?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*j4jyEtmsHD9a2ggBJ5zmwA.png" /></figure><p>Image really makes it obvious what really is one-hot encoding so, I won’t be getting into it. If you got problems, you can watch 5 minutes of one-hot encoding explanation video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*qHKOkXSF6bRN8G-e3Qe4Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*UqOcX5RQNsdDgHtpOruofw.png" /></figure><p>Here we created our OneHotEncoder object and fitted the df_cat data frame.</p><p>Since encoder’s transform function doesn’t return dataframe, we need to convert it to dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*MCE2qLciJEvLJ4D31OqPkA.png" /></figure><p>return values is sparse matrix which is a different representation of a matrix that consists of a lot of 0s. Why is it used? It is more efficient in terms of storage and speed.</p><pre>encoded_cat = pd.DataFrame(encoder.transform(df_cat).toarray(), columns=encoder.get_feature_names_out(), index=df_cat.index)<br>encoded_cat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*NFmwPUDcmkBbigH7BRilvQ.png" /></figure><p>Now we got 18 columns from only 4 categorical columns.</p><p>Now it is time to concatenate these encoded_cat and our original df_mdl dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*AHX78Qf9Q1hkbj2vOg189w.png" /></figure><p>our df_mdl now hsa 30 columns.</p><p>We are really close to modeling. Let’s identify X values (features) and y (target value)</p><pre>X = df_mdl.drop(&quot;booking_status&quot;, axis=1)<br>y = df_mdl[&quot;booking_status&quot;]</pre><p>We got one more step before getting to modeling and that is outlier detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*bOEb9gojsSvDpKV3k03ONg.png" /></figure><p>In first cell, we have initialized our localoutlierfactor and fit_predict the X features. It gave us -1 and 1s. -1 means it is outleir and 1 is normal.</p><p>In second cell, we saw the indices and total number of outliers</p><p>Finally, we have dropped them from our X and y data frames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*gf0Wg2bWhW4VZWnUVaR0WQ.png" /></figure><h3>5. Explore many different models and shortlist the best ones.</h3><h3>6. Fine-tune your models and combine them into a great solution.</h3><p>We will be covering those 2 steps in one go. Let’s do it.</p><h4>Splitting dataframe into training and test datasets</h4><pre># let&#39;s first split the dataframe into X and y<br>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)</pre><p>I will be going through 3 algorithms</p><ol><li>DecisionTreeClassifier</li><li>RandomForestClassifier</li><li>GradientBoostingClassifier</li></ol><h4>Decision Tree Classifier(DTC)</h4><p>I will first go for hyperparameter-tuning directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*e7J2uBNdVrPQbfLNc8vt0w.png" /></figure><p>Our best hyperparameters listed, let’s try them out in cross-validation-score algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*3cqGaiSYplUYgDa6pBFWPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*mSDdFBv4qcdBApw6pyGDkg.png" /></figure><p>DTC performs around 85% which is not bad at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*uRL1_a69SQ1TzZOBbfDlyg.png" /></figure><h4>Random Forest Classifier(RFC)</h4><p>Let’s implement the same steps to RFC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*1hFuuDQWeWGW8h_bOsplFw.png" /></figure><p>let’s move on to cross validation score</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*XdK5xGigRbxQLgXVoawu_g.png" /></figure><p>RFC performs slightly better than DTC with a mean of 88% accuracy and 0.005 std which is pretty impressive.</p><h4>Gradient Boosting Classifier(GBC)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*tFNGnStAeXRtdpwRvZNtQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*Ayjv5Qfo3jyFdAS0UF7ryw.png" /></figure><p>GBC also performs like RFC with a 87% mean accuracy and 0.007std.</p><h4>Model Selection</h4><p>GBC and RFC performs the best so far and DTF performs slighlty worse than those two other models. However, there is one more metric that we need to take into consideration that is speed of the models Since it will be pretty important in the production process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*Dsl15qdcQNdzG7JgkBhBSQ.png" /></figure><p>Even though GBC and RFC have larger accuracy scores, they took really longer time to perform than DTC.</p><p>DecissionTreeClassifier(DTC) performs 16 times faster than GradientBoostingClassifier(GBC) and 33 times than RandomForestClassifier(RFC).</p><p>So, I will choose DecisionTreeClassifier as my final model.</p><p>We came to an end of this project, I hope you enjoyed the general process and thought process of the project.</p><p>I am a newbie in the ML world and I am very open to critics and comments on my thought process. I am pretty sure I have made some mistakes or “should have written better or thought better” situations a lot.</p><p>You can reach me via</p><p>email =&gt; sekanti02@gmail.com</p><p>LinkedIn =&gt; <a href="https://www.linkedin.com/in/fatih-karahan-717931193/">https://www.linkedin.com/in/fatih-karahan-717931193/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d17829940237" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Housing SQL Data Cleaning Project]]></title>
            <link>https://medium.com/@sekanti02/housing-sql-data-cleaning-project-31b4896f5c07?source=rss-a249afbb20fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b4896f5c07</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Fatih Karahan]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 12:41:03 GMT</pubDate>
            <atom:updated>2022-04-11T12:41:03.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eLclZgHRvuloINjx.jpg" /></figure><p>Welcome to my project blog. This is completely data cleaning project. There is no data exploration, just cleaning. The exploration will be the next part. Without cleaning we can’t really take as much exploration as possible from our dataset.</p><p><strong>Here is how will it go, </strong>I will be walking you through the problems we have in the dataset and then the solution and the thought process behind it.</p><p>You can try the codes and challenges I will be describing and trying to solve on your own with the dataset you can find on my GitHub repository. Here you can find also the codes and the explanation with them.</p><p><a href="https://github.com/Fatih0234/Housing-Data-Cleaning-Project-With-SQL">GitHub - Fatih0234/Housing-Data-Cleaning-Project-With-SQL: In this Project, I have tried to clean the data and make it usable for my future analysis. Enjoy!!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A97gpsipRSwkOrCJT1TrXw.png" /></figure><p>This is how my data set looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5i6jzGOt8GQ5wOgOQ_rLw.png" /></figure><p>This SalesData column’s data type is DateTime but there is no time information here. So this is going to be first thing that should be done.</p><pre>Update dataset <br>Set SaleDate = cast(SaleDate as Date);</pre><p>This basic update comment doesn’t work, for some reason but I don’t know why exactly.</p><p>Let’s Do something else in order to make it.</p><pre><strong>Alter table</strong> dataset</pre><pre><strong>Add </strong>SaleDateConverted <strong>date</strong>;</pre><pre><strong>Update</strong> dataset</pre><pre><strong>Set</strong> SaleDateConverted =<strong> cast</strong>(SaleDate as Date);</pre><p>Here we actually first created a table then updated the new table’s value with the value we wanted to do before. This works well , so let’s continue.</p><p><strong>PropertyAddress</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*8avsMvpdKYwO9bmMtwP4mw.png" /></figure><p>Here we can see the property address is divided by “,” . We want to separate the address values because they will be handier in future analyses. For example, we will be able to look at our values by looking at only cities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXZTEYdP0BnACEXU0oEMiQ.png" /></figure><p>We have implemented this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*T2pV7NFilYDo0T6VmAuvOQ.png" /></figure><p>This is the result we wanted. The explanation is the upside of the code. If you have some doubts about code, you can always reach out to me with my connection information.</p><p>But, we haven’t done yet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTK0KjXys1ktRRTDdbzsSQ.png" /></figure><p>In the first part, we have added two columns and in the second part, we have given the values we just generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*8oQYG4_iher5ipwY_BIRhQ.png" /></figure><p>SaleDateConverted, SplitAdderss, and SplitCity columns are present in our dataset right now. So, Let’s continue.</p><p><strong>OwnerAddress</strong></p><p>Let’s now implement the same thing, for the OwnerAddress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*71H7lHHtPUINOh58eBZDIA.png" /></figure><p>Here we have 3 parts separated by 2 commas. With Substring and Charindex functions, it is going to be a bit tricky. Luckily, we got another simple function for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsLwHHlKUqOdEbrqH8VIQQ.png" /></figure><p>Unfortunately, I got the result below with the substring and charindex functions. I am sure I am giving the correct values but it kept giving the second part like this. But no worries the PARSENAME function is going to save us in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*pWYJtzn9akK4Z0OdAThm5g.png" /></figure><p>PARSENAME’s result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*nTigX6CpW1sqkVqOTV-3Qg.png" /></figure><p>Here, we can see we have reached the desired output we want.</p><p>Let’s again add the columns and give the values we want and create those separate address columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*UJxeFzqY5d-zD_cpqatbNw.png" /></figure><p>Again With the ALTER TAble and ADD columns, we are creating the columns.</p><p>When we create those columns they got null values automatically. So in the second part with the UPDATE statement, we set the values we just generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*l_fCwDetbMyTcItw1amiqg.png" /></figure><p>Everything seems correct, we are good to continue now.</p><p><strong>Missing Address</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*_EDT3FsL6CQDk0F1CueFfw.png" /></figure><p>The idea is that we can populate Some property address with the help of ParcelID. Because property address doesn’t change as long as the property exists. When the ParcelID’s of 2 property addresses are equal, their property addresses are also equal when we look at the dataset.</p><p>I know it sounds complicated. It is easier to explain what I mean by showing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*0rAOfzBkWQzxgnuRqPxppA.png" /></figure><p>In this code, we are implementing a self-join.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*yhcrqM-UW6F9SPNafMc5rQ.png" /></figure><p>As we can see, their Address information is equal and they are not the same rows. So Let’s look at the cases when the d1.UniqueID is null.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*Hpve1k63q12JLMTQWUaNzg.png" /></figure><p>the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*7m0VIrgEJoen2_kronl0fw.png" /></figure><p>The first one is the d1.PropertyAddress and we are interested in that. We would like to get the Second Property address in the place of Null values in the First Property address and in this way, we would populate the address values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*Kxvdrdc7A5ahvBsG0o0deQ.png" /></figure><p>We can do this with the ISNULL function easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpftMCk67bnz1VTcQG3TeQ.png" /></figure><p>The result is fabulous. We have generated the results we want. Now, finally we will update the null values with these values. Let’s do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*EFph5GNrY2rnDdb8aD_T4A.png" /></figure><p>With this, we have generated the address values which was null before.</p><p>Wow, that was great, wasn&#39;t it? :)</p><p><strong>Inconstant values in SoldAsVacant column.</strong></p><pre><strong>Select distinct</strong> SoldAsVacant , <strong>Count(</strong>SoldAsVacant<strong>)</strong> <strong>as</strong> CountColumn <strong>from</strong> dataset</pre><pre><strong>group by </strong>SoldAsVacant</pre><pre><strong>order by</strong> CountColumn</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*-AfqjitNMpJc1e-R35F7Gw.png" /></figure><p>As we can see, there Y and Yes and vice versa for No values. This is not good for our future analysis.</p><p>Let’s work on it. Because the number of Yes and No s are greater than Y and N s . We will convert the Y and N into Yes and No. Let’s do it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*V7TbgijFM8m8tdzRsSux1Q.png" /></figure><p>In this code, we have used a Case statement. The case statement is like if/else statement. It reads like When SoldASVacant is ‘Y’, Then give me ‘Yes’ value. The second argument( We can specify as much as we want from these.) read like When the SolAsVacant is N then give me No value. When None of those arguments give results then give me the original SoldAsVacant Value. Finally, with the End clause, we end our operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*MH0qOQZp8gyKYlKs1EK66A.png" /></figure><p>Here as we can see from result, it gives us No when the SOldAsVacant is N. Ok this works well, now let’s get into update section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*tCjOutmJo5gvIO_r280uwg.png" /></figure><p>With this Update statement, We are good to go.</p><p><strong>Duplicates</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*9yMNl2UkSBpxO4K8WW8ukA.png" /></figure><p>I will be getting back to the question of “why we have used the with statement” later.</p><p>Let’s now concentrate on the inner query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQvzqOVs5rLYeznJqiCAFw.png" /></figure><p>My assumption is that when those 5 columns (ParcelID, PropertyAddress, SaleDate, SalePrice and LegalReference) are same for two rows, ok one of those rows are duplicate. If it is three, two of them duplicate and so on.</p><p><strong>ROW_NUMBER()</strong></p><p>This function is rank window function and Gives us values from 1 to infinity with regard to partition by and order by clause. For more information, check out this function on google.</p><p>When we partition by those 5 columns I have described above, there will be a lot of 1 and when there is a value , two or more in our rows, ok that will be duplicate. Not simple to mind around it, but if you know the concept of Window function and row_number, it is going to be easier to think about it.</p><p><strong>WITH clause or a.ka CTE</strong></p><p>Because we can’t use allias in where function and we have to specificy an allias for window function, we will use it later on after calling the with statement as I did in my query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKZ8eRLyenCgEY0EbFqWBg.png" /></figure><p>Result here and those are duplicates, if you want to check the correctness of it, you can try it on your own. You can find the GitHub repository in the description section.</p><p>Let’s delete them as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*qQRR-xIbq1dv5s6BZJjAmA.png" /></figure><p>Now, We are good to go.</p><p>That’s it for this project. See you and Keep creating, Keep learning and Keep fighting.</p><p>I would like to give credit to Alex the Data Analyst. I got the data from him. You can find him on youtube.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b4896f5c07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Excel Superstore Dynamic Dashboard]]></title>
            <link>https://medium.com/@sekanti02/microsoft-excel-superstore-dynamic-dashboard-1f80f83dc44d?source=rss-a249afbb20fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f80f83dc44d</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Fatih Karahan]]></dc:creator>
            <pubDate>Wed, 23 Mar 2022 19:00:40 GMT</pubDate>
            <atom:updated>2022-03-23T19:24:45.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkbMvNM9mOSaklXzXQmVBQ.png" /></figure><p>Before starting, I want to put these things out. I am going to make this project with the vibe of a Data analyst who got a dataset from a company with a bunch of business questions to be discovered.</p><p>I believe that it is quite important to start with a bunch of business questions because, in real life, that’s what you do right? You work for a business that produces data and seeks for useful insights from those datasets and here we, as data analysts, come into the play.</p><p>In my case, as indicated above, I got a dataset with a bunch of business questions. My ultimate aim for my client is to create charts designed to answer business questions and create business insights. Put those charts into a dynamic and user-controlled dashboard. what I mean with dynamic is that the dashboard can be easily updated with upcoming data which we are gonna do actually in project and what ı mean with user-controlled is that the user, my client, can easily filter and drill-through the data as needed.</p><h3>My dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*E3-8fHOaXIYKt0w61sbMfA.png" /></figure><p>These are my column headers and their descriptions. As you can see, this is one big dataset and actually in a ideal work, you wouldn’t want one big dataset. the biggest reason for that we are going to have a lot of data and having all of them in one dataset is a bit clumsy. With that being said, we are going to split data into one fact/data set and a bunch of dimension/lookup datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6m1oS7zYb1SaP31wlOyEXw.png" /></figure><p>This is how my dataset looks like.</p><p>We are going to create 7 datasets from this one big dataset.</p><p><strong>=&gt; 4 Sale datasets</strong> (I am going to split them into 5 different dataset like 2014–2015–2016–2017 sales data) the reason why we are working like this is that every year we are going to have 1-year worth of dataset and that data needs to be adapted into our dashboard model. So, for that reason, we should work year-based different datasets. Remember our purpose is not just to put there a dashboard but a sustainable and dynamic one.</p><p><strong>=&gt; Customer dataset</strong></p><p><strong>=&gt; Product dataset</strong></p><p><strong>=&gt; Address dataset</strong></p><h4>Our workflow</h4><p>We are going to work with Excel tool with Power Pivot and Power Query.</p><p>The reason why we work with Power Query is that it will make the data cleaning process automatic and not tedious and we could load data from there to Power Pivot. With Power Pivot, we are going to be able to work with more than one table and make connections between tables and work with millions of data if needed.</p><p>Enough talking, let’s get working. I will create the Product dataset with a unique ProductId column and likewise, I will create the customer dataset with the unique CustomerID. I will do this with normal Pivot tables because it is going to narrow the dataset and give me the only unique values.</p><h4>Customer Dimension Table</h4><p>With a simple pivot tabular format, I could come up with a customer dimension table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*oY2GDUdSFuHrIPscdYUZBQ.png" /></figure><h4>Address Dimension Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*ZzyFa5eCu6FAXEQEbDBPIw.png" /></figure><p>Because Order ID is unique for every customer’s address, our primary key is Order ID. In our dataset, every person has ordered from more than one location. So this creates more address than customer. We should aware of that.</p><h4>Prdouct Dimension Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*7wHEZmac9y7SORv0gM3TfQ.png" /></figure><p>Our Product Dimension is ready as well. We didin’t have a Unit Price for each product. I have created it with the sales, quantity and discount price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*-rBclRUGpMihClKUyY4kTw.png" /></figure><p>This is my function or code for that. It is a bit long, I think. There must be a quick version of doing the same task but this is my solution anyway. At the end, this gave me the same unit Price even though that product is sold with a discount.</p><p>Finally, My Sales/Fact Tables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*Upm-YMDTM72Oi-L5-xqqkA.png" /></figure><p>This is how my file looks like right now. I have split my sale records with regard to year. This is going to be very helpful because when I receive the data from the 2018 year, the only thing I will do to add it to my folder, and my dashboard and data tables are going to be set up dynamically. That’s why we are using Power Pivot and Power Query actually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNqMWrFcxEzd05jH4BlBGg.png" /></figure><p>This is the example of the 2014-year sales dataset. Here we can see, I got Order ID which later I will use it to connect my Address table. I got the Customer ID column and Product ID column. They are my Foreign keys which are going to help me to connect with my dimension tables.</p><p>It is important to distinguish between foreign keys and primary keys. The primary key is unique and the Foreign key doesn’t have to be unique in one dataset. We generally see Primary key in Date/Fact datasets and Foreign keys in Dimension datasets.</p><h4>Now our datasets are ready to go to Power Query.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1huybOZktf5kWwfXWqM2A.png" /></figure><p>I am connecting my data into Power query and I will make some transformations to my datasets and this is going to be dynamic which means I won’t spend time when I got upcoming data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izSOtpChGWR1aTHuZ6k0Rg.png" /></figure><p>Here I am in my power query section. I will make some changes here and get back to Power Pivot and ready to implement my dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPUHpENXyIz8AV8F5Lz_Jg.png" /></figure><p>I have added 4 columns and did a few cleaning. The beauty of this Power Query is that when I later add data into my file, the steps you see on the right are going to be implemented automatically which is awesome !! Now we should make the connection with Power Pivot.</p><h4>Power Pivot</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yG8kXt9Gp5Xe85N9Nfaw6Q.png" /></figure><p>On the left-bottom, we can see my tables. Sales Datasets came here directly from Power Query and Other dimension tables, I have added manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xviu7pOXoTKPXKpD3KOznA.png" /></figure><p>Here we are going to make our connections. One of the beauties of Power Pivot is that we can work with multiple tables like this as long as we make the correct connections. Here, with the red rectangle, I have indicated my <strong>Primary key</strong> for my dimension tables and with the green one, I have indicated my <strong>Foreign key </strong>for Sale (aka Fact) dataset. Here we can see <strong>1 to *( many ) </strong>relations ( I have tried to show with arrows) which is exactly what we want.</p><p>Now we are ready to go for answering questions because we have set our workspace.</p><h4>Business Questions</h4><ol><li>Do we have a positive sales trend in time?</li><li>Which category or subcategory is sold out more?</li><li>Is there any specific category that is sold in a specific region or area?</li><li>What is our average shipping day by ship mode and area? Is there any specific region where our orders get delayed?</li><li>Who are our 5 top customers in terms of sales?</li><li>Is there any time that our products are sold more (specific time interval for example in summer seasons we might be selling more and this might be because of the fact that our some specific summer products are selling more in summer and that contributes our overall sale. We might find something interesting there)</li><li>Is there any trend that shows more orderes and sales in region where the average days to ship is low and vice versa? From here, we might conclude that our customers really care about the days to ship more than anything and we might concentrate on that issue in later time.</li><li>We might look at our top 5 products in terms of sales, quantity or profit margin.</li></ol><p>That’s all for business questions but there are a lot of things that can be potentially discovered along the way. Let’s work on it !!</p><p>andddddddddd drum roll, please !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkbMvNM9mOSaklXzXQmVBQ.png" /></figure><p>Ta daaa :) It was a lot work but worth it. It is finally ready for use. I won’t get deep into business questions but let’s get over one of them. We got a lot of slicers in this dashboard. We can take a look at specific state or a few of them and specific category. Let’s analyze the Florida — Georgia — California — Texas and Newyork in Furniture and Technology Category and see what can be discovered from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPOO2SnpgO2Xm2dKF2STtA.png" /></figure><p>This is what we got, we can see our top products and customers. The peak in the Sales Trend according to Customer type. In California, we got most Sales even though there relatively we got more average days to ship rate. Georgia is both the least sale and the most average days to ship rate which might be an indicator for the reason behind the least sales. Phones and Chairs are two things that brought the most sales to the company. In this scenario, Tables is a subcategory maybe we need to investigate because apparently it is a subcategory we don’t profit. Maybe after seeing this, we might want to take action on that. This is all for this Excel Work.</p><p><a href="https://drive.google.com/drive/folders/1kpP_cP2snM8OpcKCUGhXdCI69OGDrLst?usp=sharing">Excel Dashboard Sales - Google Drive</a></p><p>Here you can find my work and I can’t wait for your suggestions and comments on my work.</p><p>I do want to shout out to <a href="https://www.youtube.com/channel/UCiYjpuUaSfkvdZkmtDU7JRw">MyOnlineTrainingHub</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTK0CJBaqvnY%3Flist%3DPLmd91OWgLVSLy87GfZCR74BG1nhO7ER0s&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTK0CJBaqvnY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTK0CJBaqvnY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cc9e27e3dbd795e4365795361ba0c1c/href">https://medium.com/media/0cc9e27e3dbd795e4365795361ba0c1c/href</a></iframe><p>Especially from this video, I learnt a lot and inspired while doing this dashboard.</p><p>I got the dataset on <a href="https://www.kaggle.com/datasets/vivek468/superstore-dataset-final">https://www.kaggle.com/datasets/vivek468/superstore-dataset-final</a> and it is education purpose dataset.</p><p>That’s all for now. Keep creating, Keep working and Keep fighting !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f80f83dc44d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>