<?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 Luca Petriconi on Medium]]></title>
        <description><![CDATA[Stories by Luca Petriconi on Medium]]></description>
        <link>https://medium.com/@lucapetriconi?source=rss-fd256d0457bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TN0_Qyx2l45oKWGdE9jezA.jpeg</url>
            <title>Stories by Luca Petriconi on Medium</title>
            <link>https://medium.com/@lucapetriconi?source=rss-fd256d0457bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:34:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucapetriconi/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[Bullet-Proofing My Success in 2023 - My Goal-Setting Framework (That You Can Use, Too)]]></title>
            <link>https://medium.com/@lucapetriconi/bullet-proofing-my-success-in-2023-my-goal-setting-framework-that-you-can-use-too-4559aaf8e3ab?source=rss-fd256d0457bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/4559aaf8e3ab</guid>
            <category><![CDATA[goal-setting]]></category>
            <category><![CDATA[improvement]]></category>
            <category><![CDATA[goals]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[work-life-balance]]></category>
            <dc:creator><![CDATA[Luca Petriconi]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 20:30:28 GMT</pubDate>
            <atom:updated>2022-12-22T20:33:00.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RwQj7Mj7U3cPgxo8wVGew.png" /></figure><p>Ihave always had trouble setting goals. Not because I was lazy (maybe a bit), but because I didn’t <em>know</em> how to set goals. What is a meaningful goal anyway? It’s a highly personal question and there’s no one size fits all.</p><p>Contrary to me, everyone around me always seemed to have a very clear idea of their goals, of what they wanted to do in life. My parents didn’t give me that path to follow.</p><p><em>Great! I can do whatever I want.</em> Turns out that choosing from all possibilities is more overwhelming and hard than it seems — especially when you’re young. You don’t have a clue, let’s be honest.</p><p>I’ve made a mistake. I saw goal setting as something static when actually it’s a dynamic, ever-evolving process. You draw a line in the sand to start with and adjust. Then you do it again, and again.</p><h3><strong>Why sitting down on January 1st won’t help you with your goal-setting</strong></h3><p>Achieving goals is not (only) about setting them. It’s also about building a system to achieve them.</p><p>James Clear, the author of <em>Atomic Habits,</em> puts it like this:</p><blockquote>Goals are about the results you want to achieve. <a href="https://jamesclear.com/goals-systems">Systems</a> are about the processes that lead to those results.</blockquote><blockquote>If you’re having trouble changing your habits, the problem isn’t you. The problem is your system. Bad habits repeat themselves again and again not because you don’t want to change, but because you have the wrong system for change.</blockquote><blockquote>You do not rise to the level of your goals. You fall to the level of your systems.</blockquote><p>I think of it this way: A goal is my marker on a map. It’s where I want to be within a given time horizon. It’s the better me. It’s the post-goal me.</p><p>But there’s no point in setting the marker on a map when I have no means of getting there.</p><h4>This Is Where Systems Come Into Play</h4><p>The system — I think of it as my means of transportation — can make or break the entire trip. Not choosing it correctly means getting lost or not reaching my destination.</p><p>Imagine having to travel to another country or even continent. There are a couple of different ways to approach this:</p><p>Walking there would be inefficient. You’re not going to get there very quickly or without a lot of effort (assuming you want to get there as fast as possible). The system doesn’t match the goals.</p><p>Riding a horse might require less effort and you might be there quicker. Is it the best way to reach your destination though? Hardly.</p><p>Taking a plane is your best bet. That’s the vehicle of choice here.</p><p>Now, does a plane make sense if you want to get to a nearby city? Of course not. That’s why your system depends on your goal.</p><h3>How Iteration and Data Help You Improve Upon Your Results</h3><p>In the travel analogy, the question of which system to choose, i.e. the vehicle it takes, seems straightforward. This probably won’t be the case for your goal-setting system. Simply because there are infinitely more variables to consider.</p><p>Basically, the idea is to find the systems that have the highest correlation with achieving your goal. Do we know these beforehand? Of course not. Otherwise, we wouldn’t make errors.</p><p>But guess what? After the first iteration of trying out your system, you’ll be able to improve upon it. The data you collect during your first iteration helps you to do so. More on that later.</p><h4><strong>Start by drawing a line in the sand</strong></h4><p>When deciding on a goal and a system, it’s important to choose a metric. Better even, choose <em>the one metric that matters </em>(OMTM). This concept comes from the startup world and is defined as:</p><blockquote>The OMTM is the one number you’re completely focused on above everything else for your current stage.</blockquote><blockquote><em>from</em> Lean Analytics Use Data to Build a Better Startup Faster</blockquote><p>By having one metric to focus on, it’ll be easier to start out defining the success of your goal-setting machine. After a while, that line adapts. Remember, in the beginning, you don’t know how to define your success. You’re chasing a moving target. This means that your metric and approach (and even your goal) will change after a while.</p><h3>How Having a Clear Goal Can Help You Avoid Being “Falsely Productive”</h3><p>For me, there’s an almost infinite number of things I want to learn. Whether professionally, or personally. I like to learn new things. However, the older I got, the more I realized that, unfortunately, there’s not enough time for everything. You need to prioritize.</p><blockquote>While you can have virtually anything you want, you can’t have everything you want.</blockquote><blockquote><em>Ray Dalio, legendary investor,</em> <em>in his book</em> Principles</blockquote><p>While prioritization is important, there are a lot of things that trick you into believing you’re being productive. When actually, you’re just being busy.</p><p>Avoid being busy. Start being productive. Okay, but how?</p><p>Having a clear understanding of your goals, helps align your actions toward achieving your goals. When you understand your goals, you’re actively searching out those activities that lead to the maximum yield.</p><h3>Future-Proofing My Next Year — Here’s How I Do It</h3><p>I start by drawing a line in the sand. I pick goals that build on my previous experience and skill set. This doesn’t mean that you can’t learn new skills. In fact, I think it’s essential to achieving your goals. What I mean by that is that I pick a new skill or goal that I can relate to because of my previous experience or existing skills. That makes it a lot easier for me to assimilate the new information and create a meaningful context.</p><p>I quantify my goals (or make them binary, i.e., success/failure, done/not done, etc.). This helps me assess my own performance and allows me to adjust. Did I reach 30% of my goal? Okay, maybe I need to rethink my tactics. Did I reach 70% of my goal after adjusting? Great, that means I’ve learned and improved. When you’re starting out, it’s hard to set the bar. But I try to keep this in mind:</p><p><em>In 2008, Google set out to make Chrome the №1 browser on the internet. Sundai Pichai, Google’s CEO, set the ambitious goal of reaching 20 Million users by the end of 2008. By the end of the year, he missed his goal. He upped it to 50 Million users in 2009 but was shy of 12 Million by the end of 2009. In 2010, however, he set his bar even higher and surpassed it. He was able to apply his learnings from the two previous years and adjust Google’s strategy accordingly.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*-cUvkRVdVWOrJ0RZ7kBlLQ.png" /></figure><p>The important takeaway here is that you shouldn’t limit yourself to what you already <em>know</em> you can achieve. A principle Ray Dalio uses is “remember that great expectations create great capabilities”.</p><p>I define a set of tactics. As I’ve previously said, a goal is only the start. You need to know how to get there. This is especially important if you want to improve iteration upon iteration. Set out a path that you want to follow. This might not be the most straightforward path but you’ll learn to adjust. For me, it helps to make this tactic part of my regular routine. Not necessarily daily, but I don’t want to miss two days in a row.</p><p>I set an (unrealistic) time frame. Okay, setting a deadline might be a no-brainer. But here’s why setting unrealistic time frames actually help. <br> <br>Cyril Parkinson observed a phenomenon that would later be known as <a href="https://www.economist.com/news/1955/11/19/parkinsons-law"><em>Parkinson’s Law</em></a><em>.</em></p><p>It declares that <em>work expands so as to fill the time available for its completion</em>. In other words, the more time you have, the longer it’ll take you to get it done. Having a somewhat shorter time frame helps you focus on what’s really important. In design, for example, there’s an infinity of things you might want to modify or add. But does it really help with the user experience? Probably not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*8tplSZeUJDZ31wZYdaeomA.png" /></figure><p>I get started. Goals are only so good. The magic happens when you start doing the work. Someday becomes never and you’ll see your dreams fading away on the horizon.</p><blockquote>Action may not always bring happiness, but there is no happiness without action. <br><em>Benjamin Disraeli, former British Prime Minister</em></blockquote><h3>There’s No Magic To It</h3><p>Even with the greatest goal-setting framework, the work still needs to be done.</p><p>For me, goal-setting, especially writing down and examining my goals, helps me to better understand my goals.</p><p>This in turn allows me to build tactics, measurements, and a fundament for approaching and reaching my goals.</p><h4><strong>Want to connect?</strong></h4><p>You can find me on <a href="https://www.linkedin.com/in/lucapetriconi/">LinkedIn</a> and <a href="https://twitter.com/lumarrcelo">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4559aaf8e3ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google is done. Here’s why OpenAI’s ChatGPT Will Be a Game Changer.]]></title>
            <link>https://medium.com/@lucapetriconi/google-is-done-heres-why-openai-s-chatgpt-will-be-a-game-changer-98ae591ad747?source=rss-fd256d0457bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ae591ad747</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Luca Petriconi]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 20:03:16 GMT</pubDate>
            <atom:updated>2022-12-15T09:33:34.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Geck9JHWGWwsZaSlAdEZRA.png" /><figcaption>Why ChatGPT will be a game changer</figcaption></figure><h3><em>Google is done. Here’s why OpenAI’s ChatGPT Will Be a Game Changer</em></h3><h4><em>Only a day after its release, the internet is already flooded with content about OpenAI’s latest tool. Let’s dive into why it’s gonna be a game changer, shall we?</em></h4><p>Yesterday, on November 30, Sam Altman <a href="https://twitter.com/sama/status/1598038815599661056">announces the launch of ChatGPT</a>. Since then it has taken the internet by storm. And not without a reason. As you will see, this new AI could be a complete game changer.</p><p>The model is fine-tuned model based on the <a href="https://beta.openai.com/docs/model-index-for-researchers">GPT-3.5 architecture</a> and interacts in a conversational way — just like a chatbot. The model was trained using Reinforcement Learning from Human Feedback (RLHF). In addition, the guys at OpenAI used supervised fine-tuning to improve the model. There’s a big difference though:</p><p>Not only does it emulate different styles (see below), but <em>it also remembers what you as a user have told it before </em>and can retell you.</p><h3>Why This Could Mean the End Of Google</h3><p>… or Stackoverflow.</p><p>We live in what feels like rapidly evolving times (even though Peter Thiel might disagree). There are new AI tools coming out on a fairly regular basis now. With the rise of general adversarial networks, or GANs, and generative AI tools like <a href="https://openai.com/dall-e-2/">Dall-E</a> or <a href="https://huggingface.co/spaces/stabilityai/stable-diffusion">Stablediffusion</a>, we’ve seen a couple of mindblowing things. Being able to create an image from a mere text input almost feels normal now because we grow increasingly used to these kinds of things.</p><p>Here’s why ChatGPT is different, though.</p><h3>Chris Frantz on Twitter: &quot;The new chatbot from OpenAI is actually insaneReplaced Google for work todayNow it&#39;s giving great advice on games to play with my toddler tonightI could see not needing to use Google again 💀 / Twitter&quot;</h3><p>The new chatbot from OpenAI is actually insaneReplaced Google for work todayNow it&#39;s giving great advice on games to play with my toddler tonightI could see not needing to use Google again 💀</p><p>The way you interact with the ChatGPT feels different because you speak to it directly as if it were another person. There’s an exchange going on. A back-and-forth. Almost as if you were talking to a person. In fact, it makes you <a href="https://analyticsindiamag.com/chatgpt-openais-new-chatbot-takes-internet-by-storm/">second-guess if you’re talking to a person or an AI</a>.</p><p>There’s one more aspect that makes it feel different: <em>It remembers what you&#39;ve previously said</em>. This means you can iteratively work towards the desired result. In other words, you’re having a conversation.</p><p>Sam (@sama), OpenAI’s CEO, puts it like this in one of his tweets:</p><blockquote>“language interfaces are going to be a big deal, i think. talk to the computer (voice or text) and get what you want, for increasingly complex definitions of “want”! this is an early demo of what’s possible (still a lot of limitations — it’s very much a research release).”</blockquote><p>He adds that this interface seems plausible not only for this type of application but also for a future, more complex application. And if you think about it, it makes sense: Conversing is the natural way for humans to interact with one another and convey their thoughts. Or is it thinking? (I’m saying this at a moment in time when Elon Musk claims <a href="https://www.theverge.com/2022/11/30/23487307/neuralink-elon-musk-show-and-tell-2022">Neuralink is “six months” away from its first human trial</a>.)</p><p>Let’s stick with conversing for now. Let’s say you want to write an article on a given topic. For example, you could ask it to write it for you. Depending on the output, you might want to refine and modify it. That’s exactly what Twitter user @goodside did:</p><h3>Riley Goodside on Twitter: &quot;Using OpenAI&#39;s new ChatGPT to write a tutorial blog post on plotting with Pandas/Matplotlib, section-by-section, with conversational feedback. (1/3) pic.twitter.com/RxL61OI3H2 / Twitter&quot;</h3><p>Using OpenAI&#39;s new ChatGPT to write a tutorial blog post on plotting with Pandas/Matplotlib, section-by-section, with conversational feedback. (1/3) pic.twitter.com/RxL61OI3H2</p><h3>Yes, It Writes Code, too</h3><p>There’s been recent hype (or worry?) around AI-assisted coding tools like <a href="https://github.com/features/copilot">GitHub Copilot</a>. But with the amount of detail in the output of ChatGPT, the fact that it writes code, too, almost seems like a side-effect.</p><p>It’s impressive to see that it combines text and code — with formatting and commenting and all — in its output.</p><h3>Guillaume Verdon on Twitter: &quot;GPTchat can build quantum-classical neural nets 🤯🤖⚛️It&#39;s so over...😳 pic.twitter.com/le75nHXU0F / Twitter&quot;</h3><p>GPTchat can build quantum-classical neural nets 🤯🤖⚛️It&#39;s so over...😳 pic.twitter.com/le75nHXU0F</p><p>What amazes me most is one fact: It doesn’t only output the code but it also explains it. For example, imagine you&#39;re debugging and giving it code as input while asking it to find the bug. The output could look something like this:</p><h3>Amjad Masad ⠕ on Twitter: &quot;ChatGPT could be a good debugging companion; it not only explains the bug but fixes it and explain the fix 🤯 pic.twitter.com/5x9n66pVqj / Twitter&quot;</h3><p>ChatGPT could be a good debugging companion; it not only explains the bug but fixes it and explain the fix 🤯 pic.twitter.com/5x9n66pVqj</p><p>While seeing this you can easily think: “Why still search StackOverflow?”. And you’re right. How many times have you searched for a very specific question on StackOverflow and you didn&#39;t find an answer? And most importantly how much time did you spend finding it (if you did)? There are a few things to keep in mind though — for now.</p><h3>Not so Fast…</h3><p>While I don’t question that this is one of the most impressive things I’ve recently seen, it won’t mean the end of Google (just yet).</p><p>Of course, there are a few limitations to ChatGPT.</p><ul><li>For example, it won’t tell you about anything in the recent past (in 2022), since it’s been trained on data reaching back until Q4 of 2021.</li><li>It sometimes outputs plausible-sounding but incorrect answers, which is a challenging issue to fix according to OpenAI.</li><li>It can be excessively verbose and overuse certain phrases.</li><li>As far as content moderation goes, the model was trained to refuse to output inappropriate content. However, there might be some false positives and negatives.</li></ul><p>While the model will be improved upon iteratively, this is already quite impressive. What I find the most impressive is the ease to interact with it and the seeming accuracy of the outputs.</p><p>The model is open to playing around with, <a href="https://chat.openai.com/chat">here</a>. Let me tell you in the comments below what you asked and what your thoughts about it are.</p><p>For more on data-related topics and fun tech stuff, you can find me on <a href="https://twitter.com/luca_marcello">Twitter</a> and <a href="https://www.linkedin.com/in/lucapetriconi/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ae591ad747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Lake vs Data Warehouse — Key Differences, and When to Use Which]]></title>
            <link>https://medium.com/@lucapetriconi/data-lake-vs-data-warehouse-key-differences-and-when-to-use-which-9adbeb484696?source=rss-fd256d0457bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9adbeb484696</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Luca Petriconi]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 19:11:08 GMT</pubDate>
            <atom:updated>2022-10-23T19:11:08.155Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Lake vs Data Warehouse — Key Differences, and When to Use Which</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsLSzLAEL6NsJg-bVj-Vtw.png" /></figure><p>If you’re reading this article, chances are, you are familiar with the term <em>Big Data — </em>basically, huge amounts of data that are being generated by increasingly interconnected and “smart” devices. Well, data is what fuels these things: Without data, there’s no need for data analytics or data science. Few people though, know where the data actually comes from and where it is stored. Let us have a closer look.</p><h3>First Off: What Data Types Are There (And Why Does It Matter)?</h3><p>To understand why you would choose a data lake over a data warehouse, let us have a look at what types of data there are and where you can store them:</p><p><em>Structured (or “cleaned”) data</em> is your classic spreadsheet data: Everything is nice and clean (not to say there can’t be missing data or wrong formatting), and the data is organized in a table-like structure. Databases that store this type of data are called relational databases — we use SQL to manage the data in those databases. Examples of structured data are .csv or Excel files.</p><p><em>Semi-structured data</em>, as the name suggests, incorporate some elements of structured data, although they’re not organized in a tabular structure. They do, however, contain tags and elements to organize the data in a meaningful way and build hierarchies. Databases that store semi-structured data are called non-relational databases — like <a href="https://www.mongodb.com/">MongoDB</a>.</p><p><em>Unstructured data</em>, which is most of the data in the world, is raw data that doesn’t follow any schema whatsoever. They’re the richest in information but must be cleaned in most cases to make them meaningful. Examples of unstructured data are video and audio files, as well as photos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f-9qzer9tiZsIRsM" /><figcaption>Photo by <a href="https://unsplash.com/@chiclaudia?utm_source=medium&amp;utm_medium=referral">Claudia Chiavazza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Is a Data Lake?</h3><p>A data lake is a centralized data storage that can handle large amounts of structured, semi-structured, and unstructured data in its raw format. A data lake does not have any limitations regarding the account or file size and allows storing data without having to process the data first. This is incredibly convenient for companies that generate vast amounts of data as it gives them much more flexibility.</p><p><strong><em>Key Learnings:</em></strong></p><ul><li>A data lake is a centralized repository where large amounts of data can be stored</li><li>It handles structured, semi-structured, and unstructured data</li><li>Data lakes provide both flexibility and scalability and simplify data management</li><li>A data lake can be established locally or can be based in the cloud (more on that later)</li></ul><h4>Which Data Is Stored in a Data Lake?</h4><p>A data lake does not restrict a company from storing any specific kind of data, as is the case with relational databases, for example. It is a repository that is scalable and flexible, as it allows a company to store structured, semi-structured, and unstructured data. This means you can store anything from table-like data to videos, or PDFs in one place in a cost-effective manner.</p><h4>Why Do You Need a Data Lake? — The Purpose of a Data Lake</h4><ul><li>We’ve already touched on one of the main advantages of data lakes: Their flexibility. Data lakes allow you to store incredibly large amounts of data without the need to process the data first or structure them.</li><li>A data lake also puts no limit on the timeline: It keeps all the data. Not only the ones for immediate use but also for those that might be used at some point in the future.</li><li>As data lakes don’t restrict you to a certain data structure, companies have more data they can work with, which in turn can lead to better decision-making. With many advanced data analytics methods like machine learning and deep learning, companies can leverage the data and train more sophisticated models.</li><li>Data lakes are a cost-effective way to store large amounts of data, as they reduce preprocessing times that are necessary with other types of storage like data warehouses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*86dyo3nRfFPA49_s" /><figcaption>Photo by <a href="https://unsplash.com/@nananadolgo?utm_source=medium&amp;utm_medium=referral">Nana Smirnova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Is a Data Warehouse?</h3><p>A data warehouse is a data storage for structured data. The data that is stored in a data warehouse has to fit a tabular schema that has to be pre-defined. This process is called <a href="https://www.techopedia.com/definition/30899/schema-on-write">Schema-on-Write</a> and it lays the foundation for any future data ingestion. This means the data engineer needs to define what the table will look like, what an example/row means, and what the attributes/columns are supposed to represent.</p><p><strong><em>Key Learnings:</em></strong></p><ul><li>A data warehouse is a repository for structured data</li><li>It follows a tabular structure that has to be pre-defined in a process called Schema-on-Write</li><li>In the simplest form, a data warehouse is a SQL database with at least one dataset</li><li>Data warehouses are less flexible in storing data, but can readily be used to analyze the data helping analysts to drive insights much faster</li><li>A data warehouse offers high robustness and relatively low maintenance, as little to no data prep is necessary to work with the data</li></ul><h4>What Are the Characteristics of a Data Warehouse?</h4><ol><li>Data warehouses are <em>subject-oriented.</em> This means they focus on a specific theme rather than on a company’s current operations. These themes can be thought of as departments or business units, like marketing, supply chain, or inventories.</li><li>The data that is stored in data warehouses are often stored with associated times which helps to analyze historical data trends.</li><li>Data warehouses are said to be <em>non-volatile</em>. This means historical data persists and can be used for analytics and retrospective comparisons.</li><li>A data warehouse is <em>integrated</em>: It consolidates different data sources under one platform while maintaining uniformity and the standards that are set for the warehouse.</li></ol><h4>Why Do You need a Data Warehouse?</h4><ul><li>First and foremost, many companies nowadays, deal with vast amounts of data. To be able to efficiently store, process, and analyze this data has become indispensable for businesses in order to stay competitive. A data warehouse provides a central repository for structured data that can be easily accessed and analyzed through BI tools.</li><li>A data warehouse can be seen as a single source of truth as it can handle all the (structured) data within an enterprise, consolidating datasets from different sources.</li><li>Because of the characteristics of a data warehouse, it can help prevent data quality issues and inconsistencies, and create stability in data analysis and reporting.</li><li>Cloud-based data warehouses like <a href="https://cloud.google.com/bigquery">Google BigQuery</a> or <a href="https://azure.microsoft.com/en-us/">Microsoft Azure</a> can be especially cost-effective solutions for data storage, as they allow companies to scale flexibly according to their storage needs.</li></ul><h4>What Are the Types of Data Warehouses?</h4><p>Generally, we can distinguish three different types of data warehouses:</p><ul><li><strong>Enterprise Data Warehouses (EDW)</strong><br>As we have previously said, a data warehouse can consolidate an organization’s data in one place in order to run analyses it. That’s exactly what an EDW does: All data that a company store is held here and it provides the possibility to extract and process it.</li><li><strong>Operational Data Store</strong><br>As the name suggests, this type of data warehouse is especially useful for operational, i.e., day-to-day data that needs to be up to date in real-time, e.g., employee data. It is used when no other alternative like Online Transactional Processing can be used.</li><li><strong>Data Mart </strong><br>A data mart can be considered a subset of the data warehouse, representing a given business unit or line. For example, marketing, finance, or product development.</li></ul><p>It’s worth mentioning that we can also distinguish between <em>local </em>and <em>cloud-based </em>data warehouses. Traditionally, companies invested in large server rooms with tons of hardware to store their data. This provides the ability to store the data locally and provides a certain sense of independence and safety. However, on-premises data warehouses require large investments upfront, they take up space and need higher maintenance. Another issue is that they are relatively rigid in their scalability.</p><p>Cloud data warehouses can provide a cost-effective alternative for companies that need to operate flexibly as they provide a distributed service to store and manage data. Cloud data warehouses are especially useful for companies that need to scale as they provide the ability to just add storage on-demand to the data warehouse. Examples of these types of data warehouses are <a href="https://cloud.google.com/bigquery/">Google BigQuery</a> and <a href="https://aws.amazon.com/redshift/">Amazon Redshift</a>.</p><h3>Data Lake vs Data Warehouse — Differences and Similarities</h3><p>Generally speaking, you can imagine a data warehouse as an excel table and a data lake as mass storage like a USB stick. But let’s have a closer look at some of the differences and similarities:</p><h4>Data Types</h4><p>A data lake contains unstructured data. This means there are no restrictions on what can be stored. Everything from images, datasets, or audio files goes. This means users are also not limited by any imposed structure of a data lake.</p><p>A data warehouse imposes a structure (columns and rows) that needs to be followed. As a result, we cannot simply store every data we want. The data needs to follow the “rules”/structure of the data warehouse.</p><h4>Data Preparation</h4><p>Data lakes require little to no preparation as they accept any type of data without restrictions. This also means that in order to analyze the data, we need to do quite some processing first.</p><p>In data warehouses, the input data requires more preparation to match the existing schema. However, after the data has been stored, the data is readily available for analysis</p><h4>Flexibility</h4><p>A data lake provides high flexibility and scalability.</p><p>A data warehouse is less flexible for new data sources because of its rigid structure.</p><h4>Maintenance</h4><p>Data lakes require high maintenance and data management to avoid turning into a data swamp.</p><p>Data warehouses require low maintenance and high robustness due to their structure.</p><h4>Structure</h4><p>For data lakes, there is Schema-on-Read: The structure is set <em>after</em> the data is ingested. On the one hand, this increases flexibility, on the other hand, it requires more maintenance.</p><p>For data warehouses, there is Schema-on-Write: The schema or structure is defined <em>before</em> the data is stored. This increases processing times first, but once complete provides more robustness and consistency.</p><h4>Users</h4><p>Data lakes are harder to navigate, the data is more complex to process, and analysis cannot readily be deployed. The users generally are Data Scientists, Machine Learning Engineers, or Data Analysts.</p><p>Because of their relative simplicity and structure, data warehouses can be more easily managed, and the data more readily analyzed. Data warehouses are apt for business analysts and KPI reporting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iA98_n-6RE4ETVNQFumx9g.jpeg" /></figure><h3>When to Use a Data Warehouse or Data Lake?</h3><p>Data Lakes offer a great deal of flexibility when it comes to storing different types of data. However, as we have seen, this comes at the expense of higher maintenance, higher preprocessing, and more complex navigation.</p><p>Data warehouses, on the other hand, are a little bit more rigid, not as scalable as data lakes, and can be limiting regarding data sources. They do, however, serve as the “single source of truth” as they are more robust, reliable, and consistent.</p><h4>Is One Better Than the Other?</h4><p>As you can imagine, none is “better” than the other. They serve inherently different purposes. While one offers certain advantages, the other excels in different situations. Therefore, the decision to use a data lake or a data warehouse depends entirely upon your needs and upon your industry. Here’s an example:</p><h4>Choosing a Data Lake or Data Warehouse — Examples</h4><p>Imagine an organization that’s specialized in cancer research. They are likely to work with many different types of data. On the one hand, of course, there is structured recording keeping, but on the other hand, you could also easily imagine MRI scans, doctor’s notes, images, and maybe even audio. Implementing a data warehouse with a variety of data in this sector would probably not be very fruitful.</p><p>On the other hand, imagine a financial service provider. Financial data is characterized by its highly quantitative nature. As such, it can be fairly easily structured. In fact, adopting a structured approach to this type of setting allows for quicker analyses, less data maintenance, and higher confidence in those data. In this case, a data warehouse seems to be the more effective approach.</p><h3>Final Thoughts on Data Lakes and Data Warehouses</h3><p>We have distinguished both types of data storage and have seen that each of them provides its own set of benefits and drawbacks. While data lakes in general offer more flexibility and scalability, data warehouses provide robustness and confidence in data quality.</p><p>As you can see, there is a bit of a trade-off going on between the two: Of course, does more flexibility offer less structure? What a data lake offers, is impossible to achieve with a data warehouse, and vice-versa.</p><h4>There Is One Question Left</h4><p><em>Can a data lake be stored in a data warehouse or can we store a data warehouse in a data lake?</em></p><p>I really hope that after reading this article, you can answer this question (because otherwise, I have done a miserable job 😂). <em>Hint: </em>We can do only one of the two. Leave your answer in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9adbeb484696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dashboard Design — How to Make Better Dashboards for Data Analysis and Data Science]]></title>
            <link>https://medium.com/@lucapetriconi/dashboard-design-how-to-make-better-dashboards-for-data-analysis-and-data-science-5f62a8610f10?source=rss-fd256d0457bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f62a8610f10</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[dashboard-design]]></category>
            <dc:creator><![CDATA[Luca Petriconi]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 19:14:54 GMT</pubDate>
            <atom:updated>2022-10-23T19:16:23.379Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dashboard Design — How to Make Better Dashboards for Data Analysis and Data Science</h3><p><em>Dashboards play a fundamental role in many businesses, nowadays. The ability to collect and analyze user data has transformed the way companies understand customer behavior and provide better value propositions. Too often, the way the data is presented fails to communicate information effectively though. Let’s fix that!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ENMAAKTy1UFxK6rgwODNQ.png" /></figure><h3>What Is a Dashboard? — First Things First</h3><p>At the most fundamental level, a dashboard is a screen that contains relevant data about a specific purpose. It gives insights into a business’s performance by displaying KPIs, metrics, and data points. A dashboard is often used to evaluate those data to optimize a business, a business unit, or a channel and plan ahead.</p><blockquote>A dashboard is a visual display of the most important information needed to achieve one or more objectives; consolidated and arranged on a single screen so the information can be monitored at a glance.</blockquote><blockquote><em>Stephen Few, </em>Rich Data Poor Data</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAQkQGDkxLv_FVXnx8c8RQ.jpeg" /><figcaption>A car dashboard only shows essential information</figcaption></figure><h4>Did You Know Where Dashboards Got Their Name From?</h4><p>The dashboard inherits its name from automobile dashboards, which provide the driver with all the necessary information that is needed to drive the car safely. It also serves as an analogy to what must be shown on a dashboard. Think about it: We don’t need a car dashboard to display unnecessary details like the wind direction, air pressure, or news. As a matter of fact, this would actually be counterproductive.</p><h3>What Should Be Shown in a Dashboard?</h3><p>Dashboards should be able to summarize relevant data to help decision-makers make more informed decisions. This does <em>not</em> mean stuffing the dashboard with as much data as you can. It means quite the opposite: Cut out unnecessary data that doesn’t help with the decision-making process.</p><blockquote>Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.</blockquote><blockquote><em>Antoine de Saint-Exupery</em></blockquote><p><em>Before</em> designing your dashboard, you should be aware of what are you trying to achieve with the dashboard. In addition, you should define the scope of your dashboard. In most businesses or departments, it won’t help you collect all the data points at your hands and throw them onto your dashboard. Therefore, you have to decide whether you want the dashboard to focus on high-level, aggregate data, or on more granular, low-level data. It goes without saying, that the goal complements the scope and vice-versa.</p><p>The most important aspect of a dashboard is that it should answer your questions and monitor whatever you want to measure — all within the range of the eye.</p><h3>Dashboard vs. Report — Some Important Differences</h3><p>Often, you’ll see the terms dashboard and report used interchangeably but they’re something different. It’s important to know their difference if you want to effectively communicate with your stakeholders and co-workers.</p><ol><li><strong>Reports are static, and dashboards are interactive and can be live.<br></strong> Reports contain static data in the form of text or tabular data. Modern dashboards are often interactive which means they either provide live data or you can adjust the dashboard to show specific data. For example, a specific date range or data filters.</li><li><strong>Reports are longer and more detailed than dashboards. <br></strong>Reports contain more information. Not only regarding the amount of detail but also visually. Think of the dashboard as a screen where all data is fit. And a report as a scrollable document where several screens fit in. Or, as Stephen Few, a world leader in data visualization puts it: “My insistence that a dashboard should confine its display to a single screen with no need for scrolling or switching among multiple screens, might seem arbitrary and a bit finicky, but it is based on solid and practical rationale.”</li></ol><h3>What Are Common Dashboard Types?</h3><p>Even though a dashboard can reveal and contain a lot of information, in most cases, you’ll be better off creating multiple dashboards—each dashboard with a different design serving a different purpose and each one with its own goal in mind.</p><p>So, how can you leverage the data at your disposal to achieve your business goals? Create <em>different</em> <em>types</em> of dashboards! Let’s have a look at the three most common types of dashboards.</p><h4>Strategic Dashboards</h4><p>Strategic dashboards usually have a longer time horizon and are designed to help higher-level management make strategic long-term decisions. They will feature aggregate data that summarizes KPIs of a longer period, for example, a year or a quarter. As such they monitor performance metrics against company-wide, strategic goals and make sure that both are met. In contrast to analytical dashboards, which we’ll examine later, strategic dashboards often include historic data so that senior management can make sure performance benchmarks are met. The below dashboard by <a href="https://www.tableau.com/learn/articles/sales-dashboards-examples-and-templates">Tableau</a> features aggregate data giving a bird’s eye view of all the data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*rqZPWIlkxCentD9ZFgpDBg.png" /><figcaption>A strategic dashboard has a long time horizon and is usually used by senior management.</figcaption></figure><h4>Operational Dashboards</h4><p>These types of dashboards are used for daily use and in contrast to strategic dashboards, they feature real-time data to find out what is happening at a given moment. They allow the analyst to answer the question “what is happening right now?”. While strategic dashboards are mainly used for long-term decision-making and senior management, operational dashboards focus on a shorter time horizon and best fit with individual teams and their managers. Google Analytics 4 features a snapshot of what is happening right now. That’s exactly what operational dashboards are about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*7-Q1t-VsA2pe7ymHTUgMKw.png" /><figcaption>Operational dashboards help to see what is going on right now.</figcaption></figure><h4>Analytical Dashboards</h4><p>Used by data analysts and data scientists, analytical dashboards are used to make better decisions in the future and identify trends. They often feature pivot tables, drill downs, and include large amounts of data. Bi- or multivariate analyses are used to slice, restructure, and mine data to identify any performance correlations within the data. Analytical dashboards can improve decision-making within the entire company, but they do require a good understanding of the data and the technical ability to work with the data. The below can be a <a href="https://dribbble.com/shots/18597909-Universal-Data-Visualization-Bar-Chart-Horizontal">great example</a> of an analytical dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Z_vdz0oV6bkSyEsvmVfXRw.png" /><figcaption>Analytical dashboards require technical ability but can help identify trends.</figcaption></figure><h3>How to Design Your Dashboard Effectively</h3><h4>Writing Dashboard Requirements</h4><p>Most people I’ll talk to agree that the audience should come first when designing the dashboard. But when it comes to pinpointing and addressing user needs, most don’t have a clear idea of how to do that.</p><p>Gathering dashboard requirements helps in the design process and in making sure user needs are met. It essentially answers the question that arises from the above problem: “Who am I designing the dashboard for, what does the dashboard need to do, and what are my stakeholders trying to achieve with this dashboard?”. Without having a clear idea about this, your dashboard is probably not going to do its job.</p><h4>Dashboard Design: 7 Tips to Make Better Dashboards</h4><p><strong>1. Let stakeholder goals help design your dashboard</strong><br> This shouldn’t come as a surprise but is too often overlooked. I’ve seen many dashboards where it became clear afterward that the dashboard doesn’t meet stakeholders’ goals at all because they simply haven’t been considered. <br> <br>Having a good understanding of stakeholder goals can guide your dashboard design. It will give you an idea of what data to include (and more importantly which ones not to include), which metrics to choose from, and how to visualize your data.</p><p><strong>2. Start with a Question </strong><em><br> </em>What is your dashboard supposed to do? In most cases, you want to answer your or the stakeholder’s questions. <br> <br> By understanding your user’s needs, you will identify which are their most important questions. Instead of starting to design your dashboard with the idea of showing the most important data, start out by pinpointing the most important questions. The design of your dashboard will adapt to those questions and will end up doing a much better job of informing stakeholders.</p><p><strong>3. Consider Multidimensional Metrics<br></strong>When I design dashboards, I try to think in dimensions or you could also call it hierarchies. Ask yourself: Are my metrics of higher order, i.e., are they comprised of several other metrics, or are they of a lower order, meaning they cannot be broken down further? Considering the hierarchy of your metrics can give you a good understanding of how to present them in your dashboard.</p><p><strong>4. Keep in mind how your end user interacts with the dashboard</strong><em><br> </em>Many BI tools come with the ability to create dashboards and data visualizations that you can interact with. This is a crucial thing to think about when designing your dashboards. Is your end-user likely to need to filter data, or are you going to present the data in a way that there’s no need to filter? If your case is the former, you would want to think about which variables you want to filter.</p><p><strong>5. Focus on what’s relevant</strong><em><br> </em>With the number of features of modern BI tools, it’s easy to get carried away by technical frills. In most cases, you’ll be better off using the simpler version of the data point you’re trying to look at. Don’t make it too distracting to look at your dashboard. You can achieve this by increasing the <a href="https://infovis-wiki.net/wiki/Data-Ink_Ratio">data-ink ratio</a> — the proportion of the chart’s ink devoted to actually showing data-related information. Remember, your dashboard should inform stakeholders and not confuse them unnecessarily.</p><p><strong>6. Implement user feedback</strong><br> After designing your dashboard your job shouldn’t be done. Ask your end user for feedback or even observe her while she’s using the dashboard. This can give you valuable information about whether or not you’ve addressed user needs correctly. With the feedback, you receive iterate upon your initial design to keep improving your dashboard.</p><p><strong>7. Be consistent with your design</strong><em><br> </em>Let’s say you want to show the same set of metrics across different platforms. The safest way to do this is to display them with the same visualization and alignment. This makes it tremendously easier to digest the information on your dashboard. The same is true for colors: While it might be attention-grabbing to include a lot of color in your dashboard, less is definitely more. Also, consider the inherent logic of color, if you’re trying to display a map with temperatures, for example, it inherently makes more sense to display colder areas with cooler colors like blue and warmer areas with tones like orange and red.</p><h3>Wrap Up</h3><p>We’ve seen that there’s a lot more to designing a dashboard than simply dragging and dropping some graphs. <br> <br> Depending on what goal you’re trying to achieve and what end user you want to serve, you might select between an operational, analytical, and strategic dashboard. Moreover, you’ll want to start sketching your dashboard requirements, before starting out. This means having a clear idea of who you’re designing your dashboard for and what questions your dashboard should answer. Being consistent in your design and choosing simplicity over technical details will get you a long way in getting your dashboard out there.</p><p>For more on data-related topics and fun tech stuff, you can find me on <a href="https://twitter.com/luca_marcello">Twitter</a> and <a href="https://www.linkedin.com/in/lucapetriconi/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f62a8610f10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Do Twitter Sentiment Analysis with a Pre-Trained Language Model [Python]]]></title>
            <link>https://medium.com/@lucapetriconi/how-to-do-twitter-sentiment-analysis-with-a-pre-trained-language-model-87614635c40e?source=rss-fd256d0457bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/87614635c40e</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Luca Petriconi]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 19:42:23 GMT</pubDate>
            <atom:updated>2022-11-13T18:25:19.030Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to fine-tune a pre-trained language model in TensorFlow for a downstream task.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAVt5_LbQKLHq7lsaiHFEw.png" /><figcaption>Python sentiment analysis for a pre-trained language model</figcaption></figure><p>In this tutorial, we will be working with a dataset made up of Spanish tweets about COVID-19 vaccines. The data were collected in the Summer of 2021, just after the rollout of several of the COVID-19 vaccines.</p><p>The data can be downloaded from <a href="https://github.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis">here</a>.</p><h3>The Current State of NLP</h3><p>There have been two major forces driving the recent development in NLP:</p><p>Firstly, the introduction of the self-attention mechanism, in particular through the Transformers architecture. And, secondly, the leveraging of huge amounts of unlabelled data through unsupervised pre-training methods. Thus, the winning strategy has been to first pre-train a transformer-based model with vast amounts of <em>unlabelled</em> and, consequentially, fine-tune the model to make it perform better at a <em>specific</em> task. This second step is usually accomplished with <em>labeled</em> data — though much fewer learning examples are required in comparison to training the model from scratch.</p><p>Natural Language Processing (NLP) has a large variety of tasks and applications, including Automatic, or Machine Translation, Text Summarization, Text Generation, Text Classification, Question Answering, and Named Entity Recognition (NER). The ability to develop and improve these very different types of tasks have wide-reaching possibilities for developing NLP.</p><h3>Why Use Transformers and Not RNNs Or LSTMs?</h3><p><a href="https://en.wikipedia.org/wiki/Recurrent_neural_network"><em>Recurrent Neural Networks</em></a> (RNNs) got very popular in sequence modeling for supervised NLP tasks like classification and regression. Thanks to the <a href="https://en.wikipedia.org/wiki/Long_short-term_memory"><em>Long Short Term Memory</em></a> (LSTM) and <em>Gated Recurrent Unit</em> (GRU), the vanishing gradient problem got relieved which allowed the modeling of longer sequences. Yet, there are some problems associated with these models: Firstly, they are very hard to parallelize on multiple processes. Secondly, even though LSTM and GRU are great at minimizing the vanishing gradient problem, RNNs still have difficulties modeling <em>very</em> <em>long</em> sequences. With the introduction of Transformers which completely left out the recurrent unit, only relying on the attention mechanism, both problems, the parallelization issue and the vanishing gradient problem for longer sequences were solved.</p><h3>What Are Transformers in Machine Learning?</h3><p>While explaining the Transformers architecture in detail, would go beyond the scope of this article, I want to outline some conceptual features of Transformers and especially the process that’s relevant to using them.</p><figure><img alt="Transformers Architecture" src="https://cdn-images-1.medium.com/max/1024/0*_0BnXA50mIp1pi-o.png" /><figcaption>The Complete Transformers Architecture</figcaption></figure><h4><em>Unsupervised Pre-Training</em></h4><p>The Transformer is usually trained on a very large amount of data in an unsupervised, or, more precisely, semi-supervised way. When dealing with a language modeling task, this happens usually so that the model will get a general statistical understanding of a language. After pre-training, it can be fine-tuned for a downstream task. That means, it can be adapted, with a much smaller amount of data — labeled in this case — for a task that is more <em>specific, </em>like sentiment analysis.</p><h4>Attention Mechanism and Context-Free Embedding</h4><p>Transformers leave the recurrent unit completely out and solely rely on the <em>attention mechanism</em>. Through this, the model is able to capture long-term dependencies of texts — something crucial to correctly understanding a language. Contrary to RNNs, the learning also happens without any specific direction, i.e. it is non-sequential. This is also the reason we can apply parallelization when training Transformers. However, by using this non-sequential approach, the architecture understands which words are related to each other.</p><h3>Spanish Language Models</h3><p>Even though NLP as a discipline is rapidly growing, most of the efforts are concentrated on the English language. However, most of the world’s population are not native English speakers and there is a huge number of Spanish speakers in the world and on the internet.</p><p>Spanish has about <a href="https://english.elpais.com/elpais/2017/11/29/inenglish/1511950198_079424.html#:~:text=Over%20572%20million%20people%20speak,the%20Spanish%20government&#39;s%20Cervantes%20Institute.">580 million speakers in the world</a> and is the <a href="https://www.statista.com/statistics/262946/share-of-the-most-common-languages-on-the-internet/">third most common language on the internet</a>, with about 7,9% of users speaking Spanish. In addition to that, Spanish is the second most-used language on social media, according to the <a href="https://cvc.cervantes.es/lengua/espanol_lengua_viva/pdf/espanol_lengua_viva_2017.pdf">Centro Virtual Cervantes</a>.</p><p>This illustrates the importance of the active development of Spanish language models. Not only from a commercial point of view but also for educational purposes.</p><h3>How to Create Predictions With Transformers</h3><p>Before fine-tuning our own model, we will download the current state-of-the-art model, called beto-sentiment-analysis. Alternatively, the model can also be used as software, called <em>pysentimiento</em>. We will apply the model to the data we’ll be working with, and see how it performs…</p><h4>Instantiating the Model</h4><p>We will see, that our final classifier consists of two different components: the <em>AutoTokenizer </em>and the actual model.</p><p>The AutoTokenizer preprocesses the tweets. This means breaking them into smaller pieces and turning them into numbers to create tensors that can be fed into the model. The actual model which we will feed the preprocessed data, and which will produce our labels for classification. For the classification part, we will use the <em>TFAutoModelForSequenceClassification</em><strong> </strong>class that allows us to download the model we indicate. <strong>Remember, we cannot simply use <em>any </em>model, given our text is in Spanish.</strong></p><p>As mentioned earlier, the model we will be using is called <em>beto-sentiment-analysis</em>. It is based on the BETO model, which is essentially a Spanish version of the original BERT model but pre-trained exclusively on Spanish data.</p><pre>from transformers import AutoTokenizer, TFAutoModelForSequenceClassification</pre><pre># Instantiate Huggingface models<br>model_name = &#39;finiteautomata/beto-sentiment-analysis&#39;</pre><pre>model = TFAutoModelForSequenceClassification.from_pretrained(model_name, from_pt=True, num_labels=3) <br>#from_pt=True, because this model only exists in PyTorch</pre><pre>tokenizer = AutoTokenizer.from_pretrained(model_name)</pre><pre># Combining tokenizer and model into one classifier<br>classifier = pipeline(&#39;sentiment-analysis&#39;, model=model, tokenizer=tokenizer)</pre><h4>Loading the Data</h4><p>In the following, we will first store the data in a data frame. After that, we will create the predictions/labels for the tweets with our classifier pipeline from above.</p><pre>tweets_raw_df = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/scraped_tweets_ES_raw.csv&#39;)</pre><h4>Creating Labels with the Classifier Pipeline</h4><p>We will only select the first 10 tweets in the following to see how it performs.</p><pre># Create labels in an unsupervised manner with the beto-sentiment-analysis classifier:</pre><pre>## Creating lists for a new dataframe that contains the assigned label and the corresponding probability score</pre><pre>sentiment_output = []<br>sentiment_proba = []</pre><pre>## Looping through the scraped tweets and adding the predictions to the previously created lists</pre><pre>for tweet in tweets_raw_df[&#39;content&#39;][:10]: #select first 10 tweets only<br>  result = classifier(tweet) #save analyzer result<br>  sentiment_output.append(result[0][&#39;label&#39;]) #select given label<br>  sentiment_proba.append(result[0][&#39;score&#39;]) #select probability of given label<br></pre><pre># Concat results with selected columns from original dataframe<br>sentiment_beto_df = pd.concat([tweets_raw_df[:10][[&#39;date&#39;, &#39;username&#39;, &#39;content&#39;]], pd.Series(sentiment_output), pd.Series(sentiment_proba)], axis=1)</pre><pre># Rename new columns to &#39;sentiment&#39; and &#39;sentiment_probability&#39;<br>sentiment_beto_df.rename(columns={0: &#39;sentiment_output&#39;, 1: &#39;sentiment_probability&#39;}, inplace=True)</pre><pre>print(&#39;-- This df still contains the tweets that have low probability scores! --&#39;)</pre><pre>display(sentiment_beto_df)</pre><p>Our output should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlUEtIg_rg_R3Elz5_6fpA.png" /></figure><p>In only these few examples we note that there are a few tweets that don’t seem to have a high probability score. To have a higher certainty that the label is predicted correctly, we will only keep those that have a high probability (p&gt;0.9).</p><h4>Filtering for High Probability Scores</h4><p>As we can see, in the following only tweets that have a high probability are kept.</p><pre># Removing tweets that have low probability scores<br>df_high_prob = sentiment_beto_df[sentiment_beto_df[&#39;sentiment_probability&#39;]&gt;0.9].reset_index(drop=True )</pre><pre>print(&#39;-- The following df only contains tweets that have high probability scores with p&gt;0.9. --&#39;)</pre><pre>display(df_high_prob)</pre><p>Now your output should look like this — similar, but we’ve excluded the tweets with probability scores lower than 0,9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GG8bDr93W_bM0Ked7FwKQ.png" /></figure><h4>AutoTokenizer</h4><p>The <em>pipeline</em> function of the <em>transformers</em> library is made up of different parts:</p><p>The first one is the so-called <em>AutoTokenizer. </em>As mentioned earlier, the tokenizer is responsible for preprocessing our texts. It will basically create the inputs that our model can understand since it won’t be able to process the words directly.</p><p>It will first split a given text into smaller subparts, called <em>Tokens</em>. These tokens consist of words, parts of words, or punctuation symbols. NOTE: We have to make sure to instantiate `AutoTokenizer` using the same model as for classification!</p><p>In the second step, the Tokenizer will transform the tokens into numbers since our model won’t understand words or punctuations as they are. With those numbers, we can then build the tensors that we can feed our model. To do this, the tokenizer has a <em>vocab</em>, which is the part we download when we instantiate it with the <em>from_pretrained</em> method since we need to use the same vocab as when the model was pre-trained.</p><p>Since our goal is to process multiple sentences at once, we need to perform this operation differently and treat it as a <em>batch</em>.</p><blockquote>The <em>AutoTokenizer </em>will basically create the inputs that our model can understand since it won’t be able to process the words directly.</blockquote><p>This means we need to make them all to the same length, which essentially means filling empty spaces for those sentences that are shorter and truncating them for the very long sentences to be shortened to the maximum length our model can accept. In our case, the maximum length, given by the argument <em>max_length</em> is equal to 512.</p><p>Once we do the preprocessing with our tokenizer, we can use the preprocessed data to feed it to our actual model which will be able to classify between positive, negative, and neutral tweets.</p><p>The preprocessed data <em>tweets_preprocessed</em>, contains a dictionary string to a list of ints. It contains the i<em>ds of the tokens</em>, as mentioned before, but also additional arguments that will be useful to the model. Here, for instance, we also have an <em>attention mask</em> that the model will use to have a better understanding of the sequence:</p><p>The padding is automatically applied on the side expected by the model (in this case, on the right), with the padding token the model was pre-trained with. The attention mask is also adapted to take the padding into account:</p><pre># Batch operations with the AutoTokenizer</pre><pre>tweets_preprocessed = tokenizer(<br>tweets,padding=&#39;longest&#39;, # padding to match the longest sequence truncation=True,<br>max_length=None,<br>return_tensors=&quot;tf&quot; #we are working with TensorFlow<br>)</pre><p>As we can see, the outputs are objects that contain the model’s final activations along with other metadata. In order to understand them and be able to interpret them, we have to go through some additional steps, namely passing the outputs through a <em>Softmax </em>function and then applying labels to give the final output meaning.</p><pre>import tensorflow as tf</pre><pre>tf_predictions = tf.nn.softmax(model_outputs.logits, axis=-1)</pre><pre>tf_predictions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdAv0D3lLjuOSPhj5MzICA.png" /><figcaption>The output of the above operation</figcaption></figure><p>The object has the logits attribute, which will allow us to access the model’s final activations and create the labels for our output.</p><h3>Fine-Tuning the Baseline RoBERTa Model</h3><h4>Tass 2020 Task Using Labeled Data for Fine-Tuning</h4><p>We will use the recently developed <a href="https://arxiv.org/pdf/2107.07253.pdf">Spanish RoBERTa base model</a> and fine-tune it with the <a href="http://tass.sepln.org/2020/#tasks">TASS2020 Task1 dataset: General polarity at three levels, Subtask 1 Monolingual</a>.</p><p>The mentioned TASS2020 dataset for “evaluation of polarity classification systems of tweets written in Spanish” contains a total of 8,409 tweets written in Spanish. We have to keep in mind though that this number represents all the tweets from different countries. Since we’re interested in analyzing tweets in Spain, we will focus on the tweets from Spain for training.</p><p>The dataset can be found <a href="http://tass.sepln.org/2020/?page_id=74">here</a>.</p><h4>Preparing the Data</h4><p>In the following, we will start with loading two different datasets: a train set and a validation set. Then we will have a look at it. Note that we’re only loading the text and the labels.</p><p>The TASS2020 dataset consists of several training subsets. Each subset represents tweet data from a different country. We’re going to concatenate the subsets to get more training data and like this, our model will have a more robust understanding of the Spanish language.</p><p>Note that we’re loading and concatenating the data in one step!</p><pre>### TRAIN DATA ###</pre><pre># Load the different train dataframes</pre><pre>es_train = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/es_train.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre>cr_train = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/cr_train.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre>mx_train = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/mx_train.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre>pe_train = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/pe_train.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre>uy_train = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/uy_train.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre><br># Concatenate the dataframes<br>train_df = pd.concat([es_train, cr_train, mx_train, pe_train, uy_train], axis=0, ignore_index=True)</pre><pre># Removing neutral comments<br>train_df = train_df[train_df[2] != &#39;NEU&#39;]</pre><pre># Display data<br>print(&#39;TRAINING DATA\n&#39;,train_df.shape)<br>display(train_df.head())</pre><pre>### VALIDATION DATA ###</pre><pre># Load the different train dataframes</pre><pre>es_val = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/es_val.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre>cr_val = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/cr_val.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre>mx_val = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/mx_val.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre>pe_val = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/pe_val.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre>uy_val = pd.read_csv(&#39;https://raw.githubusercontent.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis/main/uy_val.tsv&#39;, sep=&#39;\t&#39;, header=None, usecols=[1,2])</pre><pre># Concatenate the dataframes<br>val_df = pd.concat([es_val, cr_val, mx_val, pe_val, uy_val], axis=0, ignore_index=True)</pre><pre># Removing neutral comments<br>val_df = val_df[val_df[2] != &#39;NEU&#39;]</pre><pre># Display data<br>print(&#39;VALIDATION DATA\n&#39;,val_df.shape)<br>display(val_df.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yj5_l20cJWyLxIoJoTHOpg.png" /><figcaption>Output: The training and Validation data with labels</figcaption></figure><pre># Show distributions of training and test data</pre><pre>import seaborn as sns<br>sns.displot(train_df[2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lj084sgyLpaowbKK5u9gEQ.png" /><figcaption>Output: The distribution of negative and positive labels</figcaption></figure><pre># Creating lists for text and labels for taining and validation data</pre><pre>## Train data<br>train_texts = list(train_df[1])<br>train_labels = list(train_df[2])</pre><pre>## Val data<br>val_texts = list(val_df[1])<br>val_labels = list(val_df[2])</pre><h4>Preprocessing with the <strong>Auto Tokenizer</strong></h4><pre># Creating tokenizer<br>from transformers import AutoTokenizer<br>tokenizer = AutoTokenizer.from_pretrained(&quot;BSC-TeMU/roberta-base-bne&quot;)</pre><pre># Preprocessing text<br>train_encodings = tokenizer(train_texts, truncation=True, padding=True)<br>val_encodings = tokenizer(val_texts, truncation=True, padding=True)</pre><h4>Creating the Dataset Objects</h4><p>Since we have to batch the data, we cannot simply forward the labels and encodings. Instead, we have to create the dataset objects with the <strong><em>.from_tensor_slice()</em></strong>-method in TensorFlow. This format allows for easy batching.</p><p>Before creating the dataset objects though, we have to keep in mind though that our model isn’t able to process any non-numeric values. We have to convert our labels to numbers as well. We’ll do this by mapping integers to the strings in the list.</p><pre># Convert the labels to ints<br>## Create a dictionary for the mapping<br>d = {&#39;N&#39;:0, &#39;P&#39;:1}</pre><pre>## Map the values in the dictionary to the three lists of labels<br>train_labels = list(pd.Series(train_labels).map(d).astype(int))<br>val_labels = list(pd.Series(val_labels).map(d).astype(int))</pre><pre># Create the tensorflow datasets from our encodings<br>train_dataset = tf.data.Dataset.from_tensor_slices((<br>dict(train_encodings),train_labels))</pre><pre>val_dataset = tf.data.Dataset.from_tensor_slices((<br>dict(val_encodings),val_labels))</pre><h3>Model Training in Native TensorFlow</h3><p>Now that we have our data prepared and created the dataset objects, we’re ready to fine-tune our model in <strong>native TensorFlow</strong>.</p><pre>from transformers import TFAutoModelForSequenceClassification</pre><pre>## Model Definition<br>roberta_model = TFAutoModelForSequenceClassification.from_pretrained(&quot;BSC-TeMU/roberta-base-bne&quot;, from_pt=True, num_labels=2)<br></pre><pre>## Model Compilation<br>optimizer = tf.keras.optimizers.Adam(learning_rate=5e-5)</pre><pre>loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)</pre><pre>metric = tf.metrics.SparseCategoricalAccuracy()</pre><pre>roberta_model.compile(optimizer=optimizer, loss=loss, metrics=metric)<br></pre><pre>## Fitting the data<br>#history = roberta_model.fit(train_dataset, validation_data=val_dataset, epochs=5, batch_size=64)</pre><pre>history = roberta_model.fit(train_dataset.shuffle(len(train_labels)).batch(64), validation_data=val_dataset.shuffle(len(val_labels)).batch(64), epochs=3, batch_size=64)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXutvDY2GPPnzgCiNxZ5WQ.png" /><figcaption>Output from the above operations</figcaption></figure><h4>Evaluation</h4><p>Calculate the average accuracy for the above model.</p><pre># Calculate the mean val_sparse_categorical_accuracy<br>print(&#39;The mean Sparse Categorical Acc for the val_set is: &#39;, np.mean(history.history[&#39;val_sparse_categorical_accuracy&#39;]))</pre><pre># And save the model<br>roberta_model.save_pretrained(&#39;Twitter_Roberta_Model&#39;)</pre><p>The model can also be found on my <a href="https://github.com/lucamarcelo/Vaccine-Tweets-Sentiment-Analysis">GitHub</a>.</p><h3>Using the Fine-Tuned Model to Create Predictions</h3><h4>Creating predictions with the pipeline</h4><pre># Instatiate the model with the tokenizer we used before and the model we just trained</pre><pre>roberta_classifier = pipeline(&#39;sentiment-analysis&#39;, model=roberta_model, tokenizer=tokenizer)</pre><pre># Let&#39;s see if it works on an example<br>roberta_classifier([&#39;Hoy no me encuentro muy bien.&#39;, &#39;Hoy es un día bonito.&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*RsfM1ePESQahc8szvIHHqg.png" /><figcaption>Output for the above test</figcaption></figure><p>Our model has now been fine-tuned on a new task and is able to classify tweets into three categories: <em>Positive</em>, <em>negative</em>, and <em>neutral</em>. We also see that with the label comes a probability score for each label which we can use to determine how sure the model is of the label it assigned.</p><h3>Creating Predictions for Our Dataset</h3><pre>## Creating lists for a new dataframe that contains the assigned label and the corresponding probability score<br>sentiment_output = []<br>sentiment_proba = []</pre><pre>## Looping through the scraped tweets and adding the predictions to the previously created lists<br>for tweet in tweets_raw_df[&#39;content&#39;]:<br>  result = roberta_classifier(tweet) #save classifier result<br>  sentiment_output.append(result[0][&#39;label&#39;])#select predicted label<br>  sentiment_proba.append(result[0][&#39;score&#39;]) #select probability </pre><pre>## Concat results with selected columns from original dataframe<br>sentiment_roberta_df = pd.concat([tweets_raw_df[[&#39;date&#39;, &#39;username&#39;, &#39;verified&#39;, &#39;followersCount&#39;, &#39;location&#39;, &#39;content&#39;, &#39;replyCount&#39;, &#39;retweetCount&#39;, &#39;likeCount&#39;]], pd.Series(sentiment_output), pd.Series(sentiment_proba)], axis=1)</pre><pre>## Rename new columns to &#39;sentiment&#39; and &#39;sentiment_probability&#39;<br>sentiment_roberta_df.rename(columns={0: &#39;sentiment_output_roberta&#39;, 1: &#39;sentiment_probability_roberta&#39;}, inplace=True)</pre><pre>print(&#39;-- This df still contains the tweets that have low probability scores! --&#39;)</pre><pre>display(sentiment_roberta_df.head(10))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdyQXz-Xd6bOMI9ZMX-V7g.png" /><figcaption>Output with predictions and probability for our initial dataset</figcaption></figure><p>At this point, we can start making modifications to the data, like renaming the labels, modifying the date, or aggregating by location. The dataset now is also fit to understand the sentiment better, for example by looking at distributions, mean values, and bi- and multivariate analysis.</p><h3><strong>Conclusions</strong></h3><p>At this point, you’re ready to take your own pre-trained language model and fine-tune it for the task you need!</p><p>We’ve seen that pre-training a model is simply not achievable for most individuals, since it requires huge amounts of data and computing resources. We can however take the pre-trained model, some labeled data for the downstream task, and fine-tune it for the task we need.</p><p>TensorFlow offers a great deal of ease to tokenize and preprocess the data, to be able to train a model and even evaluate its performance. After fine-tuning the model, you can go ahead and create predictions with the model for unseen data and analyze the data afterward to drive insights from it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87614635c40e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consensus Mechanisms: Proof of Stake vs Proof of Work]]></title>
            <link>https://medium.com/@lucapetriconi/consensus-mechanisms-proof-of-stake-vs-proof-of-work-645eb3a66b5e?source=rss-fd256d0457bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/645eb3a66b5e</guid>
            <category><![CDATA[proof-of-stake]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[proof-of-work]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Luca Petriconi]]></dc:creator>
            <pubDate>Sat, 26 Feb 2022 18:07:16 GMT</pubDate>
            <atom:updated>2022-10-23T19:24:50.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1qevY_yKicW7RamU7wfJg.png" /><figcaption>Proof of Stake vs Proof of Work</figcaption></figure><p>Blockchains are often mentioned as one of the technologies with the greatest impact on our future lives. In fact, blockchain developers, are one of the most demanded and highest-paid IT jobs, right now.</p><p><a href="https://elevatex.de/blog/web3/beginners-guide-a-simple-introduction-to-blockchain/">Blockchains can be thought of as a distributed database</a> or network without a central authority that controls it. All the participants in the networks, the so-called nodes, make up the network. The method the nodes use to agree on the state of a blockchain is called consensus mechanism (also called consensus protocol or consensus algorithm). Through these mechanisms, the state of the blockchain can be verified. This in turn makes blockchains great in areas where trust is a prerequisite.</p><p>Proof of Work (PoW), the consensus mechanism used in Bitcoin, and Proof of Stake (PoS) are the two major consensus mechanisms that allow validation of transactions and the addition of new blocks to the blockchain.</p><p>Let’s dive a bit deeper into the topic…</p><h3><strong>First Things First — What’s a Consensus Mechanism?</strong></h3><p>A <a href="https://en.wikipedia.org/wiki/Consensus_decision-making">consensus generally means reaching an agreement</a>.</p><p>Since a blockchain, or more generally speaking, a distributed network, lacks a central authority that decides on the state of the network, the nodes that make up the network need to reach an agreement on its state, meaning what transactions are valid. Reaching this agreement can be quite tricky. In this way, it also helps to democratise decision-making.</p><p>A consensus mechanism is the backbone of a blockchain and helps to coordinate the network and keep it secure. We’ve said that you can think of the blockchain as a distributed database. It’s important that every node that makes up the network has the same copy of the database. If this wasn’t the case, you’d quickly end up with conflicting information.</p><p>There are different types of consensus mechanism, depending on the blockchain and its application. We’ll dive deeper into the two major consensus mechanisms, namely Proof of Work used in Bitcoin and formerly in Ethereum and Proof of Stake which is currently used in Ethereum.</p><h3><strong>Proof of Work</strong></h3><p>When <a href="https://bitcoin.org/bitcoin.pdf">Satoshi Nakamoto invented Bitcoin</a>, he needed to make sure that the blockchain was safe. He used a consensus protocol called proof of work to achieve this. Proof of work is one of the widest-spread consensus algorithms and has also been used in Ethereum (before it changed to Proof of Stake in Ethereum 2.0), Litecoin, or Dogecoin.</p><p>In Proof of work, the nodes of the networks (in this case also referred to as <em>miners</em>), compete against each other to be the fastest in solving a highly complex math problem. In solving the math problem first, the miner gets the “proof” for his “work” and earns the right to process the next block of transaction. The miner in turn is rewarded with a pre-determined amount of cryptocurrency.</p><p>Proof of work is computationally very expensive and therefore requires an enormous amount of energy. In fact, Bitcoin has often been criticized for having a major environmental impact. Oftentimes, also specialised hardware like GPUs and high-end machines are required, which may hinder access for individual miners.</p><p><strong>Advantages of Proof of Work</strong></p><p>· Since Proof of work has been around the longest, this also means that it is the one that’s widely used by many cryptocurrencies.</p><p>· It’s said to be extremely secure since more than half of the network would need to be controlled by attackers to manipulate the network. This is also known as 51% attack.</p><p>· It attracts “miners”, the people (or nodes) that validate transactions, by rewarding them.</p><p><strong>Disadvantages of Proof of Work</strong></p><p>· Proof of work requires a lot of energy. The nodes in the network go through a computationally very expensive race of trial and error to <a href="https://andersbrownworth.com/blockchain/blockchain">find the nonce for a block</a>. Therefore, proof of work is said to have a high environmental cost</p><p>· To be able to compete with existing miners, often very expensive hardware is required, which in turn can make it difficult for individual miners to compete with so-called mining farms.</p><p>· The proof of work protocol is associated with a very slow transaction speed which in turn makes it difficult to scale the network. This is one of the reasons <a href="https://blog.ethereum.org/2022/01/24/the-great-eth2-renaming/">Ethereum made the step to proof of stake</a>.</p><h3><strong>Proof of Stake</strong></h3><p>Proof of stake is a consensus mechanism where the right to validate a transaction and adding new blocks to the network depends on how much a validator (called miner in proof of work) has staked, i.e., how much cryptocurrency the validator holds.</p><p>A computer algorithm chooses validators with a certain degree of randomness involved but those that hold more of the network’s currency have a higher likelihood to get selected. It basically rewards those that have prolonged participation through higher staking of the network’s currency.</p><p>Proof of stake, unlike proof of work, does not rely on energy to select its validators. Therefore, its energy consumption and impact on the environment is much lower. It’s also designed to address the scalability and transaction speed issues related to the proof of work protocol.</p><p><strong>Advantages of Proof of Stake</strong></p><p>· Proof of stake is not designed around a competitive process of who’s the fastest in <a href="https://andersbrownworth.com/blockchain/blockchain">finding the right nonce to the block</a>. Therefore, it requires relatively little energy to maintain, compared to proof of work.</p><p>· In contrast to the competitive proof of work, proof of stake reduces transaction times and can therefore increase transaction volume.</p><p>· Since proof of stake is more efficient than proof of work, transaction fees are lower, which also favors transaction volume.</p><p><strong>Disadvantages of Proof of Stake</strong></p><p>· In smaller networks, there’s an increased risk of a 51% attack where someone controls 51% or more of a cryptocurrency and can therefore manipulate the blockchain.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FojxfbN78WFQ%3Fstart%3D2%26feature%3Doembed%26start%3D2&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DojxfbN78WFQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FojxfbN78WFQ%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/f898c05eca9ca8d643368a8bbc41a030/href">https://medium.com/media/f898c05eca9ca8d643368a8bbc41a030/href</a></iframe><h3><strong>Alternative Consensus Mechanisms</strong></h3><p>With an increasing number of cryptocurrencies, the ways these cryptocurrencies are governed have also diversified. This list is non-exhaustive and surely, the number of consensus protocols will increase in the future.</p><p>· <strong>Delegated Proof of Stake<br> </strong>This variation of proof of stake allows someone to vote on the number of delegates to create a new block. <a href="https://cardano.org/">Cardano</a> is a well-known example for delegated proof of stake.</p><p>· <strong>Proof of Authority<br> </strong>The proof of authority consensus protocol uses a reputation-based model, where nodes need to be selected and approved by other network participants to validate new blocks. Whereas in proof of stake a validator needs to put in financial capital, in proof of authority a validator needs to put in social capital. <a href="https://www.vechain.org/">VeChain</a> is an example of a blockchain that uses proof of authority.</p><p>· <strong>Proof of History<br> </strong>In proof of history, every validator has, figuratively speaking, a built-in clock that records the specific moment an action was performed on the blockchain. In <a href="https://solana.com/">Solana</a>, for example, which uses proof of history, one lead validator at a time processes transactions and writes the network state, while other validators read the state and confirm them.</p><p>· <strong>Proof of Space/Proof of Capacity<br> </strong>In proof of space, also known as proof of capacity, a validator stakes its available hard drive space to gain the right to process and validate the next transaction. On the hard drive, several cryptographic mining solutions are stored. This means the harder drive space you have available, the higher your stakes and the higher your likelihood to process the next transaction. <a href="https://www.chia.net/">Chia</a> is a network that uses proof of space, even though it is tied to proof of time.</p><h3><strong>Key Takeaways</strong></h3><p>· Consensus mechanisms are a tool that allows decentralized networks to reach an agreement on the state of the network.</p><p>· Consensus mechanisms are the backbone of the blockchain and play a crucial role in the security of the blockchain.</p><p>· Proof of work, the first consensus mechanism, is said to be very secure but requires high amounts of energy and mining requires specialized hardware.</p><p>· Proof of stake uses the amount of the network’s cryptocurrency a validator has staked to determine the right to process and validate a block.</p><p>· Each consensus mechanism has its pros and cons and with time, we will see a greater variety of them. Some more recent consensus mechanisms include proof of history, proof of space, or proof of authority.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=645eb3a66b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Churn Modeling: A detailed step-by-step Guide in Python]]></title>
            <link>https://medium.com/@lucapetriconi/churn-modeling-a-detailed-step-by-step-guide-in-python-1e96d51c7523?source=rss-fd256d0457bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e96d51c7523</guid>
            <category><![CDATA[churn]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Luca Petriconi]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 15:20:02 GMT</pubDate>
            <atom:updated>2022-11-13T18:25:46.774Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to build a data pipeline in Python to predict customer churn.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZPpDO_jNx6LGAURB" /><figcaption>Photo by <a href="https://unsplash.com/@jangujang?utm_source=medium&amp;utm_medium=referral">JUNK</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Understanding Customer Churn</h3><p><strong>What is Customer Churn?<br></strong>Customer churn refers to when a customer ends his or her relationship with a business.</p><p><strong>Why do customers churn?<br></strong>Even though there are a variety of factors influencing churn, it mostly comes down to one of the following reasons:</p><ul><li>The customer is frustrated with the product experience.</li><li>The cost for the product exceeds the value it provides.</li><li>The product lacks appropriate customer support.</li><li>Attracting the wrong customers.</li></ul><p><strong>Why do we want to predict churn? <br></strong>Acquiring new customers can be several times more expensive than selling to existing ones. Understanding what drives churn and why customers are churning is crucial in maintaining high retention rates. Being able to accurately identify those customers at high risk of churning, may help us to create appropriate marketing strategies and retain our customers.</p><h3>Data</h3><p>The data can be downloaded from my <a href="https://github.com/lucamarcelo/Churn-Modeling">GitHub repository</a>.</p><p>We’re dealing with customer data from a telecom company. The data has 7043 examples and 20 features including the binary target variable Churn.</p><h4><strong>Workflow</strong></h4><ul><li>1) <em>EDA — What data are we dealing with?</em></li><li>2) <em>Preprocessing — Let’s clean our data</em></li><li>3) <em>Training time — Model building and comparison</em></li><li>4)<em> Predictions and Model Evaluation</em></li><li>5) <em>Conclusions and Final Thoughts</em></li></ul><h3>Hands-On!</h3><p>Enough talking, let’s jump right in by importing the libraries we need…</p><pre>## Basics <br>import numpy as np<br>import pandas as pd</pre><pre>## Visualization<br>import matplotlib as plt<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>## ML<br>from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV<br>from sklearn.preprocessing import OneHotEncoder, StandardScaler<br>from sklearn.impute import SimpleImputer<br>from sklearn.pipeline import Pipeline<br>from sklearn.feature_selection import SelectKBest<br>from sklearn.compose import ColumnTransformer<br>from sklearn.metrics import accuracy_score, classification_report, roc_auc_score, plot_roc_curve</pre><pre>## Algorithms<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.svm import SVC<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier</pre><p>… and the data:</p><pre>data_raw = pd.read_csv(&#39;<a href="https://raw.githubusercontent.com/lucamarcelo/Churn-Modeling/main/Customer%20Churn%20Data.csv">https://raw.githubusercontent.com/lucamarcelo/Churn-Modeling/main/Customer%20Churn%20Data.csv</a>&#39;, set_index=&#39;CustomerID&#39;)</pre><pre>## Split the data to create a train and test set<br>train, test = train_test_split(data_raw, test_size=0.25)</pre><h3>1. Exploratory Data Analysis — What data are we dealing with?</h3><p>Understanding what data we’re dealing with, will allow us to make better decisions about what preprocessing steps we need to apply, which classifier we’re going to choose, and how to interpret the results.</p><h4><strong>Looking at data types and correct those wrongly encoded</strong></h4><pre>data_raw.dtypes</pre><pre>## We have one variable that&#39;s wrongly encoded as string<br>data_raw[&#39;TotalCharges&#39;] = pd.to_numeric(data_raw[&#39;TotalCharges&#39;], errors=&#39;coerce&#39;)</pre><h4><strong>Missing values and Cardinality</strong></h4><p><em>Cardinality </em>refers to the number of unique values of categorical variables. The following function allows us to check for missing values, as well as cardinality.</p><pre>def missing_values(data):<br>  df = pd.DataFrame()<br>  for col in list(data):<br>    unique_values = data[col].unique()<br>    try:<br>      unique_values = np.sort(unique_values)<br>    except:<br>      pass<br>    nans = round(pd.isna(data[col]).sum()/data.shape[0]*100, 1)<br>    zeros = round((data[col] == 0).sum()/data.shape[0]*100, 1)<br>    #empty = round((data[data[col]] == &#39;&#39;).sum()/data.shape[0]*100,1)<br>    df = df.append(pd.DataFrame([col, len(unique_values), nans,  zeros]).T, ignore_index = True)<br>  return df.rename(columns = {0: &#39;variable&#39;,<br>1: &#39;Unique values&#39;,<br>2: &#39;Nan %&#39;,<br>3: &#39;zeros %&#39;,<br>#4: &#39;empty&#39;}).sort_values(&#39;Nan %&#39;, ascending=False)</pre><pre>missing_values(data_raw)</pre><ul><li><strong>Output: </strong><br>As you can see, there&#39;s only the NaNs in TotalCharges that we’re going to take care of in the preprocessing part. All categorical variables have a relatively low cardinality. This is important when choosing the encoding.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*IdwT-2-X_xc2RLa77LfByw.png" /></figure><h4><strong>Distributions</strong></h4><p>In <em>Univariate analysis, </em>we look at a single variable, while in <em>bivariate </em>and<em> multivariate analysis</em> we look at two or more than two variables, respectively.</p><p><strong>Univariate analysis</strong> involves getting histograms of each of our variables. I like to solve this by creating a figure with all histograms.</p><pre>fig, ax = plt.subplots(4, 5, figsize=(15, 12))</pre><pre>plt.subplots_adjust(left=None, bottom=None, right=None, top=1, wspace=0.3, hspace=0.4)</pre><pre>for variable, subplot in zip(data_raw.columns, ax.flatten()):<br>  sns.histplot(data_raw[variable], ax=subplot)</pre><ul><li><strong>Output:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zfiOWwTG8gO3QkNCkJQXQ.png" /><figcaption>Univariate distributions</figcaption></figure><p><strong>Bivariate analysis</strong> looks at how two variables relate to each other. This can be either two numerical, two categorical, or a mix of both variables.</p><pre><strong># Numerical-numerical variables</strong></pre><pre>sns.pairplot(data = data_raw, hue=&#39;Churn&#39;)<br>plt.show()</pre><ul><li><strong>Output: </strong><br>Having set hue=&#39;Churn&#39; allows us to differentiate between churned and staying customers. We can see that churned customers tend to have a lower tenure while at the same time having higher monthly charges.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVlJF3FohpDXCvL22g5Yeg.png" /><figcaption>Pair plot for numerical variables</figcaption></figure><p>Let’s look at the relationship between categorical and numerical variables:<br>In our case, this would allow us to answer questions like <em>“Are churned customers likely to get charged more?”,</em> <em>“When do customers churn?”, </em>or <em>“Are senior citizens more likely to churn?”.</em></p><p>Feel free to use the code block below to investigate your own questions.</p><pre><strong># Categorical-numerical variables</strong></pre><pre>fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 6))</pre><pre>## Are churned customers likely to get charged more?plt.subplot(1,3,1)<br>sns.boxplot(data_raw[&#39;Churn&#39;], data_raw[&#39;MonthlyCharges&#39;])<br>plt.title(&#39;MonthlyCharges vs Churn&#39;)</pre><pre>## When do customers churn?<br>plt.subplot(1,3,2)<br>sns.boxplot(data_raw[&#39;Churn&#39;], data_raw[&#39;tenure&#39;])<br>plt.title(&#39;Tenure vs Churn&#39;)</pre><pre>## Are senior citizen more likely to churn?<br>plt.subplot(1,3,3)<br>counts = (data_raw.groupby([&#39;Churn&#39;])[&#39;SeniorCitizen&#39;]<br>  .value_counts(normalize=True)<br>  .rename(&#39;percentage&#39;)<br>  .mul(100)<br>  .reset_index())</pre><pre>plot = sns.barplot(x=&quot;SeniorCitizen&quot;, y=&quot;percentage&quot;, hue=&quot;Churn&quot;, data=counts).set_title(&#39;SeniorCitizen vs Churn&#39;)</pre><ul><li><strong>Output:<br></strong>We can clearly see from this that monthly charges for churning customers are higher, while tenure is much lower. For senior citizens, there are actually more customers churning than staying with the company. This might be indicative that we’re not focusing on the right customer segment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gee-lD43z8fAsUudgRiSNg.png" /></figure><p>Categorical-categorical relationships allow us to investigate how churn differs across for example a specific product or different target groups. We’ll find answers to questions like <em>“How does the churn across different services look like?”, “</em>Are those receiving tech support less likely to churn?<em>”, or “ Is a specific gender more likely to churn?”.</em></p><p>Use the following code to go through all the possible categorical-categorical variable combinations.</p><pre>for col in data_raw.select_dtypes(exclude=np.number):<br>  sns.catplot(x=col, kind=&#39;count&#39;, hue=&#39;Churn&#39;,data=data_raw.select_dtypes(exclude=np.number))</pre><p>Lastly, we’ll quickly look at <strong>multivariate analysis — </strong>three or more variables<strong>. </strong>A good way to represent these relationships is heatmaps.</p><p>To be able to aggregate Churn, we first have to convert it to numeric:</p><pre>data_raw[&#39;Churn&#39;] = data_raw[&#39;Churn&#39;].map( {&#39;No&#39;: 0, &#39;Yes&#39;: 1} ).astype(int)</pre><p>We’ll pick one example and explain how to interpret it. But the same applies to all other combinations of variables.</p><pre><strong># How does PaymentMethod and Contract type affect churn?</strong></pre><pre>## Create pivot table<br>result = pd.pivot_table(data=data_raw, index=&#39;PaymentMethod&#39;, columns=&#39;Contract&#39;,values=&#39;Churn&#39;)</pre><pre>## create heat map of education vs marital vs response_rate<br>sns.heatmap(result, annot=True, cmap = &#39;RdYlGn_r&#39;).set_title(&#39;How does PaymentMethod and Contract type affect churn?&#39;)</pre><pre>plt.show()</pre><ul><li><strong>Output:<br></strong>We can directly see that customers with a month-to-month contract paying by electronic check are most likely to churn. While those with a two-year contract have a very low probability throughout.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*k96H-euxLzXTUIH-2WTWZQ.png" /><figcaption>A heatmap is a good idea for multivariate analysis</figcaption></figure><h4>Conclusions from EDA</h4><p>Now that we have a better understanding of what’s going on in our data, we can already draw a few conclusions:</p><ul><li>Our target variable is not perfectly balanced. This is important when choosing what algorithm and what evaluation metric we use.</li><li>Most variables in the dataset are categorical. We will need to encode them.</li><li>There are a few NaNs that we need to impute.</li><li>Those paying by electronic check are much more likely to churn.</li><li>It seems that those who have a month-to-month contract are more likely to churn.</li><li>Customers receiving tech support are less likely to churn.</li><li>The ones that contracted Fiber are more likely to churn compared to those with DSL.</li><li>It seems that MonthlyCharges play an important role in whether a customer will stay with the company or not. On the one side, customers that churn, pay on average almost 22% more. While seniors pay as much as 34% more on average - and that&#39;s even 37% when they churn.</li><li>SeniorCitizen are also more likely to churn and to stay longer.</li><li>The average tenure is lower for churned customers.</li></ul><h3>2. Preprocessing — Let’s Clean our Data</h3><p>I’m pretty sure everyone has heard that Data Scientists spend about 80% of their time preparing the data. However, there’s a great deal we can automate and tricks we can help ourselves with. One of them is the use of a <em>pipeline</em>.</p><h4>Creating a pipeline</h4><p>Our pipeline will consist of the preprocessing steps followed by an estimator at the end of the pipeline. This is a general convention since scikit learn’s pipelines will call fit_transform on all the pipeline steps except the last one, where it will only call fit. Depending on our requirements, we can for example include imputation, scaling, encoding, and dimensionality reduction.</p><p><em>Why use a pipeline for preprocessing?</em></p><ul><li><strong>It prevents data leakage<br></strong>Data leakage happens when we include information from the data we’re trying to predict during training. This happens for example when we calculate the mean for imputation for the <em>whole</em> dataset instead of only for the training data. Our performance estimation would then be overly optimistic. A pipeline makes it really easy to avoid data leakage since we call fit on the training data and predict on the test data.</li><li><strong>It minimizes errors</strong><br>With manual preprocessing, there are a lot more, smaller steps involved, and sometimes every variable needs to be done individually. A pipeline streamlines this process and minimizes the possibility of errors.</li><li><strong>Cleaner looking code</strong><br>The pipeline is written once and then we only need to call the corresponding method. As a result, the code is cleaner easier to read.</li><li><strong>Cross-validate the whole pipeline</strong><br>Instead of cross-validating only the estimator, we can cross-validate the whole pipeline. The same applies to hyperparameter tuning.</li></ul><h4>Preprocessing steps in our pipeline</h4><ul><li><strong>Imputation<br></strong>We discovered a few empty strings in TotalCharges and passed them to NaN.We will use sci-kit learn&#39;s SimpleImputer.</li><li><strong>Scaling<br></strong>Algorithms that measure distances between data points work much better when the data is scaled. The idea is to make different numerical ranges comparable to each other. We will use scikit-learn’s StandardScaler.</li><li><strong>Categorical Encoding<br></strong>We’ve previously seen that our dataset contains mostly categorical variables. Since most machine learning algorithms do not understand non-numeric data, we will need to convert them to numeric. Since all the features have a very low cardinality, we will go with the OneHotEncoder.</li><li><strong>Feature Selection<br></strong>Our pipeline will also include a feature selection part where we will only select the best-performing features. We’ll use scikit learn’s SelectKBest.</li></ul><h3>3. Traning Time — <em>Model building and comparison</em></h3><h4>Data Splitting</h4><p>Before starting we have to make sure we include the right data in our model. We’ll split it into training and test and separate features from the target.</p><pre>train, test = train_test_split(data_raw, test_size=0.25, random_state=123)</pre><pre>X = train.drop(columns=&#39;Churn&#39;, axis=1)<br>y = train[&#39;Churn&#39;]</pre><h4>Building the pipeline</h4><p>Think of the preprocessor as a collection of pipelines, each one designed to handle a specific type of data — one for numerical and one for categorical features. ColumnTransformer lets us selectively apply preprocessing steps.</p><pre>## Selecting categorical and numeric features<br>numerical_ix = X.select_dtypes(include=np.number).columns<br>categorical_ix = X.select_dtypes(exclude=np.number).columns</pre><pre>## Create preprocessing pipelines for each datatype<br>numerical_transformer = Pipeline(steps=[<br>(&#39;imputer&#39;, SimpleImputer(strategy=&#39;median&#39;)),<br>(&#39;scaler&#39;, StandardScaler())])</pre><pre>categorical_transformer = Pipeline(steps=[<br>(&#39;encoder&#39;, OrdinalEncoder()),<br>(&#39;scaler&#39;, StandardScaler())])</pre><pre>## Putting the preprocessing steps together<br>preprocessor = ColumnTransformer([<br>(&#39;numerical&#39;, numerical_transformer, numerical_ix),<br>(&#39;categorical&#39;, categorical_transformer, categorical_ix)],<br>remainder=&#39;passthrough&#39;)</pre><h4>Finding the best baseline model</h4><p>The idea is to find the algorithm that performs best at its baseline level, i.e. without tweaking, and select it to further improve it through hyperparameter tuning. We’re going to loop through different algorithms and see which one performs best — <em>Note that we’re using </em><em>roc_auc as an evaluation metric!</em></p><pre>## Creat list of classifiers we&#39;re going to try out<br>classifiers = [<br>KNeighborsClassifier(),<br>SVC(random_state=123),<br>DecisionTreeClassifier(random_state=123),<br>RandomForestClassifier(random_state=123),<br>AdaBoostClassifier(random_state=123),<br>GradientBoostingClassifier(random_state=123)<br>]</pre><pre>classifier_names = [<br>&#39;KNeighborsClassifier()&#39;,<br>&#39;SVC()&#39;,<br>&#39;DecisionTreeClassifier()&#39;,<br>&#39;RandomForestClassifier()&#39;,<br>&#39;AdaBoostClassifier()&#39;,<br>&#39;GradientBoostingClassifier()&#39;<br>]</pre><pre>model_scores = []</pre><pre>## Looping through the classifiers<br>for classifier, name in zip(classifiers, classifier_names):<br>  pipe = Pipeline(steps=[<br>  (&#39;preprocessor&#39;, preprocessor),<br>  (&#39;selector&#39;, SelectKBest(k=len(X.columns))),<br>  (&#39;classifier&#39;, classifier)])<br>  score = cross_val_score(pipe, X, y, cv=10, scoring=&#39;roc_auc&#39;).mean() <br>  model_scores.append(score)</pre><p>Now it’s time to compare the scores:</p><pre>model_performance = pd.DataFrame({<br>  &#39;Classifier&#39;:<br>    classifier_names,  <br>  &#39;Cross-validated AUC&#39;:<br>    model_scores<br>}).sort_values(&#39;Cross-validated AUC&#39;, ascending = False, ignore_index=True)</pre><pre>display(model_performance)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*rD42sVm_n0itINfzsEv-2g.png" /><figcaption>Overview of our baseline models</figcaption></figure><h4>Hyperparameter Tuning</h4><p>Now that we’ve identified our best candidate, we can go on to hyperparameter tuning. Essentially, this means finding the best “settings” of the algorithm.</p><p>Let’s get our final pipeline:</p><pre>pipe = Pipeline(steps=[<br>  (&#39;preprocessor&#39;, preprocessor),<br>  (&#39;selector&#39;, SelectKBest(k=len(X.columns))),<br>  (&#39;classifier&#39;, GradientBoostingClassifier(random_state=123))<br>])</pre><p><em>How do we know what to tune?<br></em>We can change <em>a lot</em> of hyperparameters through the whole pipeline. Are we going to try them all? No! Cross-validation is expensive and we will therefore focus on a limited number of hyperparameters. We can get a full list of all hyperparameters with pipe.get_params().keys().</p><p>The idea behind GridSearchCV is that we specify the parameters and their corresponding values we want to search. GridSearch will try all possible combinations and determines which one performed best.</p><pre>grid = {<br>  &quot;selector__k&quot;: k_range,<br>  &quot;classifier__max_depth&quot;:[1,3,5],<br>  &quot;classifier__learning_rate&quot;:[0.01,0.1,1],<br>  &quot;classifier__n_estimators&quot;:[100,200,300,400]<br>}</pre><pre>gridsearch = GridSearchCV(estimator=pipe, param_grid=grid, n_jobs= 1, scoring=&#39;roc_auc&#39;)</pre><pre>gridsearch.fit(X, y)</pre><pre>print(gridsearch.best_params_)<br>print(gridsearch.best_score_)</pre><ul><li><strong>Output:</strong></li></ul><pre>{&#39;classifier__learning_rate&#39;: 0.1, &#39;classifier__max_depth&#39;: 1, &#39;classifier__n_estimators&#39;: 400, &#39;selector__k&#39;: 16} </pre><pre>0.8501488378467128</pre><h3>4. Creating predictions for unseen data</h3><p>The testdata will help us get a more accurate estimate of the performance of our model. Even though we did cross-validation, we still want to test the model on completely unseen data. Our pipeline has learned the parameters from the training data and will now apply those to the test data.</p><pre>## Separate features and target for the test data<br>X_test = test.drop(columns=&#39;Churn&#39;, axis=1)<br>y_test = test[&#39;Churn&#39;]</pre><pre>## Refitting the training data with the best parameters<br>gridsearch.refit</pre><pre>## Creating the predictions<br>y_pred = gridsearch.predict(X_test)<br>y_score = gridsearch.predict_proba(X_test)[:, 1]</pre><pre>## Looking at the performance<br>print(&#39;AUCROC:&#39;, roc_auc_score(y_test, y_score), &#39;\nAccuracy:&#39;, accuracy_score(y_test, y_pred))</pre><pre># Plotting the ROC curve<br>plot_roc_curve(gridsearch, X_test, y_test)<br>plt.show()</pre><ul><li><strong>Output:</strong></li></ul><pre>AUCROC: 0.8441470897420832  <br>Accuracy: 0.7927314026121521</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*paA0w3nDz1qc5MECgLTZig.png" /></figure><h3>5. Conclusions and Final Thoughts</h3><p>In this project, we’ve worked with customer data to get an understanding of the factors that drive churn. We’ve performed exploratory data analysis to understand which variables affect churn. We saw that churned customers are likely to be charged more and often have a month-to-month contract.</p><p>We’ve gone from the raw data that had some wrongly encoded variables, some missing values, and a lot of categorical data, to a clean and correctly encoded dataset by automating our preprocessing with a pipeline.</p><p>By comparing different classifiers, we selected the best baseline model and tuned its hyperparameters using GridSearchCV.</p><p>We were able to predict churn for new data — in practice this could be for example new customers — with an AUC of 0.844.</p><p>An additional step to further improve our model’s performance would be feature engineering — creating new features by combining or transforming existing ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e96d51c7523" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>