random - python - 创建随机数矩阵的简单方法

我试图创建一个随机数字矩阵,但是我的解决方案太长,看起来难看,


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



这看起来不错,但是在我的实现中


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



这是非常不可读的,并且不适合一行。

时间:

请看一下numpy.random.rand

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

给定形状中的随机值。

创建给定形状的数组,并通过[0, 1)上的均匀分布将它传播为随机样本。


>>> import numpy as np


>>> np.random.rand(2,3)


array([[ 0.22568268, 0.0053246 , 0.41282024],


 [ 0.68824936, 0.68086462, 0.6854153 ]])



你可以删除range(len())


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



但实际上,你应该使用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]])



不推荐使用np.random.randint()作为numpy.random.random_integers()


random_matrix = numpy.random.randint(min_val,max_val,(<num_rows>,<num_cols>))



看起来你在做Coursera机器学习神经网络练习的python实现。 这是我为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



首先,创建numpy数组,然后将它转换为matrix ,请参阅下面的代码:


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)




random_matrix = [[random.random for j in range(collumns)] for i in range(rows)


for i in range(rows):


 print random_matrix[i]




x = np.int_(np.random.rand(10) * 10)



使用map-reduce的答案:-


map(lambda x: map(lambda y: ran(),range(len(inputs[0]))),range(hiden_neurons))



创建随机整数数组的一种简单方法是:


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



以下输出0到10之间随机整数的2乘3矩阵:


a = np.random.randint(10, size=(2,3))




#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



...