import random
seed = random.random()
random_seed = random.Random(seed)
random_vec = [ random_seed.random() for i in range(10)]
The above is essentially:
np.random.randn(10)
But I am not able to figure out how to set the seed?
I'm not sure why you want to set the seed—especially to a random number, even more especially to a random float (note that random.seed wants a large integer).
But if you do, it's simple: call the numpy.random.seed function.
Note that NumPy's seeds are arrays of 32-bit integers, while Python's seeds are single arbitrary-sized integers (although see the docs for what happens when you pass other types).
So, for example:
In [1]: np.random.seed(0)
In [2]: s = np.random.randn(10)
In [3]: s
Out[3]:
array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799,
-0.97727788, 0.95008842, -0.15135721, -0.10321885, 0.4105985 ])
In [4]: np.random.seed(0)
In [5]: s = np.random.randn(10)
In [6]: s
Out[6]:
array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799,
-0.97727788, 0.95008842, -0.15135721, -0.10321885, 0.4105985 ])
Same seed used twice (I took the shortcut of passing a single int, which NumPy will internally convert into an array of 1 int32), same random numbers generated.
To put it simply random.seed(value) does not work with numpy arrays.
For example,
import random
import numpy as np
random.seed(10)
print( np.random.randint(1,10,10)) #generates 10 random integer of values from 1~10
[4 1 5 7 9 2 9 5 2 4]
random.seed(10)
print( np.random.randint(1,10,10))
[7 6 4 7 2 5 3 7 8 9]
However, if you want to seed the numpy generated values, you have to use np.random.seed(value).
If I revisit the above example,
import numpy as np
np.random.seed(10)
print( np.random.randint(1,10,10))
[5 1 2 1 2 9 1 9 7 5]
np.random.seed(10)
print( np.random.randint(1,10,10))
[5 1 2 1 2 9 1 9 7 5]
Related
I am trying to find a way to run a function through a whole ndarray using the indexes of every value as parameters. A regular loop is quite slow and I can't find a way to make it work using numpy built-in functions. The next example code summarizes what i'm trying to do. Thanks in advance.
import numpy as np
arr = np.arange(10).reshape(2, 5)
print(arr)
def example_func(row, col, value):
return(row + col + value)
for row in range(arr.shape[0]):
for col in range(arr.shape[1]):
arr[row, col] = example_func(row, col, arr[row, col])
print(arr)
[[0 1 2 3 4]
[5 6 7 8 9]]
[[ 0 2 4 6 8]
[ 6 8 10 12 14]]
What you try to do can be done with meshgrid.
Return coordinate matrices from coordinate vectors.
n_rows, n_cols = arr.shape
col_matrix, row_matrix = np.meshgrid(np.arange(n_cols), np.arange(n_rows))
result = arr + col_matrix + row_matrix
print(result)
This returns
[[ 0 2 4 6 8]
[ 6 8 10 12 14]]
I have this code:
import numpy as np
a = np.arange(10)
b = a + 1
c = np.add(a, 1)
print("a:", a)
print("b:", b)
print("c:", c)
Which prints:
a: [0 1 2 3 4 5 6 7 8 9]
b: [ 1 2 3 4 5 6 7 8 9 10]
c: [ 1 2 3 4 5 6 7 8 9 10]
I want to know what is the difference between a + 1 and np.add(a, 1)?
numpy.add is the NumPy addition ufunc. Addition operations on arrays will usually delegate to numpy.add, but operations that don't involve arrays will usually not involve numpy.add.
For example, if we have two ordinary ints:
In [1]: import numpy
In [2]: numpy.add(1, 2)
Out[2]: 3
In [3]: type(_)
Out[3]: numpy.int64
In [4]: 1 + 2
Out[4]: 3
In [5]: type(_)
Out[5]: int
numpy.add will coerce the inputs to NumPy types, perform NumPy addition logic, and produce a NumPy output, while + performs ordinary Python int addition and produces an ordinary int.
Aside from that, numpy.add has a lot of additional arguments to control and customize how the operation is performed. You can specify an out array to write the output into, or a dtype argument to control the output dtype, or many other arguments for advanced use cases.
The following code produces different outputs:
import numpy as np
from numba import njit
#njit
def resh_numba(a):
res = a.transpose(1, 0, 2)
res = res.copy().reshape(2, 6)
return res
x = np.arange(12).reshape(2, 2, 3)
print("numpy")
x_numpy = x.transpose(1, 0, 2).reshape(2, 6)
print(x_numpy)
print("numba:")
x_numba = resh_numba(x)
print(x_numba)
Output:
numpy
[[ 0 1 2 6 7 8]
[ 3 4 5 9 10 11]]
numba:
[[ 0 4 8 2 6 10]
[ 1 5 9 3 7 11]]
What is the reason for this? I'm suspecting some order='C' vs order='F' happening somewhere, but I expected both numpy and numba to use order='C' by default everywhere.
It is to a bug due (at least) to the np.ndarray.copy implementation, I opened an issue here: https://github.com/numba/numba/issues/3557
I cannot fully understand the behaviour of theano.scan().
Here's an example:
import numpy as np
import theano
import theano.tensor as T
def addf(a1,a2):
return a1+a2
i = T.iscalar('i')
x0 = T.ivector('x0')
step= T.iscalar('step')
results, updates = theano.scan(fn=addf,
outputs_info=[{'initial':x0, 'taps':[-2]}],
non_sequences=step,
n_steps=i)
f=theano.function([x0,i,step],results)
print f([1,1],10,2)
The above snippet prints the following sequence, which is perfectly reasonable:
[ 3 3 5 5 7 7 9 9 11 11]
However if I switch the tap index from -2 to -1, i.e.
outputs_info=[{'initial':x0, 'taps':[-1]}]
The result becomes:
[[ 3 3]
[ 5 5]
[ 7 7]
[ 9 9]
[11 11]
[13 13]
[15 15]
[17 17]
[19 19]
[21 21]]
instead of what would seem reasonable to me (just take the last value of the vector and add 2):
[ 3 5 7 9 11 13 15 17 19 21]
Any help would be much appreciated.
Thanks!
When you use taps=[-1], scan suppose that the information in the output info is used as is. That mean the addf function will be called with a vector and the non_sequence as inputs. If you convert x0 to a scalar, it will work as you expect:
import numpy as np
import theano
import theano.tensor as T
def addf(a1,a2):
print a1.type
print a2.type
return a1+a2
i = T.iscalar('i')
x0 = T.iscalar('x0')
step= T.iscalar('step')
results, updates = theano.scan(fn=addf,
outputs_info=[{'initial':x0, 'taps':[-1]}],
non_sequences=step,
n_steps=i)
f=theano.function([x0,i,step],results)
print f(1,10,2)
This give this output:
TensorType(int32, scalar)
TensorType(int32, scalar)
[ 3 5 7 9 11 13 15 17 19 21]
In your case as it do addf(vector,scalar), it broadcast the elemwise value.
Explained in another way, if taps is [-1], x0 will be passed "as is" to the inner function. If taps contain anything else, what is passed to the inner function will have 1 dimension less then x0, as x0 must provide many initial steps value (-2 and -1).
I have to use dynamic programming in a python script.
I defined a numpy array u with shape=(N,K).
I want to pick one element for each column, therefore generating a K-uplets.
How would you proceed to loop efficiently across all K-uplets generated this way ? A solution would be to use
import itertools
itertools.combination_with_replacement(list,K)
where list = [0..N-1], but I will need to build iteratively each of my K-uplets using the output (index) of the itertools method.
Is there a more direct way to proceed ?
Thanks
Vincent
You can build the K-uplet with arr[ind, np.arange(K)]. Of course, that's actually a NumPy ndarray, but they are easy to convert to tuplets if you really want tuplets: tuple(arr[ind, np.arange(K)]).
import numpy as np
import itertools as IT
N, K = 5,3
arr = np.arange(N*K).reshape(N,K)
print(arr)
# [[ 0 1 2]
# [ 3 4 5]
# [ 6 7 8]
# [ 9 10 11]
# [12 13 14]]
for ind in IT.combinations_with_replacement(range(N), K):
print(arr[ind, np.arange(K)])
# [0 1 2]
# [0 1 5]
# [0 1 8]
# [ 0 1 11]
# ...