133

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.

strpeter
  • 2,562
  • 3
  • 27
  • 48
user2173836
  • 1,461
  • 2
  • 15
  • 19

13 Answers13

116

You can drop the range(len()):

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

But really, you should probably use numpy.

In [9]: numpy.random.random((3, 3))
Out[9]:
array([[ 0.37052381,  0.03463207,  0.10669077],
       [ 0.05862909,  0.8515325 ,  0.79809676],
       [ 0.43203632,  0.54633635,  0.09076408]])
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • how to get random ints? – Jack Twain Apr 09 '14 at 10:12
  • 53
    `numpy.random.random_integers(low, high, shape)`, e.g. `numpy.random.random_integers(0, 100, (3, 3))` – Pavel Anossov Apr 09 '14 at 11:18
  • What is the term for the double bracket notation being used in the signature of random? I'm not familiar with it. – Emile Victor Aug 12 '17 at 13:53
  • @EmileVictor `numpy.random.random` like many of the other `numpy.random` methods accept shapes, i.e. N-tuples. So really the outside parantheses represent calling the method `numpy.random.random()`, and the inside parantheses are syntactic sugar for instantiating the tuple `(3, 3)` that is passed into the function. – Vivek Jha Jan 23 '18 at 23:31
  • @EmileVictor In fact, the following are equivalent: `numpy.random.random((3, 3))`, `numpy.random.rand(3, 3)`, `numpy.random.uniform((3, 3))` [Feel free to check out this post for more detail](https://stackoverflow.com/questions/30762832/difference-between-functions-generating-random-numbers-in-numpy) – Vivek Jha Jan 23 '18 at 23:33
  • 3
    `numpy.random.random_integers()` is deprecated. Use `numpy.random.randint()` instead. https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html – Max Apr 27 '19 at 15:32
  • numpy.random.randint(low, high, shape)) – Camilo Soto Nov 10 '20 at 19:44
  • for last numpy versions use: numpy.random.randint(low, high, shape) https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html – Camilo Soto Nov 10 '20 at 19:46
106

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 ]])
Noki
  • 870
  • 10
  • 22
root
  • 76,608
  • 25
  • 108
  • 120
34

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

random_matrix = np.random.randint(min_val,max_val,(<num_rows>,<num_cols>))
mgrotheer
  • 431
  • 4
  • 12
nk911
  • 477
  • 4
  • 3
6

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
Cartesian Theater
  • 1,920
  • 2
  • 29
  • 49
5

For creating an array of random numbers NumPy provides array creation using:

  1. Real numbers

  2. Integers

For creating array using random Real numbers: there are 2 options

  1. random.rand (for uniform distribution of the generated random numbers )
  2. random.randn (for normal distribution of the generated random numbers )

random.rand

import numpy as np 
arr = np.random.rand(row_size, column_size) 

random.randn

import numpy as np 
arr = np.random.randn(row_size, column_size) 

For creating array using random Integers:

import numpy as np
numpy.random.randint(low, high=None, size=None, dtype='l')

where

  • low = Lowest (signed) integer to be drawn from the distribution
  • high(optional)= If provided, one above the largest (signed) integer to be drawn from the distribution
  • size(optional) = Output shape i.e. if the given shape is, e.g., (m, n, k), then m * n * k samples are drawn
  • dtype(optional) = Desired dtype of the result.

eg:

The given example will produce an array of random integers between 0 and 4, its size will be 5*5 and have 25 integers

arr2 = np.random.randint(0,5,size = (5,5))

in order to create 5 by 5 matrix, it should be modified to

arr2 = np.random.randint(0,5,size = (5,5)), change the multiplication symbol* to a comma ,#

[[2 1 1 0 1][3 2 1 4 3][2 3 0 3 3][1 3 1 0 0][4 1 2 0 1]]

eg2:

The given example will produce an array of random integers between 0 and 1, its size will be 1*10 and will have 10 integers

arr3= np.random.randint(2, size = 10)

[0 0 0 0 1 1 0 0 1 1]

SUJITKUMAR SINGH
  • 359
  • 3
  • 10
4

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)
Artem
  • 3,304
  • 3
  • 18
  • 41
Lokesh Sharma
  • 411
  • 5
  • 6
2
x = np.int_(np.random.rand(10) * 10)

For random numbers out of 10. For out of 20 we have to multiply by 20.

Nikolay Mihaylov
  • 3,868
  • 8
  • 27
  • 32
2

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

Marquistador
  • 1,841
  • 19
  • 26
2

A simple way of creating an array of random integers is:

matrix = np.random.randint(maxVal, size=(rows, columns))

The following outputs a 2 by 3 matrix of random integers from 0 to 10:

a = np.random.randint(10, size=(2,3))
Alex Myers
  • 6,196
  • 7
  • 23
  • 39
Runner
  • 21
  • 1
1

An answer using map-reduce:-

map(lambda x: map(lambda y: ran(),range(len(inputs[0]))),range(hiden_neurons))
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
GodMan
  • 2,561
  • 2
  • 24
  • 40
1
random_matrix = [[random.random for j in range(collumns)] for i in range(rows)
for i in range(rows):
    print random_matrix[i]
falsetru
  • 357,413
  • 63
  • 732
  • 636
PythonUser
  • 11
  • 1
  • Interpreted loops are typical of what should be avoided. Use numpy C vectorized operations which are way faster and simplify code. `random_matrix = numpy.random.rand(rows, columns)` ([random.rand](https://het.as.utexas.edu/HET/Software/Numpy/reference/generated/numpy.random.rand.html)) – mins Feb 15 '21 at 11:34
0
#this is a function for a square matrix so on the while loop rows does not have to be less than cols.
#you can make your own condition. But if you want your a square matrix, use this code.

import random

import numpy as np

def random_matrix(R, cols):

        matrix = []

        rows =  0

        while  rows < cols:

            N = random.sample(R, cols)

            matrix.append(N)

            rows = rows + 1

    return np.array(matrix)

print(random_matrix(range(10), 5))
#make sure you understand the function random.sample
vimuth
  • 5,064
  • 33
  • 79
  • 116
0

numpy.random.rand(row, column) generates random numbers between 0 and 1, according to the specified (m,n) parameters given. So use it to create a (m,n) matrix and multiply the matrix for the range limit and sum it with the high limit.

Analyzing: If zero is generated just the low limit will be held, but if one is generated just the high limit will be held. In order words, generating the limits using rand numpy you can generate the extreme desired numbers.

import numpy as np

high = 10
low = 5
m,n = 2,2

a = (high - low)*np.random.rand(m,n) + low

Output:

a = array([[5.91580065, 8.1117106 ],
          [6.30986984, 5.720437  ]])