<?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 Laksmi Amalia Wulandiari on Medium]]></title>
        <description><![CDATA[Stories by Laksmi Amalia Wulandiari on Medium]]></description>
        <link>https://medium.com/@amalia.wulandiari?source=rss-59685185473a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kzMibD7vX0OES1bB</url>
            <title>Stories by Laksmi Amalia Wulandiari on Medium</title>
            <link>https://medium.com/@amalia.wulandiari?source=rss-59685185473a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:02:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amalia.wulandiari/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[LEARNING PYTHON FUNCTIONS | with 3 Case Studies]]></title>
            <link>https://medium.com/@amalia.wulandiari/learning-python-functions-with-3-case-studies-d3340fdb8f58?source=rss-59685185473a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3340fdb8f58</guid>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[hands-on]]></category>
            <dc:creator><![CDATA[Laksmi Amalia Wulandiari]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 06:05:55 GMT</pubDate>
            <atom:updated>2024-08-31T06:05:55.274Z</atom:updated>
            <content:encoded><![CDATA[<p>Hands-on Projects to Enhance Your Python Skills in Function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUbFXQqqOFoYHuFIgdswuQ.png" /></figure><p>Hi everyone!</p><p>Whenever I prepare for an exam, interview, or test, I find that writing it down serves as a great way to help me study. In this article, I’d like to share insights about Functions in Python 🐍, with the hope that it will be a valuable resource for fellow data analyst enthusiasts.</p><p>In Python, a function is a block of reusable code that performs a specific task. We can define a function using the def keyword, followed by the name, parentheses (), and a colon :. Inside the function, we can write the code that executes when the function is called. Function allowed us to avoid repetition by enabling us to call the same block of code over and over again. In short, its <strong>simplify </strong>our task in coding!</p><h3>Key Points about Functions in Python:</h3><ol><li><strong>Definition</strong>: Functions are defined using the def keyword, followed by the function name, parentheses (), and a colon :. The code that makes up the function is written indented under this line.</li><li><strong>Parameters</strong>: Functions can take parameters (inputs) that allow you to pass data into the function. These parameters are specified inside the parentheses when defining the function.</li><li><strong>Return Value</strong>: A function can return a value using the return statement. This allows the function to send data back to the part of the program that called it.</li><li><strong>Calling a Function</strong>: To execute the function, you “call” it by writing the function name followed by parentheses. If the function requires parameters, you pass them inside these parentheses.</li></ol><p><strong>Here is a simple example, we want to create a greeting function:</strong></p><pre># Function<br>def hello():<br>    print(&#39;Hello!&#39;)<br><br># Calling the function<br>hello()<br><br># Result<br>Hello!</pre><p><strong>def</strong>is the keyword that define the function itself, followed by the function name hello and closed with ():. This is the first line of the function, we can finally put the code of the function print(&#39;Hello!) under it. We want to show <strong>Hello!</strong> everytime we call the function.</p><p>After writing the function, we can called it with the_function_name() in this case is hello(). Voila! We have a greeting function that greet us everytime we call it, <em>to kick out the loneliness </em>🥺💔.</p><p>We can modify it to show who we want to greet using this function by adding parameter.</p><pre># Function<br>def hello(name):<br>    print(&#39;Hello! &#39;+ name)<br><br># Calling the function<br>hello(&#39;Laksmi&#39;)<br><br># Result<br>Hello! Laksmi</pre><p>Make it more personal, a nice touché.</p><blockquote><strong>Functions are like magic spells — say the right words, and voila, you’ve got results! Just make sure you don’t summon a syntax error. </strong>🧙‍♂️✨</blockquote><h3>STEPS TO SOLVE CASE STUDY</h3><ol><li><strong>Understand the Requirements</strong>: Break down what each function needs to do.</li><li><strong>Design the Functions</strong>: Plan the structure of your functions — what parameters they will take and what they will return.</li><li><strong>Implement the Functions</strong>: Write the code for each function.</li><li><strong>Test the Functions</strong>: Run your functions with various inputs to ensure they work as expected.</li></ol><h3>CASE STUDY</h3><p>Let’s use a case study that will help us practice our Function skills and build a grreeaat logical and problem-solving abilities. We will working on 3 case study that has different difficulties levels ( Easy — Medium — Hard)</p><h4>Case Study 1 — Easy | Simple Temperature Converter</h4><p>We are building a basic temperature converter that converts temperatures between Celsius and Fahrenheit. The function should take an input temperature in either Celsius (<strong>℃</strong>) or Fahrenheit (<strong>℉</strong>) and convert it to the other unit.</p><h4>Task:</h4><p>Create a function called convert_temp that takes two parameters:</p><ul><li>temp: The temperature value, we will use <strong>float type</strong> because we need a data type that can work on decimal number and can represent fractional values.</li><li>unit: The unit of the temperature as a string (&#39;C&#39; for Celsius or &#39;F&#39; for Fahrenheit).</li></ul><pre># Function<br>def convert_temp(temp, unit):<br>  if unit.upper() == &#39;C&#39;:<br>    return (temp * 9/5) + 32  # C to F<br>  if unit.upper() == &#39;F&#39;:<br>    return (temp - 32) * 5/9  # F to C<br>  else:<br>    return &#39;Wrongy-wrongy, please put the correct unit! C or F&#39;</pre><p>The usage of .upper in unit.upper() mean, to automatically transform the input unit to Uppercase, just in case we forgot to write it in uppercase letter.</p><p>Aside from the calculation, we also need to put the else: condition to prevent error, because nobody like it! Better to have an else return than an error statement.</p><h4>Case Study 2 — Medium| Grade Calculator</h4><p>We want to create a function to calculate the final grade for a student based on their scores across different assessments. The grades are based on the following categories:</p><ul><li>Assignments: 40%</li><li>Midterm Exam: 30%</li><li>Final Exam: 30%</li></ul><p>The function should calculate the weighted average of the grades and determine the final grade based on the following scale:</p><ul><li>A: 90-100</li><li>B: 80-89</li><li>C: 70-79</li><li>D: 60-69</li><li>F: Below 60</li></ul><p>Create a function called grade_calc that takes three parameters, and return the final letter grade:</p><ul><li>assignments: The average score of assignments (float).</li><li>midterm: The score of the midterm exam (float).</li><li>final_exam: The score of the final exam (float).</li></ul><pre># Function<br>def grade_calc(assignments, midterm, final):<br>  grade = (assignments * 0.4) + (midterm * 0.3) + (final * 0.3)<br><br>  if grade &gt;= 90:<br>    return &#39;A&#39;<br>  elif grade &gt;= 80 and grade &lt; 90:<br>    return &#39;B&#39;<br>  elif grade &gt;= 70 and grade &lt; 80:<br>    return &#39;C&#39;<br>  elif grade &gt;= 60 and grade &lt; 70:<br>    return &#39;D&#39;<br>  else:<br>    return &#39;F&#39;<br><br># Calling the function<br>grade_calc(50, 70, 45)<br><br># Result<br>&#39;F&#39;</pre><p>Easy right? Well, not for the student, they need to study harder!</p><h4>Case Study 3 — Hard| <strong>Online Bookstore System</strong></h4><p>Let’s develop a simple system for an online bookstore. We need to manage its inventory of books, and handling customer orders. We will perform all the task with <strong>FUNCTION </strong>🎉 !</p><p><strong>1. Manage Inventory</strong></p><p>Create a function called add_book that adds a book to the inventory. The function should take the following parameters:</p><ul><li>title: The title of the book (string).</li><li>author: The author of the book (string).</li><li>price: The price of the book (float).</li><li>quantity: The number of copies available (integer).</li></ul><p>The function should store this information in a list of <strong>dictionaries </strong>📚.</p><p>In Python, a <strong>dictionary </strong>is a built-in data type that allows us to store and manage data in key-value pairs. It’s similar to a real-life dictionary where we look up a word (key) to find its definition (value). Dictionaries are mutable, meaning we can change their content after they are created.</p><pre># Dictionary for Inventory<br>inventory = []<br><br># Function<br>def add_book(title, author, price, quantity):<br>  book = {<br>          &#39;title&#39; : title,<br>          &#39;author&#39; : author,<br>          &#39;price&#39; : price,<br>          &#39;quantity&#39; : quantity<br>      }<br><br>  inventory.append(book)<br><br># Calling the Function<br>add_book(&#39;Hello!&#39;, &#39;Laksmi&#39;, 50000, 100)<br><br># Check the Dictionary<br>print(inventory)<br>[{&#39;title&#39;: &#39;Hello!&#39;, &#39;author&#39;: &#39;Laksmi&#39;, &#39;price&#39;: 50000, &#39;quantity&#39;: 100}]</pre><p><strong>2. Process Order</strong></p><p>Create a function called order that processes a customer order. The function should check if the book is in the inventory and if there’s enough stock. If the order can be fulfilled, it should reduce the quantity in the inventory and calculate the total price. If not, it should return a message indicating that the order cannot be fulfilled.</p><p>The function should take the following parameters:</p><ul><li>title: The title of the book (string).</li><li>quantity: The number of copies the customer wants to buy (integer).</li></ul><pre># Function<br>def order(title, quantity):<br>  for book in inventory:<br>    if book[&#39;title&#39;] == title:<br>      if int(book[&#39;quantity&#39;]) &gt;= quantity:<br>        book[&#39;quantity&#39;] -= quantity<br>        cost = book[&#39;price&#39;] * quantity<br>        return &#39;Success! 👍 it costs you &#39; + str(cost)<br>      else:<br>        return &#39;Not enough &#39; + title + &#39; books for you 😔&#39;<br>  return &#39;We don\&#39;t have this &#39; + title + &#39; book, sorry! 🙁&#39;<br><br># Calling the Function<br>order(&#39;Hello!&#39;, 99)<br>&#39;Success! 👍 it costs you 4950000&#39;<br><br># Let&#39;s try calling it again<br>order(&#39;Hello!&#39;, 11)<br>&#39;Not enough Hello! books for you 😔&#39;<br><br># Let&#39;s try looking out for different book title<br>order(&#39;Love&#39;, 11)<br>We dont have this Love book, sorry! 🙁</pre><p>That’s it, we reach the end of the line! Apart from all this case studies, function actually can also be used for data cleaning and manipulation in Exploratory Data Analysis. We will talk about it later in other article !</p><p>Hopefully with this article, we can improve our Python skills way much more!</p><p>I eagerly wait for any input or opinion regarding this project, don’t hesitate to contact me via <strong>email</strong> | <strong>amalia.wulandiari@gmail.com</strong>, or just visit my <a href="https://www.linkedin.com/in/laksmiamalia/"><strong>LinkedIn</strong></a> profile!</p><p>Thank you so much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3340fdb8f58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CLUSTERING CLUTTERED GAMES ️| Python | K-Mean Clustering]]></title>
            <link>https://medium.com/@amalia.wulandiari/clustering-cluttered-games-%EF%B8%8F-python-k-mean-clustering-77a7802513e7?source=rss-59685185473a------2</link>
            <guid isPermaLink="false">https://medium.com/p/77a7802513e7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[kmeans-clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[segmentation]]></category>
            <dc:creator><![CDATA[Laksmi Amalia Wulandiari]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 17:26:35 GMT</pubDate>
            <atom:updated>2024-08-10T17:26:35.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Based on #kaching! 💸💸</h3><p>Hi everyone!</p><p>In this post, I want to share my project of <strong>Clustering the Games, based on their Sales Performance Regionally</strong> (North America, Europe, Japan, and other market) and Globally 🗺️. I’m using <strong>K-Means clustering</strong>, and before the modeling, I conducted <strong>Exploratory Data Analysis (EDA) </strong>to clean, and dig deep to understand and extract perfect insights.</p><p><strong>Clustering</strong> is a technique in data analysis and machine learning used to group a set of objects or data points in such a way that objects in the same group (<strong>called a cluster</strong>) are more similar to each other, share common traits or characteristics, than to those in other groups. The goal of clustering is to identify <strong>patterns</strong>, <strong>trends</strong>, or <strong>structures </strong>within the data by organizing it into meaningful subgroups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*lK0bN1IYHA5Hikh-DTz0Wg.png" /></figure><p><strong>Clustering </strong>is often used in unsupervised learning where there are no predefined labels or categories. Additionally, it can be widely used in various fields, including customer segmentation, image recognition, market research, and etc.</p><p>In essence, clustering helps in simplifying complex datasets by grouping similar data points together, making it easier to analyze and derive insights.</p><blockquote><strong>It’s like when you put all the weirdos in one corner of the room and suddenly, they start to make sense.</strong></blockquote><blockquote><em>The Office</em>, Season 4, Episode 13 (“Dinner Party”)</blockquote><h4>Let’s understand the dataset first</h4><p>In ths project, I’m using <strong>video games sales</strong> dataset from <strong>Kaggle </strong>called <a href="https://www.kaggle.com/datasets/gregorut/videogamesales/code"><strong>vgsales</strong></a>. The dataset contain <strong>16.500 games</strong> that generated <strong>100.000 copies</strong> of sales, from multiple platform. It has eleven (11) columns:</p><p>🏆 <strong>Rank </strong>: Ranking of overall sales<br>🤖 <strong>Name </strong>: The games name<br>📱 <strong>Platform </strong>: Platform of the games release (i.e. PC,PS4, etc.)<br>📅 <strong>Year </strong>: Year of the game’s release<br>🏵️ <strong>Genre </strong>: Genre of the game<br>🕹️ <strong>Publisher </strong>: Publisher of the game<br>💰 <strong>NA_Sales </strong>: Sales in North America (in millions)<br>💰 <strong>EU_Sales </strong>: Sales in Europe (in millions)<br>💰 <strong>JP_Sales </strong>: Sales in Japan (in millions)<br>💰 <strong>Other_Sales </strong>: Sales in Other Region (in millions)<br>💰 <strong>Global_Sales </strong>: Sales Globally (in millions)</p><h4>Library used</h4><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><p><strong>Explanation for each library :</strong></p><p><strong>Pandas</strong> is a powerful data manipulation and analysis library allow us to work with structured data easily (<strong>cleaning</strong>, <strong>manipulation</strong>, and <strong>analysis</strong>). It can be used to read data from various file formats like CSV, Excel, JSON, etc.</p><p><strong>NumPy </strong>is the fundamental package for numerical computing in Python. It provides support for large multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.</p><p><strong>Matplotlib </strong>is a plotting library for creating static, animated, and interactive visualizations in Python. It is highly customizable and is often used for generating plots and charts.</p><p><strong>Seaborn </strong>is built on top of Matplotlib and provides a high-level interface for drawing attractive and informative statistical graphics. It simplifies the creation of complex plots with less code.</p><h4>Data Cleaning</h4><pre># Check the dataset<br><br>games.info()<br><br> #   Column        Non-Null Count  Dtype  <br>---  ------        --------------  -----  <br> 0   Rank          16598 non-null  int64  <br> 1   Name          16598 non-null  object <br> 2   Platform      16598 non-null  object <br> 3   Year          16327 non-null  float64<br> 4   Genre         16598 non-null  object <br> 5   Publisher     16540 non-null  object <br> 6   NA_Sales      16598 non-null  float64<br> 7   EU_Sales      16598 non-null  float64<br> 8   JP_Sales      16598 non-null  float64<br> 9   Other_Sales   16598 non-null  float64<br> 10  Global_Sales  16598 non-null  float64</pre><pre># Check if there any duplicated values<br><br>games.duplicated().sum()<br><br>0</pre><pre># Count null values<br><br>games.isna().sum()<br><br>Rank 0<br>Name 0<br>Platform 0<br>Year 271<br>Genre 0<br>Publisher 58<br>NA_Sales 0<br>EU_Sales 0<br>JP_Sales 0<br>Other_Sales 0<br>Global_Sales 0</pre><p>Because there are no duplicated values in the dataset (YAY! 🌟), we can move on to handle the missing values. We have two columns that has missing values, <strong>Year </strong>and <strong>Publisher</strong>. To fill the missing value for <strong>Publisher</strong> we must identify the common publisher for each platform, so we can fill in based on the information. On the other hand, for <strong>Year</strong> we decide to drop the null values, since there are no valid parameter to help fill the null values,to avoid ambiguous result.</p><p>In the dataset, the <strong>Year </strong>column currently stored as a float, which displays values with a decimal point <strong>(e.g., 2008.0, 2009.0). </strong>Since the <strong>Year </strong>column represents years, it is more appropriate and cleaner to store these values as integers. The presence of <strong>.0</strong> is unnecessary and can be misleading, as years are inherently whole numbers without fractional components. So, we need to change it to <strong>Integer</strong>.</p><p>Filling in the missing values for <strong>Publisher </strong>:</p><pre># Fill in null values &#39;Publisher&#39;<br># Identify the most common publisher for each platform<br><br>most_publishers = games.groupby(&#39;Platform&#39;)[&#39;Publisher&#39;].agg(lambda x: x.mode().iloc[0] if not x.mode().empty else None)<br><br># Fill missing publisher values using this mapping<br><br>def fill_publisher(row):<br>    if pd.isnull(row[&#39;Publisher&#39;]):<br>        return most_publishers.get(row[&#39;Platform&#39;], row[&#39;Publisher&#39;])<br>    return row[&#39;Publisher&#39;]<br><br>games[&#39;Publisher&#39;] = games.apply(fill_publisher, axis=1)</pre><p>Drop the rows of <strong>Year</strong> that has null values :</p><pre># Drop rows where &#39;Year&#39; column has null values<br><br>games = games.dropna(subset=[&#39;Year&#39;])</pre><p>Change the data type of <strong>Year :</strong></p><pre>games[&#39;Year&#39;] = games[&#39;Year&#39;].astype(int)</pre><p>CORRELATION AND DESCRIPTIVE ANALYSIS</p><pre># Let&#39;s do Descriptive Statistics with the dataframe<br><br>games.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*hK5xHCQQBU0QUCV2Dg6gEQ.png" /></figure><p><strong>NA_Sales</strong> (<strong>North America)</strong> has a broad range with a highly right-skewed distribution. Many entries are low or zero, with a few extreme values driving the high standard deviation. <strong>EU_Sales</strong> (<strong>Europe</strong>) also shows a right-skewed distribution, with many zero or low values with high standard deviation. <strong>JP_Sales </strong>(<strong>Japan</strong>) follows a similar pattern to NA_Sales and EU_Sales, with many zero or very low values. <strong>Sales</strong> in <strong>North America</strong> has the highest number of sales among other region.</p><pre># correlation heatmap<br><br>numerical_games.corr()<br><br># Correlation Heatmap<br><br>correlation = numerical_games.corr()<br>sns.heatmap(correlation,<br>            annot=True,  # Annotate the cells with correlation coefficients<br>            fmt=&quot;.2f&quot;,   # Format the annotations to 2 decimal places<br>            cmap=&quot;coolwarm&quot;,  # Set the color map<br>            linewidths=0.5,  # Set the width of the lines that divide cells<br>            square=True)  # Make the cells square</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*lwZ6vWQohfvZI4nrCnjsNQ.png" /></figure><p>The <strong>Year</strong> variable shows very weak correlations with <strong>sales </strong>variables, indicating <strong>minimal impact of the year on sales figures</strong>. <strong>Global_Sales</strong> is very strongly positively correlated with all other <strong>sales </strong>variables and moderately negatively correlated with <strong>rank</strong>.</p><h4>Univariate Analysis</h4><pre># Number of Games on Each Platform<br><br># Set style for seaborn<br>sns.set(style=&quot;whitegrid&quot;)<br><br># Create a countplot for the &#39;Platform&#39; column<br>plt.figure(figsize=(15, 6))<br>platform_order = games[&#39;Platform&#39;].value_counts().index<br>ax = sns.countplot(y=games[&#39;Platform&#39;], order=platform_order, palette=&#39;viridis&#39;)<br><br># Add labels to each bar<br>for p in ax.patches:<br>    width = p.get_width()<br>    plt.text(width + 50, p.get_y() + p.get_height() / 2,<br>             f&#39;{int(width)}&#39;, ha=&#39;center&#39;, fontsize=10, va=&#39;center&#39;)<br><br>plt.title(&#39;Number of Games on Each Platform&#39;, fontsize=14)<br>plt.xlabel(&#39;Count&#39;, fontsize=10)<br>plt.ylabel(&#39;Platform&#39;, fontsize=10)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ADoNdIXc4rFZWaS2xx_Cw.png" /></figure><p>As we can see games disribution over the year dominated with <strong>GAMES published for Nintendo DS with 13,1%</strong>, followed by <strong>Playstation 2 with only 0.1% different at 13%</strong>, and in the third place is <strong>Playstation 3 with 8.0%</strong>. Upon analyzing the distribution of games across various platforms, it’s evident that <strong>older platforms</strong> have a <strong>higher number of game variants</strong> compared to <strong>newer platforms</strong>. Historically, game development was more concentrated on fewer platforms, leading to a higher concentration of games on these older systems.</p><pre># Univariate Analysis on &#39;Year&#39;<br><br>plt.figure(figsize=(15, 10))<br>ax = sns.histplot(games[&#39;Year&#39;], bins=30, kde=True)<br><br># Adding annotations<br>bin_edges = ax.patches[0].get_bbox().get_points()[:, 0]<br>for patch in ax.patches:<br>    height = patch.get_height()<br>    if height &gt; 0:<br>        plt.text(patch.get_x() + patch.get_width() / 2, height + 10,<br>                 f&#39;{int(height)}&#39;, ha=&#39;center&#39;, fontsize=10, va=&#39;bottom&#39;)<br><br>plt.title(&#39;Distribution of Release Years&#39;, fontsize=14)<br>plt.xlabel(&#39;Year&#39;, fontsize=10)<br>plt.ylabel(&#39;Frequency&#39;, fontsize=10)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TyiJxsjvXq1QSyIUsv47oQ.png" /></figure><p><strong>Year 2009</strong> was the peak of games distribution, with <strong>2859</strong> games, released at that year. Improvements in gaming technology and the rise of new gaming platforms.</p><p>Several major game franchises released new titles in 2009, driving up the number of game releases. Titles from popular franchises such as “Call of Duty: Modern Warfare 2”, “Assassin’s Creed II”, and “Uncharted 2: Among Thieves” were released, contributing to the high number of game launches.</p><p>The rise of digital distribution platforms, such as Steam and the PlayStation Network, made it easier for developers to release games and for consumers to purchase them. This shift reduced barriers to entry for game developers.</p><pre> # Univariate Analysis on &#39;Genre&#39;<br><br>plt.figure(figsize=(15, 6))<br>ax = sns.countplot(y=games[&#39;Genre&#39;], order=games[&#39;Genre&#39;].value_counts().index,<br>                   palette=&#39;magma&#39;)<br><br># Adding annotations with custom font size and color<br>for patch in ax.patches:<br>    width = patch.get_width()<br>    if width &gt; 0:<br>        plt.text(width + 5, patch.get_y() + patch.get_height() / 2,<br>                 f&#39;{int(width)}&#39;, ha=&#39;left&#39;, va=&#39;center&#39;, fontsize=10, color=&#39;purple&#39;)<br><br>plt.title(&#39;Number of Games in Each Genre&#39;, fontsize=14)<br>plt.xlabel(&#39;Count&#39;, fontsize=10)<br>plt.ylabel(&#39;Genre&#39;, fontsize=10)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZ5unmExX-DAIUfbA3yVJQ.png" /></figure><p>Overall, <strong>Action</strong> is the top game genre ever produced. Action games are known for their high engagement levels, offering dynamic gameplay and immediate feedback, which attract a large audience. The action genre encompasses a variety of subgenres such as shooters, fighting games, and adventure-action hybrids, catering to different player preferences.</p><p>The <strong>second most popular genre, is Sport</strong>, known for simulating real-life sports and appealing to sports enthusiasts. It attracts both sports fans and gamers, with popular franchises release new versions yearly, keeping the genre fresh and relevant.</p><p>Next we have <strong>‘Misc’</strong> and <strong>‘Role-Playing Games’</strong> encompasses a wide range of unique and innovative games that don’t fit into traditional genres, and focuses on deep and engaging narratives.</p><h4>Bivariate Analysis</h4><pre># Platform x Genre<br><br># Create a DataFrame with count values for dot plot<br>count_data = games.groupby([&#39;Platform&#39;, &#39;Genre&#39;]).size().reset_index(name=&#39;Count&#39;)<br><br>plt.figure(figsize=(12, 8))<br>sns.scatterplot(data=count_data, x=&#39;Platform&#39;, y=&#39;Genre&#39;, size=&#39;Count&#39;, hue=&#39;Count&#39;, palette=&#39;viridis&#39;, sizes=(50, 500))<br>plt.title(&#39;Counts of Games by Platform and Genre&#39;)<br>plt.xlabel(&#39;Platform&#39;)<br>plt.ylabel(&#39;Genre&#39;)<br>plt.legend(title=&#39;Count&#39;)<br>plt.xticks(rotation=45)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxpAxmnnp64AZJg36aeiOA.png" /></figure><p>Each platform has their own specialty, and a few of the games are multi-platform games, meaning that it can be played on different type of platform. Many games, especially those from major franchises, are developed to be played across multiple platforms, including Sony’s PlayStation consoles. Multi-platform games allow developers to reach a wider audience by ensuring that their titles are available on as many systems as possible. This trend is particularly evident in popular genres like sports and action, where games like FIFA and Call of Duty are released on various platforms simultaneously.</p><p>For Sony-based Platform (PS, PS2, PS3, PSP, and PS4) <strong>Sports</strong>, and <strong>Action </strong>are the most games available on platform. For Nintendo (DS, 3DS, Wii, and WiiU), They mostly cover <strong>all type of genres</strong>, especially <strong>Miscellanous </strong>and <strong>Action</strong>.</p><pre># Global Sales by Genre<br><br>plt.figure(figsize=(12, 8))<br>sns.stripplot(data=games, x=&#39;Genre&#39;, y=&#39;Global_Sales&#39;, jitter=True, palette=&#39;Set2&#39;)<br>plt.title(&#39;Global Sales Distribution by Genre&#39;)<br>plt.xlabel(&#39;Genre&#39;)<br>plt.ylabel(&#39;Global Sales (in millions)&#39;)<br>plt.xticks(rotation=45)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*H5RyRLdIZF5d_nCCuESK2w.png" /></figure><p>Based on sales, the best-selling genre was Sports, followed by Platform, Racing, and Role-Playing.</p><ol><li>Sports games lead the pack, often due to the annual release cycles of popular franchises like FIFA, Madden NFL, and NBA 2K. These games have a broad appeal, particularly in North America and Europe, where sports culture is deeply ingrained. The competitive nature and continuous updates with each new season help maintain strong sales year after year.</li><li>Platform Classic Appeal: Platform games, which involve guiding characters through obstacles to reach a goal, have been popular since the early days of gaming. Iconic franchises like Super Mario, Sonic the Hedgehog, and Crash Bandicoot have helped this genre maintain strong sales. The nostalgic factor and appeal to a wide demographic, from children to adults, contribute to its success.</li><li>Racing High-Speed Thrills: Racing games, led by franchises like Mario Kart, Gran Turismo, and Need for Speed, have a dedicated fan base. The thrill of high-speed competition, combined with realistic graphics and physics in some titles, keeps players coming back. Racing games often have a strong multiplayer component, further driving their popularity.</li><li>Role-Playing (RPG) Immersive Worlds: RPGs have captivated players with their deep storylines, character development, and immersive worlds. Franchises like Final Fantasy, The Elder Scrolls, and Pokémon have not only sold millions of copies but have also built long-lasting fan communities. RPGs often feature extensive gameplay hours, making them a great value proposition for players, which supports their strong sales.</li></ol><pre># Genre vs Top Publisher<br><br># Aggregate number of games per genre and publisher<br>genre_publisher_counts = games.groupby([&#39;Genre&#39;, &#39;Publisher&#39;]).size().reset_index(name=&#39;Count&#39;)<br><br># Get top N publishers<br>top_publishers = genre_publisher_counts[&#39;Publisher&#39;].value_counts().head(10).index<br>filtered_data = genre_publisher_counts[genre_publisher_counts[&#39;Publisher&#39;].isin(top_publishers)]<br><br># Create bubble plot<br>plt.figure(figsize=(14, 10))<br>scatter = plt.scatter(<br>    x=filtered_data[&#39;Publisher&#39;],<br>    y=filtered_data[&#39;Genre&#39;],<br>    s=filtered_data[&#39;Count&#39;] * 10,  # Scale size of the marker<br>    c=filtered_data[&#39;Count&#39;],       # Color by count<br>    cmap=&#39;viridis&#39;, alpha=0.7, edgecolors=&#39;w&#39;<br>)<br><br>plt.colorbar(scatter, label=&#39;Number of Games&#39;)<br>plt.title(&#39;Bubble Plot of Genres vs Top Publishers with Game Count&#39;)<br>plt.xlabel(&#39;Publisher&#39;)<br>plt.ylabel(&#39;Genre&#39;)<br>plt.xticks(rotation=90)<br>plt.yticks(rotation=0)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*rxgLn8uEx77e5omHA0aA9A.png" /></figure><p>For each publisher, has different focus on type of games they mostly released on different consoles. For example, Electronic Arts focussed on Sport genre games as well as Digital Entertainment. While CAPCOM mainly designed Action genre games.</p><h4>Multivariate Analysis</h4><pre># Sales Trend by Region and Globally<br><br># Convert &#39;Year&#39; to datetime<br>games[&#39;Year&#39;] = pd.to_datetime(games[&#39;Year&#39;], format=&#39;%Y&#39;)<br><br># Aggregate sales data by year<br>annual_sales = games.groupby(games[&#39;Year&#39;].dt.year).agg({<br>    &#39;NA_Sales&#39;: &#39;sum&#39;,<br>    &#39;EU_Sales&#39;: &#39;sum&#39;,<br>    &#39;JP_Sales&#39;: &#39;sum&#39;,<br>    &#39;Other_Sales&#39;: &#39;sum&#39;,<br>    &#39;Global_Sales&#39;: &#39;sum&#39;<br>})<br><br># Plot line chart<br>plt.figure(figsize=(14, 8))<br>plt.plot(annual_sales.index, annual_sales[&#39;NA_Sales&#39;], marker=&#39;o&#39;, label=&#39;NA Sales&#39;)<br>plt.plot(annual_sales.index, annual_sales[&#39;EU_Sales&#39;], marker=&#39;o&#39;, label=&#39;EU Sales&#39;)<br>plt.plot(annual_sales.index, annual_sales[&#39;JP_Sales&#39;], marker=&#39;o&#39;, label=&#39;JP Sales&#39;)<br>plt.plot(annual_sales.index, annual_sales[&#39;Other_Sales&#39;], marker=&#39;o&#39;, label=&#39;Other Sales&#39;)<br>plt.plot(annual_sales.index, annual_sales[&#39;Global_Sales&#39;], marker=&#39;o&#39;, linestyle=&#39;--&#39;, label=&#39;Global Sales&#39;)<br><br>plt.title(&#39;Annual Sales Trends by Region vs. Global Sales&#39;)<br>plt.xlabel(&#39;Year&#39;)<br>plt.ylabel(&#39;Sales (in millions)&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><p>Globally, peak sales was in 2008. By 2008, the seventh generation of gaming consoles, including the PlayStation 3, Xbox 360, and Nintendo Wii, had been widely adopted globally. These consoles brought significant advancements in graphics, online gaming, and gameplay experiences, attracting a large number of gamers. Gaming had expanded into new markets, including emerging economies, where access to gaming consoles and software was becoming more widespread. This global expansion further contributed to the overall sales peak. In 2012, the global video game industry was in a transition period between the seventh and eighth generations of consoles. Many consumers held off on purchasing new games or consoles, waiting for the next generation of hardware (Xbox One and PlayStation 4), leading to a temporary drop in sales.</p><h4>Multivariate Regression Model</h4><pre># Features and target variable<br><br>X = games[[&#39;NA_Sales&#39;, &#39;EU_Sales&#39;, &#39;JP_Sales&#39;, &#39;Other_Sales&#39;]]<br>y = games[&#39;Global_Sales&#39;]<br><br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error, r2_score<br><br># Split the data<br>X_train, X_test, y_train, y_test = train_test_split(X, y, <br>test_size=0.2, random_state=42)<br><br># Create the model<br>model = LinearRegression()<br><br># Train the model<br>model.fit(X_train, y_train)<br><br># Predict on the test set<br>y_pred = model.predict(X_test)<br><br># Evaluate the model<br>mse = mean_squared_error(y_test, y_pred)<br>r2 = r2_score(y_test, y_pred)<br><br>print(f&#39;Mean Squared Error: {mse}&#39;)<br>print(f&#39;R^2 Score: {r2}&#39;)<br><br>Mean Squared Error: 2.7154099641219024e-05<br>R^2 Score: 0.999993644506754</pre><pre># Coefficients<br>coefficients = model.coef_<br>features = X.columns<br><br>for feature, coef in zip(features, coefficients):<br>    print(f&#39;Feature: {feature}, Coefficient: {coef}&#39;)<br><br>Feature: NA_Sales, Coefficient: 0.9999454169004024<br>Feature: EU_Sales, Coefficient: 0.9998342205985951<br>Feature: JP_Sales, Coefficient: 1.0000740556504368<br>Feature: Other_Sales, Coefficient: 0.9993494002659005</pre><pre># Plot predictions vs actual values<br>plt.figure(figsize=(10, 6))<br>plt.scatter(y_test, y_pred, alpha=0.5)<br>plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], color=&#39;red&#39;, linestyle=&#39;--&#39;)<br>plt.xlabel(&#39;Actual Global Sales&#39;)<br>plt.ylabel(&#39;Predicted Global Sales&#39;)<br>plt.title(&#39;Actual vs Predicted Global Sales&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rF2Yb3RfnrJisy_86sF4nA.png" /></figure><p>As we can see, based on the chart, the <strong>predicted</strong> sales and <strong>actual</strong> sales follow the same pattern. This indicates that the model is effectively capturing the underlying trend in the data, suggesting that it is making accurate predictions. The alignment between predicted and actual sales patterns implies that the model’s forecasting ability is reliable for understanding future sales behavior.</p><h4>Modeling</h4><p><strong>K-means clustering</strong> is a popular algorithm used in unsupervised machine learning for partitioning a dataset into distinct groups or clusters. The goal is to divide the data into kkk clusters, where each data point belongs to the cluster with the nearest mean.</p><pre>from sklearn.preprocessing import StandardScaler<br>from sklearn.cluster import KMeans<br>from sklearn.decomposition import PCA<br><br># Convert categorical variables to numerical<br>games_encoded = pd.get_dummies(games, columns=[&#39;Genre&#39;, &#39;Platform&#39;], drop_first=True)<br><br># Scale the data<br>scaler = StandardScaler()<br>scaled_data = scaler.fit_transform(games_encoded.select_dtypes(include=[&#39;float64&#39;, &#39;int64&#39;]))<br><br># Choose the number of clusters using the Elbow method<br>sse = []<br>for k in range(1, 11):<br>    kmeans = KMeans(n_clusters=k, random_state=42)<br>    kmeans.fit(scaled_data)<br>    sse.append(kmeans.inertia_)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(range(1, 11), sse, marker=&#39;o&#39;)<br>plt.xlabel(&#39;Number of Clusters&#39;)<br>plt.ylabel(&#39;SSE&#39;)<br>plt.title(&#39;Elbow Method for Optimal Number of Clusters&#39;)<br>plt.show()<br><br># Perform KMeans clustering<br>optimal_k = 4  # Example: Choosing 4 clusters<br>kmeans = KMeans(n_clusters=optimal_k, random_state=42)<br>games_encoded[&#39;Cluster&#39;] = kmeans.fit_predict(scaled_data)<br><br># Perform PCA for visualization<br>pca = PCA(n_components=2)<br>principal_components = pca.fit_transform(scaled_data)<br>pca_df = pd.DataFrame(data=principal_components, columns=[&#39;PC1&#39;, &#39;PC2&#39;])<br>pca_df[&#39;Cluster&#39;] = games_encoded[&#39;Cluster&#39;]<br><br>plt.figure(figsize=(10, 6))<br>sns.scatterplot(x=&#39;PC1&#39;, y=&#39;PC2&#39;, hue=&#39;Cluster&#39;, data=pca_df, palette=&#39;viridis&#39;)<br>plt.title(&#39;Game Segments Based on Genre, Platform, and Sales&#39;)<br>plt.show()<br><br># Cluster Summary - Exclude non-numeric columns from aggregation<br>numeric_cols = games_encoded.select_dtypes(include=[&#39;float64&#39;, &#39;int64&#39;]).columns<br>cluster_summary = games_encoded.groupby(&#39;Cluster&#39;)[numeric_cols].mean()<br>print(cluster_summary)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cy4B1Kzu3RatooFLErIQpA.png" /></figure><pre>                 Rank   NA_Sales  EU_Sales  JP_Sales  Other_Sales  Global_Sales                 <br>Cluster                                                             <br>0        12000.305147   0.039620  0.016243  0.020743     0.004892   0.082056<br>1           15.000000  12.714444  6.887778  3.952593     2.449630  26.005926 <br>2         3931.719303   0.376344  0.195627  0.101022     0.064727   0.737654<br>3          252.451389   2.455116  1.712199  0.694190     0.547199   5.408403</pre><p><strong>Cluster 1</strong> stands out as the cluster with the most successful games globally, indicating these are likely the top-performing games across all regions, dominated with <strong>Platform</strong>, <strong>Role-Playing</strong>, and <strong>Sports</strong> genre, while <strong>Simulation</strong> genre was the lowest performance out of all genre.. Games in this cluster can be used as marketing standard, to help improve performance from the other clusters.</p><p><strong>Cluster 0</strong> contains games that perform poorly in all regions, possibly indicating niche or less popular genres or platforms, dominated with <strong>Action</strong>, <strong>Sports</strong>, and <strong>Adventure</strong> genre, while <strong>Platform</strong> genre has the lowest sale. Strategy for this cluster are consider whether these games need reworking, rebranding, or could be targeted to niche audiences better.</p><p><strong>Cluster 2</strong> and <strong>Cluster 3</strong> show varying degrees of regional success, with <strong>Cluster 3</strong> being moderately successful globally. Both of the cluster are dominated with <strong>Action</strong> genre. This cluster could be targeted for region-specific marketing strategies, as they show potential in certain regions.</p><p>That’s the end of the line, we reach the conclusion that based on the sales performance, we can segment the games into four different clusters, Cluster 0, Cluster 1, Cluster 2, Cluster 3. Each cluster has their own characteristic, and genre.</p><p>In case you wonder, where is your favorite game stand? Is it <strong>0,1,2,3</strong>? Relax I got you!</p><p>To make it easier for you to understand the clustering results (and find your games), I also create a simple app interface using <strong>Streamlit</strong>, that concluded the analysis and modeling. You can access the app <a href="https://game-clustering-app-4nhawjircc2rfp5vily7tu.streamlit.app/"><strong>here</strong></a>.</p><p>Thank you for reading my article! Hopefully, It can help new aspiring data scientist like me to write, learn and explore the data world.</p><p>I eagerly wait for any input or opinion regarding this project, don’t hesitate to contact me via <strong>email</strong> | <strong>amalia.wulandiari@gmail.com</strong>, or just visit my <a href="https://www.linkedin.com/in/laksmiamalia/"><strong>LinkedIn</strong></a> profile!</p><p>For full code, please visit my <a href="https://github.com/laksmiamalia/game-clustering-app"><strong>Github </strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a7802513e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Simple Dashboard Using PowerBI]]></title>
            <link>https://medium.com/@amalia.wulandiari/how-to-create-simple-dashboard-using-powerbi-565ae530178a?source=rss-59685185473a------2</link>
            <guid isPermaLink="false">https://medium.com/p/565ae530178a</guid>
            <category><![CDATA[reporting-dashboard]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[insights-and-data]]></category>
            <category><![CDATA[power-bi-tutorials]]></category>
            <dc:creator><![CDATA[Laksmi Amalia Wulandiari]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 20:17:23 GMT</pubDate>
            <atom:updated>2024-07-20T13:42:22.744Z</atom:updated>
            <content:encoded><![CDATA[<h4>No worries its beginner friendly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DvlXyNSU9oALAUIhf9F6Q.png" /></figure><p>Where do I start…</p><p>After a long break I would love to share another article with all of you ! Now I want to write about Microsoft Power BI, and I’m excited to share my <strong>beginner-friendly</strong>, simple reporting dashboard. Hopefully with this article, we all can elevate ourselves and be a <strong>grrreat</strong> <strong><em>insights-hunter</em></strong><em>.</em></p><blockquote>“Insight is the first condition of Art.” — <strong>George Henry Lewes</strong></blockquote><h4>What is Microsoft PowerBI ?</h4><p><strong>Microsoft Power BI</strong> is a business analytics tool developed by Microsoft. It provides interactive visualizations and business intelligence capabilities with an interface simple enough for end users to create their own reports and dashboards. Power BI is designed to connect to a wide range of data sources, transform raw data into meaningful insights, and present them in visually appealing formats.</p><p><a href="https://powerbi.microsoft.com/">source</a></p><p>For this project, I’m using a simple dataset generated by<strong> ChatGPT</strong>. Copy and paste this to your PowerBI, for practice ! <a href="https://bit.ly/TRAIN-POWERBI">Click here</a> for the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*8JOLS0_ue3_0UyOUmLu3Yg.png" /></figure><p><strong>Data Explanation:</strong></p><ul><li><strong>Transaction ID</strong>: Unique identifier for each transaction.</li><li><strong>Date</strong>: Date of the transaction. (yyyy-mm-dd)</li><li><strong>Product</strong>: Name of the product sold.</li><li><strong>Units Sold</strong>: Quantity of units sold for each product.</li><li><strong>Unit Price</strong>: Price per unit of the product.</li><li><strong>Cost per Unit</strong>: Cost incurred per unit.</li><li><strong>Revenue</strong>: Total revenue generated from the transaction (Units Sold * Unit Price).</li></ul><h4>Let’s get started !</h4><p><strong>STEP 1 | Gather your data</strong></p><p>Before we start examining, analyzing or even charting, we need to ensure that our data is clean and appropriate for analysis. Is common to clean and/or manipulate the data before we put it on the dashboard, to minimize the possibilities of extracting wrong insights ! <strong>(No, no, me no likey!)</strong></p><p>But, because our data is basically a ‘<em>practice data</em>’, and it already ‘<em>cleaned</em>’, we can proceed through next step without the need to clean or manipulate it. Perhaps we can exercise <strong>cleaning </strong>and <strong>manipulating </strong>in other time.</p><h4>STEP 2 | Load Data into Power BI</h4><p>Open <strong>PowerBI</strong>, and then select Get Data under Home menu, and select the data source, our data source (e.g. Excel, or Text/CSV). Follow the prompt and then don’t forget to connect and load our data to PowerBI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*y9qoWrNOrx195caaoOvuGA.png" /></figure><p>After succesfully load the data, we can transform it inside PowerBI, using <strong>Power Query Editor</strong>. We able to perform data transformation (renaming columns, and changing the data type).</p><p>For this case, we need to add Profit Column. How to add it?</p><p>Click <strong>Add Column</strong> - <strong>Custom Column</strong>, and then write the formula :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfpnwYKcu-mgA5GekEiPrg.png" /></figure><p>Click OK, and voila! We now have <strong>Profit Column</strong> !</p><h4>STEP 3 | Create Measures and Calculations</h4><p>Using modeling, we can create a new measure. A measure is a calculation used to analyze data within our dataset. Measures are created using <strong>DAX (Data Analysis Expressions)</strong> formulas and are often used to perform dynamic calculations on data that change based on the context of the report visualizations, such as the <strong>filters </strong>applied or the data selection.</p><p>Where to find it?</p><p>Click on <strong>Modeling </strong>and then choose <strong>New Measures</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*-rY514qE05I9lbmZi9bXPg.png" /></figure><p>Here are some example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*GDghP6mBMi5Pv8hFEKJ2Yw.png" /></figure><p>Above, we try to calculate <strong>Total Sales</strong> by summing up the <strong>Revenue Column</strong> from <strong>Train’s Table</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*49wVbJBjFE9ZGbkKLfNhFA.png" /></figure><p>Above, we try to calculate <strong>Profit</strong> by substracting total <strong>Revenue, from Revenue Column, </strong>with <strong>total Cost</strong>, from <strong>Cost per Unit Column, </strong>from <strong>Train’s Table</strong>.</p><p>Easy huh ! Just like playing with <strong>excel </strong>but in different universe !</p><p><strong>STEP 4 | Build Visualization — FINALLY</strong></p><p>In Microsoft PowerBI we can just click any visualization we want to put inside our reporting dashboard. There are various types of visualization we can use for our reporting dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*752aJ238NYNTXLJcRHYDUw.png" /></figure><p><strong>But remember!</strong> Not all chart can be used for all types of data. There are some data that works like magic with line chart, but not with pie chart. So, we need to understand clearly what type of visualization we can use for our data, to deliver an<strong> impeccable insights</strong> to our dashboard lover.</p><p><strong>Revenue and Profit</strong></p><p>First of all, we want to show total revenue and profit from our products. Because it is basically just a number, we can use <strong>CARD</strong>.</p><p>Choose card from<strong> Visualization Pane</strong>, and drag <strong>Revenue </strong>from <strong>Data Pane</strong> to <strong>Values field</strong>, below <strong>Visualization Options</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*yPMdRKJh_8hWwjZQjwk-1w.png" /></figure><p>Repeat the step for profit card, until we have this appears on our dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*FledFYXaCdkfN_GCxGRZEw.png" /></figure><p>Unappealing right? I know, but we just getting started, Let’s move on to the next visualization. We can beautify our dashboard later !</p><p><strong>Total Unit Sold</strong></p><p>Next, we want to display the quantity of each product sold. Here we will use bar chart. <strong>Why?</strong> A bar chart is effective for comparing discrete categories, such as different products. We can quickly identify which products are top sellers.</p><p>Try repeating the same step as revenue and profit card, but using bar chart. Don’t forget to add Product in the X-Axis, because we want to see total sales from each product, not overall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*n-9xW88LGoZr0QwGBTIigA.png" /></figure><blockquote>Fun Fact : PowerBI can suggest automatically what type of chart you can use for visualize certain dataset. Just thick the box of column name, and PowerBI will generate the best chart based on your data.</blockquote><p><strong>Revenue Over Time</strong></p><p>Okay, we need to know the revenue over time, not just total revenue like we just generate using card. We will be using <strong>Line Chart</strong>.</p><p>Why again ? A line chart is ideal for showing trends and changes over time across different time periods (<strong>days, months, years</strong>).</p><p>Repeat the same step, but now using Line Chart. Fill the X-Axis with date, and Y-Axis with Revenue. We can choose what type of date we want to use. Full format, or just monthly view or daily view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*9ornpk4yJcxTVZLHMzpaMQ.png" /></figure><p>What a sale…</p><p><strong>Profit by Product</strong></p><p>Okay, now we want to see how much profit made for each product, and compare it. We will use Pie Chart or Donut Chart.</p><p>Let me hear why ?</p><p>A pie chart is useful for showing proportions and percentages of a whole. We can easily compare the contribution of each product to the overall profit, identify which products are more profitable, or see the share of profit each product contributes.</p><p>Repeat the same step, but now using Pie or Donut Chart. I prefer Donut Chart than Pie Chart, because it looks more <em>cute?</em> hehe. Fill the X-Axis with Product, and Y-Axis with Profit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*WV2kVTomIzIvTO9wq6IGgQ.png" /></figure><p>I think we have all the visualizations we need ! Let’s beautify our dashboard.</p><h4>STEP 5 | Customize</h4><p>We can format our charts, from colors, labels, and titles. For color, Microsoft PowerBI have various built-in theme, that automatically change the whole design of your dashboard, just one click away.</p><p>Click <strong>View </strong>- <strong>Themes</strong>, there we can find many options provided by Microsoft PowerBI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*fFOwaXdlaOQDeeMAi1Emcg.png" /></figure><p>Choose one, and it will automatically change our dashboard ! No hassle !</p><p>We can change the titles, labels, and many more from Format visual menu, inside the Visualization Pane. Explore all the options, be creative !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*7-IqH3ihzEwo-iBbB_gtVA.png" /></figure><p>Here is my dashboard, I added the dashboard title, another Card that showed Total Unit Sold, and slicer to filter my dashboard either from date or product. Annd, as we can see, it’s a dark theme !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rq9YmLWrY6c0XbMEMKB8rg.png" /></figure><h4>STEP 6 | Finalize it !</h4><p>We can finalize it by saving our report. Yay us !</p><p>We can save it either locally or publicly share our report so the world able to see it. I usually save my dashboard locally, and create a github repository specifically for my dashboard projects.</p><p>You can visit my repository <a href="https://github.com/laksmiamalia/DASHBOARD">here</a>, it’s not much but I thrive to always learn and improving myself! There are always room to improve and growth, right?</p><p>Well, we reached the end of the line. Hopefully this article can be the starting line for you to design an insightful reporting dashboard !</p><p>Just small tips, when customizing the dashboard, make sure you don’t use different type of font, and format for each chart. Neatness is one of the key aspect to deliver a perfect message or insights from our dashboard. Maintain a consistent naming convention across our dashboard to ensure clarity and coherence.</p><p>Not everyone is coming from the same field as we are, so we need to create a dashboard that is insightful and user friendly for anyone who want to use it. And thankfully, Microsoft PowerBI is so helpful. There are still many other features that we haven’t discussed yet, but I think we already manage the first small step, building a reporting dashboard using PowerBI.</p><p>So what are you waiting for? Share your dashboard to me, I would LOVEE to see it. I eagerly wait for any input or opinion regarding this article, don’t hesitate to contact me via <strong>email</strong> | <strong>amalia.wulandiari@gmail.com</strong>, or just visit my <a href="https://www.linkedin.com/in/laksmiamalia/"><strong>LinkedIn</strong></a> profile!</p><p>Who know? You can design it better than I do !</p><p>CHEEERS !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=565ae530178a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bank Customer Churn Analysis| SQL — Python]]></title>
            <link>https://medium.com/@amalia.wulandiari/bank-customer-churn-analysis-sql-python-fa6e2324c245?source=rss-59685185473a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa6e2324c245</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[churn-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Laksmi Amalia Wulandiari]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 04:12:11 GMT</pubDate>
            <atom:updated>2023-07-13T04:12:11.936Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bank Customer Churn Analysis| SQL — Python</h3><p>Hi everyone!</p><p>In this article, I want to share one of my SQL project, analyzing the possibility of bank <strong>customer churn</strong> based on insights gathered from the datasets. Insights from personal info such as <strong>age</strong>, <strong>gender</strong>, <strong>income </strong>and <strong>demographic location</strong>, <strong>type of card</strong>, <strong>products</strong>, their <strong>credit score</strong> and <strong>how long</strong> the customer has been with the bank. It is advantageous for the bank to know how to retain customer loyalty, rather than looking out for another customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ou6_4HPH92ydQggMMscIuw.png" /></figure><p><strong>Customer attrition</strong>, also known as <strong>customer churn</strong>, <strong>customer turnover</strong>, or <strong>customer defection</strong>, is the loss of clients or customers. Companies often use it as one of their key business metrics, because recovered long-term customers can be worth much more to a company than newly recruited clients.</p><p>There are two types of churn, <strong>Voluntary Churn</strong> and <strong>Involuntary Churn</strong>. <strong>Voluntary churn</strong> occurs due to a <strong>decision by the customer</strong> to switch to another company or service provider, <strong>Involuntary churn</strong> occurs <strong>due to circumstances</strong> such as a customer’s relocation to a long-term care facility, death, or the relocation to a distant location.</p><p>For this project, we will concentrate on <strong>Voluntary Churn</strong>, because it can be occurs due to factors of the company-customer relationship which companies control, such as how billing interactions are handled or how after-sales help is provided.</p><p><a href="https://en.wikipedia.org/wiki/Customer_attrition"><strong>source</strong></a></p><h3>DATASET EXPLANATION</h3><p><a href="https://www.kaggle.com/datasets/radheshyamkollipara/bank-customer-churn">Bank Customer Churn</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*NtBsjNNDxR2JM2AiYEhW7Q.png" /></figure><p>We are using customer_churn_records table, which contain multiple columns, with <strong>customerid </strong>act as primary key of the table.</p><ol><li><strong>RowNumber</strong> : Corresponds to the record (row) number</li><li><strong>CustomerId</strong> : Customer’s id number</li><li><strong>Surname</strong> : Customer’s surname</li><li><strong>CreditScore</strong> : Prediction of customer credit behavior</li><li><strong>Geography</strong> : Customer’s location</li><li><strong>Gender</strong> : Customer’s gender information</li><li><strong>Age</strong> : Customer’s age information</li><li><strong>Tenure</strong> : Number of years the customer has been stay with the bank</li><li><strong>Balance</strong> : Customer’s balance information in their account</li><li><strong>NumOfProducts</strong> : Number of products that a customer has purchased</li><li><strong>HasCrCard</strong> : Whether or not a customer has a credit card</li><li><strong>IsActiveMember</strong> : Whether or not a customer is active</li><li><strong>EstimatedSalary</strong> : Customer’s estimated salary amount</li><li><strong>Exited</strong> : Whether or not the customer left the bank</li><li><strong>Complain</strong> : Whether customer has complaint or not</li><li><strong>Satisfaction Score</strong> : Customer satisfaction score against the bank</li><li><strong>Card Type</strong> : Type of card hold by the customer</li><li><strong>Points Earned</strong> : Points earned by the customer for using credit card</li></ol><pre># show column in table = customer_churn_records<br><br>q=&#39;&#39;&#39;<br>  <br>  SELECT * FROM customer_churn_records<br><br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkkTUpA9R5uGz_usTlXG4A.png" /></figure><h3>QUERY | CUSTOMER CHURN</h3><h4>Import Package</h4><pre>import psycopg2 # PostgreSQL database adapter<br>import pandas as pd # to analyze data<br>from sqlalchemy import create_engine # facilitates the communication between Python programs and databases</pre><p>First we count how many customer churned based on the <strong>exited </strong>column.</p><pre># count total customer that is churn/exited or not <br><br>q=&#39;&#39;&#39;<br>  <br>  WITH temp_churn AS(<br>    SELECT exited,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  COUNT(exited) as Total<br>  FROM temp_churn<br>  GROUP BY 1<br><br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*-SFy4guL1TmKPydDX2rAog.png" /></figure><p>From <strong>10.000 customers</strong>, almost<strong> 20% </strong>of it <strong>exited </strong>or <strong>churned </strong>from the Bank. Even though the number is not that big, but still, if we can’t figure the problem out now, it can grow even more.</p><p>Now let’s check the type of customer churn status based on multiple aspects, from <strong>isactivemember</strong>, <strong>gender</strong>, <strong>demographic</strong>, <strong>age</strong>, <strong>temp_tenure</strong>, <strong>creditscore</strong>, <strong>numofproducts</strong>, <strong>satisfaction_score</strong>, <strong>complain</strong>, <strong>hascrcard</strong>, <strong>card_type</strong>, <strong>point_earned</strong>, <strong>estimatedsalary</strong>, and <strong>balance</strong>.</p><pre># count how many active customer that churn<br><br>q=&#39;&#39;&#39; <br><br>  WITH temp_isactivemember AS(<br>    SELECT exited,<br>    CASE <br>       WHEN isactivemember = 1 THEN &#39;Active&#39;<br>       ELSE &#39;Not Active&#39;<br>    END AS isactivemember<br>    from customer_churn_records<br>    )<br>  <br>  SELECT isactivemember,<br>  COUNT (CASE WHEN exited = 1 THEN 1 END) AS Churn,<br>  COUNT (CASE WHEN exited = 0 THEN 1 END) AS Not_Churn<br>  FROM temp_isactivemember<br>  GROUP BY 1<br><br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*OwPOmP4C7qR9dnZuW7dy1Q.png" /></figure><pre># count total customer that is churn/exited or not based on their gender<br><br>q=&#39;&#39;&#39;<br>  <br>  SELECT gender,<br>  COUNT(gender) as Total,<br>  COUNT(case when exited = 1 then 1 end) as Churn,<br>  COUNT(case when exited = 0 then 1 end) as Not_churn<br>  FROM customer_churn_records<br>  GROUP BY 1<br><br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*2kq885c3J7T0Wy2ODJuctQ.png" /></figure><pre># count how many customer that churn based on their demographic<br><br>q=&#39;&#39;&#39; <br><br>  SELECT geography,<br>  COUNT (CASE WHEN exited = 1 THEN 1 END) AS Churn,<br>  COUNT (CASE WHEN exited = 0 THEN 1 END) AS Not_Churn<br>  FROM customer_churn_records<br>  GROUP BY 1<br><br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*tbLD3YB9Qyr4TsBxuqe44w.png" /></figure><pre># count how many customer that churn based on their group age<br><br>q=&#39;&#39;&#39; <br><br>    SELECT <br>    CASE <br>        WHEN age &lt;= 20 THEN &#39;Group &lt;= 20&#39;<br>        WHEN age &gt;= 21 AND age &lt;= 40 THEN &#39;Group 21-40&#39;<br>        WHEN age &gt;= 41 AND age &lt;= 60 THEN &#39;Group 41-60&#39;<br>        ELSE &#39;Group &gt; 60&#39;<br>    END AS age_category,<br>    COUNT(CASE WHEN exited = 1 then 1 end) as Churn,<br>    COUNT(CASE WHEN exited = 0 then 1 end) as Not_Churn<br>    FROM customer_churn_records<br>    GROUP BY 1<br>    ORDER BY 1<br><br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*EP2cWw0oEoKZ8dqnEPPKXQ.png" /></figure><pre># count total customer that is churn/exited or not based on how long <br># they&#39;ve been as customer<br><br>q=&#39;&#39;&#39;<br>  <br>  WITH temp_tenure AS(<br>    SELECT tenure,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  AVG(tenure) as Average_tenure<br>  FROM temp_tenure<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*gzZMInIRyW24kk3L_CvTbg.png" /></figure><pre># count how many customer that churn based on the amount of credit score <br># (average, highest and lowest)<br><br>q=&#39;&#39;&#39;<br><br>   WITH temp_creditscore AS(<br>    SELECT creditscore,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  AVG(creditscore) as avg_creditscore,<br>  MAX(creditscore) as max_creditscore,<br>  MIN(creditscore) as min_creditscore<br>  FROM temp_creditscore<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*2jkALiz-djlr4tCPGK6HEg.png" /></figure><pre># count how many customer that churn based on how many bank product they use<br><br>q=&#39;&#39;&#39;<br><br>   WITH temp_bankprod AS(<br>    SELECT numofproducts,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  AVG(numofproducts) as avg_numofproducts<br>  FROM temp_bankprod<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*xswkQdmUXrZIhoeyCgarSw.png" /></figure><pre># count how many customer that churn based on the average score of customer <br># satisfaction score towards the bank<br><br>q=&#39;&#39;&#39;<br><br>   WITH temp_satisfaction AS(<br>    SELECT satisfaction_score,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  AVG(satisfaction_score) as satisfaction_level<br>  FROM temp_satisfaction<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*ctQCrV82Xx0NfVkKy-V9qg.png" /></figure><pre># count how many customer that churn based on the amount of complain filed by customer<br><br>q=&#39;&#39;&#39;<br><br>   WITH temp_complain AS(<br>    SELECT complain,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  COUNT(complain) as complain<br>  FROM temp_complain<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*L_xsyEpQH-x9xTAQhHZZqg.png" /></figure><pre># count how many customer that churn based on credit card ownership<br><br>q=&#39;&#39;&#39; <br><br>    WITH temp_hascrcard AS(<br>    SELECT hascrcard,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  COUNT (CASE WHEN hascrcard = 1 THEN 1 END) AS has_creditcard,<br>  COUNT (CASE WHEN hascrcard = 0 THEN 1 END) AS no_creditcard<br>  FROM temp_hascrcard<br>  GROUP BY 1<br><br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*6kQGHT0q8gazsXDkC_ZWsA.png" /></figure><pre># count how many customer that churn based on the their card type<br><br>q=&#39;&#39;&#39;<br><br>   WITH temp_card AS(<br>    SELECT card_type,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  COUNT(CASE WHEN card_type = &#39;PLATINUM&#39; THEN 1 END) as PLATINUM,<br>  COUNT(CASE WHEN card_type = &#39;DIAMOND&#39; THEN 1 END) as DIAMOND,<br>  COUNT(CASE WHEN card_type = &#39;GOLD&#39; THEN 1 END) as GOLD,<br>  COUNT(CASE WHEN card_type = &#39;SILVER&#39; THEN 1 END) as SILVER<br>  FROM temp_card<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*hIwJlbMqCkOP_7Cl88UEJA.png" /></figure><pre># count how many customer that churn based on the amount of point customer earned<br><br>q=&#39;&#39;&#39;<br><br>   WITH temp_point AS(<br>    SELECT point_earned,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  AVG(point_earned) as avg_point,<br>  MAX(point_earned) as max_point,<br>  MIN(point_earned) as min_point<br>  FROM temp_point<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*7bBLqziHUUSkroKSsYyM2w.png" /></figure><pre># count how many customer that churn based on customer estimated salary<br><br>q=&#39;&#39;&#39;<br><br>   WITH temp_salary AS(<br>    SELECT estimatedsalary,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  AVG(estimatedsalary) as avg_salary,<br>  MAX(estimatedsalary) as max_salary,<br>  MIN(estimatedsalary) as min_salary<br>  FROM temp_salary<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*A3oZkI_XpLHlEiXbWF-Yjw.png" /></figure><pre># count how many customer that churn based on the amount of customer&#39;s bank balance<br># (average, highest, lowest)<br><br>q=&#39;&#39;&#39;<br><br>   WITH temp_balance AS(<br>    SELECT balance,<br>    CASE <br>       WHEN exited = 1 THEN &#39;Churn&#39;<br>       ELSE &#39;Not Churn&#39;<br>    END AS STATUS<br>    from customer_churn_records<br>    )<br>  <br>  SELECT STATUS,<br>  AVG(balance) as avg_balance,<br>  MAX(balance) as max_balance,<br>  MIN(balance) as min_balance<br>  FROM temp_balance<br>  GROUP BY 1<br>  <br>&#39;&#39;&#39;<br><br>df = pd.read_sql(q,engine_postgresql)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*fP5p4EmOK5nwMOWhF2cUUQ.png" /></figure><h3>CONCLUSION</h3><p>Based on above <strong>QUERY</strong>, there are some category that can help us identify what aspects that really affected customer to <strong>churn</strong>. It doesn’t matter how long the customer has stayed with the bank, they can still <strong>churn</strong>, or customer that has, let’s say, fairly amount of saving on their bank account, can still <strong>churn</strong>.</p><p>Customer in the age category between <strong>41 to 60</strong>, are more likely to churn than any other age category. To fix this problem, bank can focused on creating or enhancing their product and services that can help attract and maintain customer in certain age category, like smoother service with minimum queue time for older customer.</p><p>Customer who <strong>has credit card</strong> tends to not churn and stay with the bank. It probably best for the bank to convince more customer to apply for credit cards with various promotion, that depends on customer segmentation, which can be based on their <strong>type of card</strong> [ Diamond, Platinum, Gold, Silver ], <strong>gender</strong>, <strong>age</strong>, <strong>expenses</strong>, and <strong>demographic location</strong>.</p><p>Satisfaction score from customer who stay and churn is a <strong>little alarming [ 3.017960 / 2.997547 ]</strong>. Bank need to evaluate, to keep the satisfaction score between churn customer and customer who stay, at distance, and keep active customer which is less likely to churn.</p><p>Thank you for reading my article! Hopefully, It can help new aspiring data scientist like me to write, learn and explore the data world.</p><p>I eagerly wait for any input or opinion regarding this project, don’t hesitate to contact me via <strong>email</strong> | <strong>amalia.wulandiari@gmail.com</strong>, or just visit my <a href="https://www.linkedin.com/in/laksmiamalia/"><strong>LinkedIn</strong></a> profile!</p><p>For full code, please visit my <a href="https://github.com/laksmiamalia/SQL-Project"><strong>Github </strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa6e2324c245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SENTIMENT ANALYSIS | HOTEL REVIEW [Python-NLTK]]]></title>
            <link>https://medium.com/@amalia.wulandiari/sentiment-analysis-hotel-review-python-nltk-846738de727f?source=rss-59685185473a------2</link>
            <guid isPermaLink="false">https://medium.com/p/846738de727f</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Laksmi Amalia Wulandiari]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 14:33:59 GMT</pubDate>
            <atom:updated>2023-04-04T14:33:59.732Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I want to share my recent work. My first ever <strong>SENTIMENT ANALYSIS. </strong>Here I’m using <strong>Tripadvisor hotel review </strong>and for machine learning model, I’m using <strong>Random Forest </strong>and <strong>Logistic Regression</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*75QIGkBYRF6LgAeuzKKyNw.png" /><figcaption>fig. 1 Hotel Review Sentiment Analysis</figcaption></figure><h3>WHAT IS SENTIMENT ANALYSIS?</h3><p><a href="https://en.wikipedia.org/wiki/Sentiment_analysis">source</a></p><p><strong>Sentiment Analysis</strong> is the process of computationally identifying and categorizing opinions expressed in a piece of text, with the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information.</p><p>By using sentiment analysis, it can help understand customer needs and gather <strong>insights </strong>to help decide future marketing moves, and correctly identifying the problem.</p><blockquote><strong>Language is power, life and the instrument of culture, the instrument of domination and liberation</strong></blockquote><blockquote>Angela Carter</blockquote><p>How to read and translate customer reviews for analysis?</p><h3>NLTK — Natural Language Toolkit</h3><p><a href="https://www.nltk.org/">source</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*OPejJjdo5zLFCS9MAtE89Q.png" /><figcaption>fig.2 NLTK — Natural Language Toolkit</figcaption></figure><p><strong>NLTK</strong> is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning.</p><p>Natural Language Processing <a href="https://www.nltk.org/book/">with Python</a> provides a practical introduction to programming for language processing. It guides the reader through the fundamentals of writing Python programs, working with corpora, categorizing text, analyzing linguistic structure, and more.</p><h3>DATASET EXPLANATION</h3><p><a href="https://www.kaggle.com/datasets/thedevastator/tripadvisor-hotel-reviews">TripAdvisor Hotel Reviews</a></p><p>The dataset contains 3 columns, with 20.491 rows for each column :</p><ul><li><strong>S.No</strong> : Unique identifier for each review</li><li><strong>Review</strong> : Text of the review</li><li><strong>Rating</strong> : Rating of the review on a five-star scale</li></ul><h3>SENTIMENT ANALYSIS USING NLTK</h3><h4>Import Library</h4><p><strong>Install and import required libraries for the project.</strong></p><pre>import numpy as np # for array, linear algebra<br>import pandas as pd # for data processing<br>import matplotlib.pyplot as plt # to crreate stat and visualize data<br>import matplotlib as mpl  # to visualize data<br>import seaborn as sns # to visualize data<br>import matplotlib.colors as mcolors # to visualize colors<br>import string # collection of alphabets, words or other characters<br>import re # regular expression support<br>import gensim # representing documents as semantic vectors<br><br>!pip install nltk # package for NLP<br>import nltk <br><br>!pip install wordcloud # for wordcloud</pre><p><strong>Import NLTK packages.</strong></p><pre>from nltk import pos_tag # Part-of-Speech (POS) tagging<br>from nltk.stem import WordNetLemmatizer # lemmatize a word<br>from nltk.stem.porter import PorterStemmer # Information Retrieval<br>from nltk.tokenize import word_tokenize # splits sentence into words <br>from nltk.tokenize import WhitespaceTokenizer # splits on and discards only whitespace characters<br>from nltk.corpus import wordnet # large lexical database of English words<br>from nltk.sentiment.vader import SentimentIntensityAnalyzer # sentiment analyzer<br><br>nltk.download(&#39;stopwords&#39;)<br>nltk.download(&#39;averaged_perceptron_tagger&#39;)<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;omw-1.4&#39;)<br>nltk.download(&#39;vader_lexicon&#39;)</pre><p><strong>Import other package.</strong></p><pre>from matplotlib.cm import ScalarMappable # for colormap <br>from matplotlib.lines import Line2D # line segment in (x,y) coordinate space<br>from mpl_toolkits.axes_grid1.inset_locator import inset_axes # give our figure extra personalities<br>from textwrap import wrap # modifying the behavior of functions. <br>from wordcloud import WordCloud # to visualize text<br>from sklearn.feature_extraction.text import TfidfVectorizer # converts a collection of raw documents into a matrix<br>from gensim.test.utils import common_texts # training corpus<br>from gensim.models.doc2vec import Doc2Vec, TaggedDocument #  representing documents as a vector<br>from PIL import Image # import image<br><br># For Machine Learning Model<br>from sklearn import preprocessing # utility functions<br>from sklearn.impute import SimpleImputer # replace missing values<br>from sklearn.ensemble import RandomForestClassifier # learning algorithm Random Forest<br>from sklearn.linear_model import LogisticRegression # learning algorithm Logistic Regression<br>from sklearn.model_selection import train_test_split # create training and test data<br>from sklearn.metrics import accuracy_score, recall_score, confusion_matrix<br>from sklearn.metrics import roc_auc_score, recall_score<br>from sklearn import tree # for modeling<br>from sklearn.metrics import classification_report # for classification report</pre><h4>Load Dataset</h4><pre>df = pd.read_csv(&#39;TripAdvisor.csv&#39;, encoding = &#39;ISO-8859-1&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*i8ktFU5aYT9ycGe7O0NRVA.png" /></figure><pre>df.info()<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 20491 entries, 0 to 20490<br>Data columns (total 3 columns):<br> #   Column  Non-Null Count  Dtype <br>---  ------  --------------  ----- <br> 0   S.No.   20491 non-null  int64 <br> 1   Review  20491 non-null  object<br> 2   Rating  20491 non-null  int64 <br>dtypes: int64(2), object(1)<br>memory usage: 480.4+ KB</pre><h4>Data Pre-Processing</h4><p><strong>Data Cleaning &amp; Manipulation</strong></p><p>To ease up our analysis and modeling process and speed up computation time, let’s extract <strong>sample data</strong> from our dataset.</p><pre># Sample data<br><br>df = df.sample(frac = 0.1, replace = False, random_state=42)</pre><p>There is S.No. column that kind of <strong>redundant </strong>with <strong>index</strong>, so we need to <strong>drop </strong>it.</p><pre># drop unused column<br><br>df = df.drop([&#39;S.No.&#39;], axis = 1)</pre><p>Check any <strong>null </strong>and <strong>duplicated </strong>values.</p><pre># Count null values<br><br>df.isna().sum()<br>Review    0<br>Rating    0<br>dtype: int64</pre><pre># Check if there any duplicated values<br><br>df.duplicated().sum()<br>0</pre><p><strong>GREAT!</strong> <strong>No null </strong>and <strong>duplicated </strong>values in our dataset, so we can proceed for next step.</p><p>Let’s download stop words file.</p><p><a href="https://gist.github.com/ZohebAbai">source</a></p><pre># upload stopwords txt<br><br>gist_file = open(&quot;gist_stopwords.txt&quot;, &quot;r&quot;)<br>content = gist_file.read()<br>stopwords = content.split(&quot;,&quot;)<br>gist_file.close()</pre><p>Next, we need to clean up the <strong>review</strong> column:</p><ul><li>Create a function to help <strong>identify </strong>type of the words (adjective, verb, noun, adverb)</li><li>Remove ‘<strong>empty</strong>’ review and words with only 1 letter</li><li><strong>Lower </strong>all text</li><li><strong>Tokenize</strong> and <strong>split </strong>text to words</li><li>Remove <strong>numbers </strong>and <strong>stop words </strong>( ‘a’, ‘an’, ‘the’, ‘of’, ‘in’, etc.), to help <strong>improve accuracy </strong>to give more focus to the important information</li><li><strong>Part-of-Speech (POS) tagging</strong>: Categorizing words in a text (corpus) in correspondence with a particular part of speech, depending on the definition of the word and its context indicates how the word functions in meaning as well as grammatically within the sentence</li><li><strong>Lemmatize the text</strong>: transform every word into their root form (caring to care)</li></ul><pre># return the wordnet object value<br>def get_wordnet_pos(pos_tag):<br>    if pos_tag.startswith(&#39;J&#39;):<br>        return wordnet.ADJ<br>    elif pos_tag.startswith(&#39;V&#39;):<br>        return wordnet.VERB<br>    elif pos_tag.startswith(&#39;N&#39;):<br>        return wordnet.NOUN<br>    elif pos_tag.startswith(&#39;R&#39;):<br>        return wordnet.ADV<br>    else:<br>        return wordnet.NOUN<br><br>def clean_text(text):<br>    # remove \t<br>    text = text.replace(&#39;\t&#39;, &#39;&#39;)<br>    # lower text<br>    text = text.lower()<br>    # tokenize text and remove puncutation<br>    text = [word.strip(string.punctuation) for word in text.split(&quot; &quot;)]<br>    # remove words that contain numbers<br>    text = [word for word in text if not any(c.isdigit() for c in word)]<br>    # remove stop words<br>    text = [x for x in text if x not in stopwords]<br>    # remove empty tokens<br>    text = [t for t in text if len(t) &gt; 0]<br>    # pos tag text<br>    pos_tags = pos_tag(text)<br>    # lemmatize text<br>    text = [WordNetLemmatizer().lemmatize(t[0], get_wordnet_pos(t[1])) for t in pos_tags]<br>    # remove words with only one letter<br>    text = [t for t in text if len(t) &gt; 1]<br>    # join all<br>    text = &#39; &#39;.join(text)<br>    return(text)</pre><pre># Apply clean_text function<br><br>df[&#39;Clean_Review&#39;] = df[&#39;Review&#39;].apply(lambda x: clean_text(x))<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*RGQ8tMAmd9G7CO3LTOgTdw.png" /></figure><p>Add <strong>sentiment analysis </strong>column.</p><pre># add sentiment analysis<br><br>sid = SentimentIntensityAnalyzer()<br><br>df[&#39;Sentiments&#39;] = df[&#39;Review&#39;].apply(lambda x: sid.polarity_scores(x))<br>df = pd.concat([df.drop([&#39;Sentiments&#39;], axis=1), df[&#39;Sentiments&#39;].apply(pd.Series)], axis=1)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjg6CdgXJgJXxWy1yFJ03g.png" /></figure><p>Now let’s transform each <strong>text</strong> into <strong>numerical </strong>vectors.</p><pre># create doc2vec vector columns<br>documents = [TaggedDocument(doc, [i]) for i, doc in enumerate(df[&#39;Clean_Review&#39;].apply(lambda x: x.split(&#39; &#39;)))]<br><br># train a Doc2Vec model with our text data<br>model = Doc2Vec(documents, vector_size=5, window=2, min_count=1, workers=4)<br><br># transform each document into a vector data<br>doc2vec_df = df[&#39;Clean_Review&#39;].apply(lambda x: model.infer_vector(x.split(&quot; &quot;))).apply(pd.Series)<br>doc2vec_df.columns = [&#39;doc2vec_vector_&#39; + str(x) for x in doc2vec_df.columns]<br>df = pd.concat([df, doc2vec_df], axis=1)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQyW8z_KXvOO8N_aJZiU7Q.png" /></figure><p>Add the <strong>TF-IDF</strong> (<strong>Term Frequency — Inverse Document Frequency</strong>) values for every words to find out which word that has useful information for analysis.</p><p>The <strong>TF-IDF</strong> metric solves this problem:</p><ul><li><strong>TF </strong>computes the classic number of times the word appears in the text</li><li><strong>IDF </strong>computes the relative importance of this word which depends on how many texts the word can be found</li></ul><pre># add tf-idfs<br><br>tfidf = TfidfVectorizer(min_df = 10)<br>tfidf_result = tfidf.fit_transform(df[&#39;Clean_Review&#39;]).toarray()<br>tfidf_df = pd.DataFrame(tfidf_result, columns = tfidf.get_feature_names())<br>tfidf_df.columns = [&#39;word_&#39; + str(x) for x in tfidf_df.columns]<br>tfidf_df.index = df.index<br>df = pd.concat([df, tfidf_df], axis=1)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttX0G1mlYMFz_urX3Nn9_Q.png" /></figure><p>Create Positive and Negative review binary column. For this dataset, we categorize all 5-star review as a Good Review, while all review from 4-star to 1-star, we categorize it as Bad Review.</p><p><strong>WHY?</strong></p><p><strong>5-star</strong> review means that we providing <strong>good services </strong>or <strong>products </strong>to customers. Whilst for <strong>4-star</strong> review means customer or reviewer <strong>enjoyed </strong>our service<strong> but may point out some areas for improvement</strong>, so it is <strong>not a good thing</strong>. For 3-star to 1-star review, we can considered it as a bad review.</p><pre># create the positive and negative label column<br><br>df[&#39;posneg&#39;] = df[&#39;Rating&#39;].apply(lambda x: 0 if x &lt; 5 else 1)</pre><h4>Exploratory Data Analysis</h4><p><strong>Positive / Negative Reviews wordCloud</strong></p><pre># Calculate Positive and Negative Review<br><br>train_pos = df[ df[&#39;posneg&#39;] == 1]<br>train_pos = train_pos[&#39;Clean_Review&#39;]<br>train_neg = df[ df[&#39;posneg&#39;] == 0]<br>train_neg = train_neg[&#39;Clean_Review&#39;]</pre><pre># Generate WordCloud Function<br># using mask/shape = cloud<br><br>def wordCloud_generator(data, color, color_map):<br>    <br>    wave_mask = np.array(Image.open(&#39;cloud.png&#39;))<br>    <br>    wordcloud = WordCloud(width = 1000, height = 1000,<br>                          background_color =color,<br>                          min_font_size = 12,<br>                          colormap= color_map,<br>                          mask = wave_mask<br>                         ).generate(&#39; &#39;.join(data.values))<br>    <br>    # plot the WordCloud image                        <br>    plt.figure(figsize = (10, 10), facecolor = None) <br>    plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;) <br>    plt.axis(&#39;off&#39;)<br>    <br>    plt.show() </pre><pre># WordCloud for Positive Review<br><br>wordCloud_generator(train_pos, &#39;white&#39;, &#39;ocean&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*tYnSM1SvPTpEx9Fm3FYpcw.png" /><figcaption>fig.3 wordCloud for Positive Reviews</figcaption></figure><pre># Wordcloud for Negative Review<br><br>wordCloud_generator(train_neg, &#39;white&#39;, &#39;Reds&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Cw5TP7x3oaou-B9b7jbGPQ.png" /><figcaption>fig.4 wordCloud for Negative Reviews</figcaption></figure><p>Based on the fig. 3 and 4, there is only slight difference between <strong>Positive Reviews</strong> and <strong>Negative Reviews</strong>. Both review are dominated with words like hotel, room, stay, time. But, in <strong>Positive Reviews</strong> there are alsoother words, that much more positive and constructive, such as excellent, fantastic, beautiful, wonderful, and love. While <strong>Negative Reviews</strong> contains <strong>neutral </strong>to <strong>negative </strong>words, such as bad, problem, small, service, and leave.</p><p>It means that even though both <strong>Positive</strong> and <strong>Negative</strong> <strong>Reviews </strong>mostly consist the same words, but it has different meaning.</p><p><strong>Rating Proportion</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*Ye7qIeOUcr18J6E8qM-aWA.png" /><figcaption>fig.5 Barchart for Rating Proportion</figcaption></figure><p>Based on fig. 5, from <strong>1 </strong>to <strong>5-star</strong>, rating proportion is dominated with <strong>5-star</strong> review with almost surpassing <strong>1000 reviews</strong>. But if we look closely, total amount of <strong>1</strong> to <strong>4-star</strong> review, is still higher than <strong>5-star</strong> review.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*tThBHJrfyt_y7y1QVjaCHg.png" /><figcaption>fig.6 Positive and Negative Reviews Proportion</figcaption></figure><p><strong>Positive and Negative Reviews [Top 10]</strong></p><pre># Top 10 positive reviews<br><br>df[df[&#39;Words&#39;] &gt;= 5].sort_values(&#39;pos&#39;, <br>                                  ascending = False)[[&#39;Clean_Review&#39;, <br>                                                      &#39;pos&#39;]].head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*IXrVXy54oYecy3tpBLinEQ.png" /></figure><pre># Top 10 negative reviews<br><br>df[df[&#39;Words&#39;] &gt;= 5].sort_values(&#39;neg&#39;, <br>                                 ascending = False)[[&#39;Clean_Review&#39;, <br>                                                     &#39;neg&#39;]].head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*UK9QuaOJ8tIOCojMqpjAyg.png" /></figure><p>Obviously for <strong>Positive Reviews</strong>, the reviews dominated with words that show high customer satisfaction, such as great, excellent, fabulous, and adore. While for <strong>Negative Reviews,</strong> dominated with words that show low customer satisfaction, such as bad, horrify, awful, and disappointing.</p><p>Even though both <strong>Positive </strong>and <strong>Negative</strong> <strong>Reviews </strong>almost share the same words, but each word give <strong>different interpretation</strong>. Word like hotel, room, stay, time in positive reviews, indicated that customer felt happy, and delighted with it. While in Negative Reviews, the same words (hotel, room, stay, time ) indicated customer complain for it.</p><h3>MACHINE LEARNING MODELING</h3><h4>Data Pre-Processing</h4><pre># drop the Review and Clean_Review Column, because we won&#39;t use it<br><br>df = df.drop([&#39;Review&#39;, &#39;Clean_Review&#39;], axis = 1)</pre><pre># Split dataset<br><br>X = df.drop([&#39;posneg&#39;],axis = 1)<br>Y = df[&#39;posneg&#39;]</pre><h4>Random Forest</h4><p><a href="https://www.section.io/engineering-education/introduction-to-random-forest-in-machine-learning/#:~:text=Advantages%20of%20random%20forest,over%20the%20decision%20tree%20algorithm.">source</a>, <a href="https://www.ibm.com/id-en/topics/random-forest#:~:text=Random%20forest%20is%20a%20commonly,both%20classification%20and%20regression%20problems">source</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*NLxaCi2boN6swCqWzzx72w.png" /><figcaption>fig. 7 Random Forest</figcaption></figure><p><strong>Random forest</strong> is a commonly-used machine learning algorithm trademarked by <strong>Leo Breiman</strong> and <strong>Adele Cutler</strong>, which combines the output of multiple decision trees to reach a single result. Its ease of use and flexibility have fueled its adoption, as it handles both classification and regression problems.</p><p>Random Forest also can perform both <strong>regression</strong> and <strong>classification</strong> tasks. A random forest produces good predictions that can be understood easily. It can handle large datasets efficiently. The random forest algorithm provides a higher level of accuracy in predicting outcomes over the decision tree algorithm.</p><pre># split the dataset (train/test)<br><br>X_train_rf, X_test_rf, y_train_rf, y_test_rf = train_test_split(X, <br>                                                    Y, test_size=0.25, <br>                                                    random_state=42)</pre><pre># train the model<br><br>model = RandomForestClassifier(random_state=42)<br>model.fit(X_train_rf, y_train_rf)<br>preds = model.predict(X_test_rf)</pre><pre># print classification report<br><br>classification_decision1 = (classification_report(y_test_rf, <br>                                                  model.predict(X_test_rf)))<br>print(classification_decision1)<br><br>              precision    recall  f1-score   support<br><br>           0       0.99      1.00      0.99       288<br>           1       1.00      0.98      0.99       225<br><br>    accuracy                           0.99       513<br>   macro avg       0.99      0.99      0.99       513<br>weighted avg       0.99      0.99      0.99       513</pre><p><strong>Random Fores</strong>t modeling able to achieve <strong>97% </strong>precision for negative reviews, it means that <strong>97%</strong> negative reviews are correctly classified as negative reviews, while <strong>3%</strong> of negative reviews are classified incorrectly. For positive reviews, it achieved <strong>100%</strong>, it means that all positive reviews are classified as positive reviews and none of the positive reviews are classified incorrectly.</p><p>Recall value or True Positive Rate (TPR), predicted how much a machine learning model correctly identifies all relevant cases withing the dataset. In this case, our model able to predicted that <strong>100%</strong> from the dataset are True Positive for negative reviews, and <strong>96%</strong> from the dataset are True Positive for positive reviews.</p><p>F1-score value measures how many times the model made a correct prediction accurately. Our logistic regression model able to predict<strong> 99%</strong> correctly for negative reviews and <strong>98%</strong> correctly for positive reviews.</p><h4>Logistic Regression</h4><p><a href="https://www.techtarget.com/searchbusinessanalytics/definition/logistic-regression#:~:text=Logistic%20regression%20is%20a%20statistical,or%20more%20existing%20independent%20variables.">source</a>, <a href="https://www.researchgate.net/publication/353514662_Sentimental_Analysis_using_Logistic_Regression#:~:text=Sentiment%20analysis%20has%20emerged%20as,prediction%20of%20the%20data%20set.">source</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*7Eyys0pB3GPsHcsnRwOEzg.png" /><figcaption>fig. 8 Logistic Regression, <a href="https://en.wikipedia.org/wiki/Logistic_regression">source</a></figcaption></figure><p><strong>Logistic regression</strong> is a statistical analysis method to predict a binary outcome, such as yes or no, based on prior observations of a dataset. A logistic regression model predicts a dependent data variable by analyzing the relationship between one or more existing independent variables. Here we are using logistic regression for the effective accuracy and the prediction of the data set.</p><pre># split the dataset (train/test)<br><br>X_train_lr, X_test_lr,y_train_lr,y_test_lr = train_test_split(X,<br>                                                Y,<br>                                                test_size = 0.3,<br>                                                random_state = 42)</pre><pre># train the model<br><br>logreg = LogisticRegression(random_state=42)<br>logreg.fit(X_train_lr, y_train_lr)</pre><pre># print classification report<br><br>classification_decision2 = (classification_report(y_test_lr, <br>                                                  logreg.predict(X_test_lr)))<br>print(classification_decision2)<br><br>              precision    recall  f1-score   support<br><br>           0       1.00      1.00      1.00       350<br>           1       1.00      1.00      1.00       265<br><br>    accuracy                           1.00       615<br>   macro avg       1.00      1.00      1.00       615<br>weighted avg       1.00      1.00      1.00       615</pre><p><strong>Logistic Regression</strong> conclude a higher overall value than <strong>Random Forest</strong>, from precision, recall, and F1 score for positive and negative reviews.</p><p>Precision value equal to <strong>100%</strong> for <strong>0</strong>, means that all negative reviews are classified as negative reviews and none of the negative reviews are classified incorrectly. While precision value for positive reviews equal to <strong>0.99</strong>, it means that <strong>99%</strong> of positive reviews are classified as positive reviews and <strong>1%</strong> of the positive reviews are classified incorrectly.</p><p>Recall value or True Positive Rate (TPR), predicted how much a machine learning model correctly identifies all relevant cases withing the dataset. In this case, our model able to predicted that <strong>99%</strong> from the dataset are <strong>True Positive</strong> for negative reviews, and <strong>100%</strong> from the dataset are <strong>True Positive</strong> for positive reviews.</p><p>F1-score value measures how many times the model made a correct prediction accurately. Our logistic regression model able to predict <strong>100%</strong> correctly for negative reviews and <strong>99%</strong> correctly for positive reviews.</p><p>Thank you for reading my article! Hopefully, It can help new aspiring data scientist like me to write, learn and explore the data world.</p><p>For full code, please visit my Github :</p><p><a href="https://github.com/laksmiamalia/Hotel-Review-Sentiment-Analysis/blob/main/README.md">Hotel-Review-Sentiment-Analysis/README.md at main · laksmiamalia/Hotel-Review-Sentiment-Analysis</a></p><p>I eagerly wait for any input or opinion regarding this project, don’t hesitate to contact me via <strong>email</strong> | <strong>amalia.wulandiari@gmail.com</strong>, or just visit my <a href="https://www.linkedin.com/in/laksmiamalia/"><strong>LinkedIn</strong></a> profile!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=846738de727f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IKEA Product Analysis and Price Prediction Using Linear Regression]]></title>
            <link>https://medium.com/@amalia.wulandiari/ikea-product-analysis-and-price-prediction-using-linear-regression-644e52542f35?source=rss-59685185473a------2</link>
            <guid isPermaLink="false">https://medium.com/p/644e52542f35</guid>
            <category><![CDATA[ridge-regression]]></category>
            <category><![CDATA[linear-regression-python]]></category>
            <category><![CDATA[lasso-regression]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Laksmi Amalia Wulandiari]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 11:02:37 GMT</pubDate>
            <atom:updated>2023-03-01T15:57:24.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>[ RIDGE &amp; LASSO ]</h3><p>This is my first attempt writing an article about Exploratory Data Analysis [EDA] and Modeling with Linear Regression for <strong>IKEA Product Price Prediction</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*BbUyjoECwQGzKOSIU7gptQ.png" /><figcaption>fig. 1 IKEA Product Analysis and Price Prediction</figcaption></figure><p>IKEA is a furniture design company that specializes in the sale of flat-packed furniture, kitchen appliances, and other home accessories. IKEA is named after the initials of founder Ingvar Kamprad, Elmtaryd, the farm on which he grew up, and Agunnaryd, the nearby village.</p><p>IKEA has vision to create a better everyday life for the many people from their products. This vision goes beyond home furnishing, and to have a positive impact on the world — from the communities to help our customers live a more sustainable life at home.</p><p>IKEA constantly challenging themselves and others to make more from less without compromising on quality. Every day, everywhere, IKEA do their best to discover and eliminate unnecessary costs, because low prices are impossible without low costs.</p><p><a href="https://about.ikea.com/en">Get to know IKEA</a></p><p>Based on <strong>IKEA Financial Report</strong> from 2017–2022, there are some up and down on customer <strong>Website Visit. </strong>The numbers start arose in 2020 and peaked in 2021. But, in 2022, the number of customer who visit the website start to decline almost half million.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*oW-zJuoob-XwnG_TGIucXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*5V4yJu-IUE94y5WRnblHHA.png" /><figcaption>fig. 2–3 Net Income, Website Visit [ in million, 2017–2022 ]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*F1X1eoTziAdP-DDdhZKq_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*kxfOGSbt2_GHbRFfxen74g.png" /><figcaption>fig. 4–5 Sales of Goods and Cost of Good Sold, Operational Cost and Net Income [ in million, 2017–2022 ]</figcaption></figure><p>Eventhough in 2021, is the peak number of customer website visit, the <strong>Net Income</strong> is much lower than in 2020. Probably because in 2021 after some countries already recovered from <strong>COVID-19</strong>, customer prefer to shop offline than online. It showed in fig. 4, that there is an increase value of <strong>Sales of Goods</strong> in 2021.</p><p>The trend for <strong>Sales of Goods </strong>from 2017–2022 has the same pattern with <strong>Cost of Good Sold.</strong> But over the year the gap between two lines are getting closer, it means that there is an increase in <strong>Cost of Good Sold </strong>each year.</p><p><strong>IKEA Operational Cost </strong>is peaked in 2022. Because in 2022, <strong>IKEA </strong>grew in its number of co-workers during FY22, because <strong>IKEA</strong> expanding their business, by opening a few new offline store. The decline in <strong>IKEA Net Income</strong> particularly effected by the consequences of the war in Ukraine. <strong>IKEA </strong>decided to scaled down their store in Rusia and Belarus after nearly a four-month pause, that led to one-time costs in relation to writing down assets and provisioning of cost.</p><h3>DATASET EXPLANATION</h3><p><a href="https://www.kaggle.com/datasets/thedevastator/ikea-product">IKEA Products</a></p><p>The dataset contains 14 columns and 3694 rows of data.</p><ul><li><strong>item_id</strong> : Item identification number</li><li><strong>name </strong>: The name of the product</li><li><strong>category </strong>: The category of the product</li><li><strong>price </strong>: The price of the product [SR]</li><li><strong>old_price </strong>: The old price of the product [ No old price/ SR 995 / Other ]</li><li><strong>sellable_online </strong>: Whether or not the IKEA product is sellable online [True/False]</li><li><strong>link </strong>: A link to IKEA product [link]</li><li><strong>other_colors </strong>: Other colors that the IKEA product is available in [Yes/No]</li><li><strong>short_description </strong>: A short description of the IKEA product</li><li><strong>designer </strong>:<strong> </strong>The designer of the IKEA product</li><li><strong>depth </strong>: The depth of the IKEA product</li><li><strong>height </strong>: The height of the IKEA product</li><li><strong>width </strong>: The width of the IKEA product</li></ul><h3>PRODUCT ANALYSIS [ EDA ] AND PRODUCT PRICE PREDICTION USING LINEAR REGRESSION</h3><h4>Import Libraries</h4><p>Install / import required libraries for the project:</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from statsmodels.stats.power import TTestIndPower<br>import matplotlib as mpl<br><br>from matplotlib.cm import ScalarMappable<br>from matplotlib.lines import Line2D<br>from mpl_toolkits.axes_grid1.inset_locator import inset_axes<br>from textwrap import wrap<br>from pandas.plotting import parallel_coordinates</pre><h4>Load Dataset</h4><pre>df = pd.read_csv(&#39;ikea.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tcgXOYGR5Q9UraN_4q2zzQ.png" /></figure><pre>df.info()<br><br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 3694 entries, 0 to 3693<br>Data columns (total 14 columns):<br> #   Column             Non-Null Count  Dtype  <br>---  ------             --------------  -----  <br> 0   Unnamed: 0         3694 non-null   int64  <br> 1   item_id            3694 non-null   int64  <br> 2   name               3694 non-null   object <br> 3   category           3694 non-null   object <br> 4   price              3694 non-null   float64<br> 5   old_price          3694 non-null   object <br> 6   sellable_online    3694 non-null   bool   <br> 7   link               3694 non-null   object <br> 8   other_colors       3694 non-null   object <br> 9   short_description  3694 non-null   object <br> 10  designer           3694 non-null   object <br> 11  depth              2231 non-null   float64<br> 12  height             2706 non-null   float64<br> 13  width              3105 non-null   float64<br>dtypes: bool(1), float64(4), int64(2), object(7)<br>memory usage: 378.9+ KB</pre><h4>DATA PRE-PROCESSING</h4><p><strong>Data Cleaning &amp; Manipulation</strong></p><p>There is one column <strong>Unnamed: 0</strong> that doesn’t represent anything, kind of redundancy with the <strong>index</strong>, so we can drop it. We also need to check is there any null and duplicated values.</p><pre># drop unused column<br>df = df.drop([&#39;Unnamed: 0&#39;], axis = 1)</pre><pre># Count null values<br>df.isna().sum()<br><br>item_id                 0<br>name                    0<br>category                0<br>price                   0<br>old_price               0<br>sellable_online         0<br>link                    0<br>other_colors            0<br>short_description       0<br>designer                0<br>depth                1463<br>height                988<br>width                 589<br>dtype: int64</pre><pre># Check if there any duplicated values<br>df.duplicated().sum()<br><br>0</pre><p>As we can see there are no <strong>duplicated value </strong>in our data, and the <strong>null values</strong> come from the dimension columns with different amount of null. We can fill it in with <strong>average median</strong> value for each dimension from the same product category.</p><pre># Count the median value for depth for each categories<br>median_depth = df.groupby([&#39;category&#39;])[&#39;depth&#39;].median().reset_index()<br>median_depth.columns = [&#39;category&#39;, &#39;MedianDepth&#39;]<br><br># Count the median value for height for each categories<br>median_height = df.groupby([&#39;category&#39;])[&#39;height&#39;].median().reset_index()<br>median_height.columns = [&#39;category&#39;, &#39;MedianHeight&#39;]<br><br># Count the median value for width for each categories<br>median_width = df.groupby([&#39;category&#39;])[&#39;width&#39;].median().reset_index()<br>median_width.columns = [&#39;category&#39;, &#39;MedianWidth&#39;]<br><br># Create new dataframe that contain the median for each dimensions, from each categories<br>median_size = pd.merge(pd.merge(median_depth,median_height,on=&#39;category&#39;),<br>median_width,on=&#39;category&#39;)<br>median_size</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*_KYESp9jSDejPufQchr4ag.png" /></figure><pre># Merge the median dataframe with existing dataframe<br>df = pd.merge(df,median_size,on=&#39;category&#39;)<br><br># Fill the null values in each dimension column, <br># with the average median value<br>df[&#39;depth&#39;] = df[&#39;depth&#39;].fillna(df[&#39;MedianDepth&#39;])<br>df[&#39;height&#39;] = df[&#39;height&#39;].fillna(df[&#39;MedianHeight&#39;])<br>df[&#39;width&#39;] = df[&#39;width&#39;].fillna(df[&#39;MedianWidth&#39;])</pre><pre># Let&#39;s check it again!<br>df.isna().sum()<br><br>item_id              0<br>name                 0<br>category             0<br>price                0<br>old_price            0<br>sellable_online      0<br>link                 0<br>other_colors         0<br>short_description    0<br>designer             0<br>depth                0<br>height               0<br>width                0<br>MedianDepth          0<br>MedianHeight         0<br>MedianWidth          0<br>dtype: int64</pre><p>Now we don’t have any null values in our dimension columns, let’s drop the Median Column fromour dataframe.</p><pre># Drop the Median Columns<br>df.drop([&#39;MedianDepth&#39;, &#39;MedianHeight&#39;, &#39;MedianWidth&#39;], <br>        axis= &#39;columns&#39;, inplace = True)</pre><pre># create new column product volume [ D X H X W ]<br>df[&#39;volume&#39;] = df[&#39;depth&#39;] * df[&#39;height&#39;] * df[&#39;width&#39;]</pre><p>The old_price column has wrong datatype, let’s change it from <strong>object / string</strong> to <strong>float</strong>, so it can have the same data type as price , for our further analysis.</p><pre># Find out the value in old_price column<br>df[&#39;old_price&#39;].values</pre><p>There are 2 types of values from old_price column, <strong>No old price</strong> and the one that display product price with <strong>SR 0,000</strong>. If the row value = <strong>No old price</strong>, we can fill it with the price value with assumption that the product is a newly released so it won&#39;t have and old_price.</p><pre># Create the fix_old_price function<br>def fix_old_price(df):<br>    <br>    # fill in price to old_price for No old price<br>    if df[&#39;old_price&#39;]  == &#39;No old price&#39;:<br>        return df[&#39;price&#39;]<br><br>    # remove SR and , from old_price<br>    elif df[&#39;old_price&#39;][-4:] != &#39;pack&#39;:<br>        return float(str(df[&#39;old_price&#39;])[3:].replace(&#39;,&#39;,&#39;&#39;))<br>        <br>    else:<br>        return np.nan<br><br># create new column price_diff, to help identified is there any different <br># between price with old_price<br>df[&#39;price_diff&#39;] = (df[&#39;old_price&#39;] != &#39;No old price&#39;).astype(int)<br><br># apply the function<br>df[&#39;old_price&#39;] = df.apply(fix_old_price, axis=1)<br>df[[&#39;price&#39;, &#39;old_price&#39;]].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*9ScCQ_9hCsqfhp72Wwi6Og.png" /></figure><pre># Re-check for null values<br>df.isna().sum()<br><br>item_id               0<br>name                  0<br>category              0<br>price                 0<br>old_price            10<br>sellable_online       0<br>link                  0<br>other_colors          0<br>short_description     0<br>designer              0<br>depth                 0<br>height                0<br>width                 0<br>volume                0<br>price_diff            0<br>dtype: int64</pre><pre># Fill the old_price column with null values with price<br>df[&#39;old_price&#39;] = df[&#39;old_price&#39;].fillna(df[&#39;price&#39;])</pre><pre># Create column to calculate the different amount between price and old_price<br>df[&#39;diff_amount&#39;] = df[&#39;old_price&#39;] - df[&#39;price&#39;]</pre><pre># Check it again!<br>df.isna().sum()<br><br>item_id              0<br>name                 0<br>category             0<br>price                0<br>old_price            0<br>sellable_online      0<br>link                 0<br>other_colors         0<br>short_description    0<br>designer             0<br>depth                0<br>height               0<br>width                0<br>volume               0<br>price_diff           0<br>diff_amount          0<br>dtype: int64</pre><pre># Create correlation Heatmap<br>correlation = df.corr()<br>sns.heatmap(correlation, annot=True, fmt=&#39;.2f&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*Xq3N7hqPB3G2doLhlvK0WA.png" /><figcaption>fig. 6 Correlation Heatmap IKEA Dataset</figcaption></figure><p>price and old_price has higher correlation with width rather than two other dimension unit [ depth and height ], and both price and old_price are highly correlated with each others and obviously with price_diff.</p><p>From three types of product dimension, volume has highest correlation with width, followed with depth then height. volume also correlated with price and old_price</p><p>We will drop some column that can create <strong>multicolinearity</strong>, later for modelling purposes.</p><pre># Let&#39;s do Descriptive Statistics with the dataframe<br>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPH0NjLcRlBo3SDgEftkww.png" /></figure><h4>EXPLORATORY DATA ANALYSIS [EDA]</h4><p><strong>Distribution Plot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*E0jw4IFX773kRBJWQ-7h0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*lQBHAbXssSAWFYUFfelw7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*XNviTKtykoUXHziTc_zOpA.png" /><figcaption>fig. 7–9 Distribution Plot for Produc Dimension [ width, depth, height ]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*WN_uMtgs7Ev6LOGHkfI4Ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*vGaffPs7p_GnsnYAjX3p3A.png" /><figcaption>fig. 10–11 Distribution Plot for Product price and old_price</figcaption></figure><p>All distribution plot for product dimension and price [ fig. 7–11 ] are skewed to the right, which means the <strong>mean</strong> <strong>value </strong>is greater than the <strong>median value </strong>for each feature, and dominated with product with lower price, and smaller size.</p><p><strong>Most Produced Product Category</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*mhas3VfJd8EMbGmAa_GRCw.png" /><figcaption>fig. 12 Most Produced Product Categories</figcaption></figure><p>Based on fig. 12, IKEA mostly produced <strong>Table and Desks </strong>with more than 600 different products. Followed by <strong>Bookcases and Shelving Units</strong>, and then <strong>Chairs</strong>. The least product category produced by <strong>IKEA</strong> is <strong>Room Dividers</strong>, well probably because customers doesn’t need it as much as the <strong>TOP 3 Product Categories</strong>.</p><p><strong>Product Comparison on Price, Colors, and Online Availability</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*rZ6Tb39rBXhotuhbqURXtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*tKDurdRz4MfHf2J3Q3rHNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*DV0eYC9_UYjJBZB8pwfSWg.png" /><figcaption>fig. 13–15 Product Proportion on Price, Colors, and Online Availability</figcaption></figure><p>Product that has no price difference, or has no old_price, are much more than product that has price difference. It means, <strong>IKEA</strong> prefer to launch a new line of product to attract more customer and stay strong in such a competitive market.</p><p>Product that has other color options and product that only has one color, is almost has the same proportion. Most of <strong>IKEA </strong>products are available online.</p><p><strong>The Relationship Between Price with Old Price and Product Volume/Dimension</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*f6QVpuX_rgKRI8VEq2-paw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*zp_vShHBQBAe76V_NehlMQ.png" /><figcaption>fig. 16–17 Old Price vs Price, Volume vs Price</figcaption></figure><p>There are linear connection between price and old_price, the higher the price the value of old_price also increase. The dimension or volume of the products also affect the price. The bigger the product, the higher the price will be, like wardrobe, sofa, beds, table and desk.</p><p><strong>Color Options or Online Availability? Which One More Affected Product Price?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*l9r4L1wlxNMg5NojfZ11nQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*dsvIMXZHGQERuwQXbUrxEw.png" /><figcaption>fig. 18–19 Price vs Other Colors, Price vs Sellable Online</figcaption></figure><p>other_colors availability kind of affect the product price but not that much, eventhough, product with more than one color option, still has a chance of higher product price probability. Product that available online or sellable_online, also has higher product price probability than product that is not available online.</p><p>Almost all product in <strong>IKEA </strong>are available online, but the other colors availability of the product is not that much. Probably because <strong>IKEA </strong>more focused on functional home products at the lowest prices, so they tend to create as many as product types, and not the varieties of colors from one product.</p><h3><strong>PRICE PREDICTION WITH LINEAR REGRESSION</strong></h3><h4>What is Linear Regression?</h4><p><a href="https://linuxhint.com/house-price-prediction-linear-regression/">source</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*95BBtA2z98hhARy7opyrog.png" /><figcaption>fig. 20 Linear Regression</figcaption></figure><p><strong>Linear Regression</strong> is a supervised machine learning model that attempts to model a linear relationship between dependent variables (Y) and independent variables (X). Every evaluated observation with a model, the target (Y)’s actual value is compared to the target (Y)’s predicted value, and the major differences in these values are called residuals. The Linear Regression model aims to minimize the sum of all squared residuals.</p><p><strong>Model Evaluation</strong> :</p><p><strong>Mean Absolute Error [MAE]</strong> : mean of the absolute values of the individual prediction errors on over all instances in the test set</p><p><strong>Root Mean Square Error [RMSE] : </strong>The standard deviation of the residuals (prediction errors)</p><p><strong>Mean Absolute Percentage Error [MAPE] :</strong> is a measure of prediction accuracy of a forecasting method in statistics</p><h4>Data Pre-Processing</h4><p>Let’s prepare our dataset. We need to encoded the categoricals features or columns from our dataset.</p><pre># Encoding the df_categoricals, for modeling<br>from sklearn.preprocessing import LabelEncoder<br>col = list(df_categoricals)<br>df_categoricals[col] = df_categoricals[col].apply(LabelEncoder().fit_transform)</pre><pre># Create new dataframe, with encoded categoricals feature<br>df_update = pd.concat([df_categoricals, df_numericals], <br>axis=1, join=&#39;inner&#39;)<br><br>df_update.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBGtYiQcOokBx_O6qTev_g.png" /></figure><p>Before we start our modeling process, we need to see is there any <strong>multicolinearity</strong> with our target feature : price . We will calculate the <strong>VIF Score </strong>[<strong> Variance Inflation Factor </strong>] of the features or columns, to help us see is there any <strong>multicolinearity</strong>.</p><p>A <strong>Variance Inflation Factor</strong> is a tool to help identify the degree of multicollinearity. Multiple regression is used when a person wants to test the effect of multiple variables on a particular outcome. The dependent variable is the outcome that is being acted upon by the independent variables — the inputs into the model.</p><p><strong>Multicollinearity</strong> exists when there is a linear relationship, or correlation, between one or more of the independent variables or inputs. Multicollinearity creates a problem in the multiple regression model because the inputs are all influencing each other. [<a href="https://www.investopedia.com/terms/v/variance-inflation-factor.asp#:~:text=What%20Is%20VIF%20Used%20for,cause%20problems%20for%20regression%20models.">source</a>]</p><p>First, let’s drop some unused features : item_id , old_price</p><pre># drop unused column : item_id, link, short description, old_price<br>df_numericals = df_numericals.drop([&#39;item_id&#39;, &#39;old_price&#39;], axis = 1)<br></pre><p>Next, let’s split the dataset [20/80].</p><pre># split train test<br>from sklearn.model_selection import train_test_split<br><br>feature = df_update.drop(columns=&#39;price&#39;)<br>target = df_update[[&#39;price&#39;]]<br><br># First splitting: pretrain and test<br>feature_price_pretrain, feature_price_test, target_price_pretrain, <br>target_price_test = train_test_split(feature, <br>target, test_size=0.20, random_state=42)<br><br># Second splitting: train and validation<br>feature_price_train, feature_price_validation, target_price_train, <br>target_price_validation = train_test_split(feature_price_pretrain, <br>target_price_pretrain, test_size=0.20, random_state=42)</pre><pre># calculate VIF scores<br>from statsmodels.stats.outliers_influence import variance_inflation_factor as vif <br>from statsmodels.tools.tools import add_constant<br><br>X = add_constant(feature_price_train)<br><br>vif_df = pd.DataFrame([vif(X.values, i) <br>               for i in range(X.shape[1])], <br>              index=X.columns).reset_index()<br>vif_df.columns = [&#39;feature&#39;,&#39;vif_score&#39;]<br>vif_df = vif_df.loc[vif_df.feature!=&#39;const&#39;]<br>vif_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*i3OP81cGB_3796_L5oFAtg.png" /></figure><pre># heatmap correlation<br>price_train = pd.concat([feature_price_train, target_price_train], axis=1)<br>corr = price_train.corr()<br><br>plt.figure(figsize=(10,7))<br>sns.heatmap(corr, annot=True, fmt=&#39;.2f&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*YomxtQ6Ybc4bRH4wH98jQg.png" /><figcaption>fig. 21 Correlation Heatmap</figcaption></figure><p>Based on above heatmap, we choose to drop width, height and depth, and decided to keep volume that already represent product size and/or dimension.</p><pre># drop redundant features<br>feature_price_train = feature_price_train.drop(columns=[&#39;width&#39;, <br>&#39;height&#39;, &#39;depth&#39;])<br>feature_price_validation = feature_price_validation.drop(columns=[&#39;width&#39;, <br>&#39;height&#39;, &#39;depth&#39;])<br>feature_price_test = feature_price_test.drop(columns=[&#39;width&#39;, &#39;height&#39;, <br>&#39;depth&#39;])</pre><pre># Re-calculate VIF scores<br>from statsmodels.stats.outliers_influence import variance_inflation_factor as vif <br>from statsmodels.tools.tools import add_constant<br><br>X = add_constant(feature_price_train)<br><br>vif_df = pd.DataFrame([vif(X.values, i) <br>               for i in range(X.shape[1])], <br>              index=X.columns).reset_index()<br>vif_df.columns = [&#39;feature&#39;,&#39;vif_score&#39;]<br>vif_df = vif_df.loc[vif_df.feature!=&#39;const&#39;]<br>vif_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*GtTrxpkjmfBw6zcRm0E5kw.png" /></figure><p>GREAT! Now we have a reasonable <strong>VIF Score</strong> for our dataset. Because a <strong>VIF</strong> equal to <strong>one</strong> means variables are not correlated and multicollinearity does not exist in the regression model.</p><h4>RIDGE Regression</h4><p>We need to know what is the best <strong>lambda value</strong> for our <strong>Linear Regression</strong> model [ 0.01, 0.1, 1, 10 ]. <strong>Lambda </strong>is a parameter used for Regularization. It is used to avoid overfitting.</p><pre>from sklearn.linear_model import Ridge<br><br># train the model<br>X_price_train = feature_price_train.to_numpy()<br>y_price_train = target_price_train.to_numpy()<br>y_price_train = y_price_train.reshape(len(y_price_train),)<br><br># define the model<br># 4 models with 4 different alphas (lambda)<br>ridge_reg_pointzeroone = Ridge(alpha=0.01, random_state=42)<br>ridge_reg_pointone = Ridge(alpha=0.1, random_state=42)<br>ridge_reg_one = Ridge(alpha=1, random_state=42)<br>ridge_reg_ten = Ridge(alpha=10, random_state=42)<br><br># fit the model (training)<br>ridge_reg_pointzeroone.fit(X_price_train, y_price_train)<br>ridge_reg_pointone.fit(X_price_train, y_price_train)<br>ridge_reg_one.fit(X_price_train, y_price_train)<br>ridge_reg_ten.fit(X_price_train, y_price_train)</pre><pre># Calculate the best lambda value<br>from sklearn.metrics import mean_squared_error<br><br>X_price_validation = feature_price_validation.to_numpy()<br>y_price_validation = target_price_validation.to_numpy()<br>y_price_validation = y_price_validation.reshape(len(y_price_validation),)<br><br>alphas = [0.01, 0.1, 1., 10]<br>models = [ridge_reg_pointzeroone,<br>          ridge_reg_pointone,<br>          ridge_reg_one,<br>          ridge_reg_ten]<br><br>for model, alpha in zip(models, alphas):<br>    y_predict_validation = model.predict(X_price_validation)<br>    rmse = np.sqrt(mean_squared_error(y_price_validation,y_predict_validation))<br>    print(f&#39;RMSE of Ridge regression model with alpha = {alpha} is {rmse}&#39;)<br><br>RMSE of Ridge regression model with alpha = 0.01 is 987.252730825766<br>RMSE of Ridge regression model with alpha = 0.1 is 987.2517050840987<br>RMSE of Ridge regression model with alpha = 1.0 is 987.2418462723093<br>RMSE of Ridge regression model with alpha = 10 is 987.1705130199575</pre><p>Lambda value = 10 has the lowest <strong>RMSE</strong>, so we choose it as the best lambda value for our <strong>Ridge Regression</strong>.</p><pre># Calculate the Price Prediction Model for Ridge Regression<br>ridge_best = ridge_reg_ten<br><br>coef_df = pd.DataFrame({<br>    &#39;feature&#39;:[&#39;intercept&#39;] + feature_price_train.columns.tolist(),<br>    &#39;coefficient&#39;:[ridge_best.intercept_] + list(ridge_best.coef_)<br>})<br><br>coef_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*7F-a_gACh4ReU9RCY7dpJQ.png" /></figure><p>Holding all other features is zero, the average product price is <strong>97.781584</strong>.</p><h4><strong>LASSO Regression</strong></h4><p>Like <strong>Ridge Regression</strong>, we need to know what is the best <strong>lambda value</strong> for our <strong>Linear Regression</strong> model [ 0.01, 0.1, 1, 10 ], to avoid <strong>overfitting</strong>.</p><pre>from sklearn.linear_model import Lasso<br><br># train the model<br>X_price_train = feature_price_train.to_numpy()<br>y_price_train = target_price_train.to_numpy()<br>y_price_train = y_price_train.reshape(len(y_price_train),)<br><br># define the model<br># 4 models with 4 different alphas (lambda)<br>lasso_reg_pointzeroone = Lasso(alpha=0.01, random_state=42)<br>lasso_reg_pointone = Lasso(alpha=0.1, random_state=42)<br>lasso_reg_one = Lasso(alpha=1, random_state=42)<br>lasso_reg_ten = Lasso(alpha=10, random_state=42)<br><br># fit the model (training)<br>lasso_reg_pointzeroone.fit(X_price_train, y_price_train)<br>lasso_reg_pointone.fit(X_price_train, y_price_train)<br>lasso_reg_one.fit(X_price_train, y_price_train)<br>lasso_reg_ten.fit(X_price_train, y_price_train)</pre><pre># Calculate the best lambda value<br>from sklearn.metrics import mean_squared_error<br><br>X_price_validation = feature_price_validation.to_numpy()<br>y_price_validation = target_price_validation.to_numpy()<br>y_price_validation = y_price_validation.reshape(len(y_price_validation),)<br><br>alphas = [0.01, 0.1, 1., 10]<br>models = [lasso_reg_pointzeroone,<br>          lasso_reg_pointone,<br>          lasso_reg_one,<br>          lasso_reg_ten]<br><br>for model, alpha in zip(models, alphas):<br>    y_predict_validation = model.predict(X_price_validation)<br>    rmse = np.sqrt(mean_squared_error(y_price_validation,y_predict_validation))<br>    print(f&#39;RMSE of Lasso regression model with alpha = {alpha} is {rmse}&#39;)<br><br>RMSE of Lasso regression model with alpha = 0.01 is 987.252465278707<br>RMSE of Lasso regression model with alpha = 0.1 is 987.2500761521387<br>RMSE of Lasso regression model with alpha = 1.0 is 987.2825197186934<br>RMSE of Lasso regression model with alpha = 10 is 987.5125295988878</pre><p>Lambda value = 0.1 has the lowest <strong>RMSE</strong>, so we choose it as the best lambda value for our <strong>Lasso Regression</strong>.</p><pre># Calculate the Price Prediction Model for Lasso Regression<br>lasso_best = lasso_reg_pointone<br><br>coef_df = pd.DataFrame({<br>    &#39;feature&#39;:[&#39;intercept&#39;] + feature_price_train.columns.tolist(),<br>    &#39;coefficient&#39;:[lasso_best.intercept_] + list(lasso_best.coef_)<br>})<br><br>coef_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*oJJb5VZPbq348eMtEfihaQ.png" /></figure><p>Holding all other features is zero, the average product price is <strong>71.844397</strong>.</p><h4><strong>Training Error / Model Evaluation</strong></h4><p><strong>RIDGE Regression</strong></p><pre># prepare prediction result on train data<br>y_predict_train = ridge_best.predict(X_price_train)<br><br>from sklearn.metrics import mean_squared_error<br>from sklearn.metrics import mean_absolute_error<br>from sklearn.metrics import mean_absolute_percentage_error<br><br>print(&#39;RMSE for training data is {}&#39;.format(np.sqrt(mean_squared_error(y_price_train, <br>y_predict_train))))<br>print(&#39;MAE for training data is {}&#39;.format(mean_absolute_error(y_price_train, <br>y_predict_train)))<br>print(&#39;MAPE for training data is {}&#39;.format(mean_absolute_percentage_error(y_price_train, <br>y_predict_train)))<br><br>RMSE for training data is 998.6901837298269<br>MAE for training data is 654.1170892121919<br>MAPE for training data is 3.5985254264731696</pre><pre># Testing Error<br><br># prepare prediction result on test data<br>X_price_test = feature_price_test.to_numpy()<br>y_predict_test = ridge_best.predict(X_price_test)<br><br># ground truth target<br>y_price_test = target_price_test.to_numpy()<br>y_price_test = y_price_test.reshape(len(y_price_test),)<br><br>from sklearn.metrics import mean_squared_error<br>from sklearn.metrics import mean_absolute_error<br>from sklearn.metrics import mean_absolute_percentage_error<br><br>print(&#39;RMSE for testing data is {}&#39;.format(np.sqrt(mean_squared_error(y_price_test, <br>y_predict_test))))<br>print(&#39;MAE for testing data is {}&#39;.format(mean_absolute_error(y_price_test, <br>y_predict_test)))<br>print(&#39;MAPE for testing data is {}&#39;.format(mean_absolute_percentage_error(y_price_test, <br>y_predict_test)))<br><br>RMSE for testing data is 1019.9781385549287<br>MAE for testing data is 654.3331930612878<br>MAPE for testing data is 4.249702968219504</pre><p><strong>LASSO Regression</strong></p><pre># prepare prediction result on training data<br>y_predict_train = lasso_best.predict(X_price_train)<br><br>from sklearn.metrics import mean_squared_error<br>from sklearn.metrics import mean_absolute_error<br>from sklearn.metrics import mean_absolute_percentage_error<br><br>print(&#39;RMSE for training data is {}&#39;.format(np.sqrt(mean_squared_error(y_price_train, <br>y_predict_train))))<br>print(&#39;MAE for training data is {}&#39;.format(mean_absolute_error(y_price_train, <br>y_predict_train)))<br>print(&#39;MAPE for training data is {}&#39;.format(mean_absolute_percentage_error(y_price_train, <br>y_predict_train)))<br><br>RMSE for training data is 998.6638772559531<br>MAE for training data is 654.4635527199952<br>MAPE for training data is 3.6049379799109906</pre><pre># prepare prediction result on test data<br>X_price_test = feature_price_test.to_numpy()<br>y_predict_test = lasso_best.predict(X_price_test)<br><br># ground truth target<br>y_price_test = target_price_test.to_numpy()<br>y_price_test = y_price_test.reshape(len(y_price_test),)<br><br>from sklearn.metrics import r2_score<br>from sklearn.metrics import mean_absolute_error<br>from sklearn.metrics import mean_absolute_percentage_error<br><br>print(&#39;RMSE for testing data is {}&#39;.format(np.sqrt(mean_squared_error(y_price_test, <br>y_predict_test))))<br>print(&#39;MAE for testing data is {}&#39;.format(mean_absolute_error(y_price_test, <br>y_predict_test)))<br>print(&#39;MAPE for testing data is {}&#39;.format(mean_absolute_percentage_error(y_price_test, <br>y_predict_test)))<br><br>RMSE for testing data is 1019.9710520387995<br>MAE for testing data is 654.9349302761653<br>MAPE for testing data is 4.263537130230902</pre><p>Both RIDGE and LASSO, has higher value of <strong>MAE</strong>, <strong>MAPE</strong>, and <strong>RMSE</strong> for testing data than the training data, but not too much so we can claimed that both RIDGE and LASSO are not underfit. The reason why testing data is higher, because the model hasn’t seen the testing data before. But looking at the scale of the values in training and testing for <strong>RMSE </strong>it looks like we can <strong>generalized </strong>the model.</p><h3>CONCLUSION</h3><p>Based on our price prediction modeling product, both <strong>RIDGE </strong>and <strong>LASSO </strong>conclude the same results. Features that affected <strong>positively </strong>to product price are <strong>sellable_online</strong> [ product availability online ] and <strong>category </strong>[ product category ]. While <strong>other_colors</strong> and <strong>price_diff</strong> [ price different between current and old price ] affected negatively to product price.</p><p>Product that available online, has higher price probability than product that only sell offline, it means that <strong>IKEA </strong>needs to increase their <strong>online selling. </strong>It will also help increase their <strong>Sales of Goods</strong> with minimum <strong>Operational Cost</strong>.</p><p><strong>IKEA </strong>needs to create product that exclusively available online, but with offline product display, so it can attract customer when they come to offline store, and also visit the website, for online purchase.</p><p><strong>IKEA </strong>needs to focused on creating product with minimalized color option, to help reduced <strong>production cost</strong>, and optimize product variaties based on customer needs.</p><p>Thank you for reading my article! Hopefully, It can help new aspiring data scientist like me to write, learn and explore the data world.</p><p>For full code, please visit my Github :</p><p><a href="https://github.com/laksmiamalia/IKEA-Product-Analysis-and-Price-Prediction">GitHub - laksmiamalia/IKEA-Product-Analysis-and-Price-Prediction: Here we try to analyze IKEA Product Analysis and create Model for Product Price Prediction Using Linear Regression Model</a></p><p>Or connect with me via <a href="https://www.linkedin.com/in/laksmiamalia/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=644e52542f35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of Security Features on Banknotes]]></title>
            <link>https://medium.com/@amalia.wulandiari/analysis-of-security-features-on-banknotes-b3c2271c9991?source=rss-59685185473a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3c2271c9991</guid>
            <category><![CDATA[security-feature]]></category>
            <category><![CDATA[forgery]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[banknote]]></category>
            <dc:creator><![CDATA[Laksmi Amalia Wulandiari]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 16:33:43 GMT</pubDate>
            <atom:updated>2022-12-02T16:37:04.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RJ1__faIIq1v7oHQjR-4tA.jpeg" /><figcaption>fig. 1 Currencies from afew countries</figcaption></figure><p>Security features is a feature of a product, designed to provide access security 🔒 for the product. It is really important, especially in Banknotes.</p><p>This is my first writing attempt, and in this article, we are going to analyze the effect of <strong>security features</strong> embedded on the notes on forgery and country economic status. For analyzing and visualizing process, we use python.</p><pre>import pandas as pd # for data processing<br>import numpy as np # for array, linear algebra<br>import matplotlib.pyplot as plt # to crreate stat and visualize data<br>import seaborn as sns # to visualize data</pre><p><strong>Banknotes </strong>is a piece of paper money, constituting a central bank’s promissory note to pay a stated sum to the bearer on demand. Banknotes were originally issued by commercial banks, which were legally required to redeem the notes for legal tender (usually gold or silver coin) when presented to the chief cashier of the originating bank. To prevent counterfeiting, it’s important to secured Banknotes with the best security features.</p><p>Each country has their own concern on choosing the type of security features for its banknotes. Sometimes, the higher the denominations, the better security features on it. But, some country choose to standardize their banknotes security features, without concerning the denomination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ugkDM90YuKIYsG88bQP3FQ.jpeg" /><figcaption>fig. 2 Swiss Franc embedded the same features for all denomination</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_I0LyU7FdBWmIB-9n7ohNw.jpeg" /><figcaption>fig. 3 Indonesia Rupiah embedded different features based on it denomination value</figcaption></figure><p>There are 3 Levels of security features :</p><ol><li><strong>Level 1</strong><br>Verifiable by people, can be easily checked by sight, feeling, and moving banknotes</li><li><strong>Level 2</strong><br>Machine-readable in the commercial market. invisible to naked eye, but can be checked in commercialcash cycle</li><li><strong>Level 3</strong><br>Exclusive method of authentication in central banks. Optimized for high automation detection in central banks, also for forensic usage.</li></ol><h3><strong>CURRENCIES WITH MOST AND LEAST SECURITY FEATURES</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1B3UJHesqRj8dP3svrCCKA.jpeg" /><figcaption>fig. 4 Top 10 Countries with Highest Amount of Security Features on Banknotes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgiW-Q_zAZuMMlODpn_tHg.jpeg" /><figcaption>fig. 5 Bottom 10 Countries with Least Ampunt of Security Features on Banknotes</figcaption></figure><p>Based on fig. 4, the number one country with most security features embedded on their notes is <strong>Russia</strong> with total <strong>23</strong> features, followed by followed by <strong>Switzerland </strong>[17 features], <strong>Mexico </strong>[17 features], <strong>Malaysia</strong> [17 features] and <strong>Poland </strong>[16 features]<strong>.</strong> Which is way much more than average number of <strong>Security Features</strong> used on other countries banknotes, <strong>10</strong>.</p><pre># average numbers of overall security features used on banknotes<br><br>mean_tot = int(df[&#39;Total&#39;].mean())<br>mean_tot<br><br>10</pre><h4>Currency with Most Security Features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*5RD7txJOmSHKuAiGty652Q.jpeg" /><figcaption>fig. 6 Some security features embedded on <strong>Russian Ruble</strong></figcaption></figure><p><strong>Russian Ruble</strong> has the most complete security features on all levels. Most security features on <strong>Russian Ruble</strong> are from Level 1 with <strong>16</strong> in total, <strong>3</strong> features on Level 2, and <strong>4</strong> features on Level 3 [total 23 features]. Well, it’s not an odd things, consider now Russian Ruble is one of the strongest and highest value currency in the world, as well make it well protected and secured to minimize the forgery, without complicated it and to ease the detection.</p><p>There are some advanced and unique features, like <strong>OVMI Ink </strong>and <strong>Microperforation</strong>. <strong>OVMI Ink</strong> or <strong>SPARK</strong>, is a multi-level (visual and machine readable) security feature. The ink contains a special magnetic pigment located with the help of magnetic fields within the ink layer. When the banknote is tilted, there is a combination of the colour changing effect and the dynamic effect of the ink movement (bright parts of the image “change” places). While <strong>Microperforation, </strong>is a security feature, consisting of micro holes made by laser and forming an image seen in transmitted light (the holes look like bright spots). The area of the banknote with the holes does not feel rough to the touch</p><h4>Currency with Least Security Features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tfyamm9-J4NMuyybYuJxMg.jpeg" /><figcaption>fig. 7 Some security features embedded on <strong>Kenyan Shilling</strong></figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Kenya"><strong>Kenya</strong></a><strong> </strong>is the third largest economy in <a href="https://en.wikipedia.org/wiki/Sub-Saharan_Africa">Sub-Saharan Africa</a>, coming behind <a href="https://en.wikipedia.org/wiki/Economy_of_Nigeria">Nigeria</a> and <a href="https://en.wikipedia.org/wiki/Economy_of_South_Africa">South Africa</a>. Compared to its neighbors, Kenya has a well-developed social and physical infrastructure. <strong>The Security Features, </strong>embedded on it has great function proportion by needed, despite it is not as much or as advanced as <strong>Russian Ruble, </strong>such as<strong> watermark</strong>, <strong>security thread,</strong> and <strong>raised ink/intaglio print</strong>.</p><h3><strong>SECURITY FEATURED USAGE BASED ON COUNTRY ECONOMICAL STATUS</strong></h3><p>Here, we will analyze and compare the banknotes security features for the richest and poorest country in the world. We can define the value of a country based on their Gross Domestic Product [GDP] which is a measure of wealth in the country coming from sources including export revenues, incomes, consumption, and the value of goods and services the country produces in a span of a year. The GDP per capita is the wealth divided by the number of inhabitants in the country, which is a helpful measurement that can provide insight into the quality of life in a country. If the GDP per capita is high, this can often indicate the wealth and prosperity of the country’s inhabitants. [<a href="https://www.worldatlas.com/articles/the-richest-countries-in-the-world.html#:~:text=PPP">source</a>]</p><p><strong>LUXEMBOURG</strong> is a small landlocked country in Western Europe known for high-income levels and a low unemployment rate. It borders Belgium to the west and north, Germany to the east, and France to the south, declared as the richest country in Europe, with <strong>GDP per capita (PPP): $140,694</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaCRLaJTSfnNHaW3rwlabQ.jpeg" /><figcaption>fig. 8 <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.visitluxembourg.com%2Fdestinations%2Fluxembourg-city&amp;psig=AOvVaw3hMg1kKcXEi1x76ZzQb1IQ&amp;ust=1670080162754000&amp;source=images&amp;cd=vfe&amp;ved=0CBAQjRxqFwoTCNjcpMmb2_sCFQAAAAAdAAAAABAE">Luxembourg</a></figcaption></figure><p>Whilst <strong>Luxembourg</strong> crowned as the richest country in the world, <strong>Somalia</strong> is the poorest country in the world with <strong>GDP per capita of USD 303</strong>. Somalia — located in the Horn of Africa — has been wracked by violence for decades. Currently, the government’s main security challenge is combating the Islamist insurgency group Al-Shabab, which aims to establish an independent state within the country. This violence and vulnerability to drought are likely to continue to weigh on growth ahead, meaning that Somalia will be the poorest country in the world in 2026. [<a href="https://www.focus-economics.com/blog/the-poorest-countries-in-the-world">source</a>]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*OQR9sk0ERnBJZMajNUH9Eg.jpeg" /><figcaption>fig. 9 <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Ftwitter.com%2Findependentmi20%2Fstatus%2F1453736147352383491%3Flang%3Dar-x-fm&amp;psig=AOvVaw2d6EgTeNSnmWfn8qbYYuKL&amp;ust=1670080380512000&amp;source=images&amp;cd=vfe&amp;ved=0CBAQjRxqFwoTCKj147Cc2_sCFQAAAAAdAAAAABAE">Somalia</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*BQT6-ih-CWxpPLZf-vbt5A.png" /><figcaption>fig. 10 Security features comparison barchart <strong>Luxembourg vs Somalia</strong></figcaption></figure><p>Based on the fig. 10, the amount of security features planted on <strong>Luxembourg </strong>and <strong>Somali </strong>banknotes is quite different. <strong>Somali Shilling</strong> only has <strong>6</strong> security features in total [Level 1 : 3, Level 2 : 2, and Level 1 : 1], while <strong>Luxembourg</strong> is using <strong>Euro</strong> which is consider as one of the most powerfull currency in the world, with <strong>11</strong> security features in total [Level 1 : 6, Level 2 : 4, Level 3 : 1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7RdYK3f_lYpLGeH0dfL9jA.jpeg" /><figcaption>fig. 11 Some security features embedded on <strong>EURO</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ErREjLI2A0kPuaeDpgGyWw.png" /><figcaption>fig. 12 Some security features embedded on <strong>Somali Shilling</strong></figcaption></figure><p>Due to Somalia still in its own civil war, it is perfectly reasonable for them to only attach small amount of security features on their notes. Half of the features, are Level 1 security features, that used standard and common features offset and intaglio feature, to help ease the detection for counterfeiting and absolutely inexpensive production cost. That is obviously one of the biggest concern, due to the country current condition. They need to produce a simple and economical banknotes, for daily usage.</p><p>On the other hand, with wide usage of it around Europe [19 countries], and soaring value of the currency, Euro is the second-largest reserve currency as well as the second-most traded currency in the world after the United States dollar. Either it need to be easily detected by sight, or by machine, the notes must be really secured. Security features embedded on the notes is simple but quite sophisticated. They only use selected type of features, with no redundants function, and quite advanced.</p><h3><strong>THE MOST SECURED BANKNOTES</strong></h3><p>The <strong>New Zealand Dollar</strong>, is one of the banknotes that tend to avoid forgery. One of the main reason is, it used Polymer substrate, and have several security features to make them harder to counterfeit. [<a href="https://www.lovemoney.com/galleries/72755/the-worlds-most-and-least-counterfeited-currencies?page=2">source</a>]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*mEJiFuIgIwA84q_JJIht_w.jpeg" /><figcaption>fig. 13 Some security features embedded on <strong>NZD</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*M7Uoc7Wd85R0YRn6q8dB9Q.png" /><figcaption>fig. 14 Security features proportion from each level [<strong>NZD</strong>]</figcaption></figure><p>Based on the fig. 14, security features used on <strong>NZD</strong>, are mostly consist of level 1 security features, and total security features used on the notes just slightly below the average number of security features. One of the feature that help <strong>NZD</strong> crowned as the fake-proof notes, is the <strong>Polymer Substrate</strong> which is designed to be harder to counterfeited. And the <strong>NZD</strong> is not using any Level 3 features, but still manage as the least counterfeited banknotes, by optimize the Level 1 and Level 2 features. so it help to ease the verification or counterfeit identification, by sight, feeling, and moving the banknotes. No hassle to check it anytime anywhere.</p><h3>THE MOST COUNTERFEITED CURRENCIES</h3><p>Counterfeit money is currency produced without the legal sanction of a state or government, usually in a deliberate attempt to imitate that currency and so as to deceive its recipient. Producing or using counterfeit money is a form of fraud or forgery, and is illegal. Some of the ill-effects that counterfeit money has on society include, a reduction in the value of real money; and an increase in prices (inflation) due to more money getting circulated in the economy — an unauthorized artificial increase in the money supply; a decrease in the acceptability of paper money; and losses, when traders are not reimbursed for counterfeit money detected by banks, even if it is confiscated. [<a href="https://en.wikipedia.org/wiki/Counterfeit_money">source</a>]</p><p>Based on <a href="https://www.nbarizona.com/blog/tips-to-avoid-counterfeit-currencies-/">nbarizona</a>, <strong>Mexican Peso</strong>, is the most counterfeited banknotes with roughly <strong>300.000</strong> counterfeit bills, amounting to about <strong>99.1</strong> million pesos, with the most common denominations counterfeited being the <strong>20, 100 and 50 peso notes</strong>. While this may not seem like a lot, it’s worth noting that unsuspecting tourists are one of the easier ways to get these counterfeit bills into circulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*wunW3nD2uayzcufm9kvfsw.jpeg" /><figcaption>fig. 15 Some security features embedded on <strong>Mexican Peso</strong></figcaption></figure><p><strong>British Pound</strong> also one of the most counterfeited currencies in the world, even though it features many state-of-the-art anti-counterfeiting features. According to a report by the Bank of England, some <strong>33,000</strong> counterfeit notes were spotted and removed from circulation in the first half of 2020 alone. The most common among those was the <strong>£20 note</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*DQ9xyabbFCuRJBs46_ICeQ.jpeg" /><figcaption>fig. 16 Some security features embedded on <strong>British Poundsterling</strong></figcaption></figure><p>The <strong>US Dollar</strong> also the most commonly counterfeited currency in the world according to the Federal Reserve Bank of Boston. With counterfeiting operations active not just in the US.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ikxs9fHfyKkmsLeUxKneeA.jpeg" /><figcaption>fig. 17 Some security features embedded on <strong>USD</strong></figcaption></figure><p>Let’s find out the amount of security features on <strong>Mexican Peso</strong>, <strong>British Pound</strong> and <strong>US Dollar.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*rYcG0pEFHPBmDqEUphdenw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*kUKLrudeGzvQN11Vx06jZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*7EAZAOfOmI9tzH1Jej5ehw.png" /><figcaption>[from Left to Right] fig. 18–20 Security features proportion for <strong>Mexican Peso, British Poundsterling, and United States Dollar</strong></figcaption></figure><p>Based on the fig. 18–20, security features used on <strong>Mexican Peso</strong>, <strong>British Pound</strong> and <strong>US Dollar</strong>, are dominated with <strong>Level 1</strong> security features, and only <strong>Mexican Peso</strong> embedded level 3 security features on their notes. Even though, most of the counterfeit case, is due to <strong>personal gain</strong> and <strong>political battle</strong>, it is without doubt the easier access to acknowledge the forged banknotes, can help reduce the probability of forgery.</p><p>But none of the currencies above, using Level 3 features, an exclusive method of authentication in central banks. Optimized for high automation detection in central banks, also for forensic usage. Maybe it because they want the currencies more detection friendly without complicated the process.</p><h3><strong>THE MOST USED SECURITY FEATURES</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*S0pq_EzwbDm5HSVjZ_glcw.png" /><figcaption>fig. 21 Top 10 Most Used Security Features</figcaption></figure><p>Based on the fig. 21, we can see, that the most used security features are common features that already been used for a long time. The number one feature is <strong>Blind Code</strong> which is reasonable, because it also used to help the impaired vision to identify the notes. <strong>Blind code</strong> mostly print with <strong>Intaglio print</strong>, a printing technique from a plate, where printing elements are incised into the surface.</p><p>Followed by <strong>Watermark</strong> and <strong>Rectoverso</strong>, which is two easiest features to spot without any hassle, just direct the notes to the light, and we can spot it. For <strong>watermark</strong> we can see the invisible image, and for <strong>rectoverso</strong>, both parts that printed on one side and on the other side of the notes match up and create a complete image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*bxxBWwyodKA8ATlqhjcjFg.jpeg" /><figcaption>fig. 22 <strong>Blind Code</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*wh3wFol_xE1HEAr_N7ub9w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*-Xcilc-bSx0KX-hysYiFGg.jpeg" /><figcaption>fig. 23 <strong>Rectoverso</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/74/1*SFzfTNLSJHlHwJwjS0gnnw.jpeg" /><figcaption>fig. 24 <strong>Watermark</strong></figcaption></figure><h3><strong>CONCLUSION</strong></h3><p>Security features comes at different level, and usage. It has function as security and/or aesthetic on the banknotes. Even though, sometime the higher the level of security features on banknotes means the better security on it, but a simpler design and security features of banknotes, can also quite secured. Simplify the security features, by not using redundant type of security features, might help not only secured the notes, but also reduced the production cost.</p><p>Take example from <strong>NZD</strong>, which crowned as one of the most secured banknotes in the world. It only has <strong>9 security features</strong> printed on the notes, and mostly from a <strong>Level 1</strong> security features that easy to verified, can be easily checked by sight, feeling, and moving the banknotes. No hassle to check it anytime anywhere.</p><p>Aside from <strong>NZD </strong>being the most secured banknotes in the world, <strong>Russian Ruble</strong> has the most security features embedded on it with total <strong>23</strong> features [Level 1: 16, Level 2: 3, Level 3: 4]. No wonder, <strong>Russian Ruble</strong> still one of the strongest currency in the world, the amount of security features on it, can be one of the cause.</p><p>The economic condition of the country, also can affect the amount of security features used on banknotes. Just like <strong>Luxembourg</strong> that crowned as the richest country, the currency they used is Euro, which is the second-largest most reserved currency in the world. It featured quite sophisticated security features, but with on point function for each features. While <strong>Somalia</strong>, which from their <strong>GDP </strong>is the poorest country in the world, their currency only has a few security features on it. That condition might because <strong>Somalia</strong> need simple banknotes, either from production side or economical value.</p><p>Talking about forgery, <strong>Mexican Peso</strong> is the most counterfeited banknotes to date, followed by <strong>British Pound</strong> and <strong>United States Dollar</strong>. If we take closer look to the security features on each currencies, has different amount of security features. Sometimes, high amount of security features doesn’t mean is forgery proof, but it will help early detection of counterfeited notes, and minimize the chance being circulated widely.</p><blockquote>Thank you for reading! For full code, please refer on this <a href="https://github.com/laksmiamalia/project-security-features">link</a>!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3c2271c9991" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>