Simple way to create matrix of random numbers

前端 未结 13 1662
灰色年华
灰色年华 2020-12-12 21:20

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 ra         


        
相关标签:
13条回答
  • 2020-12-12 21:57

    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)
    
    0 讨论(0)
  • 2020-12-12 21:57
    x = np.int_(np.random.rand(10) * 10)
    

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

    0 讨论(0)
  • 2020-12-12 22:01
    #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
    
    0 讨论(0)
  • 2020-12-12 22:02

    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]])
    
    0 讨论(0)
  • 2020-12-12 22:03

    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
    
    0 讨论(0)
  • 2020-12-12 22:03

    An answer using map-reduce:-

    map(lambda x: map(lambda y: ran(),range(len(inputs[0]))),range(hiden_neurons))
    
    0 讨论(0)
提交回复
热议问题