<?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 Murat Yıldırım on Medium]]></title>
        <description><![CDATA[Stories by Murat Yıldırım on Medium]]></description>
        <link>https://medium.com/@murattyldrm7?source=rss-bbf7f745dc16------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*347mfDzrE4IDlWUN</url>
            <title>Stories by Murat Yıldırım on Medium</title>
            <link>https://medium.com/@murattyldrm7?source=rss-bbf7f745dc16------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:59:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@murattyldrm7/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[I Adapted Karpathy’s microGPT to Predict Temperature — Pure Python, Zero Libraries]]></title>
            <link>https://medium.com/@murattyldrm7/i-adapted-karpathys-microgpt-to-predict-temperature-pure-python-zero-libraries-e842ea2f7ae4?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/e842ea2f7ae4</guid>
            <category><![CDATA[microgpt]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[andrej-karpathy]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 14:31:58 GMT</pubDate>
            <atom:updated>2026-04-11T14:31:58.386Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Turning a character-level language model into a time series regressor without touching the transformer core.</em></p><p>A few weeks ago I came across Andrej Karpathy’s microgpt — a single-file GPT implementation in dependency-free Python. No PyTorch, no NumPy. Just math, random, and a surprisingly complete autograd engine packed into a Value class.</p><p>The original code trains on a list of names and generates new ones. Educational, minimal, and at first glance not well-suited for time series regression.</p><p>I wanted to find out how far that was actually true. The goal: adapt it to predict hourly temperatures in Basel using one year of real meteorological data, while keeping the transformer architecture intact. Here’s what I changed, what I kept, and what I learned along the way.</p><h3>What microGPT actually does</h3><p>Before the changes, it’s worth understanding what the original code does at a mechanical level.</p><p>It’s a character-level language model. The tokenizer is a lookup table — each unique character maps to an integer ID. The model learns a probability distribution over the next token given the previous ones. Loss is cross-entropy. Output is a softmax over vocab_size logits.</p><p>The transformer follows a GPT-2-style decoder-only skeleton, but simplified: token embedding plus positional embedding, RMSNorm instead of LayerNorm, no biases, ReLU instead of GeLU, causal multi-head self-attention. A single-file, quite compact implementation.</p><p>The autograd engine (Value) is essentially micrograd — each node stores its children and local gradients, and backward() does a topological sort and walks it in reverse, accumulating gradients via the chain rule.</p><h3>The problem with applying it directly to temperature data</h3><p>Numbers and characters are fundamentally different input types.</p><p>A character tokenizer assumes a finite discrete vocabulary. The character &#39;a&#39; maps to index 4 — you pull row 4 from the embedding matrix. That works because there are maybe 27 unique characters.</p><p>Temperature is continuous. 23.4°C doesn&#39;t have a token ID. And even if you discretized it, the embedding lookup would destroy the ordinal relationship — there&#39;s no reason the model should know that 23°C is close to 24°C.</p><p>The right approach is a linear projection: take the scalar value and multiply it by a weight matrix to get a dense vector. This preserves continuity and lets gradients flow back through the actual temperature value.</p><p>Three other things needed to change:</p><ul><li>Output layer: instead of vocab_size logits fed into softmax, a single scalar — a regression head.</li><li>Loss function: cross-entropy assumes a probability distribution over categories. One of the most natural choices for regression is MSE: loss = (pred - target) ** 2.</li><li>Inference: no sampling, no temperature scaling — just denormalize the output and report the predicted degree.</li></ul><p>Everything in between — attention, MLP, residual connections, RMSNorm — stays exactly as Karpathy wrote it.</p><p>Three core changes to the transformer itself were enough. On the data side, time-series-appropriate windowing, a chronological split, and leakage fixes were also necessary — those are just as critical as the architecture changes, and I cover them separately below.</p><h3>The changes, concretely</h3><h3>Input: lookup table → projection</h3><p>Original:</p><pre>tok_emb = state_dict[&#39;wte&#39;][token_id]  # row lookup</pre><p>Adapted:</p><pre>tok_emb = linear([Value(temp_val)], state_dict[&#39;wte&#39;])  # 1 → n_embd</pre><p>wte is now shaped (n_embd, 1) instead of (vocab_size, n_embd). A single normalized float gets projected into a 16-dimensional vector.</p><h3>Output: distribution → scalar</h3><p>Original:</p><pre>logits = linear(x, state_dict[&#39;lm_head&#39;])  # (vocab_size,)</pre><p>Adapted:</p><pre>out = linear(x, state_dict[&#39;lm_head&#39;])  # (1,)<br>return out[0]</pre><p>lm_head is now (1, n_embd).</p><h3>Loss: cross-entropy → MSE</h3><p>Original:</p><pre>probs = softmax(logits)<br>loss = -probs[target_id].log()</pre><p>Adapted:</p><pre>target = Value(y_true)<br>loss = (pred - target) ** 2</pre><h3>Data: documents → sliding windows</h3><p>The original iterates over documents (names). The adapted version uses a sliding window over the normalized temperature sequence:</p><pre>for i in range(len(train_norm) - block_size):<br>    x = train_norm[i:i + block_size]<br>    y = train_norm[i + block_size]<br>    train_windows.append((x, y))</pre><p>block_size = 24 — the model sees the last 24 hours and predicts the next one.</p><p>During the forward pass, each hour is fed sequentially into gpt(), building up the key-value cache along the way. Only the final prediction is used for the loss.</p><h3>The train/test split problem</h3><p>This is the part that’s easy to get wrong.</p><p>A naive implementation would normalize the entire dataset first, then shuffle all windows and split. That creates two leakage problems:</p><p>Normalization leakage: the min and max used for normalization include future data. At inference time, you won’t have that information.</p><p>Temporal leakage: shuffling time series windows destroys temporal ordering. The model can end up training on windows that come <em>after</em> the windows it’s evaluated on — effectively learning from the future.</p><p>The fix is straightforward but order-dependent:</p><pre># Split first<br>split = int(len(temps) * 0.8)<br>train_temps = temps[:split]<br>test_temps  = temps[split:]</pre><pre># Compute statistics from train only<br>min_temp = min(train_temps)<br>max_temp = max(train_temps)</pre><pre># Normalize both sets with train statistics<br>train_norm = [normalize(t) for t in train_temps]<br>test_norm  = [normalize(t) for t in test_temps]</pre><pre># Shuffle only train windows<br>random.shuffle(train_windows)<br># test_windows stays chronological</pre><p>This gives a realistic estimate of how the model performs on genuinely unseen future data.</p><h3>Results</h3><p>Dataset: Basel hourly temperature, ~10,800 hours. 80/20 chronological split. n_embd=16, n_layer=1, n_head=4, block_size=24, 500 training steps.</p><pre>--- Test Results (10 consecutive samples) ---<br>Actual: -1.98°C  |  Predicted: -2.54°C  |  Error: 0.56°C<br>Actual: -2.26°C  |  Predicted: -2.74°C  |  Error: 0.48°C<br>Actual: -2.62°C  |  Predicted: -3.01°C  |  Error: 0.39°C<br>Actual: -2.89°C  |  Predicted: -3.36°C  |  Error: 0.47°C<br>Actual: -2.92°C  |  Predicted: -3.61°C  |  Error: 0.69°C<br>Actual: -3.22°C  |  Predicted: -3.64°C  |  Error: 0.42°C<br>Actual: -2.58°C  |  Predicted: -3.91°C  |  Error: 1.33°C<br>Actual: -2.86°C  |  Predicted: -3.30°C  |  Error: 0.44°C<br>Actual: -3.13°C  |  Predicted: -3.55°C  |  Error: 0.42°C<br>Actual: -3.45°C  |  Predicted: -3.77°C  |  Error: 0.32°C</pre><p>Mean absolute error across these 10 consecutive test samples: 0.55°C. This isn’t a formal benchmark — the goal was to show how little the transformer core needs to change to adapt to regression. For a single-layer transformer with 3,488 parameters, trained in pure Python without any vectorization, it’s a reasonable result.</p><p>The sample predictions suggest the model is picking up on short-term autocorrelation — temperatures change slowly and the 24-hour context provides a strong signal. The cases it likely struggles with most are abrupt changes: a weather front moving through, a sudden overnight freeze. The largest errors in the samples appear in those regions.</p><h3>What the transformer is actually doing here</h3><p>It’s worth being explicit about the role of attention in this setup.</p><p>Each hour is processed sequentially. When pos_id=23 is evaluated, the key-value cache contains the representations of the previous 23 hours. Attention computes a weighted sum over those cached values — the query from the current hour is compared against all stored keys, and the values are aggregated proportionally.</p><p>Given the short-term autocorrelation structure of temperature data, you’d expect recent hours to receive higher attention weights. The model may also be attending to hours that represent the daily cycle minimum or maximum — though I haven’t verified this with attention map visualizations.</p><p>Q, K, V are learned as separate parameter matrices — each receives its own gradient contribution — but they’re optimized jointly over the same loss. Wq learns to ask useful questions, Wk learns to expose the right features for matching, Wv learns to carry the information that actually helps the prediction. Nobody tells them which role to play. They find it through gradient descent.</p><h3>What I’d change next</h3><p>The current bottleneck isn’t architectural — it’s throughput. Pure Python scalar autograd is brutally slow, which limits how much the model can actually learn.</p><p>More training steps would help the most. The loss is still declining at step 500 — the model hasn’t converged.</p><p>n_layer=2 would add representational capacity without changing the fundamental approach.</p><p>block_size=48 would give the model access to two days of history, which might help capture the daily cycle more cleanly.</p><p>Replacing the scalar autograd with even a minimal NumPy implementation would unlock proper matrix operations and make the training loop orders of magnitude faster.</p><h3>Final thought</h3><p>The interesting part of this exercise isn’t the result — 0.55°C mean error across 10 samples is fine but not remarkable. The interesting part is how little of the transformer needed to change.</p><p>The attention mechanism, MLP with residual connections, positional encoding, autograd engine — all of it carries over directly from a character-level language model to a continuous regression problem. Three core changes to the transformer itself; time-series-appropriate windowing and a leakage-free split on the data side. Much less than I expected.</p><p>The same attention backbone, given the right input and output representation, adapts to quite different sequence types. That’s the part worth keeping in mind.</p><p>Code : <a href="https://github.com/muratyildirim2/microgpt-weather-prediction/blob/main/model.ipynb">https://github.com/muratyildirim2/microgpt-weather-prediction/blob/main/model.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e842ea2f7ae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Hard Negative Sampling Truly Supercharges Recommendation Systems]]></title>
            <link>https://medium.com/@murattyldrm7/why-hard-negative-sampling-truly-supercharges-recommendation-systems-762671a41657?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/762671a41657</guid>
            <category><![CDATA[hard-negative-sampling]]></category>
            <category><![CDATA[negative-sampling]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 11:47:30 GMT</pubDate>
            <atom:updated>2025-11-28T11:47:30.175Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building a recommendation system today, you’re almost certainly working with implicit feedback. Every click, every view, every purchase tells you something about what users like. But here’s the catch: users rarely tell you what they don’t like. They just scroll past, and you’re left guessing.</p><p>This is the fundamental challenge of modern recommendation systems. We have plenty of positive signals, but the negative space is a mystery. To solve this, engineers have long relied on a simple assumption: if a user didn’t interact with an item, we’ll treat it as a negative example. This technique is called negative sampling, and it’s been a cornerstone of recommendation system training for years.</p><p>For a long time, the standard approach was random negative sampling. You’d pick items uniformly at random from the catalog and assume the user wasn’t interested in them. It’s simple, it’s fast, and it works well enough. But recently, a more sophisticated technique called hard negative sampling has been taking over the industry.</p><p>The conventional wisdom says hard negative sampling creates larger gradients, helping the model learn faster. But research from Zhang et al. (“Revisiting Neural Retrieval on Accelerators”, KDD 2022) reveals something far more interesting: hard negative sampling doesn’t just speed up training. It fundamentally changes what your model is optimizing for.</p><h3>The Problem with Easy Examples</h3><p>Imagine you’re teaching a child to recognize dogs. In the first approach, you show them a picture of a golden retriever next to a picture of a toaster. The child immediately points to the dog. They’ve learned something, sure, but what exactly? They’ve learned that dogs aren’t shiny metal kitchen appliances. Not particularly useful when they encounter a wolf while hiking.</p><p>Now imagine the second approach. You show them a picture of a golden retriever next to a picture of a wolf. Suddenly, the child has to pay attention. They notice the shape of the ears, the curve of the snout, the way the tail hangs. They’re learning what actually makes a dog a dog, not just what makes it different from obviously unrelated objects.</p><p>This is exactly what happens in recommendation systems. When you use random negative sampling, you’re essentially showing your model the easiest possible comparisons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCloMn9v5JgSWAWtmKCd-A.png" /></figure><p><strong>Let’s make this concrete with a real example.</strong></p><h3>Case Study: The “Gaming Laptop” Dilemma</h3><p>Meet Alex. Alex is a hardcore PC gamer browsing an electronics e-commerce store, specifically looking for high-end gaming laptops with NVIDIA RTX 4080 graphics cards and high refresh rate screens.</p><p><strong>With Random Negative Sampling:</strong></p><ul><li>Positive Example: An ASUS ROG Strix Gaming Laptop ($2,500)</li><li>Random Negative Example: A Hello Kitty Toaster ($30) or a Garden Hose ($15)</li></ul><p>The model easily learns that Alex prefers “Computers” over “Kitchen Appliances.” Great. But when ranking items, it fills Alex’s feed with <em>any</em> computer. It might recommend a weak $300 Chromebook intended for basic schoolwork. Why? Because compared to a toaster, a Chromebook looks a lot like a gaming laptop. They both have screens and keyboards.</p><p>The model optimized for global ranking is happy because it successfully ranked the Chromebook (computer) higher than the Toaster (non-computer). But Alex is frustrated and leaves the site.</p><p><strong>With Hard Negative Sampling:</strong></p><ul><li>Positive Example: An ASUS ROG Strix Gaming Laptop ($2,500)</li><li>Hard Negative: A sleek Dell XPS 13 Productivity Laptop ($2,000)</li></ul><p>Wait, why is the Dell XPS a negative? The model predicted high interest because it’s a laptop, it’s expensive, and it’s popular. But Alex didn’t click on it.</p><p>By selecting this hard negative, you force the model to ask: “Why did Alex ignore this premium laptop?” The model digs deeper into the features. It learns that despite both being expensive laptops, Alex specifically cares about GPU specs and refresh rate, not just the category “Laptop.”</p><p>The result: the model stops showing generic laptops and starts understanding the nuance of “Gaming” vs. “Ultrabook.” Your top 5 recommendations are now exclusively high-performance gaming rigs, not random computers. This is the difference between a user who bounces and a user who converts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHpvg3ATeZPs3bDApaFGRw.png" /></figure><h3>The Mathematical Revolution</h3><p>Here’s where things get truly interesting, and where most explanations of hard negative sampling fall short.</p><p>The standard training approach for recommendation systems, Bayesian Personalized Ranking (BPR), optimizes a metric called AUC (Area Under the ROC Curve). AUC measures how well your model ranks relevant items above irrelevant ones across your entire catalog.</p><p>But think about what that actually means. If you have a million items in your catalog, AUC cares equally about whether the relevant item appears at rank 10 versus rank 500,000. Both cases represent a relevant item being ranked above an irrelevant one, and both contribute to the AUC score.</p><p>In the real world, this is completely disconnected from how recommendation systems actually work. Nobody scrolls through 500,000 items. Users see the top 10, maybe the top 20 if you’re lucky. What happens at rank 500,000 is utterly irrelevant to user experience and business metrics.</p><p><strong>This is where the research breakthrough comes in.</strong></p><p>When you equip BPR with hard negative sampling — specifically a technique called Dynamic Negative Sampling (DNS) — the mathematical objective function transforms. You’re no longer optimizing standard AUC. You’re <em>approximately</em> optimizing something called One-way Partial AUC (OPAUC).</p><h3>What is One-way Partial AUC?</h3><p>Unlike standard AUC which calculates area under the entire ROC curve, OPAUC restricts evaluation to a specific region. Think of it as measuring your model’s performance only where it matters most.</p><p>There are two common variants:</p><ol><li><strong>FPR-constrained pAUC:</strong> Measures performance only at low false positive rates (e.g., FPR ∈ [0, 0.1]). Useful when false alarms are costly.</li><li><strong>TPR-constrained pAUC:</strong> Measures performance only at high true positive rates (e.g., TPR ∈ [0.8, 1.0]). Useful when missing positives is costly.</li></ol><p>For recommendation systems, we care about the first variant. We want to minimize false positives at the very top of our ranking — those precious first few slots that users actually see.</p><p><strong>Why does this matter?</strong></p><p>Standard AUC has a weak correlation with the metrics that actually matter for business: Recall@K, Precision@K, NDCG@K. OPAUC, on the other hand, has a much stronger connection to these top-K metrics. Maximizing OPAUC provides theoretical bounds on Precision@K and Recall@K.</p><p>The key insight: if you want your top 10 recommendations to be good, you need to be optimizing OPAUC, and hard negative sampling is the mechanism that gets you there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwHbRTqjZDcNjFPZKCsi0w.jpeg" /></figure><h3>From Theory to Practice</h3><p>Understanding the theory is one thing, but making it work in production is another. Here are two critical guidelines that every engineer building recommendation systems should internalize.</p><h3>Guideline 1: Hardness Must Be Controllable</h3><p>You can’t just flip a switch labeled “hard negatives” and expect optimal results. Different datasets, different user behaviors, and different business goals all require different levels of sampling hardness. Your system needs tunable parameters.</p><p><strong>Dynamic Negative Sampling (DNS)</strong> works like this:</p><ol><li>Sample N candidates uniformly at random from your catalog</li><li>Compute predicted scores for each candidate</li><li>Select the top M highest-scoring items as your negatives</li></ol><p>The ratio M/N controls hardness. Smaller M relative to N increases difficulty because you’re selecting only the very hardest negatives from your candidate pool.</p><p><strong>Alternative: Softmax-based sampling</strong> with a temperature parameter. Lower temperatures concentrate sampling around the highest-scoring items, creating harder negatives.</p><h3>Guideline 2: Match Hardness to Your Target K</h3><p>This is perhaps the most practical insight for real-world implementation: the hardness of your sampling should be inversely proportional to the K in your top-K metric.</p><p>If you’re building sidebar recommendations where only 5 items are displayed, you need extremely hard negatives. The model has to be incredibly precise. Every mistake is visible to the user.</p><p>If you’re building the first stage of a retrieval system pulling top 100 candidates for a downstream ranker, you can afford softer negatives. You just need relevant items broadly in that top tier.</p><p>The experimental evidence backs this up: as the target K decreases from 50 to 20 to 10 to 5, the optimal sampling parameters shift consistently toward harder settings.</p><h3>Implementation</h3><p>Here’s how Dynamic Negative Sampling works in practice:</p><pre>import torch<br><br>def dynamic_negative_sampling(<br>    user_emb, <br>    all_item_embs, <br>    n_candidates=200, <br>    m_negatives=5,<br>    positive_ids=None<br>):<br>    &quot;&quot;&quot;<br>    Hard Negative Sampling via DNS strategy.<br>    <br>    Args:<br>        user_emb: User embedding vector [emb_dim]<br>        all_item_embs: All item embeddings [num_items, emb_dim]<br>        n_candidates: Size of random candidate pool (N)<br>        m_negatives: Number of hard negatives to select (M)<br>        positive_ids: Item IDs to exclude (user&#39;s positive interactions)<br>    <br>    Returns:<br>        Indices of selected hard negative items<br>    &quot;&quot;&quot;<br>    num_items = all_item_embs.shape[0]<br>    <br>    # Step 1: Uniformly sample N random candidate indices<br>    candidate_indices = torch.randperm(num_items)[:n_candidates]<br>    <br>    # Optional: Remove positive items from candidates<br>    if positive_ids is not None:<br>        mask = ~torch.isin(candidate_indices, positive_ids)<br>        candidate_indices = candidate_indices[mask]<br>    <br>    # Step 2: Get embeddings for candidates<br>    candidate_embs = all_item_embs[candidate_indices]<br>    <br>    # Step 3: Compute scores (dot product)<br>    scores = torch.matmul(candidate_embs, user_emb)<br>    <br>    # Step 4: Select top M highest-scoring as hard negatives<br>    _, top_indices = torch.topk(scores, k=min(m_negatives, len(scores)))<br>    hard_negative_ids = candidate_indices[top_indices]<br>    <br>    return hard_negative_ids<br><br># Usage insight:<br># For Top-5 recommendations (K=5), set m_negatives close to 5<br># For Top-100 retrieval (K=100), m_negatives can be 20-50</pre><h3>Important Considerations</h3><p>Before adopting hard negative sampling, be aware of these trade-offs:</p><h3>Computational Cost</h3><p>Hard negative sampling requires computing scores for N candidates before selecting negatives. With random sampling, you just pick indices — no computation needed. For large-scale systems processing millions of training examples, this overhead adds up.</p><p><strong>When it’s worth it:</strong> When your top-K metrics directly impact business outcomes (conversion, engagement, revenue).</p><p><strong>When to be cautious:</strong> Early-stage experimentation where training speed matters more than marginal accuracy gains.</p><h3>The False Negative Problem</h3><p>Here’s a subtle but important issue: that “hard negative” might actually be something the user would love but hasn’t discovered yet.</p><p>If Alex hasn’t seen the new Razer gaming laptop, your model might select it as a hard negative (high predicted score, no interaction). But Alex would actually love it — he just hasn’t encountered it yet.</p><p><strong>Mitigation strategies:</strong></p><ul><li>Don’t make M too small (keep some diversity in negatives)</li><li>Consider exposure data if available (only use items the user has seen but rejected)</li><li>Periodically mix in some random negatives to maintain exploration</li></ul><h3>Cold-Start Challenges</h3><p>Hard negative sampling relies on meaningful model scores. For new users or new items with little interaction data, the scores are essentially random noise.</p><p><strong>Practical approach:</strong> Use random sampling for cold-start scenarios, gradually transitioning to harder negatives as you accumulate interaction data.</p><h3>The Bigger Picture</h3><p>Hard negative sampling represents something deeper than a training trick. It’s a fundamental shift in how we think about recommendation system optimization.</p><p>For years, the ML community has focused on loss functions and architectures. We’ve spent enormous effort designing clever neural networks and sophisticated training objectives. But the sampling strategy — often treated as an implementation detail — turns out to be just as important.</p><p>By changing how you sample negatives, you’re effectively changing your loss function from one that optimizes global ranking quality to one that optimizes top-of-list precision.</p><p>If you’re still using uniform random sampling, you’re leaving significant performance on the table. Your model is spending its capacity distinguishing relevant items from obviously irrelevant ones, rather than learning the subtle distinctions that matter for the recommendations users actually see.</p><p>The fix isn’t complicated. It’s a few lines of code. But the impact on your top-K metrics — and ultimately on user experience — can be substantial.</p><h3>RESOURCES</h3><blockquote><a href="https://arxiv.org/pdf/2302.03472"><strong><em>https://arxiv.org/pdf/2302.03472</em></strong></a></blockquote><blockquote><a href="https://arxiv.org/html/2403.00844v1"><strong><em>https://arxiv.org/html/2403.00844v1</em></strong></a></blockquote><blockquote><a href="https://claude.ai/"><strong><em>https://claude.ai</em></strong></a><strong><em>/</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=762671a41657" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Noise Contrastive Estimation (NCE): Efficient Training with Candidate Sampling]]></title>
            <link>https://medium.com/@murattyldrm7/noise-contrastive-estimation-nce-efficient-training-with-candidate-sampling-47c7386b1223?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c7386b1223</guid>
            <category><![CDATA[negative-sampling]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[nce]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 18:29:35 GMT</pubDate>
            <atom:updated>2025-01-01T18:32:50.533Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In machine learning tasks with large output spaces — like predicting the next word in a sentence or recommending an item from a massive catalog — computing probabilities for all possible classes becomes computationally expensive. This challenge is particularly significant in applications like natural language processing and recommender systems, where the number of classes (words, items) can range in the millions.</p><p><strong>Noise Contrastive Estimation (NCE)</strong> offers a scalable solution by transforming this problem into a simpler classification task. This article introduces <strong>candidate sampling</strong> and explains how NCE optimizes models for large-scale applications.</p><p><strong>1. The Problem of Scalability in Recommender Systems</strong></p><p>In recommendation systems like those used by Netflix or Spotify, the number of items (e.g., movies or songs) can be enormous. For every user interaction, the model needs to:</p><p>• Predict scores for all items.</p><p>• Optimize based on true interactions.</p><p>Directly comparing all user-item pairs becomes computationally prohibitive. To solve this, we use <strong>candidate sampling</strong>: selecting a manageable subset of items for training.</p><p><strong>2. What is Candidate Sampling?</strong></p><p>Candidate sampling is a technique to address the scalability issue in machine learning tasks with large output spaces. Instead of evaluating every possible class (e.g., every movie or song) for every training example, candidate sampling focuses on a smaller, manageable subset of “candidates.” This subset typically includes:</p><p>• The <strong>true target classes</strong> (e.g., the actual items a user interacted with).</p><p>• A random sample of <strong>negative classes</strong> (e.g., items the user likely did not interact with).</p><p>By reducing the set of classes the model evaluates, candidate sampling significantly lowers computational costs, making large-scale problems feasible.</p><p><strong>How Candidate Sampling Works:</strong></p><p>For each training example:</p><p>1. Select the <strong>positive samples</strong> (true targets).</p><p>2. Add <strong>negative samples</strong> from the remaining classes using a predefined distribution (e.g., based on popularity or frequency).</p><p>3. Train the model to distinguish between positive and negative samples.</p><p>This process enables models to learn efficiently without having to compute probabilities for the entire output space.</p><p><strong>3. How Noise Contrastive Estimation (NCE) Works</strong></p><p>NCE builds on candidate sampling by reframing the task of probability estimation into a simpler classification problem. Instead of directly predicting the probabilities for each class, NCE asks the model to classify each sample as either:</p><p>• A <strong>positive sample</strong> (from the true target set).</p><p>• A <strong>noise sample</strong> (from a predefined noise distribution).</p><p>This reduces the computational burden while maintaining the quality of the learned model.</p><p><strong>Key Components of NCE:</strong></p><p>1. <strong>Positive Samples</strong>:</p><p>• The true target classes for each training example (e.g., movies a user has watched).</p><p>• The model is expected to assign high probabilities to these examples.</p><p>2. <strong>Noise Distribution</strong>:</p><p>• A probability distribution used to sample negative examples (noise samples).</p><p>• Typically based on class frequencies (e.g., item popularity) to generate realistic negative samples.</p><p>• The choice of noise distribution is critical, as an inappropriate distribution can harm the model’s performance.</p><p>3. <strong>Objective Function</strong>:</p><p>• NCE reframes probability estimation as a binary classification task:</p><p>• The model learns to classify a sample as “positive” (target class) or “noise” (negative example).</p><p>• <strong>Loss Function</strong>: NCE uses a sigmoid function and negative log-likelihood to compute the loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*b0UBPFR5RdavZ-UCdaSleQ.png" /></figure><p>• Instead of directly calculating the normalization term in softmax, NCE approximates it, significantly reducing computational costs.</p><p><strong>4. Advantages of NCE</strong></p><p>1. <strong>Scalability</strong>: NCE reduces the computational complexity of training models on large output spaces, making it ideal for applications like natural language processing and recommendation systems.</p><p>2. <strong>Efficiency</strong>: By focusing only on a subset of candidate classes, NCE avoids the need to compute scores for all classes.</p><p>3. <strong>Versatility</strong>: NCE is widely used in models like Word2Vec, where the vocabulary size can reach millions, and in recommender systems with extensive catalogs.</p><p><strong>5. Implementing NCE: A Practical Example</strong></p><p>Here’s how NCE can be applied to a recommender system scenario where we predict user interactions with movies.</p><p><strong>Step 1: Define the Problem</strong></p><p>• <strong>Input</strong>: User features (e.g., preferences or past interactions).</p><p>• <strong>Output</strong>: A movie the user is likely to watch next.</p><p>• <strong>Challenge</strong>: The dataset contains thousands of movies, making it computationally expensive to predict probabilities for all.</p><p><strong>Step 2: Set Up NCE</strong></p><p>1. Create a noise distribution based on movie popularity.</p><p>2. Sample a small number of negative examples for each user interaction.</p><p>3. Train the model to classify positive and noise samples.</p><p><strong>Step 3: Python Implementation</strong></p><p>Below is a simple Python example of NCE for a movie recommender system:</p><pre>import numpy as np<br>import pandas as pd<br><br>def nce_candidate_sampling(interactions, num_negatives=5):<br>    &quot;&quot;&quot;<br>    Generate positive and noise samples for NCE-based training.<br>    &quot;&quot;&quot;<br>    # Calculate noise distribution (e.g., item popularity normalized)<br>    movie_popularity = interactions[&#39;movieId&#39;].value_counts()<br>    noise_dist = movie_popularity / movie_popularity.sum()<br>    <br>    samples = []<br>    for user in interactions[&#39;userId&#39;].unique():<br>        # Get movies the user has interacted with<br>        watched = set(interactions[interactions[&#39;userId&#39;] == user][&#39;movieId&#39;])<br>        <br>        # Get movies not interacted with by the user<br>        unwatched = set(noise_dist.index) - watched<br>        <br>        # Positive samples (interaction data)<br>        pos_samples = [(user, movie, 1) for movie in watched]<br>        samples.extend(pos_samples)<br>        <br>        # Noise (negative) samples based on the noise distribution<br>        if len(unwatched) &gt; 0:<br>            neg_samples = np.random.choice(<br>                list(unwatched),<br>                size=min(num_negatives, len(unwatched)),<br>                p=noise_dist[list(unwatched)] / noise_dist[list(unwatched)].sum(),<br>                replace=False<br>            )<br>            samples.extend([(user, movie, 0) for movie in neg_samples])<br>    <br>    return pd.DataFrame(samples, columns=[&#39;userId&#39;, &#39;movieId&#39;, &#39;label&#39;])<br><br># Generate samples for NCE<br>training_data = nce_candidate_sampling(positive_interactions, num_negatives=5)<br></pre><p>REFERENCES</p><p><a href="https://www.tensorflow.org/extras/candidate_sampling.pdf">https://www.tensorflow.org/extras/candidate_sampling.pdf</a></p><p><a href="https://movielens.org/">MovieLens</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c7386b1223" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Local Personal Assistant with Ollama and LangChain: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@murattyldrm7/building-a-local-personal-assistant-with-ollama-and-langchain-a-step-by-step-guide-00996dff7234?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/00996dff7234</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[faiss]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 21:45:48 GMT</pubDate>
            <atom:updated>2024-12-30T21:45:48.002Z</atom:updated>
            <content:encoded><![CDATA[<p>Retrieval-Augmented Generation (RAG) systems are revolutionizing how AI interacts with external knowledge. By combining retrieval techniques with powerful generative models, RAG systems enable applications that provide accurate and contextual answers using domain-specific data. In this article, I’ll walk you through building a RAG system using Flask and LangChain, leveraging Ollama’s Solar model for embeddings and retrieval.</p><h3>What We’ll Build</h3><p>We’ll create a personal assistant that can:</p><ul><li>Process and understand personal data (emails, calls, meetings)</li><li>Answer questions about your activities</li><li>Run completely locally using Ollama models</li><li>Provide accurate, context-aware responses</li><li>Present information through a clean web interface</li></ul><ol><li><strong>Ollama embeddings</strong></li></ol><pre>class PersonalData:<br>    def __init__(self):<br>        self.embeddings = OllamaEmbeddings(model=&quot;solar&quot;)<br>        self.vector_store = FAISS.from_documents(documents, self.embeddings)</pre><p><strong>FAISS (Facebook AI Similarity Search)</strong> is a library designed to efficiently search through large datasets of high-dimensional vectors. It is widely used in applications like information retrieval, recommendation systems, and nearest neighbor search, especially when working with embeddings generated by machine learning models.</p><p>2. <strong>QA Chain</strong></p><pre>class RAGProcessor:<br>    def __init__(self):<br>        self.llm = OllamaLLM(model=&quot;solar&quot;)<br>        self.qa_chain = RetrievalQA.from_chain_type(<br>            llm=self.llm,<br>            chain_type=&quot;stuff&quot;,<br>            retriever=self.vector_store.as_retriever()<br>        )</pre><p><strong>Components of the QA Chain:</strong></p><p><strong>a. llm=self.llm:</strong> Specifies the generative language model to be used for answering questions.</p><p><strong>b. chain_type=”stuff”:</strong> Indicates the type of chain to use. The “stuff” chain is a basic type that concatenates all retrieved documents and passes them to the LLM as context.</p><p><strong>c. retriever=self.vector_store.as_retriever():</strong> Uses the vector store as the retriever. Converts the vector store into a retriever object, enabling it to search for relevant documents based on a query.</p><pre>text_splitter = RecursiveCharacterTextSplitter(<br>chunk_size=1000,<br>chunk_overlap=200,<br>length_function=len<br>)</pre><p>RecursiveCharacterTextSplitter is a text splitting tool used to break large text into smaller, manageable chunks. This is particularly useful for applications like information retrieval or working with AI models that have context length limitations. In the provided code, the RecursiveCharacterTextSplitter is configured with three main parameters:</p><p><strong>a. chunk_size</strong></p><p>This parameter defines the maximum length of each text chunk in characters.</p><p>• <strong>Value:</strong> chunk_size=1000</p><p>• <strong>Meaning:</strong> Each chunk will have a maximum length of 1000 characters.</p><p><strong>b. chunk_overlap</strong></p><p>This parameter specifies how much overlap there will be between consecutive chunks.</p><p>• <strong>Value:</strong> chunk_overlap=200</p><p>• <strong>Meaning:</strong> Each chunk will share 200 characters with the next one.</p><p><strong>c. length_function</strong></p><p>This determines how the length of the text is measured.</p><p>• <strong>Value:</strong> length_function=len</p><p>• <strong>Meaning:</strong> The length of the text is measured using Python’s built-in len function, which counts characters.</p><h3><strong>Key Components</strong></h3><h4>1. Vector Store Setup</h4><pre>def initialize_vector_store():<br>    &quot;&quot;&quot;Initialize or load the vector store with documents.&quot;&quot;&quot;<br>    try:<br>        if os.path.exists(&quot;vectorstore&quot;):<br>            print(&quot;Loading existing vector store...&quot;)<br>            vector_store = FAISS.load_local(<br>                &quot;vectorstore&quot;, <br>                embeddings,<br>                allow_dangerous_deserialization=True<br>            )<br>            return vector_store<br>    except Exception as e:<br>        print(f&quot;Error loading vector store: {e}&quot;)<br>        print(&quot;Creating new vector store...&quot;)<br>        <br>    # Create docs directory if it doesn&#39;t exist<br>    if not os.path.exists(&quot;docs&quot;):<br>        print(&quot;Creating docs directory...&quot;)<br>        os.makedirs(&quot;docs&quot;)<br>        # Create a sample document if docs directory is empty<br>        with open(&quot;docs/sample.txt&quot;, &quot;w&quot;) as f:<br>            f.write(&quot;This is a sample document for the Solar RAG system.&quot;)<br>    <br>    # Load documents<br>    print(&quot;Loading documents...&quot;)<br>    loader = DirectoryLoader(<br>        &quot;docs/&quot;,<br>        glob=&quot;**/*.txt&quot;,<br>        loader_cls=TextLoader<br>    )<br>    documents = loader.load()</pre><h4>2. Question-Answering Chain</h4><pre>prompt_template = &quot;&quot;&quot;You are a helpful AI assistant. Use the following pieces of context to answer the question.<br><br>Context: {context}<br>Question: {question}<br><br>Answer in a helpful and detailed way.&quot;&quot;&quot;<br><br>qa_chain = RetrievalQA.from_chain_type(<br>    llm=llm,<br>    chain_type=&quot;stuff&quot;,<br>    retriever=vector_store.as_retriever(search_kwargs={&quot;k&quot;: 3}),<br>    return_source_documents=True,<br>    chain_type_kwargs={&quot;prompt&quot;: PROMPT}<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rMw4euiKGWecSAU6d1ATEw.png" /><figcaption>Example</figcaption></figure><h3>Conclusion</h3><p>In this guide, we explored building a powerful local personal assistant using Ollama and LangChain. By combining FAISS vector store for efficient document retrieval, the Solar model for embeddings, and a Flask-based web interface, we created a system that can process and understand personal data while maintaining privacy by running completely locally.</p><p>REFERENCES :</p><p><a href="https://python.langchain.com/v0.1/docs/integrations/llms/ollama/">Ollama | 🦜️🔗 LangChain</a></p><p><a href="https://chatgpt.com/">https://chatgpt.com</a></p><p><a href="https://faiss.ai/index.html">Welcome to Faiss Documentation - Faiss documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00996dff7234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Recommendation System with LightFM]]></title>
            <link>https://medium.com/@murattyldrm7/building-a-recommendation-system-with-lightfm-35394c8d90fb?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/35394c8d90fb</guid>
            <category><![CDATA[movielens]]></category>
            <category><![CDATA[lightfm]]></category>
            <category><![CDATA[sparse-matrix]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 18:25:54 GMT</pubDate>
            <atom:updated>2024-11-30T18:34:35.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KV2G4p5fKPFOp-Rj" /></figure><h3><strong>Introduction</strong></h3><p>Recommendation systems are at the core of personalized user experiences in various domains, from streaming services to e-commerce platforms. They help users discover relevant content by predicting preferences based on historical interactions. However, one of the biggest challenges in building these systems is dealing with <strong>sparse data</strong> — datasets where most user-item interactions are missing.</p><p>To address this, tools like <strong>LightFM</strong> have emerged as powerful solutions. LightFM is a hybrid recommendation system library that effectively utilizes <strong>sparse matrices</strong> to handle large-scale datasets. It combines collaborative filtering and content-based techniques, making it versatile for a wide range of recommendation tasks.</p><p>In this article, we’ll explore the fundamentals of recommendation systems, the role of sparse and dense matrices in their operation, and how to implement a practical recommendation system using LightFM.</p><h3><strong>What is LightFM?</strong></h3><p>LightFM is a Python library designed specifically for building recommendation systems. It excels in scenarios where you need to handle sparse data and integrate both <strong>collaborative filtering</strong> and <strong>content-based filtering</strong> techniques. The library is lightweight, flexible, and highly efficient, making it a popular choice for real-world applications.</p><p><strong>Key Features of LightFM</strong></p><p>1. <strong>Hybrid Model</strong>:</p><ul><li>Combines collaborative filtering (user-item interactions) with content-based filtering (user or item metadata).</li><li>Ideal for systems where both interaction data and additional features like user demographics or item categories are available.</li></ul><p>2. <strong>Sparse Matrix Compatibility</strong>:</p><ul><li>Works directly with sparse matrices, enabling efficient handling of large-scale datasets.</li></ul><p>3. <strong>Customizable Loss Functions</strong>:</p><ul><li>LightFM provides several loss functions to optimize for different objectives:</li><li><strong>WARP (Weighted Approximate-Rank Pairwise)</strong>: Focused on maximizing the rank of positive interactions.</li><li><strong>BPR (Bayesian Personalized Ranking)</strong>: Optimizes pairwise rankings for personalized recommendations.</li><li><strong>Logistic Loss</strong>: Optimizes for binary classification problems.</li></ul><p>4. <strong>Scalability</strong>:</p><ul><li>Handles billions of interactions efficiently by leveraging sparse data structures and multi-threaded computation.</li></ul><p>5. <strong>Ease of Use</strong>:</p><ul><li>Simple API for quick prototyping while providing advanced options for fine-tuning.</li></ul><h3><strong>How Does LightFM Work?</strong></h3><p>At its core, LightFM builds a model by learning embeddings for users and items. These embeddings capture latent features (hidden relationships) that help predict the likelihood of user-item interactions. Here’s how it works:</p><p>1. <strong>Input Data</strong>:</p><ul><li>A sparse matrix representing user-item interactions (e.g., ratings, clicks, or purchases).</li><li>Optional metadata for users and items to enrich the recommendation model.</li></ul><p>2. <strong>Training</strong>:</p><ul><li>LightFM optimizes the embeddings using one of the provided loss functions, depending on the task (ranking, classification, etc.).</li></ul><p>3. <strong>Prediction</strong>:</p><ul><li>Once trained, the model can predict interactions for new or unseen user-item pairs by calculating the dot product of their embeddings.</li></ul><p>4. <strong>Evaluation</strong>:</p><ul><li>The model’s performance can be evaluated using metrics like precision, recall, and AUC (Area Under the Curve).</li></ul><h3><strong>Why Choose LightFM?</strong></h3><p>LightFM is an excellent choice for scenarios where:</p><ul><li><strong>Data is sparse</strong>: Most recommendation datasets are sparse (e.g., users interact with only a small fraction of items).</li><li><strong>Hybrid recommendations</strong> are needed: You want to combine collaborative and content-based approaches.</li><li><strong>Scalability</strong> is a priority: You need to handle large datasets efficiently.</li></ul><h3><strong>Understanding Sparse and Dense Matrices in Recommendation Systems</strong></h3><p>Recommendation systems often deal with large user-item datasets where most interactions are missing. For instance, in a movie recommendation system, a typical user only rates a small fraction of the available movies. This results in a <strong>sparse matrix</strong>, where the majority of elements are zero. To fully appreciate the power of LightFM, it’s essential to understand the distinction between <strong>sparse</strong> and <strong>dense</strong> matrices and their relevance in recommendation systems.</p><h4><strong>What is a Sparse Matrix?</strong></h4><p>A <strong>sparse matrix</strong> is a matrix where most elements are zero. Instead of storing every element (including zeros), sparse matrices optimize storage by keeping only non-zero values and their indices. This makes them highly efficient for datasets with large dimensions but minimal non-zero entries.</p><h4><strong>What is a Dense Matrix?</strong></h4><p>A <strong>dense matrix</strong> stores all elements, including zeros. While this representation is straightforward, it is inefficient for sparse data as it consumes unnecessary memory for storing zeros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BwIrS3bGz5HqpmpR.png" /></figure><h3><strong>Why Sparse Matrices Matter in Recommendation Systems</strong></h3><p>Sparse matrices are critical for the scalability and efficiency of recommendation systems:</p><p>1. <strong>Memory Efficiency</strong>:</p><ul><li>Sparse matrices store only non-zero elements, saving memory. For example, a user-item matrix with millions of users and items but only thousands of interactions can be represented compactly using sparse formats.</li></ul><p>2. <strong>Faster Computations</strong>:</p><ul><li>Algorithms can skip over zero entries, focusing only on non-zero interactions. This significantly reduces computational overhead.</li></ul><p>3. <strong>Scalability</strong>:</p><ul><li>Sparse matrices allow recommendation systems to handle massive datasets that would be infeasible with dense matrices.</li></ul><h3><strong>Sparse Matrix Representations</strong></h3><p>Various formats are used to represent sparse matrices efficiently. Here are the most common ones:</p><p>1. <strong>COO (Coordinate List)</strong>:</p><p>• Stores non-zero values along with their row and column indices.</p><p>• Best for constructing sparse matrices dynamically.</p><p>• Example:</p><p>• <strong>Data</strong>: [5, 4, 5]</p><p>• <strong>Row</strong>: [0, 1, 2]</p><p>• <strong>Column</strong>: [0, 1, 3]</p><p>2. <strong>CSR (Compressed Sparse Row)</strong>:</p><p>• Compresses the rows of the matrix for efficient arithmetic operations (e.g., matrix multiplication).</p><p>• Ideal for matrix computations.</p><p>• Example:</p><p>• <strong>Data</strong>: [5, 3, 4, 5]</p><p>• <strong>Column Indices</strong>: [0, 2, 1, 3]</p><p>• <strong>Row Pointers</strong>: [0, 2, 3, 4]</p><p>3. <strong>DOK (Dictionary of Keys)</strong>:</p><p>• Uses a Python dictionary to store (row, column) as keys and non-zero values as values.</p><ul><li>Best for dynamic updates to sparse matrices.</li></ul><h3><strong>Implementing a Recommendation System with LightFM</strong></h3><p>Now that we’ve discussed the role of sparse matrices in recommendation systems, let’s implement a practical example using the <strong>LightFM </strong>library. We’ll work with the <strong>MovieLens 100K dataset</strong>, a standard benchmark for evaluating recommendation systems.</p><p><strong>1. Loading and Preparing the Data</strong></p><p>The system begins by loading two key datasets:</p><ul><li><strong>User-item interactions</strong>: This dataset captures user behavior, such as movie ratings. In the case of the MovieLens dataset, each interaction includes a user_id, item_id, and a rating.</li><li><strong>Item metadata</strong>: This dataset contains descriptive information about the items (e.g., movie titles).</li></ul><p>Once the data is loaded:</p><ul><li>The user_id and item_id columns are mapped to internal indices using LightFM’s Dataset class.</li><li>A <strong>sparse matrix</strong> of user-item interactions is created, where rows represent users, columns represent items, and values represent ratings.</li></ul><p><strong>2. Creating Sparse Interaction Matrices</strong></p><p>The interaction data is converted into a <strong>sparse matrix</strong> format. Each user-item pair with a rating is stored as a non-zero entry. This matrix serves two purposes:</p><ul><li>It feeds the training process with the relationships between users and items.</li><li>It ensures memory efficiency by ignoring zero entries, which represent missing interactions.</li></ul><p>Sparse matrices are critical here because the vast majority of user-item combinations are zero. Instead of storing these zeros explicitly, the sparse format focuses only on relevant data.</p><pre># Function to prepare data and train the model<br>def prepare_and_train_model(data, test_size=0.2, epochs=30):<br>    &quot;&quot;&quot;Prepares the data and trains the model.&quot;&quot;&quot;<br>    try:<br>        # Train-test split<br>        train_data, test_data = train_test_split(<br>            data, <br>            test_size=test_size, <br>            random_state=42,<br>            stratify=data[&#39;user_id&#39;]<br>        )<br>        <br>        # Dataset creation<br>        dataset = Dataset()<br>        dataset.fit(data[&#39;user_id&#39;], data[&#39;item_id&#39;])<br>        <br>        # Build interaction matrices using original ratings<br>        interactions_train, _ = dataset.build_interactions(<br>            zip(train_data[&#39;user_id&#39;], train_data[&#39;item_id&#39;], train_data[&#39;rating&#39;])<br>        )<br>        <br>        interactions_test, _ = dataset.build_interactions(<br>            zip(test_data[&#39;user_id&#39;], test_data[&#39;item_id&#39;], test_data[&#39;rating&#39;])<br>        )<br>        <br>        # Train LightFM model<br>        model = LightFM(<br>            loss=&#39;warp&#39;,<br>            learning_rate=0.05,<br>            no_components=30<br>        )<br>        <br>        model.fit(interactions_train, epochs=epochs, num_threads=4, verbose=True)<br>        <br>        # Evaluate the model<br>        train_auc = auc_score(model, interactions_train).mean()<br>        test_auc = auc_score(model, interactions_test).mean()<br>        logger.info(f&quot;Train AUC: {train_auc:.4f}&quot;)<br>        logger.info(f&quot;Test AUC: {test_auc:.4f}&quot;)<br>        <br>        return model, dataset, interactions_train, interactions_test</pre><p><strong>3. Training the Model</strong></p><p>The LightFM model is trained on the user-item interaction matrix using a specific loss function. In our system:</p><ul><li><strong>WARP (Weighted Approximate-Rank Pairwise)</strong> loss is used. It optimizes for ranking, ensuring that relevant items are ranked higher than irrelevant ones.</li><li>The model learns <strong>embeddings</strong> for users and items, which are vector representations that capture latent features (hidden relationships) between them.</li></ul><p>For example, if a user frequently interacts with action movies, the embeddings will learn to associate that user with the latent features of action movies.</p><p><strong>4. Making Predictions</strong></p><p>Once the model is trained, it can predict the likelihood of a user interacting with an item. This prediction is based on the dot product of the user and item embeddings. The higher the score, the more likely it is that the user will engage with the item.</p><p>To make predictions:</p><p>1. The system computes scores for all items for a specific user.</p><p>2. Items the user has already interacted with are excluded from recommendations (to avoid redundancy).</p><p>3. The items with the highest scores are selected as recommendations.</p><pre>def recommend_movies(model, user_id, dataset, interactions_matrix, items_data, num_recommendations=5):<br>    &quot;&quot;&quot;Provides movie recommendations for a user.&quot;&quot;&quot;<br>    try:<br>        n_items = interactions_matrix.shape[1]<br>        scores = model.predict(user_id, np.arange(n_items))<br>        <br>        # Exclude movies already rated by the user<br>        watched_mask = interactions_matrix[user_id].toarray().flatten() &gt; 0<br>        scores[watched_mask] = -np.inf<br>        <br>        # Get top recommendations<br>        top_items = np.argsort(-scores)[:num_recommendations]<br>        <br>        item_labels = list(dataset.mapping()[2].keys())<br>        recommendations = [<br>            {<br>                &#39;title&#39;: items_data[items_data[&#39;item_id&#39;] == item_labels[i]][&#39;title&#39;].iloc[0],<br>                &#39;score&#39;: float(scores[i])<br>            }<br>            for i in top_items<br>        ]<br>        return recommendations</pre><p><strong>5. Evaluating the Model</strong></p><p>The system evaluates its performance using metrics such as:</p><ul><li><strong>Precision@k</strong>: Measures how many of the top-k recommendations are relevant to the user.</li><li><strong>AUC (Area Under the Curve)</strong>: Evaluates the model’s ability to rank relevant items higher than irrelevant ones.</li></ul><p>These metrics help assess whether the model is effectively predicting user preferences.</p><p><strong>6. Generating Recommendations</strong></p><p>For a given user, the system generates personalized recommendations:</p><ul><li>The trained model predicts scores for all items the user has not interacted with.</li><li>The items with the highest predicted scores are returned as recommendations.</li></ul><p>For instance, if a user has rated several sci-fi movies highly, the system will likely recommend other sci-fi movies with similar latent features.</p><pre> # Add new user data to interaction matrix<br>        new_interactions = dok_matrix(interactions_train.shape, dtype=np.float32)<br>        for _, item_id, rating in user_interactions:<br>            item_idx = dataset.mapping()[2][item_id]<br>            new_interactions[0, item_idx] = rating<br>            <br>        # Get recommendations<br>        recommendations = recommend_movies(<br>            model, 0, dataset, new_interactions.tocsr(), <br>            items_data, num_recommendations=10<br>        )</pre><p><strong>Conclusion</strong></p><p>Building a recommendation system using <strong>LightFM</strong> highlights the versatility and efficiency of hybrid models in addressing the challenges of sparse data. By seamlessly integrating collaborative filtering with content-based approaches, LightFM not only improves prediction accuracy but also enables personalized recommendations at scale.</p><p>The use of <strong>sparse matrices</strong> optimizes memory and computational efficiency, making it suitable for handling large datasets common in real-world applications. Moreover, LightFM’s customizable loss functions and scalable architecture allow it to adapt to diverse recommendation tasks, from movie suggestions to e-commerce personalization.</p><p>In this implementation, the <strong>MovieLens dataset</strong> demonstrates how a simple yet powerful framework can deliver meaningful user experiences through effective training, prediction, and evaluation pipelines. By leveraging latent feature embeddings, the system captures hidden patterns and relationships, ensuring that recommendations align with user preferences.</p><p>As recommendation systems continue to evolve, tools like LightFM set the foundation for further innovation. Whether you’re a data scientist or a developer, adopting such frameworks will help you build robust, scalable, and accurate recommendation systems that drive engagement and value for users.</p><p><strong>References</strong> :</p><p><a href="https://grouplens.org/datasets/movielens/100k/">https://grouplens.org/datasets/movielens/100k/</a></p><p><a href="https://www.geeksforgeeks.org/sparse-matrix-representation/">https://www.geeksforgeeks.org/sparse-matrix-representation/</a></p><p><a href="https://making.lyst.com/lightfm/docs/home.html">https://making.lyst.com/lightfm/docs/home.html</a></p><p><a href="https://chatgpt.com/">https://chatgpt.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35394c8d90fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Uygulamalarında RAG, Function Calling ve LangChain Agents]]></title>
            <link>https://medium.com/@murattyldrm7/ai-uygulamalar%C4%B1nda-rag-function-calling-ve-langchain-agents-6e5298681ae6?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e5298681ae6</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-function-calling]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 17:22:01 GMT</pubDate>
            <atom:updated>2024-10-25T17:37:29.693Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Bu yazıda, modern AI uygulamalarında bilgiye erişim ve yanıt oluşturma sürecini nasıl geliştirebileceğinizi anlatacağız. RAG, Function Calling, ve LangChain ajanlarının kullanımı, AI sistemlerinin daha güncel, doğru, ve anlamlı yanıtlar üretmesini sağlar.</strong></p><h3><strong>1-Retrieval-Augmented Generation (RAG) Nedir?</strong></h3><p>RAG (Retrieval-Augmented Generation), özellikle büyük dil modelleriyle (LLM’ler) çalışırken eksik ya da güncel olmayan bilgileri tamamlamak ve daha doğru yanıtlar üretmek için kullanılan bir tekniktir. RAG modelleri, geleneksel dil modellerinin yanı sıra bilgi alma (retrieval) süreçlerini kullanarak daha doğru ve güncel veriler sağlar.</p><p>RAG, iki ana bileşeni bir araya getirir:</p><p><strong>Retrieval (Bilgi Alma): </strong>Model, belirli bir soruya ya da isteğe uygun olarak büyük veri kümelerinden bilgi alır. Bu bilgi kaynakları; dokümanlar, veritabanları, bilgi grafikleri ya da web sayfaları gibi çeşitli yerlerden olabilir.<br><strong>Generation (Üretim):</strong> Model, alınan bu bilgiyi kullanarak özgün ve doğru bir yanıt oluşturur.<br>RAG ile çalışan bir sistem, önce soruya en uygun bilgiyi veri kaynağından çeker, ardından bu bilgiyi dil modeliyle birleştirerek kullanıcıya yanıt sunar.</p><p><strong>RAG Kullanım Alanları</strong></p><p><strong>Soru-Cevap Sistemleri:</strong> Bilgi alma süreçlerini kullanarak, kullanıcı sorularına daha doğru yanıtlar sunar.<br><strong>Doküman İnceleme: </strong>Belirli bir konu hakkında ilgili dokümanları bulur ve özet çıkarır.<br><strong>Müşteri Destek Asistanları:</strong> Güncel bilgiye ihtiyaç duyan müşteri destek chatbot’ları için RAG modelleri kullanılabilir.<br><strong>Arama Motorları: </strong>Kullanıcıya daha ilgili ve doğru bilgi sunmak için arama motorlarında RAG teknolojisi uygulanabilir.</p><h3>2-Function Calling Nedir?</h3><p>Function Calling, GPT-4 gibi büyük dil modellerini harici araçlara ve sistemlere bağlamanızı sağlar. Bu özellik, AI asistanlarının daha güçlü yetenekler kazanması ve uygulamalar ile modeller arasında derin entegrasyonlar kurmanıza yardımcı olur. Örneğin, bir AI asistanı kullanıcı taleplerini işleyerek veritabanından bilgi alabilir, rapor hazırlayabilir veya kullanıcıya göre özelleşmiş hesaplamalar yapabilir.</p><p><strong>Örnek Kullanım Alanları<br></strong>Function Calling, pek çok kullanım alanında faydalıdır:</p><p><strong>Veri çekme:</strong> Kullanıcının son siparişini öğrenmesi gibi durumlarda.<br><strong>Hesaplama yapma:</strong> Matematiksel işlemleri gerçekleştiren asistanlar için.<br><strong>Zengin iş akışları: </strong>Verileri çekip yapılandırılmış hale getirip kaydeden veri akışları oluşturmak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OGnT0ezi1xyGsQBo.png" /></figure><p>Başlangıç olarak, kod tabanınızdaki hangi fonksiyonun model tarafından çağrılabileceğine karar vermelisiniz. Örneğin, <strong>get_delivery_date</strong> adlı bir fonksiyonla siparişin teslimat tarihini belirlemek isteyebilirsiniz.</p><pre># Siparişin teslim tarihini getiren örnek fonksiyon<br>def get_delivery_date(order_id: str) -&gt; datetime:<br>    # Veritabanına bağlanır ve siparişin teslim tarihini alır<br>    conn = sqlite3.connect(&#39;ecommerce.db&#39;)<br>    cursor = conn.cursor()<br>    # ...</pre><p>Bu fonksiyonun model tarafından nasıl çağrılacağını tanımlamak için JSON Şema yapısını kullanmalısınız. Örneğin:</p><pre>{<br>    &quot;name&quot;: &quot;get_delivery_date&quot;,<br>    &quot;description&quot;: &quot;Müşteri siparişinin teslim tarihini alır.&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>            &quot;order_id&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;Müşterinin sipariş kimliği&quot;<br>            }<br>        },<br>        &quot;required&quot;: [&quot;order_id&quot;],<br>        &quot;additionalProperties&quot;: false<br>    }<br>}</pre><p>Bu tanımı Chat Completions API ile birlikte modelin kullanması gereken bir “araç” olarak gönderin.</p><pre>tools = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;function&quot;: {<br>            &quot;name&quot;: &quot;get_delivery_date&quot;,<br>            &quot;description&quot;: &quot;Müşteri siparişinin teslim tarihini alır.&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;order_id&quot;: {&quot;type&quot;: &quot;string&quot;}<br>                },<br>                &quot;required&quot;: [&quot;order_id&quot;],<br>                &quot;additionalProperties&quot;: False<br>            }<br>        }<br>    }<br>]<br><br>messages = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Sen bir müşteri destek asistanısın.&quot;},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Siparişimin teslim tarihini öğrenebilir miyim?&quot;}<br>]<br><br>response = openai.chat.completions.create(<br>    model=&quot;gpt-4o&quot;,<br>    messages=messages,<br>    tools=tools<br>)</pre><p>Model, uygun parametreleri belirlediğinde yanıt verecektir. Modelin bir fonksiyon çağrısı oluşturduğu durumda, çağrının parametrelerini alabilir ve fonksiyonu çağırabilirsiniz.</p><pre>tool_call = response.choices[0].message.tool_calls[0]<br>arguments = json.loads(tool_call[&#39;function&#39;][&#39;arguments&#39;])<br>order_id = arguments.get(&#39;order_id&#39;)<br><br>delivery_date = get_delivery_date(order_id)</pre><p>Fonksiyonun sonucunu elde ettikten sonra, modeli bilgilendirmek için bu sonucu bir mesaj olarak API’ye iletebilirsiniz:</p><pre>function_call_result_message = {<br>    &quot;role&quot;: &quot;tool&quot;,<br>    &quot;content&quot;: json.dumps({<br>        &quot;order_id&quot;: order_id,<br>        &quot;delivery_date&quot;: delivery_date.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>    }),<br>    &quot;tool_call_id&quot;: response[&#39;choices&#39;][0][&#39;message&#39;][&#39;tool_calls&#39;][0][&#39;id&#39;]<br>}<br><br>completion_payload = {<br>    &quot;model&quot;: &quot;gpt-4o&quot;,<br>    &quot;messages&quot;: [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Sen bir müşteri destek asistanısın.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Siparişimin teslim tarihini öğrenebilir miyim?&quot;},<br>        response[&#39;choices&#39;][0][&#39;message&#39;],<br>        function_call_result_message<br>    ]<br>}<br><br>response = openai.chat.completions.create(<br>    model=completion_payload[&quot;model&quot;],<br>    messages=completion_payload[&quot;messages&quot;]<br>)<br>print(response)</pre><p><strong>Structured Outputs</strong></p><p>Structured Outputs (Yapılandırılmış Çıktılar), modelin parametreleri JSON Şemanıza uygun şekilde oluşturmasını garanti eder. “strict”: true parametresi ekleyerek bu özelliği etkinleştirebilirsiniz.</p><pre>from pydantic import BaseModel<br>import openai<br><br>class GetDeliveryDate(BaseModel):<br>    order_id: str<br><br>tools = [openai.pydantic_function_tool(GetDeliveryDate)]<br><br>messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Siparişimin teslim tarihini öğrenebilir miyim?&quot;}]<br><br>response = client.chat.completions.create(<br>    model=&#39;gpt-4o-2024-08-06&#39;,<br>    messages=messages,<br>    tools=tools<br>)<br>print(response.choices[0].message.tool_calls[0].function)</pre><h3>3-LangChain ve Ajanlar (Agents)</h3><p>Agents, büyük dil modellerini kullanarak hangi işlemi yapacaklarına ve hangi sırayla ilerleyeceklerine karar veren yapılardır. Zincirler (chains), bir dizi işlemi belirli bir sırayla, kodla belirlenmiş bir şekilde çalıştırır. Agents ise dil modelini bir akıl yürütme motoru olarak kullanarak dinamik bir işlem sırası oluşturur.</p><p><strong>Temel Bileşenler:<br>AgentAction:</strong> Ajanın alması gereken işlemi ve girdi değerlerini içeren bir veri sınıfıdır.<br><strong>AgentFinish:</strong> Ajanın son kullanıcı yanıtını döndürebileceği yapı.<br><strong>Intermediate Steps:</strong> Ajanın önceki adımlardaki işlemlerini ve çıktılarını tutar.<br><strong>AgentExecutor:</strong> Ajanın hangi adımı yapması gerektiğini belirleyen ve ilgili araçları çağırarak çıktıları yöneten çalışma ortamı.</p><h3>4-LangChain ile Serper Google Arama API Entegrasyonu</h3><p>Serper, düşük maliyetli bir Google Arama API’sidir ve arama sonuçlarının yanı sıra bilgi kutusu ve bilgi grafiği gibi ek veriler sağlar. Bu API’yi LangChain ile kullanarak, ajanların dış veri kaynaklarından bilgi çekmesini sağlayabilirsiniz. Örneğin, bir kullanıcıdan gelen bir soruya yanıt bulmak için Google’da arama yapmak istediğinizde, Serper API’yi kullanarak arama işlemini gerçekleştirebilirsiniz.</p><p>Serper API ile çalışan bir ajan oluşturmak için aşağıdaki adımları izleyin:</p><pre>from langchain_community.utilities import GoogleSerperAPIWrapper<br>from langchain_openai import OpenAI<br>from langchain.agents import initialize_agent, Tool, AgentType<br><br>os.environ[&#39;OPENAI_API_KEY&#39;] = &quot;OPENAI_API_KEY&quot;<br><br>llm = OpenAI(temperature=0)<br>search = GoogleSerperAPIWrapper()<br><br>tools = [<br>    Tool(<br>        name=&quot;Intermediate Answer&quot;,<br>        func=search.run,<br>        description=&quot;Arama yapmanız gerektiğinde kullanışlı.&quot;<br>    )<br>]<br><br>self_ask_with_search = initialize_agent(<br>    tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True<br>)<br><br>answer = self_ask_with_search.run(&quot;What is the hometown of the reigning men&#39;s U.S. Open champion?&quot;)<br>print(answer)</pre><p><strong>Çıktı<br></strong>Ajan, sorguya yanıt bulmak için Serper API aracını kullanarak sırasıyla şu adımları izler:</p><p>İlk olarak, şampiyonun kim olduğunu bulur.<br>Ardından, bu şampiyonun memleketini arar.<br>Son olarak, kullanıcıya yanıt olarak şampiyonun memleketini döndürür.</p><pre>Entering new AgentExecutor chain...<br>Yes.<br>Follow up: Who is the reigning men&#39;s U.S. Open champion?<br>Intermediate answer: Current champions Carlos Alcaraz, 2022 men&#39;s singles champion.<br>Follow up: Where is Carlos Alcaraz from?<br>Intermediate answer: El Palmar, Spain<br>&gt; Finished chain.<br>&#39;El Palmar, Spain&#39;</pre><p><strong>KAYNAKLAR</strong></p><p><a href="https://www.langchain.com/">LangChain: Observe, Evaluate, and Deploy Reliable AI Agents</a></p><p><a href="https://platform.openai.com/docs/api-reference/introduction">https://platform.openai.com/docs/api-reference/introduction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e5298681ae6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Milvus ile Vektör Veritabanında Insert ve Query İşlemleri]]></title>
            <link>https://medium.com/@murattyldrm7/milvus-ile-vekt%C3%B6r-veritaban%C4%B1nda-insert-ve-query-i%CC%87%C5%9Flemleri-49c57744281c?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/49c57744281c</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[milvus]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[recommendations]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 20:54:54 GMT</pubDate>
            <atom:updated>2024-08-31T22:29:59.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*4V820tWBGIV9u5iaJe-weA.png" /></figure><h3>Giriş</h3><p>Modern makine öğrenimi ve yapay zeka uygulamaları, genellikle büyük miktarda veriyle çalışır. Bu veriler, örneğin metinler, resimler veya ses dosyaları, genellikle yüksek boyutlu vektörler şeklinde temsil edilir. Bu vektörler, benzerlik araması (similarity search), kümeleme (clustering), sınıflandırma (classification) gibi işlemlerde kullanılır. Geleneksel veritabanları, bu tür yüksek boyutlu verilerle etkili bir şekilde başa çıkmakta zorlanır. Bu noktada, Milvus gibi vektör veritabanları devreye girer.</p><h3>Milvus Nedir?</h3><p>Milvus, büyük ölçekli veriler üzerinde hızlı ve yüksek performanslı benzerlik araması yapabilen bir açık kaynak vektör veritabanıdır. Özellikle yapay zeka ve makine öğrenimi uygulamalarında kullanılır. Milvus, verileri vektör formatında saklar ve bu vektörler arasında hızlı benzerlik aramaları yapar. Bu, özellikle görüntü işleme, öneri sistemleri, doğal dil işleme (NLP) gibi alanlarda son derece yararlıdır.</p><h3>Vektör Veritabanlarının Avantajları</h3><p><strong>Yüksek Performanslı Benzerlik Aramaları:</strong></p><p>Milvus, milyonlarca vektör arasında hızlı arama yapabilir. Geleneksel veritabanlarının aksine, yüksek boyutlu vektör verilerinde etkili arama yapabilmek için optimize edilmiştir. Bu sayede, büyük ölçekli veri setlerinde benzerlik aramaları gerçekleştirmek mümkün olur.</p><p><strong>Esnek Veri Saklama:</strong></p><p>Vektör veritabanları, farklı türdeki verileri (metin, resim, ses vb.) vektörler halinde saklayabilir. Milvus, bu vektörleri organize eder ve kullanıcıların bu veriler üzerinde çeşitli işlemler yapmasına olanak tanır.</p><p><strong>Kolay Entegrasyon:</strong></p><p>Milvus, mevcut makine öğrenimi ve yapay zeka modelleriyle kolayca entegre edilebilir. Bu, geliştiricilerin kendi modellerini kullanarak verileri Milvus üzerinde saklamasına ve sorgulamasına imkan tanır.</p><h3>Insert ve Query İşlemleri</h3><h4>Insert (Veri Ekleme):</h4><p>Vektör veritabanına veri eklemek, geleneksel veritabanlarındaki INSERT işlemlerine benzer. Ancak burada, eklenen veriler yüksek boyutlu vektörler olarak temsil edilir. Örneğin, bir metin embedding modeli kullanarak bir metni vektöre dönüştürebilir ve bu vektörü Milvus veritabanına ekleyebilirsiniz.</p><p>Öncelikle, ham veriler (örneğin metinler) embedding model aracılığıyla vektörlere dönüştürülür. Bu vektörler genellikle çok boyutlu (örneğin, 768 boyutlu bir vektör) olur.</p><p>Dönüştürülen vektörler, belirli bir koleksiyona (collection) eklenir. Her bir vektörün veritabanında benzersiz bir kimliği (ID) olur ve bu kimlik, vektörün sonraki işlemlerinde kullanılabilir.</p><pre>@app.route(&#39;/insert&#39;, methods=[&#39;POST&#39;])<br>def insert_data():<br>    docs = request.json.get(&#39;docs&#39;, [])<br>    if not docs:<br>        return jsonify({&quot;error&quot;: &quot;Herhangi bir doküman sağlanmadı&quot;}), 400<br><br>    vectors = embedding_fn.encode_documents(docs)<br>    data = [<br>        {&quot;id&quot;: i, &quot;vector&quot;: vectors[i], &quot;text&quot;: docs[i], &quot;subject&quot;: &quot;history&quot;}<br>        for i in range(len(vectors))<br>    ]<br><br>    try:<br>        res = client.insert(collection_name=collection_name, data=data)<br><br>        response_data = {<br>            &quot;message&quot;: &quot;Veriler başarıyla eklendi.&quot;,<br>            &quot;raw_response&quot;: str(res)<br>        }<br><br>    except Exception as e:<br>        response_data = {<br>            &quot;error&quot;: f&quot;Veriler eklenirken bir sorun oluştu: {str(e)}&quot;<br>        }<br>    <br>    return jsonify(response_data)</pre><p>Bu kod, Flask framework’ü ile oluşturulmuş bir API endpoint’i (/insert) tanımlar ve Milvus vektör veritabanına veri eklemek için kullanılır. Kullanıcıdan gelen POST isteği ile docs anahtarının altında metin dokümanları alınır. Eğer docs boşsa veya eksikse, API bir hata mesajı döndürerek işlemi sonlandırır. Alınan dokümanlar embedding fonksiyonu aracılığıyla vektörlere dönüştürülür ve her vektörle ilişkili metin verisi Milvus veritabanındaki belirtilen koleksiyona eklenir. Daha sonra bu bilgiler JSON formatında kullanıcıya döndürülür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*I5igQ9gmyjdtYZP5FekyNw.png" /></figure><h4>Query (Veri Sorgulama):</h4><p>Milvus’ta veri sorgulama işlemi, veritabanında saklanan vektörler arasında benzerlik araması yapmayı içerir. Bu aramalar, kullanıcıların belirli bir vektöre en yakın olan diğer vektörleri bulmasına olanak tanır.</p><p>Kullanıcı bir sorgu yapmak istediğinde, önce aramak istediği veriyi yine bir vektöre dönüştürür (örneğin, bir metni embedding model ile vektörize eder).</p><p>Bu vektör, Milvus’a gönderilir ve veritabanında en yakın (benzer) vektörler bulunur. Bu işlem, genellikle en yakın komşu (nearest neighbor) araması olarak adlandırılır ve Milvus bu aramaları son derece hızlı yapabilme kapasitesine sahiptir.</p><p>Sorgu sonuçları, belirli bir sınır (limit) dahilinde döndürülebilir. Döndürülen her bir sonuç, sorgu vektörüne ne kadar yakın olduğunu gösteren bir “distance” metriği ile birlikte gelir.</p><pre>@app.route(&#39;/search&#39;, methods=[&#39;POST&#39;])<br>def search_data():<br>    try:<br>        query_text = request.json.get(&#39;query&#39;, &#39;&#39;)<br>        if not query_text:<br>            return jsonify({&quot;error&quot;: &quot;No query provided&quot;}), 400<br>        <br>        query_vector = embedding_fn.encode_queries([query_text])<br><br>        res = client.search(<br>            collection_name=collection_name,<br>            data=query_vector,<br>            limit=2,<br>            output_fields=[&quot;text&quot;, &quot;subject&quot;],<br>        )<br><br>        return jsonify(res)<br><br>    except Exception as e:<br>        return jsonify({&quot;error&quot;: f&quot;An error occurred: {str(e)}&quot;}), 500</pre><p>Bu kod, Flask framework’u kullanarak Milvus vektör veritabanında metin bazlı benzerlik araması yapmanızı sağlayan bir API endpoint’i (/search) oluşturur. Kullanıcıdan gelen POST isteği ile bir metin sorgusu (query_text) alınır ve bu metin, embedding fonksiyonu aracılığıyla yüksek boyutlu bir vektöre dönüştürülür. Ardından, bu vektör Milvus veritabanına gönderilerek, koleksiyondaki en yakın (benzer) iki vektör aranır. Arama sonuçları, veritabanında depolanan ilgili metin ve konu (text ve subject) bilgileri ile birlikte JSON formatında döndürülür. Bu sayede, kullanıcı belirli bir metinle ilgili en benzer diğer verileri Milvus veritabanında bulabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*YTVQY8q2B7kySp7WrnEe4A.png" /></figure><h3>KAYNAKLAR</h3><ul><li><a href="https://milvus.io/docs/quickstart.md">Quickstart | Milvus Documentation</a></li><li><a href="https://github.com/milvus-io/milvus">GitHub - milvus-io/milvus: A cloud-native vector database, storage for next generation AI applications</a></li><li><a href="https://milvus.io/docs/v2.0.x/example_code.md">Milvus v2.0.x documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49c57744281c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matris Faktörizasyonu Nedir?]]></title>
            <link>https://medium.com/@murattyldrm7/matris-fakt%C3%B6rizasyonu-nedir-8b4badc740ec?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b4badc740ec</guid>
            <category><![CDATA[matrix-factorization]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 11:10:37 GMT</pubDate>
            <atom:updated>2024-06-20T11:10:37.168Z</atom:updated>
            <content:encoded><![CDATA[<p>Matris faktörizasyonu, bir matrisi iki daha küçük matrise çarpanlarına ayırarak, orijinal matrisi yaklaşık olarak yeniden oluşturan bir tekniktir. Tavsiye sistemlerinde yaygın olarak kullanılır ve kullanıcıların daha önce derecelendirmediği ürünleri (filmleri, kitapları, vs.) tahmin etmeye yardımcı olur.</p><p>Örneğin, kullanıcıların filmlere verdiği puanların bir matrisi olsun. Bu matrisi, kullanıcıların ve filmlerin özelliklerini temsil eden iki matrisin çarpımı olarak faktörize edebiliriz.</p><h4><strong>Kullanıcı-Film Örneği</strong></h4><p>Diyelim ki elimizde şu şekilde bir kullanıcı-film puan matrisi R var:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*cWCotwt7yhfUKNeV3_hzFA.png" /></figure><p>Burada, her satır bir kullanıcıyı, her sütun bir filmi ve her hücre de kullanıcının filme verdiği puanı temsil eder.</p><h3>Matris Faktörizasyonu Süreci</h3><p>Bu puan matrisini iki küçük matrise ayırmak istiyoruz: P ve Q. P kullanıcı matrisini, Q ise film matrisini temsil eder. Bu iki matrisi çarparak orijinal puan matrisini yaklaşık olarak elde ederiz:</p><h4>Adım 1: Başlangıç Matrislerinin Oluşturulması</h4><p>Önce, P ve Q matrislerini rastgele değerlerle başlatırız. Diyelim ki her iki matrisin boyutu 3x2 olsun (3 kullanıcı ve 2 gizli özellik).</p><pre>import numpy as np<br><br>R = np.array([<br>    [5, 3, 1],<br>    [4, 2, 1],<br>    [1, 5, 4]<br>])<br><br>N = len(R)  # Kullanıcı sayısı<br>M = len(R[0])  # Film sayısı<br>K = 2  # Gizli özellik sayısı<br><br>P = np.random.rand(N, K)  # Kullanıcı matrisini rastgele başlatma<br>Q = np.random.rand(M, K)  # Film matrisini rastgele başlatma</pre><h4>Adım 2: Hata Hesaplama ve Güncelleme Kuralları</h4><p>Amacımız, bu iki matrisi güncelleyerek tahmin edilen puan matrisi R^ = P. × Q.T ile orijinal puan matrisi R arasındaki hatayı en aza indirmek. Hata fonksiyonu olarak ortalama kare hata (MSE) kullanılır.</p><p>Hata fonksiyonumuz şöyle tanımlanır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7zKGJxKX16wt_QnOQvSgQ.png" /></figure><p>Burada, β regularization terimidir ve aşırı öğrenmeyi önlemek için kullanılır.</p><p>Güncelleme kuralları ise şöyle tanımlanır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*DmLPoaq711bmrR-ahZcVfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcjgnO_DIX7wegbbNipnzw.png" /></figure><h4>Adım 3: Matris Faktörizasyonu Fonksiyonunun Yazılması</h4><p>Bu güncelleme kurallarını kullanarak matris faktörizasyonunu gerçekleştiren fonksiyonu yazalım:</p><pre>def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02):<br>    Q = Q.T  # Transpose Q to make it easier to work with in the dot product<br>    for step in range(steps):  # Iterate over the number of steps<br>        for i in range(len(R)):  # Iterate over each user<br>            for j in range(len(R[i])):  # Iterate over each item<br>                if R[i][j] &gt; 0:  # Only consider observed ratings<br>                    eij = R[i][j] - np.dot(P[i,:],Q[:,j])  # Calculate the error of the prediction<br>                    for k in range(K):  # Iterate over each latent feature<br>                        P[i][k] = P[i][k] + alpha * (2 * eij * Q[k][j] - beta * P[i][k])  # Update the user feature matrix P<br>                        Q[k][j] = Q[k][j] + alpha * (2 * eij * P[i][k] - beta * Q[k][j])  # Update the item feature matrix Q<br>        eR = np.dot(P, Q)  # Calculate the predicted rating matrix<br>        e = 0  # Initialize the total error<br>        for i in range(len(R)):  # Iterate over each user<br>            for j in range(len(R[i])):  # Iterate over each item<br>                if R[i][j] &gt; 0:  # Only consider observed ratings<br>                    e = e + pow(R[i][j] - np.dot(P[i,:],Q[:,j]), 2)  # Add the squared error to the total error<br>                    for k in range(K):  # Iterate over each latent feature<br>                        e = e + (beta/2) * (pow(P[i][k],2) + pow(Q[k][j],2))  # Add regularization term to the total error<br>        if e &lt; 0.001:  # If the total error is less than the threshold, stop training<br>            break<br>    return P, Q.T  # Return the factorized matrices</pre><h4>Adım 4: Modelin Eğitilmesi ve Sonuçların Gösterilmesi</h4><p>Modeli eğitelim ve sonuçları gösterelim:</p><pre>nP, nQ = matrix_factorization(R, P, Q, K)<br>nR = np.dot(nP, nQ.T)<br><br>print(&quot;Orijinal Matris:&quot;)<br>print(R)<br>print(&quot;\nFaktörize Edilmiş Kullanıcı Matris (P):&quot;)<br>print(nP)<br>print(&quot;\nFaktörize Edilmiş Öğe Matris (Q):&quot;)<br>print(nQ)<br>print(&quot;\nTahmin Edilen Matris:&quot;)<br>print(nR)<br><br># Hata Hesaplama<br>from sklearn.metrics import mean_squared_error<br><br>predicted_ratings = np.dot(nP, nQ.T)<br>rmse = np.sqrt(mean_squared_error(R[R &gt; 0], predicted_ratings[R &gt; 0]))<br>print(&quot;\nRMSE:&quot;, rmse)</pre><p>Bu kod, kullanıcı ve film özelliklerini faktörize ederek orijinal puan matrisini yaklaşık olarak tahmin eder. Hata hesaplaması için RMSE kullanılarak modelin performansı değerlendirilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*7ev4jv66zgQEuyFbC0tT-g.png" /></figure><h3><strong>RESOURCES :</strong></h3><ul><li><a href="https://developers.google.com/machine-learning/recommendation/collaborative/matrix?hl=tr">Matrisi Çarpanlarına Ayırma | Machine Learning | Google for Developers</a></li><li><a href="https://d2l.ai/chapter_recommender-systems/mf.html">21.3. Matrix Factorization - Dive into Deep Learning 1.0.3 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b4badc740ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Custom Model Training Pipeline with Vertex AI]]></title>
            <link>https://medium.com/@murattyldrm7/creating-a-custom-model-training-pipeline-with-vertex-ai-b7912a8db458?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7912a8db458</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[vertex-ai-workbench]]></category>
            <category><![CDATA[custom-training]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 11:52:20 GMT</pubDate>
            <atom:updated>2024-08-31T21:55:00.948Z</atom:updated>
            <content:encoded><![CDATA[<p>In this document, we will outline the steps to create a custom model training pipeline using Vertex AI. We will start by creating a cloud storage bucket, then proceed to train a new model using custom containers. Finally, we will push the custom container image to Artifact Registry.</p><p><strong>Step 1: Create a Cloud Storage Bucket</strong></p><p>First, create a cloud storage bucket where you will store your training data and model artifacts.</p><p><strong>Step 2: Train a New Model on Vertex AI</strong></p><p>Navigate to the training section in Vertex AI and select “TRAIN NEW MODEL.”</p><p>Choose this option as we will be using a dockerized training set upload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmnJsddu-PiUq1TKdrtNRw.png" /><figcaption>Custom training</figcaption></figure><p><strong>Step 3: Uploading the Custom Container</strong></p><p>Now, let’s see how to upload the custom container.</p><p><strong>task.py</strong></p><pre>import pandas as pd<br>import tensorflow as tf<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder<br><br>data = pd.read_csv(&#39;gs://bucket_name/train.csv&#39;)<br><br>data = data.dropna()<br><br>features = [&quot;Pclass&quot;, &quot;Sex&quot;, &quot;Age&quot;, &quot;SibSp&quot;, &quot;Parch&quot;, &quot;Fare&quot;, &quot;Embarked&quot;]<br><br>label_encoders = {}<br>for feature in features:<br>    label_encoders[feature] = LabelEncoder()<br>    data[feature] = label_encoders[feature].fit_transform(data[feature])<br><br>X = data[features]<br>y = data[&quot;Survived&quot;]<br><br>X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)<br><br>model = tf.keras.Sequential([<br>    tf.keras.layers.Dense(64, activation=&#39;relu&#39;, input_shape=(X_train.shape[1],)),<br>    tf.keras.layers.Dense(64, activation=&#39;relu&#39;),<br>    tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)<br>])<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;])<br><br>model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_val, y_val))<br><br>loss, accuracy = model.evaluate(X_val, y_val)<br>print(&quot;Accuracy:&quot;, accuracy)<br><br>model.save(&#39;gs://bucket_name/titanic_model_tf&#39;)</pre><p><strong>Dockerfile</strong></p><pre>FROM us-docker.pkg.dev/deeplearning-platform-release/gcr.io/tf2-cpu.2-15.py310<br><br>WORKDIR /<br><br>COPY trainer /trainer<br><br>RUN pip install -r requirements.txt<br><br>ENTRYPOINT [ &quot;python&quot; ,&quot;-m&quot; ,&quot;trainer.task&quot; ]</pre><p><strong>requirements.txt</strong></p><pre>pandas<br>scikit-learn</pre><p><strong>Step 4: Pushing the Custom Container to Artifact Registry</strong></p><p>Next, create a repository in Artifact Registry. Then, using the terminal, push the custom container image created from the above files to this repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_RLVVbDZji0Mrolmr6c4Q.png" /><figcaption>Choose the container that was pushed before.</figcaption></figure><p><strong>Conclusion:</strong></p><p>By following these steps, you have successfully created a custom model training pipeline on Vertex AI, utilizing a dockerized training set and pushing the custom container image to Artifact Registry for future use. This updated pipeline now incorporates additional features from the Titanic dataset for improved model performance.</p><h3><strong>Resources :</strong></h3><p><a href="https://cloud.google.com/vertex-ai/docs">Gemini Enterprise Agent Platform | Google Cloud Documentation</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVRQXIiNLdAk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVRQXIiNLdAk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVRQXIiNLdAk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ee1e35781afe0bc79fada6c97e92b8f/href">https://medium.com/media/2ee1e35781afe0bc79fada6c97e92b8f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7912a8db458" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment of Google Cloud Compute Engine]]></title>
            <link>https://medium.com/@murattyldrm7/ssh-connection-from-terminal-02934673df27?source=rss-bbf7f745dc16------2</link>
            <guid isPermaLink="false">https://medium.com/p/02934673df27</guid>
            <category><![CDATA[compute-engine]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[google-cloud]]></category>
            <dc:creator><![CDATA[Murat Yıldırım]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 19:38:30 GMT</pubDate>
            <atom:updated>2024-08-31T21:53:56.734Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ll walk you through the process of deploying a project on Google Cloud Compute Engine.</p><h4>CONNECTION FROM TERMINAL</h4><ul><li>After creating an instance, click on the SSH button in the SSH section, and then select “View gcloud command”.</li><li>A panel titled “Gcloud command line” will open; copy the command in the panel.</li><li>Paste the copied command into your terminal to establish the connection.</li><li>If you’re not connected, you should log in to your gcloud account by running the command “gcloud auth login” in your terminal.</li></ul><h4>TRANSFER FILES</h4><p>You can use the command gcloud compute <strong>scp /Users/muratyildirim/Desktop/Project-/* instance-1:/home/muratyildirim/transfer-file — zone=us-central1-a</strong> to copy all files from the Project- folder on your local machine to the <strong>/home/muratyildirim/transfer-file</strong> folder on the remote machine.</p><p>Before executing this command, ensure you’ve logged in using the command <strong>gcloud auth login</strong>.<br>Additionally, you can upload files using the terminal on console.cloud.google (UPLOAD FILE).</p><h4>DOCKER CONTAINER</h4><p>Running our applications on the cloud using Docker involves the following steps:</p><p>List the running containers using the command</p><p><strong>sudo docker ps -a</strong>.</p><p>This command displays all containers.</p><p>Next, the project is built using the following command:</p><p><strong>sudo docker build -t project-name .</strong></p><p>This Docker command is used to create a Docker image. Here’s the breakdown of the command:</p><p><strong>sudo</strong>: Executes the command with superuser (root) privileges. Docker commands often require superuser privileges.</p><p><strong>docker build: </strong>Used to build a Docker image. A Docker image is a runnable package that contains an application and its dependencies.</p><p><strong>-t project-name:</strong> This flag assigns a tag to the created Docker image. This tag is used to identify the created image. In this case, a tag named “project-name” is assigned.</p><p><strong>.: </strong>Specifies the directory where the Dockerfile is located.<br>Afterward, to bring up the built project, you can use the following command:</p><p><strong>sudo docker run -p 8080:8080 -d -it project-name</strong></p><p>Here’s the breakdown of this command:</p><ul><li><strong>p 8080:8080:</strong> This flag is used for port forwarding. It forwards port 8080 from the Docker container to port 8080 on the host system.</li><li><strong>-d:</strong> This flag runs the Docker container in the background (daemon mode).</li><li><strong>-it: </strong>These two flags start an interactive terminal with the Docker container.</li><li><strong>project-name:</strong> Specifies the name given to the Docker container.</li></ul><h4>LOGGING</h4><p><strong>sudo docker logs “container_id”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02934673df27" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>