<?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 Esraeslem on Medium]]></title>
        <description><![CDATA[Stories by Esraeslem on Medium]]></description>
        <link>https://medium.com/@esraeslem11?source=rss-caaabac8085e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*B9BsqyOokwZKUsbp</url>
            <title>Stories by Esraeslem on Medium</title>
            <link>https://medium.com/@esraeslem11?source=rss-caaabac8085e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:51:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@esraeslem11/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[How to Do Linear Programming in Excel: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@esraeslem11/how-to-do-linear-programming-in-excel-a-step-by-step-guide-6a76ce100dda?source=rss-caaabac8085e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a76ce100dda</guid>
            <category><![CDATA[linear-programming]]></category>
            <category><![CDATA[excell]]></category>
            <category><![CDATA[operations-research]]></category>
            <dc:creator><![CDATA[Esraeslem]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 12:27:41 GMT</pubDate>
            <atom:updated>2026-07-22T12:27:41.270Z</atom:updated>
            <content:encoded><![CDATA[<p>Linear Programming (LP) is one of those topics that looks intimidating on paper but becomes much more approachable once you see it laid out in a spreadsheet. Most stats and operations research courses eventually ask you to solve an LP problem not just by hand, but in Excel using <strong>Solver</strong>. The good news: you don’t need to be a programmer or have specialized optimization software. Excel’s built-in Solver add-in can handle LP problems with just a bit of setup.</p><p>This guide walks through the full process from enabling Solver to structuring your spreadsheet to interpreting the output, to using a worked example so you can follow along.</p><h3>A Quick Refresher: What Is Linear Programming?</h3><p>Linear Programming is a method for finding the best outcome (maximum profit, minimum cost, etc.) in a mathematical model whose requirements are represented by <strong>linear relationships</strong>. Every LP problem has three components:</p><ol><li><strong>Decision variables </strong>are<strong> </strong>the quantities you’re trying to determine (e.g., how many units of Product A and Product B to make)</li><li><strong>Objective function</strong> is the linear expression you want to maximize or minimize (e.g., total profit)</li><li><strong>Constraints</strong> are linear inequalities or equations that limit your decision variables (e.g., limited labor hours, limited raw materials)</li></ol><p>Excel’s Solver uses the <strong>Simplex LP</strong> algorithm to find the optimal values of your decision variables. These values give you the best possible objective function value while satisfying every constraint.</p><h3>The Example We’ll Work Through</h3><p>Let’s say a small furniture workshop makes <strong>tables</strong> and <strong>chairs</strong>. Each product requires labor and wood, and the workshop wants to figure out the production mix that <strong>maximizes profit</strong>.</p><ul><li>Profit per table: $40</li><li>Profit per chair: $30</li><li>Each table requires 2 hours of labor; each chair requires 1 hour</li><li>Each table requires 1 unit of wood; each chair requires 1 unit of wood</li><li>Available labor: 40 hours per week</li><li>Available wood: 30 units per week</li></ul><p>Mathematically:</p><pre>Maximize:   Z = 40x₁ + 30x₂</pre><pre>Subject to:<br>  2x₁ + x₂  ≤ 40      (labor constraint)<br>   x₁ + x₂  ≤ 30      (wood constraint)<br>        x₁ ≥ 0, x₂ ≥ 0</pre><p>Where x₁ = number of tables, x₂ = number of chairs.</p><p>This is a small enough problem that you could solve it graphically by hand, which makes it perfect for checking that Excel gives you the right answer.</p><h3>Step 1: Enable the Solver Add-in</h3><p>Solver doesn’t ship active by default, so you’ll need to turn it on. On Mac, add-ins live under the <strong>Tools</strong> menu in the top menu bar — not under File, and not inside a ribbon dialog like on Windows.</p><ol><li>Click <strong>Tools</strong> in the top menu bar</li><li>Select <strong>Excel Add-ins…</strong> (make sure it’s this exact item. Mac Excel has both “Add-ins” and “Excel Add-ins” as separate menu entries, and Solver only lives in the latter)</li><li>In the dialog that opens, check the box next to <strong>Solver Add-in</strong></li><li>Click <strong>OK</strong></li><li>Go to the <strong>Data</strong> tab; you should now see <strong>Solver</strong> on the far right, in the Analysis group</li></ol><p>If Solver doesn’t show up right away, fully quit Excel (Cmd+Q) and reopen it. The add-in occasionally needs a fresh launch to register on the ribbon.</p><p><em>(If you ever work on this in Excel for Windows: the path there is File → Options → Add-ins → Manage: Excel Add-ins → Go → check Solver Add-in.)</em></p><h3>Step 2: Structure Your Spreadsheet</h3><p>Good LP spreadsheets follow a consistent layout: one cell per decision variable, one cell for the objective function, and one row per constraint. Here’s a layout that works well:</p><p>Cell Content</p><p>B2 Tables (x₁) decision variable, starts at 0</p><p>C2 Chairs (x₂) decision variable, starts at 0</p><p>B4 Profit per table ($40)</p><p>C4 Profit per chair ($30)</p><p>B6 Objective function: =B2*B4 + C2*C4</p><p>B9:C9 Labor coefficients (2, 1)</p><p>B10:C10 Wood coefficients (1, 1)</p><p>D9 Labor used: =B2*B9 + C2*C9</p><p>D10 Wood used: =B2*B10 + C2*C10</p><p>E9 Labor available: 40</p><p>E10 Wood available: 30</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxpXH5G27BdCa_rbi2rlmQ.png" /></figure><p>A simple way to think about it: <strong>row for each constraint, column for each variable</strong>, with a “used” column that sums up consumption and an “available” column showing the limit. This structure makes Solver setup almost mechanical, and it’s the same structure your professor will expect if you’re being graded on process, not just the final numbers.</p><h3>Step 3: Enter the Formulas</h3><p>Using the layout above:</p><ul><li><strong>B2, C2</strong>: leave as 0 for now — Solver will fill these in</li><li><strong>B6</strong> (objective cell): =B2*B4+C2*C4</li><li><strong>D9</strong> (labor used): =B2*B9+C2*C9</li><li><strong>D10</strong> (wood used): =B2*B10+C2*C10</li></ul><p>Double-check that every formula references cells rather than typed-in numbers — this is what lets Solver adjust B2 and C2 and have everything else update automatically.</p><h3>Step 4: Launch Solver and Define the Model</h3><p>Go to <strong>Data → Solver</strong>. A dialog box opens with three key sections:</p><p><strong>1. Set Objective:</strong> Click the field, then click cell <strong>B6</strong>. Choose <strong>Max</strong> (since we’re maximizing profit).</p><p><strong>2. By Changing Variable Cells:</strong> Select <strong>B2:C2 </strong>these are the cells Solver is allowed to adjust.</p><p><strong>3. Subject to the Constraints:</strong> Click <strong>Add</strong> for each constraint:</p><ul><li>D9 &lt;= E9 (labor used ≤ labor available)</li><li>D10 &lt;= E10 (wood used ≤ wood available)</li><li>B2 &gt;= 0 and C2 &gt;= 0 (non-negativity — or just check &quot;Make Unconstrained Variables Non-Negative&quot; below the constraint list)</li></ul><p><strong>4. Select a Solving Method:</strong> Choose <strong>Simplex LP</strong> from the dropdown. This is critical — Simplex LP is the algorithm designed for linear problems and is what gives you a guaranteed optimal (not just approximate) solution.</p><p>Click <strong>Solve</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*qGpt0dVdU5vHT4Ks0g05Zw.png" /></figure><h3>Step 5: Interpret the Results</h3><p>Solver will pop up a dialog asking if you want to keep the solution. Before clicking OK, notice the <strong>Reports</strong> box on the right select <strong>Answer</strong> and <strong>Sensitivity</strong>, then click OK. This generates two new sheets alongside your model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*HiaKanjZzFOBUW_JaSEM6A.png" /></figure><p>For our furniture example, Solver should return:</p><ul><li><strong>x₁ (tables) = 10</strong></li><li><strong>x₂ (chairs) = 20</strong></li><li><strong>Maximum profit = $1,000</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMjrWnoA0MZCxP0VMycrLQ.png" /></figure><p>You can sanity-check: 2(10) + 20 = 40 (labor fully used), and 10 + 20 = 30 (wood fully used). Both constraints are <strong>binding</strong>. This means the workshop is using every available hour and every unit of wood, which makes sense at an optimum.</p><h3>Bonus: Reading the Sensitivity Report</h3><p>This is the part that trips up a lot of students but is usually exactly what a stats/OR course wants you to interpret. The <strong>Sensitivity Report</strong> has two tables:</p><p><strong>Variable Cells table</strong> — shows the “Reduced Cost” for each decision variable. A reduced cost of 0 means the variable is part of the optimal solution (as both of ours are here). A nonzero reduced cost tells you how much the objective coefficient would need to improve before it becomes worthwhile to produce that item at all.</p><p><strong>Constraints table</strong> — this is where <strong>shadow prices</strong> live. The shadow price tells you how much the objective function would improve if you had one more unit of a resource. For example, if the shadow price on wood is $10, that means one additional unit of wood would increase profit by $10 — useful information if you’re deciding whether to buy more raw material. The report also gives you the <strong>allowable increase/decrease</strong> range over which that shadow price remains valid, which is often exactly what homework problems ask you to report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*_WowFZp1MtOKInpN-bJ3XQ.png" /></figure><h3>Common Mistakes to Avoid</h3><ul><li><strong>Forgetting to select “Simplex LP”: </strong>Excel defaults to a nonlinear solving method (GRG Nonlinear), which can give you a locally optimal (and wrong) answer for a linear problem.</li><li><strong>Hardcoding numbers into the objective/constraint cells:</strong> instead of referencing the variable cells. This breaks Solver’s ability to search for a solution.</li><li><strong>Missing non-negativity constraints: </strong>without them, Solver may return nonsensical negative production quantities.</li><li><strong>Not checking “Answer” and “Sensitivity” reports</strong>: if your assignment asks about shadow prices or binding constraints, you need these reports, not just the final variable values.</li><li><strong>Confusing ≤ and ≥</strong> when adding constraints a flipped inequality will silently give you a completely different (and wrong) feasible region.</li></ul><h3>Wrapping Up</h3><p>Once you’ve built one LP model in Excel, the pattern becomes very repeatable: define your variable cells, write your objective as a formula, list your constraints as “used vs. available” pairs, and let Simplex LP do the searching. The real skill your course is testing isn’t the Excel mechanics; it’s translating a word problem into decision variables, an objective function, and constraints in the first place. Once that translation is done correctly, Excel does the heavy lifting.</p><p>If you want to practice, try modifying the furniture example: what happens to the optimal mix if labor drops to 30 hours? What if the profit per chair rises to $35? Re-running Solver on small tweaks like these is a great way to build intuition for how shadow prices and binding constraints actually behave, and it’s exactly the kind of exploration that makes concepts like this stick for exams.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a76ce100dda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hibrit Öneri Sistemi: MovieLens 20M Verisiyle Adım Adım User-Based + Item-Based Collaborative…]]></title>
            <link>https://medium.com/@esraeslem11/hibrit-%C3%B6neri-sistemi-movielens-20m-verisiyle-ad%C4%B1m-ad%C4%B1m-user-based-item-based-collaborative-409a87120ae4?source=rss-caaabac8085e------2</link>
            <guid isPermaLink="false">https://medium.com/p/409a87120ae4</guid>
            <category><![CDATA[user-based-recommender]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[hybrid]]></category>
            <category><![CDATA[item-based-recommender]]></category>
            <dc:creator><![CDATA[Esraeslem]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 16:17:07 GMT</pubDate>
            <atom:updated>2026-07-09T18:59:42.645Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hibrit Öneri Sistemi: MovieLens 20M Verisiyle Adım Adım User-Based + Item-Based Collaborative Filtering</h3><p><em>Bu yazıda, 20 milyon satırlık </em><strong><em>MovieLens 20M</em></strong><em> veri setini kullanarak sıfırdan bir </em><strong><em>hibrit öneri sistemi (hybrid recommender system)</em></strong><em> kurma sürecini adım adım anlatıyorum. Sadece “şu kodu yaz” değil; her adımda ne yapıyoruz, neden bu şekilde yapıyoruz ve yolda karşıma çıkan (ve gerçek dünyada oldukça yaygın olan) bellek problemlerini nasıl çözdüğümü de paylaşıyorum. Kod tarafını GitHub’da İngilizce olarak paylaştım; bu yazıda mantığı Türkçe olarak, tanımlarla birlikte anlatıyorum.</em></p><h3>İçindekiler</h3><ol><li>Öneri sistemleri ve hibrit yaklaşım nedir?</li><li>Veri seti: MovieLens 20M</li><li>Adım 1 — Veriyi hazırlama</li><li>Adım 2 — Hedef kullanıcının izlediği filmler</li><li>Adım 3 — Aynı filmleri izleyen kullanıcılar</li><li>Adım 4 — En benzer kullanıcıları bulma (Pearson korelasyonu)</li><li>Adım 5 — Weighted rating ve ilk 5 öneri</li><li>Item-based öneri</li><li>Nihai 10 öneri — gerçek sonuçlar</li><li>Bonus: 20 milyon satırla çalışırken bellek yönetimi</li></ol><h3>1. Öneri Sistemleri ve Hibrit Yaklaşım Nedir?</h3><p><strong>Collaborative filtering (işbirlikçi filtreleme)</strong>, “benzer kullanıcılar benzer şeyleri sever” ya da “bir ürünü sevenler genelde şu ürünleri de sever” mantığına dayanan bir öneri tekniğidir. İki ana türü var:</p><ul><li><strong>User-based CF:</strong> Hedef kullanıcıya <em>benzer davranan diğer kullanıcıları</em> bulur, onların beğendiği ama hedef kullanıcının henüz izlemediği filmleri önerir. Mantık: “Senin gibi film izleyenler şunları da izlemiş.”</li><li><strong>Item-based CF:</strong> Kullanıcının beğendiği <em>bir filme benzer diğer filmleri</em> bulur. Mantık: “Bu filmi sevdiysen, şunu da seversin.”</li></ul><p><strong>Hibrit öneri sistemi</strong>, bu iki yaklaşımı aynı anda kullanıp önerileri birleştirir. Tek bir yönteme güvenmek yerine, hem “sana benzeyen insanlar” hem de “izlediğin filme benzeyen filmler” perspektifinden öneri üretmek, tavsiyelerin çeşitliliğini ve güvenilirliğini artırır.</p><h3>2. Veri Seti: MovieLens 20M</h3><p><a href="https://grouplens.org/datasets/movielens/20m/">GroupLens</a> tarafından yayınlanan bu veri seti iki dosyadan oluşuyor:</p><ul><li>movie.csv → 27.278 film; movieId, title, genres kolonları</li><li>rating.csv → <strong>20.000.263 satır</strong>; userId, movieId, rating, timestamp kolonları (138.493 farklı kullanıcı)</li></ul><p>rating.csv tek başına <strong>~690 MB</strong>. Bu boyut, ileride bahsedeceğim bellek optimizasyonlarının neden gerekli olduğunu açıklıyor.</p><pre>import pandas as pd<br>movie = pd.read_csv(<br>    &quot;data/movie.csv&quot;,<br>    dtype={&quot;movieId&quot;: &quot;int32&quot;, &quot;title&quot;: &quot;string&quot;, &quot;genres&quot;: &quot;string&quot;},<br>)<br>rating = pd.read_csv(<br>    &quot;data/rating.csv&quot;,<br>    dtype={&quot;userId&quot;: &quot;int32&quot;, &quot;movieId&quot;: &quot;int32&quot;, &quot;rating&quot;: &quot;float32&quot;},<br>    parse_dates=[&quot;timestamp&quot;],<br>)</pre><p><strong>Neden </strong><strong>dtype belirtiyoruz?</strong> Pandas varsayılan olarak tam sayılar için int64, ondalıklar için float64 kullanır — her ikisi de 8 byte. Oysa userId/movieId gibi değerler int32&#39;ye (4 byte), rating gibi 0.5 adımlı değerler float32&#39;ye (4 byte) rahatlıkla sığar. 20 milyon satırda bu, kolon başına belleği yarıya indirir. timestamp&#39;i de string olarak değil, doğrudan datetime olarak okumak hem daha az yer kaplar hem de ileride tarih karşılaştırmasını (örn. &quot;en güncel oy&quot;) kolaylaştırır.</p><h3>3. Adım 1 — Veriyi Hazırlama</h3><h3>3.1 Film adı ve türünü rating’e ekleme</h3><pre>df = rating.merge(movie, how=&quot;left&quot;, on=&quot;movieId&quot;)<br>df[&quot;title&quot;] = df[&quot;title&quot;].astype(&quot;category&quot;)<br>df[&quot;genres&quot;] = df[&quot;genres&quot;].astype(&quot;category&quot;)</pre><p>rating verisinde sadece movieId var; kullanıcı dostu bir çıktı için filmin adını (title) ve türünü (genres) movie tablosundan merge ile ekliyoruz.</p><p><strong>category dtype nedir, neden kullanıyoruz?</strong> 27.278 farklı film adı, 20 milyon satırda defalarca tekrar ediyor. Bunu düz metin (string/object) olarak tutarsanız, pandas her satır için ayrı bir string nesnesi tutar — bu, milyonlarca tekrar eden kısa metin için ciddi bir bellek israfıdır. category dtype ise arka planda sadece <strong>27.278 benzersiz değeri bir kere</strong> saklar, her satırda da o değere işaret eden küçük bir tam sayı (kod) tutar. Sonuç: neredeyse aynı bilgi, çok daha az bellekle.</p><h3>3.2 Az oy alan filmleri elemek</h3><pre>comment_counts = pd.DataFrame(df[&quot;title&quot;].value_counts())<br>comment_counts.columns = [&quot;count&quot;]<br>rare_movies = comment_counts[comment_counts[&quot;count&quot;] &lt;= 1000].index<br>common_movies = df[~df[&quot;title&quot;].isin(rare_movies)]</pre><p>Toplam 27 bin küsur filmin çoğu çok az oy almış (birkaç kişi tarafından izlenmiş nadir filmler). Bu filmler için “benzer kullanıcı” hesaplamak hem istatistiksel olarak güvenilmez (çok az veri noktası) hem de gereksiz yere pivot tablomuzu devasa büyütür. Bu yüzden <strong>1000 veya daha az oy alan filmleri</strong> veri setinden çıkarıyoruz. Sonuçta elimizde 27.278 filmden sadece <strong>3.159 “popüler” film</strong> kalıyor ama bu 3.159 film hâlâ 17.766.015 satırlık oy içeriyor.</p><h3>3.3 Pivot table: user × movie matrixi</h3><p>Amacımız satırlarda kullanıcı, sütunlarda film, hücrelerde puan olan bir tablo:</p><pre>grouped = common_movies.groupby([&quot;userId&quot;, &quot;title&quot;], observed=True)[&quot;rating&quot;].mean()<br>del common_movies<br>user_movie_df = grouped.unstack().astype(&quot;float32&quot;)</pre><p><strong>Pivot table nedir?</strong> Uzun formatlı veriyi (her satır bir olay: “şu kullanıcı şu filme şu puanı verdi”) geniş formata çevirmektir: satır = kullanıcı, sütun = film. Genelde bunun için doğrudan df.pivot_table(index=&quot;userId&quot;, columns=&quot;title&quot;, values=&quot;rating&quot;) yazılır ve çoğu tutorial da böyle anlatır. Ben burada bilerek groupby(...).mean() + unstack() ikilisini kullandım; sebebini birazdan (bölüm 10&#39;da) detaylıca anlatıyorum — kısacası, <strong>aynı sonucu üreten ama çok daha az bellek harcayan</strong> bir alternatif.</p><p>Ortaya çıkan tablo <strong>138.493 kullanıcı × 3.159 film</strong> boyutunda — yani ~437 milyon hücre. Kullanıcıların büyük kısmı filmlerin küçük bir kısmını izlediği için bu tablonun çoğu boş (NaN); bu normal ve beklenen bir durum (sparse/seyrek matris).</p><h3>4. Adım 2 — Hedef Kullanıcının İzlediği Filmler</h3><p>Örnek olarak userId = 108170 için öneri üretiyoruz (item-based bölümüyle tutarlı olsun diye proje boyunca aynı kullanıcıyı kullanıyorum):</p><pre>random_user_df = user_movie_df[user_movie_df.index == random_user]<br>movies_watched = random_user_df.columns[random_user_df.notna().any()].tolist()</pre><p>notna() ile hangi sütunların (filmlerin) boş olmadığını buluyoruz — yani kullanıcının puan verdiği filmleri. Sonuç: <strong>186 film</strong>.</p><h3>5. Adım 3 — Aynı Filmleri İzleyen Kullanıcılar</h3><pre>movies_watched_df = user_movie_df[movies_watched]<br>user_movie_count = movies_watched_df.T.notnull().sum().reset_index()<br>user_movie_count.columns = [&quot;userId&quot;, &quot;movie_count&quot;]<br>perc = len(movies_watched) * 60 / 100<br>users_same_movies = user_movie_count[user_movie_count[&quot;movie_count&quot;] &gt; perc][&quot;userId&quot;].tolist()</pre><p>Burada mantık şu: 138 binden fazla kullanıcının <strong>hepsiyle</strong> korelasyon hesaplamak hem yavaş hem de anlamsız — çoğu kullanıcının hedef kullanıcıyla ortak izlediği film sayısı çok az olacağından korelasyon güvenilmez çıkar. Bunun yerine, hedef kullanıcının izlediği 186 filmin <strong>en az %60&#39;ını (112&#39;den fazlasını)</strong> izlemiş olan kullanıcıları filtreliyoruz. Bu eşik, “gerçekten benzer zevke sahip olabilecek” kullanıcı havuzunu daraltıyor: <strong>2.326 kullanıcı</strong>.</p><h3>6. Adım 4 — En Benzer Kullanıcıları Bulma (Pearson Korelasyonu)</h3><pre>final_df = pd.concat([<br>    movies_watched_df[movies_watched_df.index.isin(users_same_movies)],<br>    random_user_df[movies_watched],<br>])<br>final_df = final_df[~final_df.index.duplicated(keep=&quot;first&quot;)]<br>corr_df = final_df.T.corr().unstack().sort_values()<br>corr_df = pd.DataFrame(corr_df, columns=[&quot;corr&quot;]).reset_index()<br>corr_df.columns = [&quot;user_id_1&quot;, &quot;user_id_2&quot;, &quot;corr&quot;]<br>top_users = corr_df[<br>    (corr_df[&quot;user_id_1&quot;] == random_user) &amp;<br>    (corr_df[&quot;corr&quot;] &gt;= 0.65) &amp;<br>    (corr_df[&quot;user_id_2&quot;] != random_user)<br>][[&quot;user_id_2&quot;, &quot;corr&quot;]].sort_values(&quot;corr&quot;, ascending=False)</pre><p><strong>Pearson korelasyonu nedir?</strong> İki değişkenin (burada: iki kullanıcının ortak izledikleri filmlere verdikleri puanlar) birlikte ne kadar tutarlı hareket ettiğini ölçen, -1 ile +1 arasında bir katsayı. +1&#39;e yakınsa “ikisi de aynı filmlere benzer şekilde yüksek/düşük puan veriyor” demektir — yani zevkleri örtüşüyor.</p><p>final_df.T.corr() burada 2.326 kullanıcının (+ hedef kullanıcı) birbirleriyle ikili korelasyonunu hesaplıyor. .unstack() ile bu kare matrisi uzun formata çeviriyoruz ki filtreleme kolay olsun.</p><p><strong>Karşılaşılan bir hata — tekrarlayan index:</strong> Hedef kullanıcı, kendi izlediği filmlerin tanım gereği %100&#39;ünü izlemiş sayıldığından, users_same_movies listesine zaten otomatik olarak giriyor. Bu da final_df&#39;te hedef kullanıcının <strong>iki kez</strong> yer almasına (bir kez listeden, bir kez random_user_df&#39;ten eklendiği için) yol açıyor. Pandas&#39;ın güncel sürümlerinde (2.1+) stack()/unstack() metodları tekrarlayan index/sütun kabul etmiyor ve hata fırlatıyor — bu, birçok eski tutorial&#39;ın güncel pandas ile artık çalışmamasının sebeplerinden biri. Çözüm basit: final_df[~final_df.index.duplicated(keep=&quot;first&quot;)] ile tekrarları temizlemek.</p><p>Sonuç olarak korelasyonu <strong>0.65 ve üzeri</strong> olan <strong>6 kullanıcı</strong> buluyoruz:</p><pre>userId         corr <br>5155          0.716 <br>11517         0.708 <br>119285        0.700 <br>121747        0.673 <br>12710         0.663 <br>82860         0.655</pre><h3>7. Adım 5 — Weighted Rating ve İlk 5 Öneri</h3><pre>top_users_ratings = top_users.merge(rating[[&quot;userId&quot;, &quot;movieId&quot;, &quot;rating&quot;]], on=&quot;userId&quot;)<br>top_users_ratings[&quot;weighted_rating&quot;] = top_users_ratings[&quot;corr&quot;] * top_users_ratings[&quot;rating&quot;]<br>recommendation_df = top_users_ratings.groupby(&quot;movieId&quot;)[&quot;weighted_rating&quot;].mean().reset_index()<br>movies_to_be_recommend = recommendation_df[recommendation_df[&quot;weighted_rating&quot;] &gt; 3.5] \<br>    .sort_values(&quot;weighted_rating&quot;, ascending=False)<br>user_based_recommendations = movies_to_be_recommend.merge(movie, on=&quot;movieId&quot;)[<br>    [&quot;movieId&quot;, &quot;title&quot;, &quot;weighted_rating&quot;]<br>].head(5)</pre><p><strong>Neden düz ortalama değil, “weighted” (ağırlıklı) ortalama?</strong> Sadece “benzer kullanıcıların ortalama puanı”nı almak yerine, her kullanıcının puanını <strong>o kullanıcının hedef kullanıcıya ne kadar benzediğiyle</strong> (korelasyon katsayısıyla) çarpıyoruz. Böylece 0.72 korelasyonlu bir kullanıcının oyu, 0.66 korelasyonlu birinin oyundan biraz daha fazla ağırlık taşıyor — “sana daha çok benzeyenin fikri biraz daha değerli” mantığı.</p><p>Sonuçlar:</p><pre>movieId  title                                       weighted_rating <br>671      Mystery Science Theater 3000:The Movie(1996)     3.582 <br>2804     A Christmas Story (1983)                         3.582 <br>3098     The Natural (1984)                               3.582 <br>5110     Super Troopers (2001)                            3.582 <br>3310     The Kid (1921)                                   3.538</pre><p>İlginç bir detay: ilk dört filmin weighted_rating değeri <strong>birebir aynı</strong> (3.582032). Tesadüf değil — 0.716406 (userId 5155&#39;in korelasyonu) × 5.0 (verdiği puan) = 3.582032. Yani bu dört film, top 6 kullanıcı arasından <strong>sadece userId 5155 tarafından</strong> 5 yıldız verilmiş ve başka hiçbir top kullanıcı tarafından oylanmamış filmler. Bu, collaborative filtering&#39;in klasik bir gerçeğini gösteriyor: <strong>veri seyrekleştikçe (sparse), tek bir kullanıcının oyu tüm skoru domine edebiliyor.</strong> Daha büyük/daha yoğun bir kullanıcı havuzunda bu tür tam eşitlikler daha az görülür.</p><h3>8. Item-Based Öneri</h3><pre>movie_id = rating[(rating[&quot;userId&quot;] == user) &amp; (rating[&quot;rating&quot;] == 5.0)] \<br>    .sort_values(&quot;timestamp&quot;, ascending=False)[&quot;movieId&quot;].iloc[0]<br>movie_title = movie.loc[movie[&quot;movieId&quot;] == movie_id, &quot;title&quot;].iloc[0]<br>movie_df = user_movie_df[movie_title]<br>corr_with_movie = user_movie_df.corrwith(movie_df).sort_values(ascending=False)<br>item_based_recommendations = corr_with_movie.drop(movie_title).head(5)</pre><p>Bu bölümde mantık tamamen farklı: kullanıcıların birbirine benzerliği değil, <strong>filmlerin birbirine benzerliği</strong> hesaplanıyor. “Kullanıcı hangi filmi en son, en yüksek puanla izledi?” sorusunun cevabını buluyoruz (Wild at Heart, 1990), sonra user_movie_df&#39;teki <strong>bu filmin sütununu diğer tüm sütunlarla korelasyonluyoruz.</strong> Mantık: &quot;Bu filme benzer şekilde puanlanan (yani aynı kullanıcı grubu tarafından sevilen/sevilmeyen) filmler, muhtemelen türce/tarzca da benzerdir.&quot;</p><p><strong>Burada ikinci bir pratik sorunla karşılaştım:</strong> pandas’ın DataFrame.corrwith() metodu, hesaplama sırasında <strong>138.493 × 3.159&#39;luk matrisin tamamını dahili olarak </strong><strong>float64&#39;e çeviriyor</strong> — bu da yaklaşık 3.5 GB&#39;lık geçici bir kopya demek. Sınırlı bellekli bir makinede bu adım process&#39;in çökmesine (out-of-memory) yol açabiliyor. Çözüm olarak, matematiksel olarak birebir aynı sonucu veren ama sütun sütun ilerleyen, her adımda sadece o sütuna ait küçük diziler üzerinde çalışan manuel bir Pearson korelasyon fonksiyonu yazdım (kodun tamamı GitHub reposunda).</p><p>Sonuç Wild at Heart (1990)&#39;a en çok benzeyen 5 film:</p><p>title corr My Science Project (1985) 0.570 Mediterraneo (1991) 0.539 The Old Man and the Sea (1958) 0.536 National Lampoon’s Senior Trip (1995) 0.533 Clockwatchers (1997) 0.483</p><h3>9. Nihai 10 Öneri</h3><p>userId = 108170 için hibrit sistemin ürettiği son liste:</p><p><strong>User-Based (5):</strong></p><ol><li>Mystery Science Theater 3000: The Movie (1996)</li><li>A Christmas Story (1983)</li><li>The Natural (1984)</li><li>Super Troopers (2001)</li><li>The Kid (1921)</li></ol><p><strong>Item-Based (5, “Wild at Heart” beğenisine göre):</strong></p><ol><li>My Science Project (1985)</li><li>Mediterraneo (1991)</li><li>The Old Man and the Sea (1958)</li><li>National Lampoon’s Senior Trip (1995)</li><li>Clockwatchers (1997)</li></ol><p>İki listenin birbirinden tamamen farklı olması aslında beklenen ve istenen bir durum: user-based liste “sana benzeyenlerin sevdiği, henüz izlemediğin filmler”i, item-based liste ise “az önce sevdiğin filme benzer filmler”i yansıtıyor. Hibrit yaklaşımın değeri de tam olarak burada tek bir sinyale değil, iki farklı bakış açısına dayanıyor.</p><h3>10. Bonus: 20 Milyon Satırla Çalışırken Bellek Yönetimi</h3><p>Bu proje, sadece algoritmik olarak değil, <strong>mühendislik olarak</strong> da öğretici oldu. Kısıtlı bellekli bir ortamda (ör. 4 GB RAM’lik bir sanal makine) bu pipeline’ı çalıştırmaya çalışırken üç farklı noktada process OOM (out-of-memory) hatasıyla çöktü. Karşılaştığım sorunlar ve çözümleri:</p><p><strong>1. </strong><strong>dtype optimizasyonu.</strong> Varsayılan int64/float64/string yerine int32/float32/category kullanmak, 20 milyon satırlık veri setinde tek başına yüzlerce MB tasarruf sağlıyor.</p><p><strong>2. Zincirleme (chained) işlemler yerine ayrı adımlar.</strong> İlk denememde pivot table’ı şöyle kurmuştum:</p><pre>user_movie_df = (<br>    common_movies.groupby([&quot;userId&quot;, &quot;title&quot;])[&quot;rating&quot;]<br>    .mean()<br>    .unstack()<br>    .astype(&quot;float32&quot;)<br>)<br>del common_movies</pre><p>Bu kod <em>çalışıyor</em> ama bellek açısından verimsiz: common_movies değişkeni, zincirin tamamı bitene kadar (yani .unstack() gibi en pahalı adım tamamlanana kadar) bellekte tutulmaya devam ediyor çünkü Python, değişkenin artık kullanılmayacağını bilmiyor, siz del demeden bırakmıyor. Çözüm, zinciri bölüp common_movies&#39;i .mean() bittiği anda silmek:</p><pre>grouped = common_movies.groupby([&quot;userId&quot;, &quot;title&quot;])[&quot;rating&quot;].mean()<br>del common_movies<br>user_movie_df = grouped.unstack().astype(&quot;float32&quot;)<br>del grouped</pre><p>Aynı sonuç, belirgin biçimde daha düşük tepe bellek kullanımı.</p><p><strong>3. Silinen bellek gerçekten geri veriliyor mu?</strong> del + gc.collect() çoğu zaman <em>yeterli değil </em>glibc&#39;nin bellek ayırıcısı (memory allocator), serbest bırakılan belleği varsayılan olarak işletim sistemine iade etmek yerine process içinde &quot;ihtiyat&quot; olarak tutar (RSS düşmez). ctypes ile libc.malloc_trim(0) çağırmak, bu belleği gerçekten serbest bırakıp bir sonraki büyük işlem için yer açıyor:</p><pre>import ctypes, gc<br>libc = ctypes.CDLL(&quot;libc.so.6&quot;)<br><br>def free_memory():<br>    gc.collect()<br>    libc.malloc_trim(0)</pre><p><strong>4. </strong><strong>corrwith() tuzağı.</strong> Yukarıda bahsettiğim gibi, pandas&#39;ın hazır corrwith() fonksiyonu kolay ama belleği aç bir seçenek. Büyük matrislerde manuel/sütun bazlı hesaplama, aynı sonucu çok daha az bellekle veriyor.</p><p><strong>5. Tekrarlayan index/başlık sorunu.</strong> Aynı film adına sahip farklı movieId&#39;ler bazen (userId, title) ikilisinin tekrarlanmasına yol açabiliyor. Bu da pandas&#39;ın yeni sürümlerinde stack/unstack hatasına neden oluyor. ~df.index.duplicated(keep=&quot;first&quot;) ile bu tür tekrarları hesaplamadan önce temizlemek gerekiyor.</p><p>Bu beş noktanın hiçbiri algoritmanın <em>sonucunu</em> değiştirmiyor sadece aynı doğru sonucu, çok daha kısıtlı bir bellek bütçesiyle üretmeyi mümkün kılıyor. Büyük veriyle (özellikle bootcamp/ödev ortamlarında sınırlı Colab/VM kaynaklarıyla) çalışan herkesin er ya da geç karşılaşacağı pratik dersler.</p><p><strong>Kaynak kod:</strong> Projenin tam kodu (İngilizce yorumlarla, README.md ve kurulum talimatlarıyla birlikte) GitHub reposunda mevcut.</p><p><a href="https://github.com/esraeslem/hybrid_recommender">https://github.com/esraeslem/hybrid_recommender</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=409a87120ae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Armut Veri Setiyle Birliktelik Kuralı Analizi (Association Rule Learning): Hizmet Tavsiye Sistemi…]]></title>
            <link>https://medium.com/@esraeslem11/armut-veri-setiyle-birliktelik-kural%C4%B1-analizi-association-rule-learning-hizmet-tavsiye-sistemi-1c833accc716?source=rss-caaabac8085e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c833accc716</guid>
            <category><![CDATA[lift]]></category>
            <category><![CDATA[arl]]></category>
            <category><![CDATA[birliktelik-kuralları]]></category>
            <category><![CDATA[support]]></category>
            <category><![CDATA[association-rule-learning]]></category>
            <dc:creator><![CDATA[Esraeslem]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 18:30:26 GMT</pubDate>
            <atom:updated>2026-07-08T18:30:26.282Z</atom:updated>
            <content:encoded><![CDATA[<h3>Armut Veri Setiyle Birliktelik Kuralı Analizi (Association Rule Learning): Hizmet Tavsiye Sistemi Nasıl Kurulur?</h3><p><em>Bu yazıda, Türkiye’nin önde gelen online hizmet platformlarından biri olan Armut’un kullanıcı verileri kullanılarak sıfırdan bir ürün veya hizmet öneri sistemi oluşturma sürecini adım adım anlatacağım. Her aşamada “ne” ve “neden” sorularına yanıt vereceğim.</em></p><p><strong>Neden Birliktelik Kuralı Analizi Yapmalıyız?</strong></p><p>Herhangi bir e-ticaret platformunda “Bunu alanlar şunu da aldı” veya Netflix’te “Bunu izleyenler şunu da izledi” gibi önerilere rastladınız mı? Bu tür önerilerin arkasında genellikle çok etkili bir yöntem olan Association Rule Learning (ARL Birliktelik Kuralı Analizi) yatmaktadır.</p><p>Bu yazıda, Armut’un müşteri hizmetleri verilerini kullanarak bu tekniği ayrıntılı bir şekilde ele alacağız. Sürecimize veri hazırlama ile başlayacağız; ardından kurallar oluşturulacak ve son olarak elde edilen sonuçlar değerlendirilecek.</p><p><strong>İş Problemi</strong></p><p>Armut, temizlik, nakliyat, tadilat gibi çeşitli hizmet alanlarında ihtiyaç duyan kullanıcıları ve bu hizmetleri sunan profesyonelleri bir araya getiren bir platformdur. Kullanıcıların hangi hizmetleri, hangi kategorilerden ve ne zaman aldığını gösteren bir veri setine sahibiz.</p><p>Amacımız oldukça açık:</p><p>Geçmişteki satın alma davranışlarını kullanarak, bir hizmeti alan kullanıcılara birlikte sıkça tercih edilen diğer hizmetleri öneren bir sistem geliştirmektir.</p><p>Bunu gerçekleştirmenin en yaygın yöntemi birliktelik kuralı analizidir. Çünkü sahip olduğumuz veriler yalnızca davranışsal ve işlemsel nitelikte olup (kullanıcı demografisi, yorumlar, puan gibi ek bilgilere yer verilmemiştir), bu durum ARL’yi ideal bir seçenek haline getirir.</p><p><strong>Veri Seti Tanıtımı</strong></p><p>Veri setinde 4 değişken var:</p><p>Değişken. Açıklama</p><p>UserIdMüşteri numarası</p><p>ServiceIdAnonimleştirilmiş servis (örn. koltuk yıkama)</p><p>CategoryIdAnonimleştirilmiş kategori (örn. temizlik, nakliyat)</p><p>CreateDateHizmetin satın alındığı tarih-saat</p><p>Burada kritik bir detay var: ServiceId tek başına yeterli bir bilgi sağlamaz. Aynı ServiceId numarası, farklı bir CategoryId altında farklı hizmetleri temsil edebilir.Örneğin CategoryId=7, ServiceId=4 &quot;petek temizliği&quot; iken CategoryId=2, ServiceId=4 &quot;mobilya montaj&quot; anlamına geliyor. Bu nedenle ilk adımımız bu iki bilgiyi birleştirerek benzersiz ve tek bir “hizmet kimliği” oluşturmak olacak.</p><pre>import pandas as pd<br>from mlxtend.frequent_patterns import apriori, association_rules<br><br>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.width&#39;, 500)<br>df_ = pd.read_csv(&quot;armut_data.csv&quot;)<br>df = df_.copy()<br>print(df.head())<br>print(df.shape)</pre><p><strong>Çıktı:</strong> 162.523 satır, 4 sütun. Yani yaklaşık 162 bin hizmet alımı kaydı üzerinde çalışacağız.</p><p>Kodlamaya başlamadan önce, kullanacağımız terimleri açıklığa kavuşturalım; bu kavramları anlamadan ortaya çıkacak tablo yalnızca anlamsız sayılardan oluşacaktır.</p><p><strong>Itemset (Öğe Kümesi): </strong>Bir arada satın alınan ürün veya hizmetlerin oluşturduğu grup.</p><p><strong>Sepet (Basket/Transaction):</strong>Bir araya getirilerek tek bir fiyata dahil edilmiş öğelerden oluşan bir koleksiyon. Bu, klasik alışveriş sepeti analizi anlamında bir faturadır; ancak veri setimizde bu tür doğal bir “fatura” kavramı yoktur — bunu kendimiz oluşturacağız (bkz. Görev 1, Adım 3)</p><p><strong>Support (Destek):</strong>Tüm işlemler genelinde bir öğe kümesinin ne sıklıkla birlikte görüldüğünü temsil eder. “Bu koleksiyon ne sıklıkla görülür? →” sorusunu yanıtlar. support(X) = X’i içeren sepet sayısı / toplam sepet sayısı.</p><p><strong>Confidence (Güven):</strong>Eğer X’i seçtiysek, Y’nin de alınma olasılığıdır. “Biri X satın alırsa, Y’yi de satın alır mı?” sorusunu yanıtlar. confidence(X→Y) = support(X ve Y) / support(X).</p><p><strong>Lift:</strong> X örneklerinin Y ile birlikte görülme olasılığının, bunlar bağımsız olsaydı beklenenden ne kadar fazla olduğunu gösteren kat çarpanı. 1’den büyük bir kaldırma (lift) değeri, X ve Y’nin rastgele dağılıma göre daha iyi ilişkili olduğunu ifade eder; değeri ne kadar yüksekse, ilişkileri o kadar güçlüdür. Öneri sistemlerinde bu değer genellikle “altın” değerdir. lift(X→Y) = confidence(X→Y) / support(Y)</p><p><strong>Antecedent / Consequent:</strong> X → Y kuralında, X’e öncül (antecedent) (premise olarak da bilinir) denir ve Y’ye sonuç (consequent) (sonuç/izlemede (result/follow-up) olarak da bilinir) denir.</p><p><strong>Apriori Algoritması</strong>: Sık öğe kümelerini (frequent itemsets) elde etmeye yönelik, öğelerin tüm kombinasyonlarını kontrol etmeyen; bunun yerine “etkinsiz (infrequent) bir kümenin alt kümeleri de etkinsizdir” fikrine dayanan ve doğrusal zamanda çalışan bir algoritma. ARL’de kuralları üretmeden önce ilk adım budur.</p><p>Bu tanımları düşünerek kod yazmaya geçebiliriz.</p><h3>Görev 1: Veriyi Hazırlama</h3><p>ARL’yi kullanabilmemiz için verilerimizin belirli bir şekilde yapılandırılması gerekir; bir tabloda her bir kayıt (satır) bir “sepeti” temsil ederken, her bir alan (sütun) tek bir “ürün/hizmet”i temsil edecektir. Elimizdeki ham veri hiç de bu şekilde görünmüyor; dolayısıyla önce verileri bu forma dönüştüreceğiz.</p><p><strong>Adım 1: Veriyi Okutma</strong></p><pre>df_ = pd.read_csv(&quot;armut_data.csv&quot;)<br>df = df_.copy()</pre><p>Neden.copy()? df_ üzerinde değişiklik yapmadan verilerle çalışabilmek için bir kopya (df) oluştururuz. Böylece bir şeyler ters giderse, dosyanın tamamını tekrar okumaya ihtiyaç duymadan orijinal verilere geri dönebiliriz.</p><p><strong>Adım 2: “Hizmet” Değişkenini Oluşturma</strong></p><pre>df[&quot;Hizmet&quot;] = df[&quot;ServiceId&quot;].astype(str) + &quot;_&quot; + df[&quot;CategoryId&quot;].astype(str)</pre><p>Neden?Yukarıda belirttiğimiz gibi, ServiceId tek başına yeterli değildir.Burada, her bir hizmet için benzersiz bir şekilde belirleyici olan bir kimlik üretmek amacıyla ServiceId ve CategoryId&#39;yi &quot;_&quot; ile birleştiriyoruz örneğin &quot;4_5&quot;. Bu birleşik Hizmet değişkeni bundan sonra ARL modelimizin ürünü olacaktır.</p><p><strong>Çıktı örneği:</strong></p><p>UserId. ServiceId CategoryId. Hizmet</p><p>25446. 4 5 4_5</p><p>22948 48 5 48_5</p><p>10618 0 8 0_8</p><p><strong>Adım 3: “SepetID” (Sepet Tanımı) Oluşturma</strong></p><p>Projemizde en temel ama aynı zamanda en zor kısım işte burasıdır. Tipik bir pazaryerinde bir sepet oldukça nettir: bir fatura bir sepettir. Ancak Armut’ta bir kullanıcıya aynı gün içinde bir hizmet sunulduğunu ve üç ay sonra ikinci bir hizmet daha verildiğini düşünün. O zaman bunların hepsinin tek bir sepette geldiğini söylemek tamamen saçma olur çünkü bunların bir arada bulunması (eşzamanlılık/örtüşme) bile mümkün olmayabilir.</p><p>Burada önümüze açık bir kural çıkıyor : “Sepet” = bir kullanıcının bir ay içinde aldığı tüm hizmetler anlamına geliyor.</p><pre>df[&quot;CreateDate&quot;] = pd.to_datetime(df[&quot;CreateDate&quot;])<br>df[&quot;NEW_DATE&quot;] = df[&quot;CreateDate&quot;].dt.strftime(&quot;%Y-%m&quot;)<br>df[&quot;SepetID&quot;] = df[&quot;UserId&quot;].astype(str) + &quot;_&quot; + df[&quot;NEW_DATE&quot;]</pre><p>Neden bu sırayla oluşturuyoruz?</p><ol><li>pd.to_datetime ile CreateDate sütununu gerçek bir tarih tipine çeviriyoruz. Yoksa sadece metin olarak kalır, tarihsel işlemler yapamayız.</li><li>dt.strftime(&quot;%Y-%m&quot;) ile de tarihten yıl-ay bilgisini alıyoruz gün ve saat artık işimize yaramıyor çünkü sepeti ay bazında tanımlıyoruz.</li><li>UserId ile bu yeni tarih değişkenini birleştirip her kullanıcının her ayı için benzersiz bir SepetID üretiyoruz .Mesela &quot;7256_2017-08&quot; gibi</li></ol><p>Böylece aynı kullanıcının farklı aylardaki alışverişleri birbirinden ayrılıyor. 7256 numaralı kullanıcının Ağustos ayındaki hizmetleri bir sepet, Ekim ayındakiler bambaşka bir sepet olarak ele alınıyor.</p><p>Çıktı örneği şöyle: UserIdHizmetNEW_DATESepetID254464_52017–0825446_2017–082294848_52017–0822948_2017–0872569_42017–087256_2017–08</p><p>Görev 1 bittiğinde elimizde artık her satırda “hangi sepette hangi hizmet var” bilgisini taşıyan, ARL’ye hazır bir veri seti var.</p><h3>GÖREV 2: Birliktelik Kuralları Üretme</h3><p><strong>Adım 1: Sepet–Hizmet Pivot Tablosu Oluşturma</strong></p><p>ARL algoritmaları (apriori dahil) veriyi belli bir formatta bekler:</p><p>satırlar sepet, sütunlar ürün/hizmet, hücreler de “bu hizmet bu sepette var mı? (1/0)” şeklinde one-hot encoded bir matris. Şu anki verimiz hâlâ “uzun format” — her satır tek bir işlem. Bunu “geniş format”a, yani pivot tabloya çevirmemiz gerekiyor.</p><pre>invoice_product_df = df.groupby([&quot;SepetID&quot;, &quot;Hizmet&quot;])[&quot;Hizmet&quot;]. \<br>    count().unstack().fillna(0). \<br>    map(lambda x: 1 if x &gt; 0 else 0)</pre><p><strong>Bu satır adım adım ne yapıyor?</strong></p><ol><li>groupby([&quot;SepetID&quot;, &quot;Hizmet&quot;])[&quot;Hizmet&quot;].count(): Her sepet-hizmet kombinasyonunun kaç kez tekrarlandığını sayar. Mesela bir kullanıcı aynı ay içinde aynı hizmeti iki kez almış olabilir.</li><li>.unstack(): Hizmet değerlerini satırlardan sütunlara yatırır böylece her hizmet kendi sütunu olur, satırlar SepetID olur.</li><li>.fillna(0): Bir sepette hiç alınmamış hizmetler NaN (boş) olarak görünür; bunları 0 ile dolduruyoruz, çünkü &quot;0 kez alındı&quot; demek.</li><li>.map(lambda x: 1 if x &gt; 0 else 0): ARL&#39;de bizi ilgilendiren &quot;kaç kez alındığı&quot; değil, &quot;alınıp alınmadığı&quot;dır. Bu yüzden 1&#39;den büyük her değeri 1&#39;e indirgiyoruz.</li></ol><p>Not: Bu satırın klasik versiyonu .applymap() kullanır. Ama.applymap() yeni pandas sürümlerinde kaldırıldı, o yüzden işlevsel olarak aynı olan.map() ile değiştirdim.</p><p>Sonuç: 71.220 sepet × 50 hizmetten oluşan bir matris.</p><p>Örnek görünüm: | SepetID | 0_8 | … | 22_0 | … | 48_50_0 | | : — — | : — — | : — — | : — — | : — — | : — — | | 2017–08 | 0 | … | 0 | … | 1 | | 2018–04 | 0 | … | 0 | … | 0 | | 10000_2017–08 | 0 | … | 0 | … | 1 |</p><p><strong>Adım 2: Apriori ile Sık Öğe Kümelerini ve Kuralları Üretme</strong></p><pre>frequent_itemsets = apriori(invoice_product_df, min_support=0.01, use_colnames=True)<br>rules = association_rules(frequent_itemsets, metric=&quot;support&quot;, min_threshold=0.01)<br>print(rules.sort_values(&quot;lift&quot;, ascending=False).head(20))</pre><p><strong>Neden iki ayrı fonksiyon var?</strong></p><ul><li>apriori() önce, en az min_support=0.01 (yani sepetlerin en az %1&#39;inde görülen) öğe kümelerini buluyor. Bunun sebebi hesaplama verimliliği: 50 hizmetin tüm kombinasyonlarını denemek yerine, zaten nadir görülen kombinasyonları en baştan eleyip aramayı hızlandırıyoruz.</li><li>association_rules() bu sık kümelerden <strong>&quot;X alınırsa Y de alınır&quot;</strong> biçiminde yönlü kurallar (antecedent → consequent) üretiyor ve her kural için support, confidence, lift gibi metrikleri hesaplıyor.</li></ul><p>Kuralları lift değerine göre büyükten küçüğe sıraladığımızda elde ettiğimiz en güçlü ilişkiler:</p><p>| Antecedent | Consequent | Support | Confidence | Lift |</p><p>| : — — | : — — | : — — | : — — | : — — | | 25_0 | 22_0 | 0.0111 | 0.259 | 5.46 | | 22_0 | 25_0 | 0.0111 | 0.234 | 5.46 | | 38_49_4 | 0 | 0.0101 | 0.151 | 3.65 | | 15_1 | 33_4 | 0.0112 | 0.093 | 3.40 | | 2_0 | 22_0 | 0.0166 | 0.127 | 2.68 |</p><p>25_0 ile 22_0 hizmetleri arasındaki lift değeri <strong>5,46</strong> . Yani bu iki hizmet birbirinden bağımsız olsaydı beklenecek olasılığın yaklaşık 5,5 katı sıklıkta birlikte alınıyorlar. Bu, gerçek ve güçlü bir davranışsal örüntüye işaret ediyor — tam da bir tavsiye motorunun aradığı türden bir sinyal.</p><p><strong>Adım 3: </strong><strong>arl_recommender Fonksiyonu ile Gerçek Zamanlı Öneri Üretme</strong></p><p>Elimizde kurallar var ama bunları “kullanıcı X’e ne önerelim?” sorusuna çeviren bir fonksiyona ihtiyacımız var.</p><pre>def arl_recommender(rules_df, product_id, rec_count=1):<br>    sorted_rules = rules_df.sort_values(&quot;lift&quot;, ascending=False)<br>    recommendation_list = []<br>    for i, product in enumerate(sorted_rules[&quot;antecedents&quot;]):<br>        for j in list(product):<br>            if j == product_id:<br>                recommendation_list.append(list(sorted_rules.iloc[i][&quot;consequents&quot;])[0])<br>    recommendation_list = list(dict.fromkeys(recommendation_list))  # tekrarları eler<br>    return recommendation_list[0:rec_count]</pre><p><strong>Mantığı nedir?</strong></p><ol><li>Kuralları lift&#39;e göre büyükten küçüğe sıralıyoruz — çünkü en güçlü ilişkileri önce önermek istiyoruz.</li><li>Sıralı kurallar içinde, antecedent tarafında aradığımız product_id&#39;nin geçtiği kuralları buluyoruz.</li><li>Bulduğumuz her kuralın consequent (sonuç) tarafındaki hizmeti öneri listesine ekliyoruz.</li><li>rec_count parametresiyle kaç öneri istediğimizi belirliyoruz.</li></ol><p><strong>Dikkat edilmesi gereken önemli bir nokta:</strong> Bu fonksiyonun yaygın versiyonlarında döngü genelde sorted_rules[&quot;antecedents&quot;].items() ile kurulur. Ama sort_values() sonrası DataFrame&#39;in index&#39;i <strong>orijinal (karışık) index&#39;i korur</strong>, items() de bu orijinal index&#39;i döndürür. Bu index, .iloc[i]&#39;nin beklediği &quot;0&#39;dan başlayan sıralı pozisyon&quot; ile örtüşmediği için kod satır kaydırması yapar ve <strong>yanlış hizmetler önerir</strong>. Test ettiğimde, &quot;2_0&quot; sorgusunun kendisini önerdiğini gördüm. Bunun yerine enumerate() kullanarak sıralamadan sonraki gerçek pozisyonları (0, 1, 2, ...) kullandım. Bu .iloc[i] ile birebir örtüşüyor ve doğru sonuç veriyor. Ayrıca aynı hizmetin birden fazla kuralda çıkıp öneri listesinde tekrar etmesini engellemek için dict.fromkeys() ile tekilleştirme ekledim.</p><p>Uygulama: En son &quot;2_0&quot; hizmetini alan bir kullanıcıya öneri</p><pre>print(arl_recommender(rules, &quot;2_0&quot;, 1))   # [&#39;22_0&#39;]<br>print(arl_recommender(rules, &quot;2_0&quot;, 2))   # [&#39;22_0&#39;, &#39;25_0&#39;]<br>print(arl_recommender(rules, &quot;2_0&quot;, 3))   # [&#39;22_0&#39;, &#39;25_0&#39;, &#39;15_1&#39;]</pre><p>Yani &quot;2_0&quot; hizmetini en son alan bir kullanıcıya öncelik sırasına göre 22_0, ardından 25_0, ardından 15_1 hizmetlerini önermemiz gerektiğini öğreniyoruz. Çünkü kurallar tablosunda 2_0 → 22_0 (lift: 2,68), 2_0 → 25_0 (lift: 2,40) ve 2_0 → 15_1 (lift: 2,15) en yüksek lift değerine sahip, 2_0&#39;ı antecedent olarak içeren kurallar.</p><p><strong>Sonuçların Yorumu ve Ne İşe Yarar?</strong></p><p>Bu analizden çıkan pratik sonuç şu: Armut, bir kullanıcı bir hizmeti aldıktan hemen sonra (uygulama içi bildirim, e-posta ya da ana sayfa önerisi olarak) bu tabloya göre ilişkili hizmeti önerebilir. Mesela:</p><ul><li>25_0 hizmetini alan bir kullanıcıya 22_0 önerildiğinde, bu öneri rastgele değil. Geçmiş 71 binden fazla sepetin analizinden çıkan, istatistiksel olarak <strong>5,5 kat daha olası</strong> bir birliktelik örüntüsüne dayanıyor.</li><li>Bu yöntemin güzelliği, herhangi bir kullanıcı demografisi, puanlama sistemi ya da içerik bilgisine (collaborative/content-based filtering’in aksine) ihtiyaç duymadan, sadece davranışsal işlem geçmişinden çalışabilmesi.</li></ul><p><strong>Yöntemin sınırlılıkları da not edilmeli:</strong></p><p>min_support=0.01 gibi eşik değerleri sonucu doğrudan etkiler. Çok düşük tutulursa anlamsız/nadir ilişkiler kural olarak görünebilir, çok yüksek tutulursa gerçek ama nadir örüntüler kaçırılabilir. Ayrıca ARL, nedensellik değil sadece <strong>birliktelik (korelasyon)</strong> yakalar — 25_0 ile 22_0 birlikte alınıyor diye biri diğerine &quot;sebep&quot; oluyor demek değildir.</p><p><strong>Kapanış</strong></p><p>Bu proje, üç basit ama kritik fikri bir araya getiriyor:</p><ul><li>Ham işlem verisini doğru bir “sepet” tanımıyla yapılandırmak,</li><li>Apriori algoritmasıyla istatistiksel olarak anlamlı birliktelikleri bulmak,</li><li>Bu birliktelikleri gerçek zamanlı, kullanıcıya özel öneriye dönüştürmek.</li></ul><p>ARL, özellikle e-ticaret ve hizmet platformlarında hâlâ üretimde en çok kullanılan tavsiye sistemi yaklaşımlarından biri basit, yorumlanabilir ve devasa veri setlerinde bile hızlı çalışabiliyor. Umarım bu yazı, hem Armut projesinin mantığını hem de ARL’nin genel çalışma prensiplerini netleştirmiştir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c833accc716" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Veri Bilimi ile Müşteri Segmentasyonu: Python ile Uçtan Uca RFM Analizi Rehberi]]></title>
            <link>https://medium.com/@esraeslem11/veri-bilimi-ile-m%C3%BC%C5%9Fteri-segmentasyonu-python-ile-u%C3%A7tan-uca-rfm-analizi-rehberi-d8fd99af3e88?source=rss-caaabac8085e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8fd99af3e88</guid>
            <category><![CDATA[rfm-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <dc:creator><![CDATA[Esraeslem]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 18:41:18 GMT</pubDate>
            <atom:updated>2026-07-07T18:41:18.495Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Gerçek bir e-ticaret veri seti üzerinde, sıfırdan segment bazlı pazarlama aksiyonlarına kadar adım adım RFM</em>.</p><p><strong>Giriş: Neden Tüm Müşterilere Aynı Muameleyi Yapmamalısınız?</strong></p><p>Bir çevrimiçi ayakkabı dükkanını yönettiğinizi farz edin. 20.000 müşteri portföyünüz var. Ancak bu 20.000 kişinin hepsi aynı değere mi sahip? Kesinlikle hayır.</p><p>Bazı müşteriler her ay dükkana uğrayarak yüksek miktarda alışveriş yaparken, bazıları yıllardır herhangi bir alışveriş yapmamış. Bir kısmı henüz yeni katılmış ve potansiyelini ortaya koymamış. Eğer bu farklı profillere aynı e-postayı gönderip aynı indirimi sunarsanız, en değerli müşterilerinizi rahatsız edebilirken kaybetmek üzere olduğunuz müşterileri de kurtaramazsınız.</p><p>RFM analizi, müşteri davranışlarını temel alarak anlamlı gruplar oluşturmanın en etkili ve kanıtlanmış yöntemlerinden biridir. Bu yazıda, FLO’nun gerçek omnichannel satış verilerini kullanarak kapsamlı bir RFM analizi yapacağız.</p><h3>RFM Nedir?</h3><p>RFM, üç metriğin baş harflerinden oluşur:</p><p>Metrik Türkçe ne anlama gelir?</p><p><strong>R</strong>ecency (Yenilik): Müşteri en son ne zaman alışveriş yaptı?</p><p><strong>F</strong>requency (Sıklık): Toplamda kaç kez alışveriş yaptı?</p><p><strong>M</strong>onetary (Parasal Değer): Toplamda ne kadar harcadı?</p><p>Mantık şu şekilde: Son zamanlarda alışveriş yapan, sık gelen ve fazla harcayan müşterileriniz en değerli müşterilerinizdir. Bu üç kriteri sayısal hâle getirip bir araya getirdiğinizde, her müşteri için bir segment kategorisi belirleyebilirsiniz; örneğin “champions” veya “hibernating” gibi etiketler belirleyebilirsiniz.</p><p><strong>Veri Seti</strong></p><p>FLO’nun 2020–2021 dönemine ait çok kanallı satış verileri kullanılmıştır. Bu veri seti, hem çevrimiçi hem de fiziksel mağazalardan alışveriş yapan 19.945 müşteriye ait 12 farklı değişken içermektedir.</p><p>master_id → Eşsiz müşteri numarası order_channel → Kullanılan alışveriş kanalı first_order_date → İlk alışveriş tarihi last_order_date → Son alışveriş tarihi order_num_total_ever_online → Toplam online sipariş sayısı order_num_total_ever_offline → Toplam offline sipariş sayısı customer_value_total_ever_online → Toplam online harcama customer_value_total_ever_offline→ Toplam offline harcama interested_in_categories_12 → Son 12 ayda alışveriş yapılan kategoriler</p><p><strong>Adım 1: Veriyi Yükleme ve İlk Keşif</strong></p><pre>import pandas as pd<br>import datetime as dt<br>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.width&#39;, 500)<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;%.2f&#39; % x)<br>df_ = pd.read_csv(&quot;flo_data_20k.csv&quot;)<br>df = df_.copy()<br>print(df.head(10))<br>print(df.shape)       # (19945, 12)<br>print(df.isnull().sum())  # Eksik değer kontrolü<br>print(df.describe().T)    # Betimsel istatistikler</pre><p>İlk olarak göz önünde bulundurulması gerekenler:</p><ul><li>order_num_total_ever_online ve order_num_total_ever_offline değişkenlerinin toplamı, her müşterinin yaptığı toplam sipariş sayısını gösterir.</li><li>Tarih sütunları başlangıçta object veri tipindedir; bunların datetime formatına dönüştürülmesi gerekmektedir.</li><li>Verilerde boş değer yoktur, ancak aykırı değerlerin bulunabileceği unutulmamalıdır.</li></ul><p><strong>Adım 2: Yeni Değişkenler Oluşturma</strong></p><p>Her müşteri hem çevrimiçi hem de fiziksel alışveriş yapıyor (omnichannel). Bu iki kanalı bir araya getirerek tek bir “toplam” değişkeni oluşturuyoruz:</p><pre># Toplam sipariş sayısı (online + offline)<br>df[&quot;order_num_total&quot;] = (df[&quot;order_num_total_ever_online&quot;] +<br>                          df[&quot;order_num_total_ever_offline&quot;])<br><br># Toplam harcama (online + offline)<br>df[&quot;customer_value_total&quot;] = (df[&quot;customer_value_total_ever_offline&quot;] +<br>                               df[&quot;customer_value_total_ever_online&quot;])</pre><p>Tarih sütunlarını dönüştürelim:</p><pre>date_columns = df.columns[df.columns.str.contains(&quot;date&quot;)]<br>df[date_columns] = df[date_columns].apply(pd.to_datetime)</pre><p><strong>Adım 3: Keşifsel Veri Analizi</strong></p><p>Şimdi kanal bazında müşteri sayısını, toplam siparişleri ve harcamaları inceleyelim:</p><pre>df.groupby(&quot;order_channel&quot;).agg(<br>    müşteri_sayısı=(&quot;master_id&quot;, &quot;count&quot;),<br>    toplam_sipariş=(&quot;order_num_total&quot;, &quot;sum&quot;),<br>    toplam_harcama=(&quot;customer_value_total&quot;, &quot;sum&quot;)<br>)</pre><p>Çıktı (yaklaşık değerler):</p><pre>müşteri_sayısı  toplam_sipariş  toplam_harcama<br>order_channel<br>Android App             9495          52269      7819062.76<br>Desktop                 2735          13517      2149111.04<br>iOS App                 2833          15109      2411257.25<br>Mobile                  4882          21679      3311732.82</pre><p>Android uygulaması hem en fazla müşteriyi hem de en yüksek ciroyu üretiyor.</p><p>En fazla kazanç getiren ilk 10 müşteri:</p><pre>df.sort_values(&quot;customer_value_total&quot;, ascending=False).head(10)[<br>    [&quot;master_id&quot;, &quot;order_num_total&quot;, &quot;customer_value_total&quot;]<br>]</pre><p><strong>Adım 4: RFM Metriklerinin Hesaplanması</strong></p><p>RFM hesaplamak için önce bir analiz tarihi belirlememiz gerekiyor. Veri setindeki en son alışveriş tarihinden 2 gün sonrasını analiz tarihi olarak alıyoruz.</p><pre>analysis_date = df[&quot;last_order_date&quot;].max() + dt.timedelta(days=2)<br># analysis_date: 2021-06-01</pre><p>Şimdi her müşteri için R, F, M metriklerini hesaplayalım:</p><pre>rfm = df.groupby(&quot;master_id&quot;).agg(<br>    recency=(&quot;last_order_date&quot;,<br>             lambda x: (analysis_date - x.max()).days),   # Kaç gün geçmiş<br>    frequency=(&quot;order_num_total&quot;, &quot;sum&quot;),                  # Toplam sipariş sayısı<br>    monetary=(&quot;customer_value_total&quot;, &quot;sum&quot;)               # Toplam harcama<br>).reset_index()<br><br>print(rfm.head())</pre><pre>master_id  recency  frequency  monetary<br>0  0000080d-5be0-... (örnek)              95          3.0    326.00<br>1  0000080f-8b15-... (örnek)             110          2.0    184.97</pre><p><strong>Not:</strong> “Recency” burada günlük bazda değerlendiriliyor. Düşük recency, müşterinin yakın zamanda aktif olduğunu gösterirken; yüksek recency ise uzun zamandır işlem yapmadığını ve risk taşıdığını belirtir.</p><p><strong>Adım 5: RF Skorlarının Hesaplanması</strong></p><p>pd.qcut() ile her metriği 1–5 arasında eşit dilimlere ayırıyoruz:</p><p>python</p><pre># Recency: düşük gün = iyi, bu yüzden etiketleri ters veriyoruz<br>rfm[&quot;recency_score&quot;] = pd.qcut(rfm[&quot;recency&quot;], 5,<br>                                labels=[5, 4, 3, 2, 1])<br># Frequency: fazla sipariş = iyi, düz sıralama yeterli<br># rank(method=&quot;first&quot;) → aynı değerli müşterilerde bin kenar çakışmasını önler<br>rfm[&quot;frequency_score&quot;] = pd.qcut(rfm[&quot;frequency&quot;].rank(method=&quot;first&quot;), 5,<br>                                   labels=[1, 2, 3, 4, 5])<br># Monetary: benzer şekilde<br>rfm[&quot;monetary_score&quot;] = pd.qcut(rfm[&quot;monetary&quot;], 5,<br>                                 labels=[1, 2, 3, 4, 5])</pre><p><strong>Not:</strong> Frekans değişkeninde sıkça tekrar eden sayılar bulunduğunda (örneğin, yüzlerce müşterinin yalnızca iki siparişi varsa) “duplicate bin edges” hatası oluşur. Bu sorunu ise .rank(method=”first”) kullanarak her değere benzersiz bir sıra atayarak çözebilirsiniz.</p><p>Recency ve Frequency skorlarını birleştirerek <strong>RF_SCORE</strong> oluşturuyoruz:</p><pre>rfm[&quot;RF_SCORE&quot;] = (rfm[&quot;recency_score&quot;].astype(str) +<br>                    rfm[&quot;frequency_score&quot;].astype(str))<br><br># Örnek RF_SCORE değerleri: &quot;55&quot;, &quot;43&quot;, &quot;11&quot;, &quot;32&quot; ...</pre><p><strong>Adım 6: Segmentlerin Tanımlanması</strong></p><p>RF_SCORE kombinasyonlarını anlamlı segment isimlerine dönüştüreceğiz. Bunun için standart bir segment haritası kullanıyoruz:</p><pre>seg_map = {<br>    r&#39;[1-2][1-2]&#39;: &#39;hibernating&#39;,        # Uzun süredir gelmeyen + az sipariş<br>    r&#39;[1-2][3-4]&#39;: &#39;at_Risk&#39;,            # Uzun süredir gelmeyen + orta sipariş<br>    r&#39;[1-2]5&#39;    : &#39;cant_loose&#39;,          # Uzun süredir gelmeyen ama çok sipariş (!)<br>    r&#39;3[1-2]&#39;    : &#39;about_to_sleep&#39;,      # Uyumaya yakın<br>    r&#39;33&#39;        : &#39;need_attention&#39;,       # Dikkat gerektiriyor<br>    r&#39;[3-4][4-5]&#39;: &#39;loyal_customers&#39;,     # Sadık müşteriler<br>    r&#39;41&#39;        : &#39;promising&#39;,            # Umut vaat eden<br>    r&#39;51&#39;        : &#39;new_customers&#39;,        # Yeni müşteriler<br>    r&#39;[4-5][2-3]&#39;: &#39;potential_loyalists&#39;, # Potansiyel sadık müşteriler<br>    r&#39;5[4-5]&#39;   : &#39;champions&#39;             # En iyi müşteriler<br>}<br><br>rfm[&quot;segment&quot;] = rfm[&quot;RF_SCORE&quot;].replace(seg_map, regex=True)</pre><p>Bu harita, satırlarda recency skorunu ve sütunlarda frequency skorunu temsil eder. Görsel öğeleri okuyarak analiz yapabiliriz. Sol üst köşe (1–2 / 1–2) = hem uzak hem seyrek = uyuyan müşteri. Sağ alt köşe (5 / 4–5) = hem yakın hem sık = şampiyon.</p><p><strong>Adım 7: Segment Analizi</strong></p><p>Her segmentin ortalama R, F, M değerlerine bakalım:</p><pre>segment_analizi = rfm.groupby(&quot;segment&quot;).agg(<br>    recency_ort=(&quot;recency&quot;, &quot;mean&quot;),<br>    frequency_ort=(&quot;frequency&quot;, &quot;mean&quot;),<br>    monetary_ort=(&quot;monetary&quot;, &quot;mean&quot;),<br>    müşteri_sayısı=(&quot;master_id&quot;, &quot;count&quot;)<br>).sort_values(&quot;monetary_ort&quot;, ascending=False).round(1)<br><br>print(segment_analizi)</pre><p>Çıktı (yaklaşık değerler):</p><pre>recency_ort  frequency_ort  monetary_ort  müşteri_sayısı<br>segment<br>champions                  17.1          12.6        1406.6             833<br>cant_loose                379.3           8.8         960.5             219<br>loyal_customers             82.3           8.5         876.4            3371<br>at_Risk                   241.0           4.6         545.9            1243<br>need_attention            113.3           3.4         373.9             380<br>potential_loyalists         29.0           3.0         344.9            2981<br>about_to_sleep            146.4           2.5         288.5             482<br>new_customers               8.5           2.0         339.3             680<br>promising                  22.4           2.0         290.3             232<br>hibernating               231.8           2.2         231.1            3604</pre><p>Bu tablo dikkat çekici bir hikâye sunuyor:</p><p>Şampiyon segmentindeki 833 müşteri ortalama 1.406 TL harcarken, pasif gruptaki 3.604 müşteri sadece 231 TL harcamış ve ortalama 232 gün boyunca geri dönmemiştir.</p><p><strong>Adım 8: İş Aksiyonları (Case Çalışmaları)</strong></p><p>Segment verileri tek başına yeterli değildir. Asıl önem taşıyan şey, bu segmentleri kullanarak doğru müşterilere uygun mesajlarla ulaştırmaktır.</p><p>Case A: Yeni Premium Kadın Ayakkabı Markası</p><p>FLO’ya yeni bir premium kadın ayakkabı markası eklenecek. Hedef kitle ise sadık olanlar ve kadın kategorisine ilgi duyan müşterilerdir.</p><pre># 1. champions ve loyal_customers segmentindeki müşterileri al<br>hedef_segmentler = rfm[rfm[&quot;segment&quot;].isin([&quot;champions&quot;, &quot;loyal_customers&quot;])][&quot;master_id&quot;]<br># 2. Bu müşterileri ana veriyle eşleştir; KADIN kategorisine ilgi şartını uygula<br>hedef_musteriler = df[<br>    (df[&quot;master_id&quot;].isin(hedef_segmentler)) &amp;<br>    (df[&quot;interested_in_categories_12&quot;].str.contains(&quot;KADIN&quot;, na=False))<br>][&quot;master_id&quot;]<br>hedef_musteriler.to_csv(&quot;yeni_marka_hedef_musteri_id.csv&quot;, index=False)<br>print(f&quot;Hedeflenen müşteri sayısı: {hedef_musteriler.shape[0]}&quot;)<br># Çıktı: ~2487 müşteri</pre><p>Bu yaklaşımın temelinde, yüksek fiyatlı bir markanın daha önce kadın ürünlerine ilgi duyan ve bu markaya güvenen sadık müşterilerini kolayca ikna edebilmesi yatıyor. Yabancı bir müşteri kazanmak yerine mevcut ilişkileri derinleştirmek, hem maliyet açısından daha avantajlı hem de çok daha etkili bir yöntemdir.</p><p>Case B: Erkek ve Çocuk Ürünlerinde %40 İndirim Kampanyası</p><p>Büyük bir indirim yapacağız. Amacımız, bu kategorilere ilgi duyan ancak uzun zamandır alışveriş yapmamış müşterileri yeniden kazanmak için harika bir fırsat sunmak.</p><p>python</p><pre># cant_loose: eskiden çok alışveriş yapıyor ama artık gelmiyor → MUTLAKA kazanılmalı<br># hibernating: tamamen uyumuş → indirimle uyandırılabilir<br># new_customers: yeni geldi → ikinci alışverişe yönlendirmek için ideal an<br>hedef_segmentler = rfm[rfm[&quot;segment&quot;].isin(<br>    [&quot;cant_loose&quot;, &quot;hibernating&quot;, &quot;new_customers&quot;]<br>)][&quot;master_id&quot;]<br>hedef_musteriler = df[<br>    (df[&quot;master_id&quot;].isin(hedef_segmentler)) &amp;<br>    (df[&quot;interested_in_categories_12&quot;].str.contains(&quot;ERKEK|COCUK&quot;, na=False))<br>][&quot;master_id&quot;]<br>hedef_musteriler.to_csv(&quot;indirim_hedef_musteri_ids.csv&quot;, index=False)<br>print(f&quot;Hedeflenen müşteri sayısı: {hedef_musteriler.shape[0]}&quot;)<br># Çıktı: ~2770 müşteri</pre><p>Adım 9: Tüm Süreci Fonksiyonlaştırma</p><p>Tekrar kullanılabilir, temiz bir pipeline:</p><p>python</p><pre>def create_rfm(dataframe, csv=False):<br>    # --- Veri Hazırlama ---<br>    dataframe[&quot;order_num_total&quot;] = (dataframe[&quot;order_num_total_ever_online&quot;] +<br>                                     dataframe[&quot;order_num_total_ever_offline&quot;])<br>    dataframe[&quot;customer_value_total&quot;] = (dataframe[&quot;customer_value_total_ever_offline&quot;] +<br>                                          dataframe[&quot;customer_value_total_ever_online&quot;])<br>    date_cols = dataframe.columns[dataframe.columns.str.contains(&quot;date&quot;)]<br>    dataframe[date_cols] = dataframe[date_cols].apply(pd.to_datetime)<br><br># --- RFM Hesaplama ---<br>    analysis_date = dataframe[&quot;last_order_date&quot;].max() + dt.timedelta(days=2)<br>    rfm = dataframe.groupby(&quot;master_id&quot;).agg(<br>        recency=(&quot;last_order_date&quot;, lambda x: (analysis_date - x.max()).days),<br>        frequency=(&quot;order_num_total&quot;, &quot;sum&quot;),<br>        monetary=(&quot;customer_value_total&quot;, &quot;sum&quot;)<br>    ).reset_index()<br>    # --- Skorlama ---<br>    rfm[&quot;recency_score&quot;] = pd.qcut(rfm[&quot;recency&quot;], 5, labels=[5, 4, 3, 2, 1])<br>    rfm[&quot;frequency_score&quot;] = pd.qcut(rfm[&quot;frequency&quot;].rank(method=&quot;first&quot;), 5,<br>                                      labels=[1, 2, 3, 4, 5])<br>    rfm[&quot;monetary_score&quot;] = pd.qcut(rfm[&quot;monetary&quot;], 5, labels=[1, 2, 3, 4, 5])<br>    rfm[&quot;RF_SCORE&quot;] = (rfm[&quot;recency_score&quot;].astype(str) +<br>                        rfm[&quot;frequency_score&quot;].astype(str))<br>    # --- Segmentleme ---<br>    seg_map = {<br>        r&#39;[1-2][1-2]&#39;: &#39;hibernating&#39;,<br>        r&#39;[1-2][3-4]&#39;: &#39;at_Risk&#39;,<br>        r&#39;[1-2]5&#39;    : &#39;cant_loose&#39;,<br>        r&#39;3[1-2]&#39;    : &#39;about_to_sleep&#39;,<br>        r&#39;33&#39;        : &#39;need_attention&#39;,<br>        r&#39;[3-4][4-5]&#39;: &#39;loyal_customers&#39;,<br>        r&#39;41&#39;        : &#39;promising&#39;,<br>        r&#39;51&#39;        : &#39;new_customers&#39;,<br>        r&#39;[4-5][2-3]&#39;: &#39;potential_loyalists&#39;,<br>        r&#39;5[4-5]&#39;   : &#39;champions&#39;<br>    }<br>    rfm[&quot;segment&quot;] = rfm[&quot;RF_SCORE&quot;].replace(seg_map, regex=True)<br>    if csv:<br>        rfm.to_csv(&quot;rfm.csv&quot;, index=False)<br>    return rfm<br><br># Kullanım<br>df = pd.read_csv(&quot;flo_data_20k.csv&quot;)<br>rfm_df = create_rfm(df, csv=True)</pre><p><strong>Sonuç: RFM’den Ne Öğrendik?</strong></p><p>Analiz sonuçlarına göre,</p><ol><li>Müşteri tabanı çeşitlilik gösteriyor. 20.000 müşterinin yaklaşık %18&#39;i (3.604 kişi) uzun bir süre boyunca aktif değil ve az miktarda harcama yapmış durumda. Bu gruba kaynak ayırmak yerine, gelir artışı sağlamak amacıyla %4&#39;lük şampiyon grubuna odaklanmak daha faydalı olacaktır.</li><li>“cant_loose” segmenti için acil müdahale yapmamız gerekiyor. Bu küçük grup (219 kişi), geçmişte sıkça alışveriş yapmış, ancak son 379 gündür geri dönmemiş. Ortalama harcama tutarları 960 TL olan bu müşterileri tekrar kazanmak için yatırım yapmak mantıklı bir seçenek.</li><li>Kategori bilgisi segmentasyonu güçlendirir. Sadece RFM verileri değil, interested_in_categories_12 gibi içerik bilgilerini de bir araya getirdiğinizde, pazarlama stratejisi çok daha etkili hale geliyor.</li><li>Fonksiyonelleştirme gereklidir.Tek seferlik bir analiz yapmak yerine, düzenli olarak çalıştırılabilir ve sürüm kontrolüne uygun bir pipeline oluşturmak daha fazla operasyonel fayda sağlar.</li></ol><p><strong>Gereksinimler</strong></p><pre>pip install pandas</pre><p>Python 3.8+ ve pandas 1.0+ yeterlidir. Bu analizin içinde Lifetimes kütüphanesine ihtiyaç bulunmamaktadır (CLTV tahmini için farklı bir makale gereklidir).</p><p><strong>Kaynaklar</strong></p><ul><li>Veri seti: Miuul / DSMLBC Data Science Bootcamp — FLO Case Study</li><li>RFM metodolojisi: Hughes, A. M. (1994). <em>Strategic Database Marketing</em></li><li>pandas dokümantasyonu: pandas.pydata.org</li></ul><p><em>Bu yazı FLO veri seti üzerinde gerçek bir analiz çalışmasının belgelenmesidir. Kod ve sonuçlar doğrudan çalıştırılabilir.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8fd99af3e88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data-Driven Marketing: Customer Segmentation Using RFM Analysis with Python]]></title>
            <link>https://medium.com/@esraeslem11/data-driven-marketing-customer-segmentation-using-rfm-analysis-with-python-7acfeafad546?source=rss-caaabac8085e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7acfeafad546</guid>
            <category><![CDATA[rfm-analysis]]></category>
            <category><![CDATA[customer-lifetime-value]]></category>
            <category><![CDATA[ab-testing]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Esraeslem]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 20:13:37 GMT</pubDate>
            <atom:updated>2026-06-30T20:49:18.372Z</atom:updated>
            <content:encoded><![CDATA[<p>While many of us know e-commerce is highly competitive today, one thing companies need to keep in mind is that using traditional marketing strategies wastes money. Customers who shop from you once every week may be different than customers who haven’t shopped from you in over one year. It is important to know this information to engage customers effectively and maximize Customer Lifetime Value (CLV). By segmenting customers based on their actual purchases, businesses can engage more effectively and maximize CLV.</p><p>In this article, we will discuss a hands-on approach to RFM (Recency, Frequency and Monetary) analysis using Python, and we will use real-world data from FLO, a leading omni-channel footwear retailer with a large number of different styles of shoes available for purchase through multiple channels, to create a robust segmentation engine that will help us implement targeted marketing campaigns successfully (i.e., emails, direct mail, etc.).</p><p><strong>What Is RFM Analysis?</strong></p><p>RFM analysis is a technique used to segment customers into groups based upon their historical purchase transactions with you.</p><p>It uses three key metrics to establish customer segment groups:</p><p>Recency (R) — How recently has the customer purchased from you? (the lower the score, the more recently the customer purchased from you);</p><p>Frequency (F) — How many times has the customer purchased from you? (the greater the score, the more frequently the customer has purchased from you);</p><p>Monetary amount (M) — The total amount of money spent by the customer in their transactions within specified time periods (the higher the score, the greater the amount the customer spent with you).</p><p>After scoring each customer based on their RFM characteristics, we can determine where they fit into your business’ customer segmentation model (or persona).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/16/0*0YC4GtNkssZOnM69.png" /></figure><p><strong>Phase 1: Gain an understanding of OmniChannel data and prepare data for analysis</strong></p><p>The OmniChannel dataset comprises roughly 20K unique customers who made transactions both online and offline during the 2020–2021 period. To calculate “true” lifetime transaction counts and values for each distinct customer, aggregating online and offline metrics is a necessary first step, a process known as feature engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*023rwUHfqwy5fAk58vGU4A.png" /></figure><p><strong>Phase 2: Calculate the RFM metrics from the OmniChannel data</strong></p><p>To calculate “Recency”, we first need to establish a date to use as “today”. One standard practice in data science when working with historical datasets is to identify the date of the most recent transaction in the full dataset and add 2 days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKcM3_SIO5AA1VhSFLqyPA.png" /></figure><p><strong>Phase 3: Create RF scores and generate behavioral segments</strong></p><p>Once the raw values have been generated, we convert them to scores between 1 and 5 using quantiles (pd.qcut).</p><p><strong>Note:</strong> For recency, lower raw numbers indicate the transaction is more recent than higher raw numbers.</p><p>Therefore, recency raw scores that are lowest will receive the highest score of 5; frequencies &amp; monetary raw scores, where higher is better, will receive a score of 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3r5bsO0gP8NNryLrZ0_Pgg.png" /></figure><p>By applying a standard segmentation matrix mapping (R×F), we have been able to cluster our customers in distinct, descriptive labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*aVxeNLTmU8xajNikGa6L4A.png" /></figure><p><strong>Phase 4: Create actionable marketing use cases</strong></p><p>Segmentation is useful for generating actions. Below are two examples of how FLO has applied this dataset in actual business scenarios.</p><p><em>Case A: Launch of an Exclusive Premium Brand Focused on High-Value Loyal Customers.</em></p><p>The Goal: FLO is launching a premium women’s shoe brand on its website with premium pricing and exclusive access to potential customers, who are women with a significant brand affinity to the category.</p><p>Target Audiences: champions, loyal_customers</p><p>Category Filter: Interested in “KADIN” (Women’s)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhVmuDa0RWPQsK9Nd9x_BA.png" /></figure><p><em>Case B: Reactivation &amp; Growth Discount Campaign Focused on Win-Back &amp; Onboarding</em></p><p>The Goal: FLO will provide a 40% discount to all existing customers to promote Future Loyalty (FLO) among Existing Customers in the Men’s and Children’s categories.</p><p>To find new customers, “cold accounts” (existing customers who are still FLO customers but have never purchased) will be re-engaged with the offer via email or other marketing channels.</p><p>Target Audiences: cant_loose, hibernating, new_customers</p><p>Category Filter: Interested in “ERKEK” (Men) or “COCUK” (Child)</p><p>Conclusion</p><p>This logic translates to a clean, reusable codebase and to moving raw data into a super-specific list of consumers, ready for programmatic CRM push notifications, email flows, and/or social media custom audience targeting. RFM analysis connects raw engineering data with your marketing strategies, and instead of wasting money by offering discounts to your elite-tier customers for no reason or by offering expensive items to someone who has already left, you will be able to deliver messages and product offerings matched to buyers’ behaviors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/16/0*iKTo-UPzAS6VDWW3.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8_NGRTeY5OCBv6E2OQeuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/48/0*1Pxc9VEyuZ2LQabd.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7acfeafad546" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>