numpy
linear function
data generation
python programming
numerical computing

numpy generate data from linear function

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Generating synthetic data from a linear function is a common step in plotting, testing regression code, and creating toy datasets for machine learning experiments. In NumPy, the basic pattern is simple: generate x values, apply the linear equation y = mx + b, and optionally add noise to simulate measurement error.

Generate Clean Linear Data

A linear function has the form y = mx + b, where m is the slope and b is the intercept.

python
1import numpy as np
2
3m = 2.5
4b = -1.0
5x = np.linspace(0, 10, 6)
6y = m * x + b
7
8print(x)
9print(y)

np.linspace is a good default because it gives evenly spaced input values across a chosen interval. If you already know the step size you want, np.arange is also fine.

Use Random x Values When Uniform Spacing Is Not Required

If the goal is to simulate scattered observations instead of plotting a neat line, random x values are often better.

python
1import numpy as np
2
3rng = np.random.default_rng(42)
4x = rng.uniform(0, 10, size=8)
5y = 3.0 * x + 5.0
6
7print(x)
8print(y)

This produces points that still lie on the same linear relationship but do not appear evenly spaced.

Add Noise for More Realistic Data

Real data almost never sits perfectly on a line. Add Gaussian noise to simulate observation error.

python
1import numpy as np
2
3rng = np.random.default_rng(42)
4x = np.linspace(0, 10, 20)
5noise = rng.normal(loc=0.0, scale=1.5, size=x.shape)
6y = 4.0 * x + 2.0 + noise
7
8print(y[:5])

This keeps the underlying linear trend while making the data look more like a real regression dataset.

Stack the Result into a Dataset Shape

If you want to pass the generated data into another tool, it is often convenient to combine the columns.

python
1import numpy as np
2
3x = np.linspace(0, 5, 6)
4y = 1.2 * x + 0.7
5
6data = np.column_stack((x, y))
7print(data)

This produces a two-column array where each row is one observation.

Generate Multifeature Linear Targets

For machine learning experiments, you may want several input features and one target generated by a linear combination.

python
1import numpy as np
2
3rng = np.random.default_rng(7)
4X = rng.normal(size=(100, 3))
5weights = np.array([2.0, -1.0, 0.5])
6bias = 3.0
7noise = rng.normal(scale=0.2, size=100)
8
9y = X @ weights + bias + noise
10
11print(X.shape)
12print(y.shape)

This is a useful pattern for quickly creating regression training data with a known ground-truth relationship.

Plotting and Testing Often Need Different Data Shapes

For plotting, evenly spaced x values from linspace usually make the line easy to inspect visually. For model testing, randomly sampled inputs plus noise are often better because they stress the code in a less artificial way. The same linear function can support both goals, but the generated dataset shape should match the purpose.

Common Pitfalls

  • Using Python loops when NumPy vectorization is simpler and faster.
  • Choosing np.arange with floating-point steps and then being surprised by endpoint behavior.
  • Forgetting that perfectly clean linear data is often too artificial for testing real pipelines.
  • Mixing up slope and intercept signs when reading back the generated data.
  • Adding noise with the wrong shape and accidentally broadcasting it in an unintended way.

Summary

  • Generate x values first, then compute y = mx + b with vectorized NumPy operations.
  • Use np.linspace for evenly spaced points and random sampling for scattered observations.
  • Add Gaussian noise when you need realistic synthetic data.
  • Use np.column_stack or matrix formulas when the data will feed a downstream model.
  • Keep the generation logic explicit so the synthetic relationship is easy to reason about later.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.