Simple way to create matrix of random numbers

2019-01-22 16:50发布

I am trying to create a matrix of random numbers, but my solution is too long and looks ugly

random_matrix = [[random.random() for e in range(2)] for e in range(3)]

this looks ok, but in my implementation it is

weights_h = [[random.random() for e in range(len(inputs[0]))] for e in range(hiden_neurons)]

which is extremely unreadable and does not fit on one line.

9条回答
神经病院院长
2楼-- · 2019-01-22 17:19

use np.random.randint() as numpy.random.random_integers() is deprecated

random_matrix = numpy.random.randint(min_val,max_val,(<num_rows>,<num_cols>))
查看更多
Explosion°爆炸
3楼-- · 2019-01-22 17:22

First, create numpy array then convert it into matrix. See the code below:

import numpy

B = numpy.random.random((3, 4)) #its ndArray
C = numpy.matrix(B)# it is matrix
print(type(B))
print(type(C)) 
print(C)
查看更多
看我几分像从前
4楼-- · 2019-01-22 17:27

Looks like you are doing a Python implementation of the Coursera Machine Learning Neural Network exercise. Here's what I did for randInitializeWeights(L_in, L_out)

#get a random array of floats between 0 and 1 as Pavel mentioned 
W = numpy.random.random((L_out, L_in +1))

#normalize so that it spans a range of twice epsilon
W = W * 2 * epsilon

#shift so that mean is at zero
W = W - epsilon
查看更多
老娘就宠你
5楼-- · 2019-01-22 17:33

When you say "a matrix of random numbers", you can use numpy as Pavel https://stackoverflow.com/a/15451997/6169225 mentioned above, in this case I'm assuming to you it is irrelevant what distribution these (pseudo) random numbers adhere to.

However, if you require a particular distribution (I imagine you are interested in the uniform distribution), numpy.random has very useful methods for you. For example, let's say you want a 3x2 matrix with a pseudo random uniform distribution bounded by [low,high]. You can do this like so:

numpy.random.uniform(low,high,(3,2))

Note, you can replace uniform by any number of distributions supported by this library.

Further reading: https://docs.scipy.org/doc/numpy/reference/routines.random.html

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-22 17:35

An answer using map-reduce:-

map(lambda x: map(lambda y: ran(),range(len(inputs[0]))),range(hiden_neurons))
查看更多
来,给爷笑一个
7楼-- · 2019-01-22 17:36

Take a look at numpy.random.rand:

Docstring: rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1).


>>> import numpy as np
>>> np.random.rand(2,3)
array([[ 0.22568268,  0.0053246 ,  0.41282024],
       [ 0.68824936,  0.68086462,  0.6854153 ]])
查看更多
登录 后发表回答