简体   繁体   中英

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.

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

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM