<?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 Rizno Fadhil on Medium]]></title>
        <description><![CDATA[Stories by Rizno Fadhil on Medium]]></description>
        <link>https://medium.com/@riznofadhil2?source=rss-7d158622173c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CB0o8yiMgXQ6fD1Y</url>
            <title>Stories by Rizno Fadhil on Medium</title>
            <link>https://medium.com/@riznofadhil2?source=rss-7d158622173c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:56:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@riznofadhil2/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[Mengapa pelanggan yang membayar paling murah justru paling setia?]]></title>
            <link>https://medium.com/@riznofadhil2/mengapa-pelanggan-yang-membayar-paling-murah-justru-paling-setia-fae1567f8a0a?source=rss-7d158622173c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fae1567f8a0a</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Rizno Fadhil]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 01:46:01 GMT</pubDate>
            <atom:updated>2026-08-24T01:46:01.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mengapa pelanggan yang membayar paling murah justru paling setia? Belajar dari Analisis 1.440 Transaksi Tiket Bioskop</h3><p><em>Sebuah studi kasus analisis pelanggan menggunakan SQL, Python, dan dashboard interaktif</em></p><p>Ada asumsi yang hampir selalu kita percaya begitu saja di dunia bisnis: <strong>pelanggan yang bayar lebih mahal pasti lebih loyal</strong>. Logikanya masuk akal, orang yang sudah mengeluarkan lebih banyak uang biasanya merasa lebih “terikat” untuk terus kembali.</p><p>Tapi ketika saya membedah <a href="https://www.kaggle.com/datasets/himelsarder/cinema-hall-ticket-sales-and-customer-behavior">data 1.440 transaksi tiket bioskop</a>, asumsi itu runtuh.</p><h3>Kenapa Proyek Ini Saya Buat</h3><p>Belakangan saya semakin tertarik pada industri ticketing dan event, bagaimana data transaksi sehari-hari bisa diolah menjadi strategi bisnis yang konkret: siapa yang perlu ditarget promo, produk mana yang perlu digenjot, dan pelanggan mana yang justru harus dijaga agar tidak pergi.</p><p>Daripada cuma membaca teorinya, saya coba praktikkan sendiri dari nol: mengambil data mentah, membersihkannya, menganalisisnya, sampai menghasilkan dashboard yang siap dipakai untuk pengambilan keputusan.</p><h3>Alur Kerja Singkat</h3><p>Saya menggunakan data penjualan tiket bioskop yang berisi informasi umur pelanggan, harga tiket, genre film yang ditonton, jenis kursi (Standar, Premium, VIP), jumlah orang yang datang bersama, dan yang paling penting, apakah pelanggan tersebut kemungkinan akan membeli tiket lagi di kemudian hari.</p><p><strong>Langkah 1 — Membersihkan Data.</strong> Seperti kebanyakan data di dunia nyata, data ini tidak langsung rapi. Ada satu kolom yang isinya bercampur antara teks (“Sendiri”) dan angka (2–7 orang) — saya rapikan menjadi dua kolom terpisah agar lebih mudah dianalisis. Ada juga beberapa nomor tiket yang ternyata “kembar” secara kebetulan (bukan transaksi ganda sungguhan), saya perbaiki tanpa menghapus data apa pun.</p><p><strong>Langkah 2 — Menjawab Pertanyaan Dasar dengan SQL.</strong> Saya menulis serangkaian query (perintah pengambilan data) di Google BigQuery, semacam “mesin pencari” khusus untuk data dalam jumlah besar, untuk melihat pola sederhana: genre mana yang paling laku, tipe kursi mana yang pelanggannya paling sering kembali, dan seterusnya.</p><p>Hasilnya cukup mengejutkan: ketika dilihat satu per satu, semua faktor ini punya tingkat “kembali beli tiket lagi” (yang saya sebut <em>retention rate</em>, atau tingkat retensi) yang <strong>relatif sama saja</strong>, di kisaran 45–54%. Tidak ada satu faktor tunggal yang benar-benar menonjol.</p><p>Ini justru jadi petunjuk penting: mungkin polanya baru terlihat kalau semua faktor ini dilihat <strong>secara bersamaan</strong>, bukan satu-satu.</p><p><strong>Langkah 3<br>Mengelompokkan Pelanggan Secara Otomatis.</strong> <br>Di sinilah saya menggunakan teknik yang disebut <em>clustering</em> (pengelompokan). Bayangkan seperti mengelompokkan murid di kelas berdasarkan kemiripan kebiasaan belajar mereka, tapi dilakukan komputer secara otomatis pada ribuan data sekaligus, dan berdasarkan banyak faktor sekaligus (umur, harga tiket, jenis kursi, jumlah rombongan), bukan cuma satu faktor seperti sebelumnya.</p><p>Setelah menguji beberapa kemungkinan jumlah kelompok, saya menemukan bahwa membagi pelanggan menjadi <strong>empat kelompok</strong> memberikan hasil yang paling masuk akal dan mudah dipahami secara bisnis.</p><h3>Empat Wajah Pelanggan Bioskop</h3><p><strong>1.Keluarga/Rombongan VIP</strong> (Retensi 47,5%)<br>Usia menengah, pilih kursi mewah, datang beramai-ramai.</p><p><strong>2.Penggemar Aksi Dewasa</strong> (Retensi 49,7%)<br>Usia lebih tua, kursi VIP, suka film Action, datang sendiri.</p><p><strong>3.Anak Muda Penggemar Sci-Fi</strong> (Retensi 46,9%)<br>Usia muda, kursi Premium, suka film Sci-Fi, datang sendiri.</p><p><strong>4.Pelanggan Hemat yang Setia</strong> (Retensi 53,4%)<br>Pilih kursi paling murah, datang sendiri.</p><p>Dan di situlah temuan paling menarik muncul: <strong>kelompok dengan harga tiket termurah justru paling sering kembali membeli tiket lagi.</strong> Bukan kelompok VIP yang bayar paling mahal, bukan kelompok keluarga yang datang rombongan besar, tapi penonton yang datang sendiri, pilih kursi paling sederhana, justru paling setia.</p><h3>Kenapa Ini Penting untuk Bisnis</h3><p>Temuan ini bukan sekadar fakta menarik untuk dipajang. Ada implikasi nyata di baliknya:</p><p><strong>Loyalitas mungkin dibentuk oleh kebiasaan, bukan gengsi.</strong> Penonton yang datang sendiri tanpa kursi mewah, mungkin menjadikan nonton film sebagai rutinitas personal, bukan acara spesial sesekali. Kebiasaan semacam ini cenderung lebih tahan lama dibanding pengalaman “mewah tapi jarang”.</p><p><strong>Pelanggan VIP butuh perhatian khusus, bukan cuma harga tinggi.</strong> Mereka menyumbang pendapatan besar per transaksi, tapi tingkat kembalinya biasa saja. Ini pertanda program loyalitas untuk kelompok ini perlu dirancang khusus, jangan asumsikan “bayar mahal otomatis setia”.</p><p><strong>Pelanggan hemat sering diremehkan, padahal justru fondasi bisnis.</strong> Karena pendapatan per transaksinya kecil, kelompok ini gampang dianggap “kurang menarik” secara bisnis. Padahal, dari sisi kesetiaan, merekalah yang paling stabil.</p><h3>Refleksi</h3><p>Proyek kecil ini mengingatkan saya pada satu hal penting dalam bekerja dengan data: <strong>asumsi bisnis yang terdengar logis belum tentu benar sampai benar-benar dicek datanya.</strong> Dan seringkali, temuan paling berharga bukan yang paling rumit secara teknis, tapi yang paling berlawanan dengan apa yang selama ini kita anggap “sudah pasti benar”.</p><h3>Skill yang saya terapkan di proyek ini</h3><p>Pembersihan data, penulisan query SQL di Google BigQuery, pengelompokan pelanggan otomatis (clustering) dengan Python, hingga penyusunan dashboard interaktif di Looker Studio, mulai dari data mentah sampai insight yang siap dipresentasikan ke stakeholder bisnis.</p><p><em>Dashboard interaktif dan kode lengkap proyek ini bisa dilihat di </em><a href="https://github.com/RiznoFadhil/cinema-ticket-analysis"><em>sini</em></a><em>.</em></p><p><em>Tertarik diskusi lebih lanjut soal data analytics atau punya kesempatan kolaborasi? Yuk terhubung di </em><a href="https://linkedin.com/in/rizno-fadhil"><em>LinkedIn saya</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fae1567f8a0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Same Spec, Different Score: Lessons from the DQLab x UjiKompetensi Python Hackathon]]></title>
            <link>https://medium.com/@riznofadhil2/same-spec-different-score-lessons-from-the-dqlab-x-ujikompetensi-python-hackathon-5aac5578d06f?source=rss-7d158622173c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aac5578d06f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[dqlab]]></category>
            <category><![CDATA[retail-analytics]]></category>
            <dc:creator><![CDATA[Rizno Fadhil]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 10:50:51 GMT</pubDate>
            <atom:updated>2026-06-15T11:31:58.415Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What happens when every participant gets the exact same problem — but the results are worlds apart?</em></p><h3>Background: DQFresh Mart and the Problem Hidden in Plain Sight</h3><p>A while back, I participated in the <strong>DQLab x UjiKompetensi Python Hackathon</strong>, themed <em>Retail Crisis &amp; Recovery</em>.</p><p>The challenge was built around a realistic business scenario: DQFresh Mart, a single-branch mini mart, had been experiencing a steady decline in total sales value over several months. Management initially blamed the broader economic slowdown, so their response was to double down on historical bestsellers, cut back on new product experiments, and tighten inventory control.</p><p>But Sophia, the store manager, suspected something wasn’t showing up on the main dashboard. After digging deeper into the transaction data, she uncovered a hidden pattern: a handful of products with small total revenue contributions were actually growing <em>consistently</em>. These products had been overlooked precisely because they kept running out of stock.</p><p>Our task as hackathon participants: <strong>reproduce Sophia’s analysis using Python</strong>, in a single script named solusi-retail.py that produces three output files:</p><ul><li>retail_insight.xlsx — containing a <strong>Rising Star</strong> sheet (hidden products with consistent growth) and a <strong>Potential Packaging</strong> sheet (bundling recommendations via Apriori)</li><li>rising_star_actual.png — a chart of actual sales values</li><li>rising_star_index.png — a relative growth index chart (base 100)</li></ul><p>I successfully produced all three files and landed at <strong>Rank #91 out of 464 participants</strong> — Top 100 Finalist. But I didn’t get a perfect score.</p><p>After the hackathon, I got access to a perfect-score solution. This article is my honest analysis of what was different — and why it matters.</p><h3>The Critical Framing: All Methodology Was Already Defined</h3><p>Before diving into the technical comparison, I need to clarify something — because this was a framing mistake I almost made myself.</p><p>When I first read the top scorer’s code, my instinct was: <em>“Smart — they used a 3-day Moving Average and a 12-day streak filter.”</em></p><p>But those <strong>weren’t their innovations</strong>. They were <strong>problem specifications</strong> that every participant had to follow:</p><blockquote>“Calculate the Moving Average (MA) of total sales value using a 3-day window for each product…”</blockquote><blockquote>“Only display products that have experienced a consistent uptrend for at least 12 consecutive days.”</blockquote><p>The problem even stated that the output charts <em>“must be exact or very close in terms of color, dimensions, and style”</em> to the provided reference visuals. A reference code snippet (snippet_code_matplotlib.py) was provided as a style guide.</p><p>This means every participant started from the exact same place: predetermined methodology, specified outputs, and even a visual template to match.</p><p><strong>What differentiated scores wasn’t <em>what</em> was built. It was <em>how precisely and elegantly</em> it was built.</strong></p><h3>Part 1: The Rising Star Engine — Same Spec, Different Execution</h3><h3>What the Problem Required</h3><p>According to the spec, the Rising Star identification process followed these exact steps:</p><ol><li><strong>Smoothing</strong>: Calculate 3-day Moving Average (MA-3) of each product’s total_nilai</li><li><strong>Uptrend identification</strong>: A product is in an “Uptrend Session” when today’s MA &gt; yesterday’s MA</li><li><strong>Count consecutive days</strong>: Track how many days in a row a product stays in an uptrend</li><li><strong>Filter</strong>: Only include products that achieved at least <strong>12 consecutive uptrend days</strong></li><li><strong>Growth %</strong>: Calculated as <strong>(End MA / Start MA − 1) × 100</strong></li></ol><p>Every participant had to implement this exact pipeline. The difference was in <em>how</em>.</p><h3>My Implementation</h3><p>I applied the logic above with an intuitive, step-by-step approach: computing MA-3 per product, then comparing today’s value to yesterday’s to determine whether a product was in an uptrend session.</p><p>The results were valid. My charts identified 4 top Rising Stars: Minyak Goreng Refill 1L, Beras Premium 5kg, Sabun Cuci Cair 1.5L, and Wajan Enamel Anti Lengket — with a relative growth index showing Minyak Goreng reaching ~1600 by the end of the period.</p><h3>The Perfect-Score Implementation</h3><p>The top scorer used full <strong>pandas vectorization</strong> — a fundamentally different approach:</p><pre># Smoothing: vectorized MA-3<br>daily_sales[&quot;ma_3&quot;] = daily_sales.groupby(&quot;nama_produk&quot;)[&quot;total_nilai&quot;].transform(<br>    lambda x: x.rolling(window=3, min_periods=1).mean()<br>)</pre><pre># Uptrend detection using diff()<br>daily_sales[&quot;is_up&quot;] = daily_sales.groupby(&quot;nama_produk&quot;)[&quot;ma_3&quot;].diff() &gt; 0<br>s = daily_sales[&quot;is_up&quot;].fillna(False)<br><br># &quot;Diff-Sign Method&quot;: group streaks without any for-loop<br>daily_sales[&quot;diff_group&quot;] = (<br>    s != s.groupby(daily_sales[&quot;nama_produk&quot;]).shift()<br>).groupby(daily_sales[&quot;nama_produk&quot;]).cumsum()<br><br># Count streak lengths, take the longest per product<br>streak_all = daily_sales[daily_sales[&quot;is_up&quot;]].groupby([&quot;nama_produk&quot;, &quot;diff_group&quot;]).size()<br>max_streaks = streak_all.groupby(&quot;nama_produk&quot;).max().reset_index(name=&#39;max_streak_days&#39;)</pre><p>Not a single explicit for loop. Every calculation happens at the array level using vectorized pandas operations.</p><p><strong>Why does this matter technically?</strong></p><p>Pandas executes vectorized operations in C under the hood, bypassing the Python interpreter for each element. The performance difference can be 10–100x on large datasets. Beyond speed, this code is also more readable to anyone fluent in the pandas paradigm — and it scales gracefully as the dataset grows.</p><p>There’s also a neat use of the <strong>walrus operator (</strong><strong>:=)</strong> from Python 3.8+:</p><pre>growth_data[&#39;growth_percentage&#39;] = (<br>    (growth_stats := growth_data[&#39;last&#39;] / growth_data[&#39;first&#39;]) - 1<br>) * 100</pre><p>This allows assignment and expression in one step — compact without sacrificing clarity.</p><h3>The Difference in Chart Output</h3><p>Even though both solutions followed the same spec, the visualizations looked noticeably different — and this is the most interesting part to analyze.</p><p><strong>My index chart</strong> showed smooth, consistent relative growth. Minyak Goreng Refill 1L reached ~1600 by period end. My legend included explicit ranking labels (“Rank 1:”, “Rank 2:”, etc.) and visually separated Top Sales from Rising Stars using different line styles.</p><p><strong>The top scorer’s index chart</strong> was far more dramatic — Minyak Goreng Refill 1L soared to ~5100. This happened because normalization was applied to raw total_nilai (which starts very small for rising products), not to the MA. Deodoran Spray also appeared as a Rising Star in their chart — absent from mine — suggesting its streak met the 12-day threshold despite volatile raw sales.</p><p>Both approaches are technically valid within the spec. But the top scorer’s charts more closely matched the reference visuals provided in the problem — and chart fidelity was an explicit scoring criterion.</p><h3>Part 2: Apriori &amp; Association Rules — Small Detail, Real Impact</h3><p>The spec here was very precise:</p><ul><li>min_support = 0.01 (1% of total transactions)</li><li>metric = &#39;lift&#39;, min_threshold = 1</li><li>Filter: at least one product in each rule must be a Rising Star; lift must be ≥ 2</li><li>Sort order: Lift → Support → Confidence</li></ul><p>Both solutions used mlxtend with the same parameters. The difference was in how Rising Star rules were filtered.</p><p><strong>My approach</strong> used sequential filtering with row-by-row conditions.</p><p><strong>The top scorer’s approach:</strong></p><pre>rules[&quot;is_star&quot;] = [<br>    not (set(a) | set(c)).isdisjoint(stars_set)<br>    for a, c in zip(rules[&quot;antecedents&quot;], rules[&quot;consequents&quot;])<br>]</pre><p>One list comprehension using set intersection. The isdisjoint() logic checks whether the union of antecedents and consequents overlaps with the Rising Star set — far more concise and idiomatic than manual filtering.</p><h3>Part 3: Visualization — DRY Principle vs. Two Separate Blocks</h3><h3>Context: The Problem Demanded Visual Precision</h3><p>This aspect is often underestimated. The problem explicitly stated that output charts <em>“must be exact or very close in terms of color, dimensions, and style.”</em> A snippet_code_matplotlib.py file was provided as a visual reference.</p><p>That means visualization wasn’t just an extra deliverable — it was a precision requirement.</p><h3>My Approach</h3><p>I built two separate visualization blocks — one for the actual chart, one for the index chart. My charts used explicit ranking labels in the legend (“Rank 1:”, “Rank 2:”, etc.) and color-coded the distinction between Top Sales (grayscale/dashed) and Rising Stars (solid colors).</p><p>The charts were informative, complete, and covered all required elements: Top 3 benchmark, all Rising Stars, date x-axis, value/index y-axis, and a full legend.</p><h3>The Top Scorer’s Approach</h3><pre>def generate_chart(chart_type=&quot;actual&quot;):<br>    fig, ax = plt.subplots(figsize=(12, 6.5))<br>    for i, item in enumerate(plot_items):<br>        data = daily_sales[daily_sales[&quot;nama_produk&quot;] == item]<br>        if chart_type == &quot;actual&quot;:<br>            y_val = data[&quot;total_nilai&quot;]<br>            title, ylabel, fname = &quot;Rising Star Actual Sales Trend&quot;, &quot;Total Sales Value&quot;, &quot;rising_star_actual.png&quot;<br>            marker = &#39;o&#39;<br>        else:<br>            base = data[&quot;total_nilai&quot;].iloc[0] if data[&quot;total_nilai&quot;].iloc[0] != 0 else 1<br>            y_val = (data[&quot;total_nilai&quot;] / base) * 100<br>            title, ylabel, fname = &quot;Performance Index (Base 100)&quot;, &quot;Index (%)&quot;, &quot;rising_star_index.png&quot;<br>            marker = &#39;s&#39;<br>            ax.axhline(100, color=&#39;black&#39;, lw=1, ls=&#39;--&#39;, alpha=0.5)</pre><pre>ax.plot(data[&quot;tgl_transaksi&quot;], y_val, label=item,<br>                color=colors[i], marker=marker, markersize=5, lw=2, alpha=0.9)<br>    ax.set_title(f&quot;{title}\nDataset: {filename}&quot;, loc=&#39;left&#39;, pad=20)<br>    ax.set_ylabel(ylabel)<br>    ax.legend(loc=&#39;center left&#39;, bbox_to_anchor=(1, 0.5), frameon=True, shadow=True)<br>    plt.grid(True, which=&#39;both&#39;, linestyle=&#39;:&#39;, alpha=0.6)<br>    plt.tight_layout()<br>    fig.savefig(fname, dpi=300)<br>    plt.close(fig)<br>generate_chart(&quot;actual&quot;)<br>generate_chart(&quot;index&quot;)</pre><p>One generate_chart() function, called twice with different parameters. This is the <strong>DRY Principle</strong> (Don&#39;t Repeat Yourself) applied cleanly — any style change only needs to happen in one place.</p><p>The plt.cm.Dark2 color palette also produced sharper, more professional contrast. And having the logic in a single reusable function makes it easier to maintain, test, and explain to others.</p><h3>Final Reflections: What This Hackathon Taught Me</h3><h3>1. Reading the spec carefully is half the job</h3><p>I initially assumed the perfect scorer made “smarter design decisions.” It turned out they simply followed the problem spec more precisely — especially the visual matching requirement that I underweighted.</p><p>In a hackathon context, <strong>spec adherence is a scoring criterion in itself.</strong> It’s not just about whether the output is logically correct — it’s about whether it matches exactly what was asked.</p><h3>2. Vectorization is a mindset, not just an optimization</h3><p>I used to think vectorization was a technique for large datasets. After reviewing this solution, I understand it differently: vectorization reflects a way of thinking about data as collective units rather than individual elements. That paradigm shapes every design decision — from streak calculation to rule filtering.</p><h3>3. The DRY Principle isn’t about saving lines of code</h3><p>Two nearly identical code blocks might not matter in a hackathon. But a reusable function signals that the author understands maintainability — a quality indicator that matters in competitions and real-world codebases alike.</p><h3>4. The gap between “code that works” and “code that’s good” is wider than I thought</h3><p>Every participant had the same spec. Everyone who delivered the outputs got some credit. But perfect scores went to those who not only got the logic right, but did it efficiently, cleanly, and precisely to spec.</p><p>That’s a higher standard — and this hackathon showed me exactly where I need to grow.</p><h3>Closing</h3><p>I don’t regret not getting a perfect score. It’s precisely the “good but not perfect” result that pushed me to compare, analyze, and write this article.</p><p>Thanks to DQLab and UjiKompetensi for a genuinely challenging problem grounded in real business context. The DQFresh Mart scenario is a great example of how data analytics can surface hidden opportunities in what looks like a downturn.</p><p><em>Have questions about pandas vectorization, Apriori, or retail analytics? Leave a comment below or connect with me on LinkedIn.</em></p><p><strong>Tags:</strong> #Python #DQLab #UjiKompetensi #Hackathon #Pandas #DataScience #RetailAnalytics #Vectorization #Matplotlib #Apriori #HackathonDQLab #PortfolioProject</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aac5578d06f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing and Predicting F1 Driver Ratings: A Data Science Approach Using Python]]></title>
            <link>https://medium.com/@riznofadhil2/analyzing-and-predicting-f1-driver-ratings-a-data-science-approach-using-python-aa152ba641a0?source=rss-7d158622173c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa152ba641a0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[f1]]></category>
            <category><![CDATA[data-science-projects]]></category>
            <category><![CDATA[motorsport]]></category>
            <dc:creator><![CDATA[Rizno Fadhil]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 01:57:30 GMT</pubDate>
            <atom:updated>2024-12-05T09:02:56.709Z</atom:updated>
            <content:encoded><![CDATA[<p>As Formula 1 continues to captivate millions around the world, the fascination with driver performance and team dynamics remains ever-present. With the advancement of data science, we can now delve deeper into the statistics behind these performances. In this post, we’ll explore a data analysis project that examines F1 driver ratings over three seasons — 2021, 2022, and 2023 — using Python, based of previous 3-official-game-series of Formula 1, F1 2021, F1 22, and F1 23.</p><h3>Libraries and Datasets</h3><p>Before diving into the analysis, let’s start by importing the necessary libraries and loading the datasets:</p><pre>import numpy as np <br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from sklearn.linear_model import LinearRegression<br>from sklearn import metrics<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error, r2_score<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p>We then load the datasets for the three seasons:</p><pre>f1_21 = pd.read_csv(&#39;F1 2021.csv&#39;)<br>f1_22 = pd.read_csv(&#39;F1 2022.csv&#39;)<br>f1_23 = pd.read_csv(&#39;F1 2023.csv&#39;)</pre><h3>Data Exploration</h3><h4>F1 2021 Season</h4><p>To begin, we explore the 2021 dataset to understand the structure and summary statistics:</p><pre>f1_21.info()<br>f1_21.describe().T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*t1EUTXO1pHyKYDS4CkVGpQ.png" /><figcaption>Picture 1. Descriptive statistics of all attributes</figcaption></figure><p>This gives us a quick overview of the data, including the drivers’ experience (EXP), racecraft (RAC), awareness (AWA), pace (PAC), and overall rating (RTG). We then proceed to visualize the top 10 drivers based on different metrics:</p><ul><li><strong>Top 10 Drivers by Rating, in this case F1 2021:</strong></li></ul><pre>data21 = f1_21.copy()<br>data21 = data21.sort_values(by=&#39;RTG&#39;, ascending=False).head(10)<br>plt.figure(figsize=(15,5))<br>sns.barplot(x=data21[&#39;Driver&#39;], y=data21[&#39;RTG&#39;], ci=None)<br>plt.ylabel(&#39;Rating&#39;, fontsize=19)<br>plt.xlabel(&#39;Driver&#39;, fontsize=15)<br>plt.title(&quot;Best Rating in F1 2021&quot;, fontsize=19)<br>plt.ylim(80,100)<br>plt.xticks(rotation=40)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*J-UCmWff9h3ZfbwmrjC6GA.png" /><figcaption>Picture 2. Top 10 Driver’s Overall Rating in F1 2021</figcaption></figure><ul><li><strong>Top 10 Drivers by Experience, Racecraft, Awareness, and Pace:</strong></li></ul><pre><br>data21exp = data21.sort_values(by=&#39;EXP&#39; , ascending=False).head(10)<br>plt.figure(figsize=(15,5))<br>sns.barplot( x=data21exp[&#39;Driver&#39;] , y=data21exp[&#39;EXP&#39;] , ci=None)<br>plt.ylabel(&#39;Experience&#39; , fontsize=19)<br>plt.xlabel(&#39;Driver&#39; , fontsize=15)<br>plt.title(&quot;Highest Experience Rating in F1 2021&quot; ,fontsize=19)<br>plt.ylim(50,100)<br>plt.xticks(rotation=40)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*X1jp2Neol1GPH9TtO85UPA.png" /><figcaption>Picture 3. Top 10 Driver’s Experience Rating in F1 2021</figcaption></figure><pre>data21rac = data21.sort_values(by=&#39;RAC&#39; , ascending=False).head(10)<br>plt.figure(figsize=(15,5))<br>sns.barplot( x=data21rac[&#39;Driver&#39;] , y=data21rac[&#39;RAC&#39;] , ci=None)<br>plt.ylabel(&#39;Racecraft&#39; , fontsize=19)<br>plt.xlabel(&#39;Driver&#39; , fontsize=15)<br>plt.title(&quot;Highest Racecraft Rating in F1 2021&quot; ,fontsize=19)<br>plt.ylim(50,100)<br>plt.xticks(rotation=40)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*e-Lyj9t15uFcml70iUdlPQ.png" /><figcaption>Picture 4. Top 10 Driver’s Racecraft Rating in F1 2021</figcaption></figure><pre>data21awa = data21.sort_values(by=&#39;AWA&#39; , ascending=False).head(10)<br>plt.figure(figsize=(15,5))<br>sns.barplot( x=data21awa[&#39;Driver&#39;] , y=data21awa[&#39;AWA&#39;] , ci=None)<br>plt.ylabel(&#39;Awareness&#39; , fontsize=19)<br>plt.xlabel(&#39;Driver&#39; , fontsize=15)<br>plt.title(&quot;Highest Awareness Rating in F1 2021&quot; ,fontsize=19)<br>plt.ylim(50,100)<br>plt.xticks(rotation=40)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*5BTxcB8KZ9kMwbp-TbqStQ.png" /><figcaption>Picture 5. Top 10 Driver’s Awareness Rating in F1 2021</figcaption></figure><pre>data21pac = data21.sort_values(by=&#39;PAC&#39; , ascending=False).head(10)<br>plt.figure(figsize=(15,5))<br>sns.barplot( x=data21pac[&#39;Driver&#39;] , y=data21pac[&#39;PAC&#39;] , ci=None)<br>plt.ylabel(&#39;Pace&#39; , fontsize=19)<br>plt.xlabel(&#39;Driver&#39; , fontsize=15)<br>plt.title(&quot;Highest Pace Rating in F1 2021&quot; ,fontsize=19)<br>plt.ylim(50,100)<br>plt.xticks(rotation=40)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Jd7nJJy4PWwghLn4eopX8A.png" /><figcaption>Picture 6. Top 10 Driver’s Pace Rating in F1 2021</figcaption></figure><p>Similar visualizations are created for experience, racecraft, awareness, and pace to highlight the top-performing drivers in each category.</p><h3>F1 2022 and F1 2023 Data Exploration</h3><p>The same process is repeated for the 2022 and 2023 datasets, allowing us to compare driver performances across the seasons. Below are the key visualizations for the 2022 and 2023 seasons:</p><ul><li><strong>Top 10 Drivers by Rating, Experience, Racecraft, Awareness, and Pace in 2022:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*EA1ScwmC9LI8Z-lCrS5YdA.png" /><figcaption>Picture 7. Top 10 Driver’s Overall Rating in F1 22</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*ye2r00YClBLLetFIYYEjRQ.png" /><figcaption>Picture 8. Top 10 Driver’s Experience Rating in F1 22</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*Nbuf5TSbaFg8AYRv5s5pwQ.png" /><figcaption>Picture 9. Top 10 Driver’s Racecraft Rating in F1 22</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*FdoMSMgvIIc62a7p78V8rw.png" /><figcaption>Picture 10. Top 10 Driver’s Awareness Rating in F1 22</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*LOZvFEGnlYJs1YKSKPUDsQ.png" /><figcaption>Picture 11. Top 10 Driver’s PaceRating in F1 22</figcaption></figure><ul><li><strong>Top 10 Drivers by Rating, Experience, Racecraft, Awareness, and Pace in 2023:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*fforEsHxKLQbbne0Hr059Q.png" /><figcaption>Picture 12. Top 10 Driver’s Overall Rating in F1 23</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*b7ze1eguQkUpvCNyuJRBFA.png" /><figcaption>Picture 13. Top 10 Driver’s Experience Rating in F1 23</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*fdFkwcCeD2WYzslCo2ralQ.png" /><figcaption>Picture 14. Top 10 Driver’s Racecraft Rating in F1 23</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*7pYtKCvbaOnmSpAoTIFYlQ.png" /><figcaption>Picture 15. Top 10 Driver’s Awareness Rating in F1 23</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*7PFRrUtsEin-7gpJiqen9w.png" /><figcaption>Picture 16. Top 10 Driver’s Pace Rating in F1 23</figcaption></figure><p>These visualizations provide insights into how drivers’ performances have evolved and who has consistently remained at the top.</p><h3>Correlation Analysis</h3><p>Next, we analyze the correlation between different attributes and the overall rating (RTG) for each season:</p><pre>corr_21 = data21.corr(numeric_only=True)[&#39;RTG&#39;].sort_values()<br>corr_22 = data22.corr(numeric_only=True)[&#39;RTG&#39;].sort_values()<br>corr_23 = data23.corr(numeric_only=True)[&#39;RTG&#39;].sort_values()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*sSZ7BBxBkWrqP5awLMjjJQ.png" /><figcaption>Picture 17. Correlation between Rating and other Attributes in F1 2021</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*mbee_G7aMJ5EzvWQghoNhg.png" /><figcaption>Picture 18. Correlation between Rating and other Attributes in F1 22</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*7yLvVjSEVnO-Ja3-WU158g.png" /><figcaption>Picture 19. Correlation between Rating and other Attributes in F1 23</figcaption></figure><p>The correlation results help identify which attributes most influence a driver’s overall rating. For example, in 2021, Pace (PAC) had the highest positive correlation with the overall rating.</p><h3>Modeling: Predicting F1 Driver Ratings</h3><p>To predict the drivers’ ratings, we use a linear regression model. The features (attributes) include awareness, experience, racecraft, and pace, while the target variable is the overall rating:</p><pre>attributes = [&#39;AWA&#39;, &#39;EXP&#39;, &#39;RAC&#39;, &#39;PAC&#39;]<br>x21 = f1_21[attributes]<br>y21 = f1_21[&#39;RTG&#39;]<br><br>x21_train, x21_test, y21_train, y21_test = train_test_split(x21, y21, test_size=0.2, random_state=0)<br>lm = LinearRegression()<br>model_21 = lm.fit(x21_train, y21_train)<br><br>y21_pred = lm.predict(x21_test)<br><br># Calculate the Mean Squared Error (MSE) and R^2 score<br>mse21 = mean_squared_error(y21_test, y21_pred)<br>r2_21 = r2_score(y21_test, y21_pred)</pre><p>We repeat this process for the 2022 and 2023 datasets to see how well the model performs each year:</p><ul><li><strong>F1 2021 Model Performance:</strong> MSE = 0.453, R² = 0.990</li><li><strong>F1 2022 Model Performance:</strong> MSE = 0.065, R² = 0.999</li><li><strong>F1 2023 Model Performance:</strong> MSE = 1.245, R² = 0.986</li></ul><p>These metrics show that the model performed exceptionally well in predicting the drivers’ ratings for each season, with R² scores close to 1, indicating a strong fit.</p><h3>Conclusion</h3><p>Through this analysis, we explored the ratings of F1 drivers over three seasons and used linear regression models to predict these ratings based on various performance metrics. The results highlight the significance of specific attributes like Pace and Racecraft in determining a driver’s overall rating.</p><p>By leveraging data science tools and techniques, we can gain a deeper understanding of what makes an F1 driver successful and predict their future performances. As the world of sports continues to embrace data-driven decision-making, such analyses will become increasingly valuable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa152ba641a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>