Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin 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
  • NumPy Arrays: Creation, Shape and Data Types From Scratch
  • NumPy Indexing, Slicing, Masks and np.where
  • NumPy Shapes: reshape, transpose, stack, concatenate and split
  • NumPy Universal Functions and Broadcasting, With the Shape Rule
  • NumPy Aggregation, Statistics and Sorting: sum, axis, percentile, argsort
  • Linear Algebra with NumPy: Dot Product, @, Determinant, Inverse and solve
  • Random Numbers in NumPy: default_rng, Seeds, Distributions and Sampling
  • Thinking in Arrays: A NumPy Student Performance Analysis
  • An Image Is a NumPy Array: Channels, Brightness, Grayscale, Invert and Crop
  • pandas Series and DataFrames: Your First Table, Inspected and Sorted
  • pandas Data IO: read_csv, to_csv, JSON, Excel and Parquet
  • pandas loc, iloc and Filtering: Label vs Position, Masks, query
  • Cleaning Messy Data in pandas: Missing Values, Duplicates, Types and Text
  • pandas groupby and merge: Split-Apply-Combine and Joining Tables
  • pandas Practice: Student Grades, Sales and an Employee Cleanup
  • 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
      • Docker Compose: Run a FastAPI App and Postgres From One File
      • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
      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
      • Terraform Modules, Remote State and Environments: One Codebase for Staging and Production
      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
      • One Request Through Every Pattern: a Map of 25 AI System Design Patterns, Stop by Stop
      • AI Engineer, ML Engineer, FDE: What Each Interview Tests, and the Trap of Answering for the Wrong Room
      • Mock Interview: Layer the Guardrails on a Refund Agent, Scored From 6 to 20 of 24
      • Mock Interview for a Forward Deployed Engineer: a Private RAG Assistant in One Region, Scored From 4 to 30 of 36
      • The Coding Round in One Picture: Twenty Minutes, Small, Correct, Tested and Said Out Loud
      • Your AI Interview Preparation Roadmap by Track: AI Engineer, ML Engineer and FDE, Plus the Final Week
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. Foundations

      Random Numbers in NumPy: default_rng, Seeds, Distributions and Sampling

      How NumPy makes random numbers you can bring back: default_rng and seeds, uniform versus normal, a bell curve from 1,000 samples, dice counts, choice with and without replacement, shuffle versus permutation, and a train/test split.

      Chaand Sheikh

      ·27 November 2026·Updated 28 November 2026Foundations

      What you will learn

      • Create a generator with np.random.default_rng and make results repeat with a seed
      • Explain why a seed fixes the whole sequence, not a single call
      • Sample uniform, normal and integer values and see a bell curve appear in a histogram
      • Pick, shuffle and split data with choice, permutation and shuffle

      Before you start

      • NumPy arrays and indexing
      • NumPy aggregation (mean, std, unique)

      So far your arrays held values you typed in or calculated. Data science also needs values that come from chance: for sampling, for testing, and for splitting data. But how can a computer be random when it only follows instructions?

      It isn't, not exactly. Think of a huge book filled with scrambled numbers. They look random, but they're already fixed on the page. A seed is the page where you start reading. Open the same page again and you read the same numbers; open another page and you get different ones. Each time you ask for more, you carry on from where you stopped. In the computer a formula plays the part of the book, which is why these are called pseudo-random numbers.

      Your random generator

      import numpy as np
      
      rng = np.random.default_rng()
      
      u = rng.random(3)
      i = rng.integers(1, 10, size=5)
      n = rng.standard_normal(3)
      
      print(type(rng).__name__)
      print(u.shape, i.shape, n.shape)
      print(bool((u >= 0).all() and (u < 1).all()))
      print(bool((i >= 1).all() and (i < 10).all()))
      Generator
      (3,) (5,) (3,)
      True
      True

      default_rng creates a Generator, an object that hands out random numbers. With no seed, the numbers change on every run, so this file only prints what stays true: random stays in [0, 1) and integers(1, 10) stays from 1 to 9. Make one generator, and get everything random from it.

      A seed brings the numbers back

      rng = np.random.default_rng(42)
      print(rng.random(3))
      
      rng2 = np.random.default_rng(42)
      print(rng2.random(3))
      
      rng3 = np.random.default_rng(7)
      print(rng3.random(3))
      [0.77395605 0.43887844 0.85859792]
      [0.77395605 0.43887844 0.85859792]
      [0.62509547 0.8972138  0.77568569]

      Same seed, same numbers, digit by digit. Run the whole file again and every line comes out the same. Let NumPy do the comparing:

      first = np.random.default_rng(42).random(5)
      second = np.random.default_rng(42).random(5)
      other = np.random.default_rng(43).random(5)
      
      print(first)
      print(second)
      print(np.array_equal(first, second))
      print(np.array_equal(first, other))
      [0.77395605 0.43887844 0.85859792 0.69736803 0.09417735]
      [0.77395605 0.43887844 0.85859792 0.69736803 0.09417735]
      True
      False

      Why does this matter? When a result looks wrong, you can run it again with the same numbers and find the problem. Someone else can get those numbers too, on the same NumPy version.

      The generator remembers its place

      rng = np.random.default_rng(42)
      
      a = rng.random(2)
      b = rng.random(2)
      print(a)
      print(b)
      
      again = np.random.default_rng(42)
      print(again.random(4))
      [0.77395605 0.43887844]
      [0.85859792 0.69736803]
      [0.77395605 0.43887844 0.85859792 0.69736803]

      b doesn't repeat a. It gets the next two numbers. A fresh generator with the same seed asking for four at once gives a then b. A seed fixes the whole sequence, and asking again moves you forward.

      In older code

      # Older code seeds one hidden, global generator
      np.random.seed(42)
      print(np.random.rand(3))
      
      # Current way: your own generator
      rng = np.random.default_rng(42)
      print(rng.random(3))
      [0.37454012 0.95071431 0.73199394]
      [0.77395605 0.43887844 0.85859792]

      You'll still see np.random.seed. It seeds one hidden generator shared by the whole program, and it's an older algorithm, so 42 gives different numbers. In new code, use default_rng.

      Distributions: flat or a bell

      A distribution is a rule for how likely each value is. Picture a spinner with equal sections: every section has the same chance, so if you count the spins the picture comes out flat. That's uniform. Now picture the heights of a large group of people. Most are near the middle and few are far from it. Count them and you get a bell. That's normal.

      rng = np.random.default_rng(42)
      
      print(rng.random(3))
      print(rng.uniform(10, 50, size=3))
      print(rng.normal(100, 15, size=3))
      
      big = rng.normal(100, 15, size=10000)
      print(round(big.mean(), 1), round(big.std(), 1))
      [0.77395605 0.43887844 0.85859792]
      [37.89472116 13.76709392 49.02489407]
      [101.91760605  95.25636111  99.74798264]
      99.8 15.1

      random is uniform from 0 up to (not including) 1. uniform(10, 50) moves that to another range. normal(100, 15) takes a centre (the mean) and a spread (the standard deviation). Ten thousand samples come out at mean 99.8 and spread 15.1: close to what you asked for, not exact, because these are samples.

      A bell from your own samples

      import numpy as np
      
      rng = np.random.default_rng(7)
      scores = rng.normal(100, 15, size=1000)
      
      counts, edges = np.histogram(scores, bins=8)
      print(counts.sum())
      for count, low in zip(counts, edges[:-1]):
          bar = '#' * round(count / 8)
          print(f"{low:6.1f} | {bar} {count}")
      1000
        51.2 | # 5
        62.1 | #### 29
        73.1 | ############## 111
        84.0 | ############################# 229
        94.9 | ######################################### 327
       105.8 | ######################### 197
       116.7 | ######### 73
       127.7 | #### 29
      Histogram counts from np.histogram with 8 bins 5291112293271977329 51.262.173.184.094.9105.8116.7127.7 bin start (normal, centre 100, spread 15, seed 7, 1,000 samples)
      The counts printed by histogram.py, drawn as bars. Nobody drew a bell; it came out of the samples.

      np.histogram cuts the range into eight equal bins and counts the values in each. The tallest bin starts at 94.9 and holds the centre of 100.

      Random whole numbers

      rng = np.random.default_rng(42)
      
      print(rng.integers(1, 10, size=8))
      print(rng.integers(1, 6, size=8, endpoint=True))
      print(rng.integers(0, 100, size=(2, 3)))
      [1 7 6 4 4 8 1 7]
      [2 1 4 6 5 5 5 5]
      [[51 12 83]
       [45 50 37]]

      The high value is left out, so integers(1, 10) gives 1 to 9. Add endpoint=True to include it, and 1 to 6 works like a dice. size can be a shape. Repeats are fine, because each draw is separate.

      Roll that dice 600 times and count the faces:

      rng = np.random.default_rng(1)
      rolls = rng.integers(1, 7, size=600)
      
      faces, counts = np.unique(rolls, return_counts=True)
      for face, count in zip(faces, counts):
          print(face, count)
      1 109
      2 85
      3 103
      4 93
      5 107
      6 103

      You'd expect about 100 each. None is exactly 100, which is normal with samples, but there's no peak in the middle. It's roughly flat: uniform.

      Picking from an array

      Picture a bag of four coloured balls.

      rng = np.random.default_rng(42)
      colors = np.array(["red", "blue", "green", "yellow"])
      
      print(rng.choice(colors, size=3))
      print(rng.choice(colors, size=3, replace=False))
      print(rng.choice(colors, size=6, p=[0.7, 0.1, 0.1, 0.1]))
      ['red' 'yellow' 'green']
      ['yellow' 'blue' 'red']
      ['red' 'yellow' 'blue' 'blue' 'red' 'red']

      By default each ball goes back in the bag, so repeats are allowed. replace=False keeps a picked ball out. p weights the bag, one chance per colour, adding up to one. Ask for five without replacement from a bag of four, and you get:

      ValueError: Cannot take a larger sample than population when replace is False

      Ask for fewer, or allow repeats.

      permutation and shuffle

      rng = np.random.default_rng(42)
      colors = np.array(["red", "blue", "green", "yellow"])
      
      mixed = rng.permutation(colors)
      print(mixed)
      print(colors)
      
      rng.shuffle(colors)
      print(colors)
      
      print(rng.permutation(6))
      ['yellow' 'green' 'blue' 'red']
      ['red' 'blue' 'green' 'yellow']
      ['yellow' 'green' 'red' 'blue']
      [2 4 0 1 3 5]

      Think of a stack of cards. permutation photocopies the stack, mixes the copy and hands it back, so colors is unchanged. shuffle mixes your own stack in place and returns nothing. Given a plain number, permutation(6) mixes 0 to 5.

      Sampling rows and splitting data

      rng = np.random.default_rng(42)
      data = np.arange(12).reshape(6, 2)
      
      print(rng.choice(data, size=2, replace=False))
      
      order = rng.permutation(len(data))
      train = data[order[:4]]
      test = data[order[4:]]
      print(order)
      print(train.shape, test.shape)
      [[0 1]
       [8 9]]
      [3 0 5 2 4 1]
      (4, 2) (2, 2)

      choice on a 2D array picks whole rows, and each row stays together. Mixing the row numbers with permutation, then taking the first four for train and the rest for test, means no row lands in both groups. That's how data is often split; train/test split and data leakage takes it further.

      Recap

      ToolRemember
      np.random.default_rng(seed)Your generator; the same seed gives the same whole sequence
      random, uniformFlat: every value in the range equally likely
      normal(mean, std)Bell: values near the centre more likely
      integers(low, high)High is left out unless endpoint=True
      choicePick from your values; replace and p control repeats and weights
      permutation / shuffleMixed copy / mixed in place

      Try it yourself: change the seed and the size in histogram.py and watch how the bars change. Or ask an AI tool to explain the result, then read every line it gives you.

      Keep going in Machine Learning · 9 of 179

      Previous
      Linear Algebra with NumPy: Dot Product, @, Determinant, Inverse and solve
      Next post
      Thinking in Arrays: A NumPy Student Performance Analysis
      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

      The Python Architect Masterclass: Full Stack to AI Engineer

      Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (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.

      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.

      NumPy Arrays: Creation, Shape and Data Types From Scratch

      Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.

      NumPy Indexing, Slicing, Masks and np.where

      Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.

      On this page

      • Your random generator
      • A seed brings the numbers back
      • The generator remembers its place
      • In older code
      • Distributions: flat or a bell
      • A bell from your own samples
      • Random whole numbers
      • Picking from an array
      • permutation and shuffle
      • Sampling rows and splitting data
      • Recap
      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

      The Python Architect Masterclass: Full Stack to AI Engineer

      Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact us
      Legal
      Terms of UsePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.