Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy generate data from linear function

Say I wanted to generate 100 or so data points from a linear function what's the best way to go about it?

An example linear function y = 0.4*x + 3 + delta

where delta is a random value drawn from a uniform distribution between -10 and +10

I want delta to be generated for each data point to give some perturbation to the data.

import numpy as np

d = np.random.uniform(-10, 10)

This seems to fit the bill for delta although I'm unsure exactly how to generate the rest incorporating this.

like image 282
Luke Vincent Avatar asked Mar 01 '16 18:03

Luke Vincent


2 Answers

I don't know how you wanted to generate x, but this will work:

In [7]: x = np.arange(100)

In [8]: delta = np.random.uniform(-10,10, size=(100,))

In [9]: y = .4 * x +3 + delta

enter image description here

like image 77
Garrett R Avatar answered Oct 19 '22 23:10

Garrett R


It all rather depends on what x values you want to evaluate your function. Assuming you want to plot from -50 to 50 just use x = np.arange(-50,50) but then you need d = np.random.uniform(-10, 10, x.size).

Then just run your function: y = 0.4*x + 3 + delta.

On the other hand if you want a linearly spaced x you can also use np.linspace or for logarithmicly spaced x: np.logspace.

In the end it could look like:

x = np.linspace(0, 100, 1000) # 1000 values between 0 and 100
# x = np.arange(-50, 50) # -50, -49, ... 49, 50
delta = np.random.uniform(-10, 10, x.size)
y = 0.4*x + 3 + delta
like image 43
MSeifert Avatar answered Oct 20 '22 00:10

MSeifert