Wednesday, May 6, 2026

Limitations of K-Means algorithm

K-means clustering, while efficient for large datasets, is limited by its sensitivity to initial centroid selection, requiring prior knowledge of K, difficulty with non-spherical shapes, and susceptibility to outliers. These limitations are generally overcome by using K-means++ for better initialization, applying the Elbow Method for optimal K, or using algorithms like DBSCAN for complex shapes. 


Limitations and Solutions:
  • Sensitivity to Initialization (Random Centroids): Randomly chosen initial centroids can lead to suboptimal, local optima solutions.
    • Solution: Use K-means++, which selects initial centroids that are spread out, leading to faster convergence and better final clusters.
  • Need to Predefine 'K' Clusters: The algorithm requires the number of clusters to be specified beforehand, which is often unknown.
    • Solution: Use the Elbow Method (plotting sum of squared errors) or the Silhouette Method to determine the optimal K value.
  • Assumption of Spherical, Same-Sized Clusters: K-means assumes clusters are spherical and similar in size, failing on elongated or complex shapes.
    • Solution: Use density-based algorithms like DBSCAN or Spectral Clustering that can identify arbitrary shapes.
  • Susceptibility to Outliers: Outliers can drastically shift the centroid positions, skewing results.
    • Solution: Remove outliers beforehand or use robust clustering variants like K-Medoids, which use actual data points as centroids.
  • Sensitive to Feature Scaling: Features with larger magnitudes dominate the distance calculations.
    • Solution: Normalize or standardize numerical data before applying K-means.
  • Hard Assignment Limitations: K-means gives absolute cluster membership (hard clustering), which doesn't handle overlapping clusters well.
    • Solution: Use Fuzzy C-Means or Gaussian Mixture Models (GMM), which allow soft assignments (probability-based). 


Modern machine learning models and industry pipelines frequently use the K-means algorithm, though its role has shifted from being the primary model to serving as a critical preprocessing step or a benchmark. While deep learning now dominates complex tasks like image or speech recognition, K-means remains a "gold standard" for unsupervised tasks due to its extreme speed and simplicity. 
Current Roles of K-Means in Modern AI
  • Deep Clustering Integration: Modern research integrates K-means directly into deep neural networks. For example, Robust Embedded Deep K-means (RED-KC) uses an autoencoder to map complex data into a simplified "latent space" where K-means can then perform clustering more effectively.
  • Feature Learning: In some computer vision and NLP tasks, K-means is used to learn "feature representations". It clusters small patches of pixels or word vectors to create a "dictionary" of features that more complex models then use for classification.
  • Dataset Analysis & Preprocessing: Data scientists use it to quickly understand the hidden structure of massive unlabeled datasets before applying more expensive deep learning models.
  • Industrial Applications (2025–2026): It continues to be a primary tool for real-world business tasks such as:
    • Customer Segmentation: Grouping millions of users by purchasing behavior.
    • Anomaly Detection: Flagging fraudulent transactions that fall outside of "normal" behavior clusters.
    • Image Compression: Reducing file sizes by clustering similar pixel colors. 
Modern Evolution & Scalability
To stay relevant for "Big Data," the algorithm has evolved with high-performance variants: 
  • Mini-Batch K-Means: Processes small random chunks of data at a time to handle datasets too large for memory.
  • GPU Acceleration: Libraries like NVIDIA's RAPIDS cuML allow K-means to run up to 50x faster on GPUs compared to traditional CPU-based versions.
  • Next-Gen Languages: New high-performance languages like Mojo are being used to rewrite K-means implementations for even faster AI development



To cluster datasets without predefining "K," you have two main strategies: using extensions of K-means that estimate \(K\) during execution, or switching to alternative algorithms designed to find the natural number of clusters automatically. 
1. K-means Extensions (The Algorithm Finds "K") 
These algorithms build upon the standard K-means logic but include internal mechanisms to test if adding more clusters improves the result. 
  • X-means: This is the direct evolution of K-means for your problem. It starts with a small \(K\) and iteratively attempts to split clusters into two. It uses the Bayesian Information Criterion (BIC) to decide if a split truly improves the model or just adds unnecessary complexity.
  • G-means: Similar to X-means, but it uses a Gaussianity test. It splits a cluster only if the data points within it do not follow a Gaussian (normal) distribution.
  • Bisecting K-means: While typically used for hierarchical structure, it can be automated to keep splitting the "worst" performing cluster until a specific quality threshold is met. 
2. Modern Alternatives (Naturally "K-less")
These algorithms are often preferred in modern pipelines because they don't assume a fixed number of clusters by design.
  • DBSCAN & HDBSCAN: These are density-based algorithms. Instead of "how many groups," they ask "where is the data most concentrated?". They automatically discover the number of clusters and are excellent at identifying outliers (noise) that K-means might otherwise force into a group.
  • Affinity Propagation: This algorithm treats every data point as a potential "representative" for a cluster. Points "vote" on their representatives until a consensus is reached, naturally resulting in a certain number of clusters without any prior input from you.
  • Mean-Shift: This is a "mode-seeking" algorithm. It shifts points toward the highest density of neighbors. The number of "modes" it finds becomes the number of clusters. 
3. Comparison for Your Use Case
Feature X-means / G-meansDBSCAN / HDBSCANAffinity Propagation
Cluster ShapeAssumes sphericalAny arbitrary shapeRoughly spherical
OutliersSensitive to themDetects/Removes themSomewhat sensitive
ComplexityFast (O(n))Medium (O(n log n))Slow (O(n²))
Best ForVarying K, clean dataNoisy data, varied shapesSmall, complex datasets
Recommendation: If your data is relatively clean and you want to stick close to the K-means style, X-means is your best bet. If your data is "messy" or has weirdly shaped clusters, HDBSCAN is the current industry standard for finding K automatically

Tuesday, May 5, 2026

Python List, NumPy Array and Pandas DataFrame

 The strength of numpy arrays is that it allows for vectorized operations (applying a calculation to the whole array at once without loops). Also the numpy array elements , unlike python list, are stored in Contiguous memory locations allowing fast operations and vectorized operations. 


C, C++, Rust, Go, FORTRAN, Swift and C# require arrays to be stored in contiguos memory locations. 


For Java object arrays and Python lists, pointers to elements are stored in contiguous locations, but not elements. However, Java primitive data type arrays are still stored in contiguous locations.


Feature Python ListNumPy ArrayPandas DataFrame
Dimensions1D (can nest)N-dimensional2D (tabular)
Data TypesHeterogeneous (mixed)Homogeneous (same)Heterogeneous (per column)
IndexingInteger-basedInteger-basedLabeled (names) & Integer
SpeedSlow for large dataFast (C-optimized)Slower than NumPy for pure math
Best ForGeneral programmingMath/Scientific computingData analysis & manipulation

JOURNEY 002 - SMART CHUNKING

StepKey ActionsOutcome
Generate Embeddings- Convert each sentence into a vector- Use Google embedding API- Store embeddings in array👉 Semantic meaning is captured numerically
Apply Clustering (KMeans)- Feed embeddings into KMeans- Choose number of clusters- Assign each sentence to a cluster👉 Similar sentences get grouped automatically
Build Smart Chunks- Combine sentences within each cluster- Preserve related context- Format into readable blocks👉 Each chunk now contains meaningful grouped knowledge
Structure the Data- Assign unique IDs- Store chunk text- Add cluster metadata👉 Data becomes RAG-ready and easy to use later

=================================================================

!pip install google-generativeai scikit-learn numpy

=================================================================

# ================================
# STEP 1: IMPORTS + API SETUP
# ================================

import google.generativeai as genai
#FOR GOOGLE COLAB
from google.colab import userdata
#FOR OTHER ENVIRONS
#import os
import numpy as np
from sklearn.cluster import KMeans
from collections import defaultdict


# 🔑 Replace with your API key
#FOR NON-COLAB
#api_key = os.environ.get("GEMINI_API_KEY")
#FOR COLAB
api_key =  userdata.get("GEMINI_API_KEY")

#if not api_key:
#    raise ValueError("API key not found. Please set GEMINI_API_KEY in Colab Secrets.")

genai.configure(api_key=api_key)

# ================================
# STEP 2: DATA SET
# ================================

documents = [
"CrashLoopBackOff occurs when a container repeatedly crashes after starting.",
"A container may crash due to missing environment variables.",
"Incorrect command or entrypoint can cause container startup failure.",
"Application errors inside the container often lead to restarts.",
"OOMKilled happens when a container exceeds its memory limit.",

"ImagePullBackOff occurs when Kubernetes cannot pull the container image.",
"Incorrect image name or tag can cause image pull failures.",
"Private registries require imagePullSecrets for authentication.",

"kubectl logs retrieves logs from a running container.",
"kubectl describe pod shows events and state transitions.",

"Pods remain pending if no node satisfies resource requests.",
"Node affinity restricts pods to specific nodes.",
"Taints prevent pods from being scheduled on certain nodes.",
"Tolerations allow pods to be scheduled on tainted nodes.",

"Liveness probes determine if a container should be restarted.",
"Readiness probes determine if a pod can receive traffic.",
"A failing readiness probe removes the pod from service endpoints.",

"ClusterIP services expose applications within the cluster.",
"NodePort services expose applications on node IPs.",

"PersistentVolumes provide storage independent of pods.",
"PersistentVolumeClaims request storage resources.",

"ConfigMaps store non-sensitive configuration data.",
"Secrets store sensitive data like passwords and tokens.",

"Deployments manage replica sets and pod updates.",
"Horizontal Pod Autoscaler scales based on CPU or metrics.",

"Pods stuck in Terminating state may have finalizers blocking deletion.",
"RBAC misconfiguration can block access to resources."
]

# ================================
# STEP 3: GENERATE EMBEDDINGS
# ================================
def get_embedding(text):
    response = genai.embed_content(
        #model="models/embedding-001", #this is now deprecated and you will get error
        model="models/gemini-embedding-001",
        content=text
    )
    return response["embedding"]

print("Generating embeddings...")

embeddings = []
for doc in documents:
    emb = get_embedding(doc)
    embeddings.append(emb)

embeddings = np.array(embeddings)

print(f"Embeddings shape: {embeddings.shape}")

# ================================
# STEP 4: CLUSTER uSING KMEANS
# ================================
NUM_CLUSTERS = 6  # 🔧 Tune this later

kmeans = KMeans(n_clusters=NUM_CLUSTERS, random_state=42)
labels = kmeans.fit_predict(embeddings)

print("Clustering complete.")

# ================================
# STEP 5: GROUP DOCUMENTS BY CLUSTER
# ================================
clustered_docs = defaultdict(list)

for doc, label in zip(documents, labels):
    clustered_docs[label].append(doc)

# ================================
# STEP 6: BUILD SMART CHUNKS
# ================================
smart_chunks = []

for cluster_id, docs in clustered_docs.items():
   
    chunk_text = f"Cluster {cluster_id}\n\n"
   
    for d in docs:
        chunk_text += f"- {d}\n"
   
    smart_chunks.append(chunk_text.strip())

# ================================
# STEP 7: ADD METADATA (FINAL DATA PREPARED)
# ================================
prepared_data = []

for i, chunk in enumerate(smart_chunks):
    prepared_data.append({
        "id": f"chunk_{i}",
        "cluster": i,
        "text": chunk
    })
# ================================
# STEP 8: INSPECT RESULTS
# ================================
for item in prepared_data:
    print(item["text"])
    print("=" * 60)

# ================================
# STEP 9: DEBUG CLUSTER QUALITY
# ================================
for cluster_id, docs in clustered_docs.items():
    print(f"\n🔹 Cluster {cluster_id} ({len(docs)} items)")
    for d in docs:
        print("-", d)


==================================================================================
Output
==================================================================================
Generating embeddings... Embeddings shape: (27, 3072) Clustering complete. Cluster 4 - CrashLoopBackOff occurs when a container repeatedly crashes after starting. - ImagePullBackOff occurs when Kubernetes cannot pull the container image. - kubectl logs retrieves logs from a running container. - kubectl describe pod shows events and state transitions. ============================================================ Cluster 2 - A container may crash due to missing environment variables. - Incorrect command or entrypoint can cause container startup failure. - Application errors inside the container often lead to restarts. - OOMKilled happens when a container exceeds its memory limit. - Liveness probes determine if a container should be restarted. ============================================================ Cluster 5 - Incorrect image name or tag can cause image pull failures. - Private registries require imagePullSecrets for authentication. - ConfigMaps store non-sensitive configuration data. - Secrets store sensitive data like passwords and tokens. ============================================================ Cluster 0 - Pods remain pending if no node satisfies resource requests. - Node affinity restricts pods to specific nodes. - Taints prevent pods from being scheduled on certain nodes. - Tolerations allow pods to be scheduled on tainted nodes. - Readiness probes determine if a pod can receive traffic. - A failing readiness probe removes the pod from service endpoints. - Horizontal Pod Autoscaler scales based on CPU or metrics. - Pods stuck in Terminating state may have finalizers blocking deletion. - RBAC misconfiguration can block access to resources. ============================================================ Cluster 1 - ClusterIP services expose applications within the cluster. - NodePort services expose applications on node IPs. ============================================================ Cluster 3 - PersistentVolumes provide storage independent of pods. - PersistentVolumeClaims request storage resources. - Deployments manage replica sets and pod updates. ============================================================ 🔹 Cluster 4 (4 items) - CrashLoopBackOff occurs when a container repeatedly crashes after starting. - ImagePullBackOff occurs when Kubernetes cannot pull the container image. - kubectl logs retrieves logs from a running container. - kubectl describe pod shows events and state transitions. 🔹 Cluster 2 (5 items) - A container may crash due to missing environment variables. - Incorrect command or entrypoint can cause container startup failure. - Application errors inside the container often lead to restarts. - OOMKilled happens when a container exceeds its memory limit. - Liveness probes determine if a container should be restarted. 🔹 Cluster 5 (4 items) - Incorrect image name or tag can cause image pull failures. - Private registries require imagePullSecrets for authentication. - ConfigMaps store non-sensitive configuration data. - Secrets store sensitive data like passwords and tokens. 🔹 Cluster 0 (9 items) - Pods remain pending if no node satisfies resource requests. - Node affinity restricts pods to specific nodes. - Taints prevent pods from being scheduled on certain nodes. - Tolerations allow pods to be scheduled on tainted nodes. - Readiness probes determine if a pod can receive traffic. - A failing readiness probe removes the pod from service endpoints. - Horizontal Pod Autoscaler scales based on CPU or metrics. - Pods stuck in Terminating state may have finalizers blocking deletion. - RBAC misconfiguration can block access to resources. 🔹 Cluster 1 (2 items) - ClusterIP services expose applications within the cluster. - NodePort services expose applications on node IPs. 🔹 Cluster 3 (3 items) - PersistentVolumes provide storage independent of pods. - PersistentVolumeClaims request storage resources. - Deployments manage replica sets and pod updates.















 

models/embedding-001 is not found for API version v1beta, or is not supported for embedContent.

 

NotFound: 404 POST https://generativelanguage.googleapis.com/v1beta/models/embedding-001:embedContent?%24alt=json%3Benum-encoding%3Dint: models/embedding-001 is not found for API version v1beta, or is not supported for embedContent. Call ListModels to see the list of available models and their supported methods.



This is because embedding-001 is being phased out in favor of gemini-embedding-001.


You can list the available models like :

for m in genai.list_models():
    if 'embedContent' in m.supported_generation_methods:
        print(m.name)

as of 05/may/2026, on colab, it listed:
models/gemini-embedding-001 models/gemini-embedding-2-preview models/gemini-embedding-2


But there is a difference in older embedding-001 and newer gemini-embedding-001.
  • Dimension Changes: This model produces 3072-dimension vectors by default. This may differ from older models (768 dimensions), potentially breaking existing vector databases.
  • Dimension Control: You can use output_dimensionality to reduce the vector size to match your existing database requirements.
  • Batch Size: This model may have strict batch size limits in certain SDK implementations






  • Journey - 001 : Naive Chunking

     # ================================

    # STEP 1: RAW DATASET

    # ================================


    documents = [


    # --- Pod Failures ---

    "CrashLoopBackOff occurs when a container repeatedly crashes after starting.",

    "A container may crash due to missing environment variables.",

    "Incorrect command or entrypoint can cause container startup failure.",

    "Application errors inside the container often lead to restarts.",

    "OOMKilled happens when a container exceeds its memory limit.",


    # --- Image Issues ---

    "ImagePullBackOff occurs when Kubernetes cannot pull the container image.",

    "Incorrect image name or tag can cause image pull failures.",

    "Private registries require imagePullSecrets for authentication.",


    # --- Debugging Commands ---

    "kubectl logs retrieves logs from a running container.",

    "kubectl describe pod shows events and state transitions.",


    # --- Scheduling Issues ---

    "Pods remain pending if no node satisfies resource requests.",

    "Node affinity restricts pods to specific nodes.",

    "Taints prevent pods from being scheduled on certain nodes.",

    "Tolerations allow pods to be scheduled on tainted nodes.",


    # --- Probes ---

    "Liveness probes determine if a container should be restarted.",

    "Readiness probes determine if a pod can receive traffic.",

    "A failing readiness probe removes the pod from service endpoints.",


    # --- Networking ---

    "ClusterIP services expose applications within the cluster.",

    "NodePort services expose applications on node IPs.",


    # --- Storage ---

    "PersistentVolumes provide storage independent of pods.",

    "PersistentVolumeClaims request storage resources.",


    # --- Configuration ---

    "ConfigMaps store non-sensitive configuration data.",

    "Secrets store sensitive data like passwords and tokens.",


    # --- Deployment & Scaling ---

    "Deployments manage replica sets and pod updates.",

    "Horizontal Pod Autoscaler scales based on CPU or metrics.",


    # --- Misc ---

    "Pods stuck in Terminating state may have finalizers blocking deletion.",

    "RBAC misconfiguration can block access to resources."


    ]



    # ================================

    # STEP 2: CLEANING FUNCTION

    # ================================


    def clean_text(text):

        return text.strip().replace("\n", " ")



    # ================================

    # STEP 3: BASIC CHUNKING

    # ================================


    def chunk_documents(docs, chunk_size=3):

        chunks = []

        

        for i in range(0, len(docs), chunk_size):

            chunk = " ".join(docs[i:i+chunk_size])

            chunks.append(chunk)

        

        return chunks


    chunks = chunk_documents(documents, chunk_size=3)



    # ================================

    # STEP 4: ADD METADATA STRUCTURE

    # ================================


    prepared_data = []


    for i, chunk in enumerate(chunks):

        prepared_data.append({

            "id": f"chunk_{i}",

            "text": clean_text(chunk)

        })



    # ================================

    # STEP 5: INSPECT OUTPUT

    # ================================


    for item in prepared_data[:5]:

        print(item)

        print("-" * 50)



    # ================================

    # OPTIONAL: SIZE CHECK

    # ================================


    print(f"Total raw documents: {len(documents)}")

    print(f"Total chunks created: {len(prepared_data)}")




    ==========================================================================

    {'id': 'chunk_0', 'text': 'CrashLoopBackOff occurs when a container repeatedly crashes after starting. A container may crash due to missing environment variables. Incorrect command or entrypoint can cause container startup failure.'} -------------------------------------------------- {'id': 'chunk_1', 'text': 'Application errors inside the container often lead to restarts. OOMKilled happens when a container exceeds its memory limit. ImagePullBackOff occurs when Kubernetes cannot pull the container image.'} -------------------------------------------------- {'id': 'chunk_2', 'text': 'Incorrect image name or tag can cause image pull failures. Private registries require imagePullSecrets for authentication. kubectl logs retrieves logs from a running container.'} -------------------------------------------------- {'id': 'chunk_3', 'text': 'kubectl describe pod shows events and state transitions. Pods remain pending if no node satisfies resource requests. Node affinity restricts pods to specific nodes.'} -------------------------------------------------- {'id': 'chunk_4', 'text': 'Taints prevent pods from being scheduled on certain nodes. Tolerations allow pods to be scheduled on tainted nodes. Liveness probes determine if a container should be restarted.'} -------------------------------------------------- Total raw documents: 27 Total chunks created: 9

    Chunking Considerations

     

    🔑 1: Chunk by meaning, not by size

    🔑 2: Keep chunks self-contained

    “If this chunk is retrieved alone, does it still make sense?”

    🔑 3: Avoid mixing unrelated topics

    🔑 4: Include cause + symptom + fix (if applicable)

    🔑 5: Maintain moderate size

    • 50–200 words per chunk (rule of thumb) 

    🔑 6: Overlap slightly

    🔑 7: Preserve important keywords

    👉 These are retrieval anchors

    🔑 8: Structure beats raw text

    Structured chunks > plain sentences

    🔑 9: One chunk = one intent

    🔑 10: Think like a query

    “What question would retrieve this?”  => no answer means weak chunk

    Things you should look for in a good RAG test data

     1. it should force semantic searching i.e. it should have cases which are not obvious for a dumb machine. e.g. given an HR database, suppose you search for "leave policy". A dumb algo will simply search for keyword "leave", collect all the data that contains the word "leave" and output it. Where as a semantically searched resultset will also include statements  containing "holidays", "off days" etc.


    2. Overlapping data: Same data should appear multiple times or may appear singularly but in different context. RAG should be able to differentiate context.


    3. Should contain some kind of ambiguity 

    4. unclear edge cases. RAG, if properly trained, should be able to conclude on edge cases, depending on avaiable data, and gracefully output if it is not able to provide accurate information.

    5. multi-hop reasoning



    Types of duplications in data: 

    1. Exact duplicates : Data contains same statement/contextual data exactly repeated at many places. 

    Models  (embedding and LLM) should be intelligent enough to identify noise vs required data in exact duplicates. Noise-> needs to be eliminated->e.g. Employees are entitled 40 leaves per year.-> If this string is encountered multiple times, it can be eliminated. But in a legal database, same sentence may appear multiple times as a sentence to different crimes, that cannot be and should not be eliminated.


    2. Semantic Duplicates : Ordering of words changed/words changed but have same meaning

    e.g. "You can change your password after first login" and "Password can be changed by the user after maiden login"

    3. Boilerplate Overlap : Common repetitive text found across many documents e.g header/footer.



    Strategies to Handle Overlapping Data
    • Semantic Splitting: Using tools to split text at semantic boundaries rather than fixed token counts reduces the need for large overlaps.
    • Deduplication: Implementing hash-based fingerprinting (for exact matches) or using clustering techniques to identify and remove near-duplicates.
    • Summarization: Detecting overlapping chunks during retrieval and summarizing them into a single, comprehensive context for the LLM.
    • Optimal Overlap Setting: Common best practices suggest a 10% to 20% overlap (e.g., 100 tokens of overlap for a 512-token chunk)

     

    Comparing features of LangGraph vs CrewAI

    LangGraph Orchestration vs CrewAI Orchestration The following table compares LangGraph and CrewAI orchestration across their menta...