Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Machine Learning
  • Supervised Learning: Features, Labels, Classification and Regression
  • NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
    • Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
    • Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
    • Attention Explained Without the Maths: Query, Key, Value and the Word "it"
    • Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
    • Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
    • Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
    • Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
    • Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
    • When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
    • Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
    • LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
    • Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
    • Serving Open Models: Continuous Batching, vLLM and Cold Starts
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      Monitoring and Release
      • Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
      • Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
      • Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
      • A/B Tests for Models: Did the New Model Make Things Better for People?
      • When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
      • Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
      • The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
      • Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      • Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
      • Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
      • Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
      • Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
      • Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
      • Recommendations, Part 1: Two Stages, Candidates Then Ranking
      • Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
      • Recommendations, Part 2: Candidate Generation With Embeddings
      • Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
      • Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
      • Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
      • Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
      • Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
      • Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
      • Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
      • Ticket Routing, Part 4: Canary, Automatic Rollback and "Does Your Small Model Reason?"
      • The ML Engineer Interview Loop: Five Rounds, What Each One Looks For, and a Simple Rubric
      • The Answer Framework for Technical Interviews: Five Moves, Scored Out of 24
      • From Symptom to Pattern: How to Answer "Which Pattern Would You Use?" in an Interview
      • The ML System Design Framework: Eight Steps, in Order, on a Spam Filter
      • ML System Design Interview: Fraud Detection for Card Payments, in Eight Steps with Numbers
      • ML System Design Interview: A Recommendation Feed, From a Score to Beat to Online Guardrails
      • ML System Design Interview: Ad Click Prediction, Sparse Features, Calibration and Late Clicks
      • Interview Answer: How Do You Roll Out a New Model Safely When True Labels Come Weeks Later?
      • Mock ML Engineer Interview, Scored: A Rollout Question Where the Labels Arrive Weeks Late
      • The ML Coding Round: K-Means, Logistic Regression and a Top-k Metric From Scratch
      • The ML Depth Round: Five Questions That Always Come, in Thirty Seconds Each
      • Presenting Your Portfolio: A Six-Section README That Shows Evidence, Not Buzzwords
      • Reading a Job Ad and Shaping Your CV: A Gap List and CV Lines You Can Stand Behind
      • How AI Questions Show Up in an ML Engineer Interview: Your Angle, the Rounds and a Good Answer
      • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
      • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
      • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
      • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
      • Coding Round: Merge Top-k From Sorted Shards, Then Fuse Two Rankings by Place
      • Mock Interview, Scored: 429s at Peak Because One Customer's Batch Job Eats the Capacity
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. Foundations

      NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs

      NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.

      Chaand Sheikh

      ·27 November 2026Foundations

      What you will learn

      • Read an array's shape and pick the right axis
      • Normalise 1,000 embeddings with broadcasting and score them with one @
      • Load a call log with the right types, then count missing values and filter
      • Summarise the log with groupby, merge, resample and hand a column back to NumPy

      Before you start

      • Basic Python

      Every embedding, every score and every log you meet as an AI engineer is either an array or a table. So here's NumPy and pandas in one pass, at the depth you actually need and not more.

      We'll use NumPy 2.5.4 and pandas 3.1.1 on two generated sample files: 1,000 embedding vectors of 384 numbers each, and a one-week log of 2,000 model calls from a help-desk assistant. Nothing here needs an API key.

      An egg carton and a spreadsheet

      Think of an egg carton: one kind of thing, in a fixed grid, two by six. That's a NumPy array: only numbers, one data type, and a shape.

      Now think of a spreadsheet. Each column has a name, and each column can hold a different kind of thing: times, words, numbers. That's a pandas DataFrame: rows and named columns.

      Embeddings and scores are arrays. Logs and results are tables.

      A list is not a vector

      First, a surprise that catches a lot of people. Multiply a plain Python list by 2, then the same numbers as a NumPy array:

      import numpy as np
      
      scores = [0.2, 0.5, 0.9]
      print("[0.2, 0.5, 0.9] * 2 =", scores * 2)
      scores = np.array([0.2, 0.5, 0.9])
      print("np.array([0.2, 0.5, 0.9]) * 2 =", scores * 2)
      [0.2, 0.5, 0.9] * 2 = [0.2, 0.5, 0.9, 0.2, 0.5, 0.9]
      np.array([0.2, 0.5, 0.9]) * 2 = [0.4 1.  1.8]

      The list didn't double the numbers. It repeated itself, so we got six items. The array multiplied every number. Same symbol, different meaning: when you want maths on numbers, you want an array.

      Shape, and the axis you collapse

      The most important word in NumPy is shape. Our embeddings file loads as one array:

      from pathlib import Path
      
      DATA = Path(__file__).resolve().parent / "data"
      vectors = np.load(DATA / "embeddings.npy")
      print("embeddings.shape =", vectors.shape, " dtype =", vectors.dtype)
      print("first vector, first 4 numbers:", np.round(vectors[0, :4], 3))
      print("mean over axis=0 (per column) ->", vectors.mean(axis=0).shape)
      print("mean over axis=1 (per row)    ->", vectors.mean(axis=1).shape)
      embeddings.shape = (1000, 384)  dtype = float32
      first vector, first 4 numbers: [-1.203  0.566  0.311  0.783]
      mean over axis=0 (per column) -> (384,)
      mean over axis=1 (per row)    -> (1000,)

      A thousand rows, one per text, and 384 numbers in each row. The axis is the direction you squash. The axis you name is the one that disappears.

      axis=0 runs down the rows, axis=1 runs across vectors (1000, 384) 384 columns 1000 rows axis=0 mean(axis=0) -> (384,) axis=1 mean(axis=1) -> (1000,)
      axis=0 runs down the rows and leaves one number per column. axis=1 runs across each row and leaves one number per row.

      Broadcasting: divide every row by its own length

      Vector search compares directions, so first every row is scaled to length 1. np.linalg.norm(..., axis=1) gives each row's length, and keepdims=True keeps the result as a column:

      lengths = np.linalg.norm(vectors, axis=1, keepdims=True)
      print("lengths.shape =", lengths.shape)
      unit = vectors / lengths
      print("length of row 0 after:", round(float(np.linalg.norm(unit[0])), 4))
      lengths.shape = (1000, 1)
      length of row 0 after: 1.0

      That's a (1000, 384) array divided by a (1000, 1) array. NumPy stretches the smaller one across each row, so every row is divided by its own length. This is broadcasting, and keepdims=True is what keeps that 1. Without it, lengths would have shape (1000,), and NumPy would line it up against the 384 columns instead of the rows, so the division fails.

      Broadcasting a (1000, 1) column across (1000, 384) vectors (1000, 384) / (1000, 1) stretched across = unit (1000, 384), length 1
      The (1000, 1) column of lengths is stretched across all 384 columns. No copy, no loop.

      Vector search in five lines

      With shape, axis and broadcasting, the core of vector search fits in one function:

      def top_k(vectors: np.ndarray, query: np.ndarray, k: int = 3) -> tuple[np.ndarray, np.ndarray]:
          """Rows most similar to the query: normalise every row, one matrix-vector product, sort."""
          unit_rows = vectors / np.linalg.norm(vectors, axis=1, keepdims=True)  # (1000, 384) / (1000, 1)
          unit_query = query / np.linalg.norm(query)
          scores = unit_rows @ unit_query  # (1000,)
          best = np.argsort(scores)[::-1][:k]
          return best, scores[best]
      
      query = vectors[42] + np.float32(0.1)
      best, best_scores = top_k(vectors, query)
      for row, score in zip(best, best_scores):
          print(f"row {row:4d}   score {score:.3f}")
      row   42   score 0.995
      row  688   score 0.143
      row  380   score 0.139

      The @ sign is one matrix-vector product: all 1,000 scores at once, shape (1000,). argsort sorts them smallest first, [::-1] reverses, and [:k] keeps the top 3. Row 42 wins at 0.995 and the next rows are far behind. That makes sense: the query was built from row 42. The search itself, with thresholds and scikit-learn's NearestNeighbors, is covered in Similarity Search: Finding the Closest Vectors.

      Loop vs vectorised

      Why not just write a loop? Here's the same dot product, both ways:

      import time
      
      start = time.perf_counter()
      loop_scores = [sum(float(a) * float(b) for a, b in zip(row, query)) for row in vectors]
      loop_ms = (time.perf_counter() - start) * 1000
      start = time.perf_counter()
      fast_scores = vectors @ query
      fast_ms = (time.perf_counter() - start) * 1000
      print(f"python loop : {loop_ms:8.1f} ms")
      print(f"vectors @ q : {fast_ms:8.3f} ms   same answer: {np.allclose(loop_scores, fast_scores, rtol=1e-4)}")
      python loop :     25.1 ms
      vectors @ q :    0.182 ms   same answer: True

      The loop multiplies one pair of numbers at a time, 384,000 times. The @ runs the same maths in compiled code. On the lecture machine the loop took about 25 ms and @ less than a fifth of a millisecond, with the same answer. Your timings will differ; the gap won't. With a million documents instead of a thousand, that gap is the difference between instant and slow.

      pandas: fix the types on load

      Now the table. The log has one row per model call: when, which user, which route, which model, the tokens, the latency, the status and optional feedback.

      import pandas as pd
      
      pd.set_option("display.width", 120)
      naive = pd.read_csv(DATA / "llm_calls.csv")
      print(naive.head(3).to_string(index=False))
      print("rows, columns:", naive.shape)
                timestamp  user_id        route       model  input_tokens  output_tokens  latency_ms       status feedback
      2026-11-02T08:22:41       12       refund large-model          2421            452      4281.0           ok      NaN
      2026-11-02T08:32:21       12       refund large-model          1966              0         NaN rate_limited      NaN
      2026-11-02T08:33:01        5 order_status small-model           986             49       447.0           ok       up
      rows, columns: (2000, 9)

      2,000 rows, 9 columns. But look at the timestamp's type:

      print("dtype of timestamp:", naive["timestamp"].dtype)
      try:
          naive["timestamp"].dt.hour
      except AttributeError as error:
          print("AttributeError:", error)
      dtype of timestamp: str
      AttributeError: Can only use .dt accessor with datetimelike values

      The CSV stores dates as text, and pandas doesn't guess. Asking for the hour fails. This is a very common bug, and the fix is one argument:

      calls = pd.read_csv(DATA / "llm_calls.csv", parse_dates=["timestamp"])
      print("dtype of timestamp:", calls["timestamp"].dtype)
      print("first hour seen:", calls["timestamp"].dt.hour.iloc[0])
      dtype of timestamp: datetime64[us]
      first hour seen: 8

      Always check your types right after loading. For a fuller health check of a new dataset (size, types, missing values, spread, balance, duplicates), see First Look at a Dataset.

      Missing values and filters

      Real logs have gaps. isna().sum() counts the missing values per column, and value_counts() tells us why:

      print(calls.isna().sum()[lambda s: s > 0].to_string())
      print(calls["status"].value_counts().to_string())
      latency_ms     373
      feedback      1336
      status
      ok              1627
      rate_limited     189
      error            184

      189 rate-limited plus 184 errors is 373 failed calls, and a failed call has no latency. That's exactly the 373 missing latencies. Feedback is empty whenever the user gave no thumbs up or down.

      A new column is one line of maths on whole columns, and a filter is a condition inside square brackets. & joins two conditions, and each one needs its own brackets:

      calls["total_tokens"] = calls["input_tokens"] + calls["output_tokens"]
      big = calls[(calls["status"] == "ok") & (calls["total_tokens"] > 3000)]
      print(f"ok calls over 3,000 tokens: {len(big)} of {len(calls)}")
      ok calls over 3,000 tokens: 138 of 2000

      Group by model

      This is the question you'll ask your logs again and again: how does each model behave? Keep the calls that worked, group by model, and compute several things at once with named aggregations:

      def model_summary(calls: pd.DataFrame) -> pd.DataFrame:
          ok = calls[calls["status"] == "ok"]
          return ok.groupby("model").agg(
              calls=("model", "size"),
              avg_total_tokens=("total_tokens", "mean"),
              median_latency_ms=("latency_ms", "median"),
              p95_latency_ms=("latency_ms", lambda s: s.quantile(0.95)),
          ).round(0)
      
      print(model_summary(calls).to_string())
                   calls  avg_total_tokens  median_latency_ms  p95_latency_ms
      model
      large-model    493            2529.0             3480.0          5553.0
      small-model   1134            1596.0             1128.0          1802.0

      p95 means 95 out of 100 calls were faster than this. The large model's median is about 3.5 seconds and its p95 about 5.5. The small model is much faster on both. A table like this is the start of every cost and latency review.

      Merge, resample, and back to NumPy

      merge joins two tables on a shared column. The users table adds a team to every call, then we sum the tokens per team:

      users = pd.read_csv(DATA / "users.csv")
      by_team = calls.merge(users, on="user_id", how="left")
      print(by_team.groupby("team")["total_tokens"].sum().sort_values(ascending=False).to_string())
      team
      engineering    811642
      sales          790208
      hr             717608
      finance        683503
      support        675909

      Engineering used the most. Because the timestamp is now a real date, resample("D") counts calls per day:

      print(calls.set_index("timestamp").resample("D").size().to_string())
      timestamp
      2026-11-02    167
      2026-11-03    294
      2026-11-04    280
      2026-11-05    301
      2026-11-06    264
      2026-11-07    299
      2026-11-08    306
      2026-11-09     89
      Freq: D

      And to_numpy() hands a column back as an array, ready for any maths:

      latencies = calls["latency_ms"].dropna().to_numpy()
      print("type:", type(latencies).__name__, " shape:", latencies.shape)
      type: ndarray  shape: (1627,)

      1,627 latencies, one per call that worked.

      Common mistakes

      • Doing maths on a Python list. * repeats it. Convert with np.array first.
      • Picking the wrong axis. Ask which dimension should disappear: rows (axis=0) or columns (axis=1).
      • Dropping keepdims=True when you divide rows by their lengths.
      • Looping over vectors when one @ does it in compiled code.
      • Not checking dtypes on load. A date read as text breaks .dt and resample.
      • Using and instead of & in a pandas filter, or forgetting the brackets around each condition.

      Quick recap

      MoveCodeResult here
      Read the shapevectors.shape(1000, 384), float32
      Collapse an axismean(axis=0) / mean(axis=1)(384,) / (1000,)
      Broadcastvectors / lengths, keepdims=Trueevery row length 1.0
      Score all rowsunit_rows @ unit_queryrow 42 at 0.995
      Types on loadparse_dates=["timestamp"]datetime64[us]
      Missing and filterisna().sum(), &373 missing latencies; 138 big ok calls
      Groupgroupby("model").agg(...)large 3480 ms median, small 1128 ms
      Join and by daymerge, resample("D")engineering on top; calls per day

      Try it yourself

      1. Change k to 5 in top_k and run it again.
      2. Group the log by route instead of by model.
      3. Remove parse_dates and see which line fails first.

      The project files and both data files are in the StudyEasy AI Community, free to join.

      Tried the exercise? Share your answer or ask a question.

      The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

      Join free on Skool

      Keep going in Machine Learning · 2 of 155

      Previous
      Supervised Learning: Features, Labels, Classification and Regression
      Next post
      First Look at a Dataset: 6 Checks Before You Plot or Model

      Related course on Udemy

      Become an AI Engineer: LLMs, RAG, Agents and MCP

      Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

      Related posts

      Supervised Learning: Features, Labels, Classification and Regression

      What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.

      On this page

      • An egg carton and a spreadsheet
      • A list is not a vector
      • Shape, and the axis you collapse
      • Broadcasting: divide every row by its own length
      • Vector search in five lines
      • Loop vs vectorised
      • pandas: fix the types on load
      • Missing values and filters
      • Group by model
      • Merge, resample, and back to NumPy
      • Common mistakes
      • Quick recap
      • Try it yourself
      Community · Free to join
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      Learn AI engineering, share what you build, and connect with other learners.

      • Free resources: lesson files, notebooks and code

      • Ask questions and join engineering discussions

      • Meet real people learning and building with AI

      Join free on Skool

      Related course on Udemy

      Become an AI Engineer: LLMs, RAG, Agents and MCP

      Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact usFAQs
      Legal
      Terms of ServicePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.