Reputation: 11
I was wondering how to add a random number in a given range to each value of an array.
I have an array composed by 1000 values which, when plotted, give me an S-curve.
The thing is, I want to add noise to this curve, which is why I want to add a random number to the values of the array, that will change for each value.
My current code is this:
import numpy as np
import matplotlib.pyplot as plt
import random
def sigmoid(z):
return 1/(1+np.exp(-z))
n=random.randint(-0.1,0.1)
y = np.arange(-5, 5, 0.01)
print(y)
for i in range(0,1000):
y[i]=y[i]+n
i=i+1
plt.plot(y, sigmoid(y), marker='x')
plt.show()
But this error comes up: "non-integer arg 1 for randrange()"
Do you have any idea on how to solve this problem?
Upvotes: 0
Views: 1480
Reputation: 3639
I'd follow the suggestion of @abe to switch from random
to numpy
library to generate your random noise.
From version 1.17, the recommended method to generate samples drawn from a uniform distribution in numpy
is using the Generator class (here you can find a great answer talking about this.).
In particular, the uniform
method of this class draws samples from a uniform distribution over the half-open interval whose extrema can be provided in input. For example, in this case:
rng = np.random.default_rng() # construct a new Generator
n = rng.uniform(-.1, .1, (10,)) # noise for each value of the sigmoid, extracted independently from an uniform distribution in [.1; 1)
Moreover, rng.uniform
accepts in input the output shape ((10,)
in the previous code)
From your question, seems that you want to add some noise drawn from a uniform distribution in [-0.1, 0.1) to the S-curve, so, probably, I'd rewrite your code as follow:
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
x = np.arange(-5, 5, 0.01) # x values
rng = np.random.default_rng() # get a default random generator
n = rng.uniform(-.1, .1, x.shape) # noise for each value of the sigmoid
y = sigmoid(x) + n # S-curve plus noise
plt.plot(x, y, marker='x')
plt.show()
Upvotes: 0
Reputation: 188
The problem is randrange()
takes int as an argument and gives an int.My approach is not smooth but at least can give you an idea.instead of putting range between range 1,10 for example make it 100,1000 so you can pick a random integer with randrange()
then you can format it and divide to get a small number between (0,1).
Upvotes: 0
Reputation: 987
The function random.randint(a, b)
only accepts integer inputs for the range values a
and b
, and will return a random integer N: a <= N <= b. Also, if you want to add noise, you shouldn't just call the function random.randint()
just once. It will add the same value to each index that way. My advice is, use np.random.rand()
function. It basically generates a random array which you can specify the shape of, with the uniform probability distribution in range [0, 1). You can scale and shift the underlying distribution just by scale * np.random.rand(shape) + shift
Upvotes: 2