Python/numpy & Pytorch
[Pytorch] Tensor shuffle, 텐서 랜덤 섞기
파송송
2023. 3. 16. 14:29
728x90
randperm(int)
입력된 숫자를 임의로 섞어주는 함수
torch.randperm(10)
tensor([9, 8, 2, 1, 3, 4, 5, 6, 7, 0])
Tensor 행 섞기
tensor의 행이 랜덤으로 섞이는 코드
a = torch.rand(3,3)
a = a[torch.randperm(a.size()[0])]
tensor([[0.5326, 0.3624, 0.3423],
[0.9065, 0.8168, 0.5219],
[0.9516, 0.3635, 0.8481]])
tensor([[0.9065, 0.8168, 0.5219],
[0.9516, 0.3635, 0.8481],
[0.5326, 0.3624, 0.3423]])
Tensor 열 섞기
a = torch.rand(3,3)
a = a[:,torch.randperm(a.size()[1])]
tensor([[0.2710, 0.9353, 0.4350, 0.5271],
[0.9104, 0.4075, 0.1962, 0.0693],
[0.3021, 0.9471, 0.8520, 0.5237]])
tensor([[0.9353, 0.5271, 0.4350, 0.2710],
[0.4075, 0.0693, 0.1962, 0.9104],
[0.9471, 0.5237, 0.8520, 0.3021]])
2개를 차례대로 진행하면 행과 열이 섞이는 Tensor를 만들 수 있지만 이를 한 줄로 표현할 수 있음
Tensor 행, 열 섞기
a = torch.rand(3,4)
row = torch.randperm(a.size()[0])
col = torch.randperm(a.size()[1])
a = a[row[:, None], col]
tensor([[0.0238, 0.2874, 0.8791, 0.2914],
[0.4763, 0.1217, 0.8829, 0.0668],
[0.8049, 0.6241, 0.4514, 0.4810]])
tensor([[0.2874, 0.0238, 0.2914, 0.8791],
[0.6241, 0.8049, 0.4810, 0.4514],
[0.1217, 0.4763, 0.0668, 0.8829]])
728x90