본문 바로가기
Python

[DL] Tensor: Random Tensor 만들기 (NumPy, PyTorch)

by ds31x 2024. 3. 29.

Tensor: Random Tensor 만들기 (NumPy, PyTorch)

Random value를 얻는데 이용되는 Probability Distribution에 따라 크게 2가지로 나눌 수 있음.

  1. Uniform Distribution
  2. Normal Distribution


 

0. Uniform Distribution

Random Variable이 가질 수 있는 값들이 모두 같은 확률을 가짐.

  • int형 element를 가지는 tensor를 반환하는 것들과
  • float형 element를 가지는 tensor를 반환하는 것으로 크게 나눌 수 있음.

가장 대표적인 함수 이름으로는 randintrand 가 있음.


0.1 randint

가장 대표적인 int형 element를 가지는 random tensor를 생성하는데 사용됨.

다음과 같이 지원됨.

np.random.randint( min, max+1, size )
np.random.randint( max+1, size)

torch.randint( min, max+1, size )
torch.randint( max+1, size)
  • max+1 은 argument값보다 하나 적은 값이 최댓값이 됨을 의미함.
  • 즉, [min, max]에 해당하는 범위의 int형 값이 동일한 확률로 선택됨.

비슷한 함수로 np.random.chocie 가 있는데, 이는 element가 가질 수 있는 값들을 가지고 있는 array 를 첫번째 argument로 받고 두번째 argument로 반환되는 random array의 shape를 입력받음(tuple 등의 형태로).


Torch에서는 torch.randperm 으로 첫번째 argument로 받은 숫자보다 1적은 int값을 max로 하고, 0을 min으로 하는 자연수들을 random한 순서로 다시 배치한 1-D tensor를 반환하는 것이 있음.

사실 np.random.choice는
element가 가질 수 있는 값들을 가지고 있는 array가 float 값들을 element로 가질 경우,
실수의 array를 반환하기 때문에 이 분류에 속한다고 보기 어려울 수도 있으나
거의 대부분 int값의 array를 사용(주로 index를 shuffle 하는 용도로 많이 이용됨.)하기 때문에 여기서 다름.


0.2 rand ***

[0,1) 의 범위 내의 값들을 동일한 확률로 뽑아 random tensor를 반환하는 대표적인 함수.

특징은 반환되는 random tensor의 shape를 각각 분리된 argument로 받는다는 점임.

다음과 같이 지원됨.

np.random.rand( d0, d1, ...)

torch.rand( d0, d1, ...)

 

비슷한 함수로 np.random.random_samplenp.random.random 이 있는데,

이들은 생성하는 array의 shape에 대한 argument를 tuple 등과 같은 collection type의 인스턴스로 이용하는 차이점을 보임.


1. Normal Distribution

Random variable이 normal distribution (Gaussian Distribution)에 따라 값이 결정됨.

  • 일반적인 normal distirbution에서 값을 얻는 방식 (normal)과
  • standard normal distribution을 사용하는 경우 (randn)으로 나뉨.

1.1 normal

Normal distribution의 parameter인 meanstd 를 argument로 입력받음.

또한 반환되는 tensor의 shape도 하나의 argument로 입력받는다.

 

다음과 같이 지원됨.

np.random.normal(mean, std, size)
np.random.normal(size) # mean=0., std=1.

torch.normal(mean, std, size)
torch.normal(size)

 


1.2 randn

mean=0. 이고 std=1. 인 standard normal distribution을 따라 element 값이 결정된다.

주의할 점은 shape를 결정하는 argument가 하나가 아닌 각 축별로 따로 따로 입력받음.

 

다음과 같이 지원됨.

np.random.randn( d0, d1, ... )

torch.randn( d0, d1, ... )

 

비슷한 함수로는 np.random.standard_normal 이 있는데 이는 shape를 하나의 argument로 받는다는 차이가 있음.

 


참고자료

https://gist.github.com/dsaint31x/a641806c56ae1d0fb594a065969154e3

 

dl_tensor_random_torch_numpy.ipynb

dl_tensor_random_torch_numpy.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

2024.09.09 - [Python] - [NumPy] 생성 및 초기화, 기본 조작 (1)

 

[NumPy] 생성 및 초기화, 기본 조작 (1)

1. ndarray 생성하기 (=tensor생성하기)np.array ( seq [,dtype])list 나 tuple 등의 sequence 객체로부터 ndarray 생성.dtype : data type of element.float64 : default type in the numpy. *uint8 : unsigned int (8bit), the most commonly used for im

ds31x.tistory.com

 


 

728x90