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

问题:创建随机数矩阵的简单方法

我正在尝试创建一个随机数矩阵,但是我的解决方案太长且看起来很丑

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)]

这是非常不可读的,并且不能放在一行上。

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.


回答 0

看看numpy.random.rand

文档字符串: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 ]])

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 ]])

回答 1

您可以删除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]])

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]])

回答 2

使用np.random.randint()numpy.random.random_integers()是过时

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

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

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

回答 3

看起来您正在执行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

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

回答 4

首先,创建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)

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)

回答 5

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

对于10中的随机数,对于20中的随机数,我们必须乘以20。

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

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


回答 6

当您说“随机数矩阵”时,您可以使用numpy作为上述的Pavel https://stackoverflow.com/a/15451997/6169225,在这种情况下,我假设与您无关的是,这些分布是什么(伪)坚持随机数。

但是,如果您需要特定的分布(我想您对统一分布很感兴趣),则numpy.random有非常有用的方法为您服务。例如,假设您要一个3×2矩阵,其伪随机均匀分布以[low,high]为边界。您可以这样做:

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

注意,您可以用uniform此库支持的任意数量的发行版代替。

进一步阅读:https : //docs.scipy.org/doc/numpy/reference/routines.random.html

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 3×2 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


回答 7

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

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

下面的代码输出从0到10的2到3的随机整数矩阵:

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

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))

回答 8

为了创建随机数数组,NumPy使用以下方法创建数组:

  1. 实数

  2. 整数

使用随机实数创建数组 有2个选项

  1. random.rand(用于均匀分布所生成的随机数)
  2. random.randn(用于所生成的随机数的正态分布)

随机兰德

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

随机兰德

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

使用随机整数创建数组

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

哪里

  • low =要从分布中得出的最低(有符号)整数
  • 高(可选)=如果提供,则从分布中得出的最大(有符号)整数上方
  • size(可选)=输出形状,即如果给定形状为例如(m,n,k),则绘制m * n * k个样本
  • dtype(可选)=结果的所需dtype。

例如:

给定的示例将生成一个介于0和4之间的随机整数数组,其大小将为5 * 5,并具有25个整数

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

为了创建5 x 5矩阵,应将其修改为

arr2 = np.random.randint(0,5,size =(5,5)),将乘法符号*更改为逗号,#

[[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:

给定的示例将生成一个介于0和1之间的随机整数数组,其大小将为1 * 10并具有10个整数

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

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

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]


回答 9

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

回答 10

使用map-reduce的答案:-

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

An answer using map-reduce:-

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

回答 11

#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
#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

回答 12

numpy.random.rand(row,column)根据给定的指定(m,n)参数生成0到1之间的随机数。因此,使用它创建一个(m,n)矩阵,并将该矩阵乘以范围限制,然后将其与上限相加。

分析:如果生成零,则仅将保持下限,但是如果生成零,将仅保持上限。顺便说一句,使用rand numpy生成限制,您可以生成极端所需的数字。

import numpy as np

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

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

输出:

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

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  ]])