난수 행렬을 만드는 간단한 방법


97

난수 행렬을 만들려고하는데 솔루션이 너무 길고보기 흉해 보입니다.

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

매우 읽기 어렵고 한 줄에 맞지 않습니다.

답변:


75

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

95

다음을 삭제할 수 있습니다 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]])

임의의 정수를 얻는 방법?
Jack Twain 2014

41
numpy.random.random_integers(low, high, shape), 예numpy.random.random_integers(0, 100, (3, 3))
Pavel Anossov 2014

무작위 서명에 사용되는 이중 괄호 표기법의 용어는 무엇입니까? 나는 그것에 익숙하지 않다.
Emile Victor

numpy.random.random다른 많은 numpy.random방법 과 마찬가지로 @EmileVictor 는 모양, 즉 N- 튜플을 허용합니다. 따라서 실제로 외부 괄호는 메서드 호출을 나타내고 numpy.random.random()내부 괄호는 (3, 3)함수로 전달되는 튜플을 인스턴스화하기위한 구문 설탕입니다 .
Vivek Jha

2
numpy.random.random_integers()더 이상 사용되지 않습니다. numpy.random.randint()대신 사용하십시오 . docs.scipy.org/doc/numpy/reference/generated/…
Max

15

사용 np.random.randint()으로 numpy.random.random_integers()사용되지 않습니다

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

5

Coursera Machine Learning Neural Network 연습의 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

3

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


2

"난수 행렬"이라고 말하면 위에서 언급 한 Pavel https://stackoverflow.com/a/15451997/6169225 처럼 numpy를 사용할 수 있습니다. ) 난수를 준수합니다.

그러나 특정 분포가 필요한 경우 (균일 분포에 관심이 있다고 생각합니다), numpy.random 매우 유용한 방법이 있습니다. 예를 들어, [low, high]로 경계가 지정된 의사 랜덤 균일 분포를 갖는 3x2 행렬을 원한다고 가정 해 보겠습니다. 다음과 같이 할 수 있습니다.

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

uniform이 라이브러리에서 지원하는 배포판 수에 관계없이 대체 할 수 있습니다 .

추가 정보 : https://docs.scipy.org/doc/numpy/reference/routines.random.html


2

임의의 정수 배열을 만드는 간단한 방법은 다음과 같습니다.

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

다음은 0에서 10까지의 임의 정수로 구성된 2 x 3 행렬을 출력합니다.

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

2

난수 배열을 만들기 위해 NumPy는 다음을 사용하여 배열 생성을 제공합니다.

  1. 실수

  2. 정수

임의의 실수를 사용하여 배열을 만드는 경우 : 두 가지 옵션이 있습니다.

  1. random.rand (생성 된 난수의 균일 한 분포)
  2. random.randn (생성 된 난수의 정규 분포 용)

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) 

임의의 정수를 사용하여 배열을 만드는 경우 :

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

어디

  • low = 분포에서 가져올 가장 낮은 (부호있는) 정수
  • high (선택 사항) = 제공되는 경우 분포에서 가져올 가장 큰 (부호있는) 정수 위의 하나
  • size (선택 사항) = 출력 모양 즉, 주어진 모양이 예를 들어 (m, n, k)이면 m * n * k 샘플이 그려집니다.
  • dtype (선택 사항) = 원하는 결과 dtype.

예 :

주어진 예제는 0과 4 사이의 임의의 정수 배열을 생성하며, 크기는 5 * 5이며 25 개의 정수를 갖습니다.

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

5x5 행렬을 만들려면 다음과 같이 수정해야합니다.

arr2 = np.random.randint (0,5, size = (5,5)), 곱셈 기호 *를 쉼표로 변경, #

[[21 1 0 1] [32 1 4 3] [2 3 0 3 3] [1 3 1 0 0] [41 2 0 1]]

eg2 :

주어진 예제는 0과 1 사이의 임의의 정수 배열을 생성하며 크기는 1 * 10이며 10 개의 정수를 갖습니다.

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

[00 0 0 1 1 0 0 1 1]


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

1

map-reduce를 사용한 답변 :-

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

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

0

numpy.random.rand (row, column)은 지정된 (m, n) 매개 변수에 따라 0에서 1 사이의 난수를 생성합니다. 따라서 그것을 사용하여 (m, n) 행렬을 만들고 범위 제한에 대한 행렬을 곱한 다음 상한과 합산하십시오.

분석 중 : 0이 생성되면 하한이 유지되지만 하나가 생성되면 상한이 유지됩니다. 즉, 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  ]])
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.