본문 바로가기

내가 보려고 만든 Pytorch

내가 공부하려고 만든 Pytorch5(3d Tensor 혼자 해보기)

3d tensor 생성

z = torch.FloatTensor(
   [
   [[0, 0, 0, 0, 0],
   [50, 50, 50, 50, 50],
   [100, 100, 100, 100, 100],
   [150, 150, 150, 150, 150],
   [0, 0, 0, 0, 0]],
   
   [[10, 10, 10, 10, 10],
   [60, 60, 60, 60, 60],
   [110, 110, 110, 110, 110],
   [160, 160, 160, 160, 160],
   [0, 0, 0, 0, 0]],
   
   [[20, 20, 20, 20, 20],
   [70, 70, 70, 70, 70],
   [120, 120, 120, 120, 120],
   [170, 170, 170, 170, 170],
   [250, 250, 250, 250, 250]],
   ]
   )
print(z)
print(f'{z.dim()}차원입니다.')
print(f'{z.shape[0]}x{z.shape[1]}x{z.shape[-1]}')
print(z.size())

tensor([[[  0.,   0.,   0.,   0.,   0.],
         [ 50.,  50.,  50.,  50.,  50.],
         [100., 100., 100., 100., 100.],
         [150., 150., 150., 150., 150.],
         [  0.,   0.,   0.,   0.,   0.]],

        [[ 10.,  10.,  10.,  10.,  10.],
         [ 60.,  60.,  60.,  60.,  60.],
         [110., 110., 110., 110., 110.],
         [160., 160., 160., 160., 160.],
         [  0.,   0.,   0.,   0.,   0.]],

        [[ 20.,  20.,  20.,  20.,  20.],
         [ 70.,  70.,  70.,  70.,  70.],
         [120., 120., 120., 120., 120.],
         [170., 170., 170., 170., 170.],
         [250., 250., 250., 250., 250.]]])
3차원입니다.
3x5x5
torch.Size([3, 5, 5])

 

Mean을 사용해 dim에 따라 어떻게 계산되는지 계산해보기

 

1. dim을 설정하지 않았을 때

z.mean()
tensor(84.6667)
total = 0
count = 0

for i in range(z.shape[0]):
    for j in range(z.shape[1]):
        for k in range(z.shape[2]):
            total += z[i][j][k]
            count += 1
            
mean = total / count
print(mean)

tensor(84.6667)

 

2. dim = 0 일때 (5X5)

z.mean(dim=0)

tensor([[ 10.0000,  10.0000,  10.0000,  10.0000,  10.0000],
        [ 60.0000,  60.0000,  60.0000,  60.0000,  60.0000],
        [110.0000, 110.0000, 110.0000, 110.0000, 110.0000],
        [160.0000, 160.0000, 160.0000, 160.0000, 160.0000],
        [ 83.3333,  83.3333,  83.3333,  83.3333,  83.3333]])
print((0+10+20)/3,(50+60+70)/3,(100+110+120)/3,(150+160+170)/3,(0+0+250)/3)

10.0 60.0 110.0 160.0 83.33333333333333

 

3. dim = 1 일때 (3x5)

z.mean(dim=1)

tensor([[ 60.,  60.,  60.,  60.,  60.],
        [ 68.,  68.,  68.,  68.,  68.],
        [126., 126., 126., 126., 126.]])
print((0+50+100+150+0)/5,(10+60+110+160+0)/5,(20+70+120+170+250)/5)

60.0 68.0 126.0

 

3. dim =2(=-1) 일때 (3x5)

 

z.mean(dim=-1)

tensor([[  0.,  50., 100., 150.,   0.],
        [ 10.,  60., 110., 160.,   0.],
        [ 20.,  70., 120., 170., 250.]])
for i in range(3):
    for j in range(5):
        num=0
        for k in range(5):
            num+=(z[i][j][k])/5
            test_tensor[i][j]=num
test_tensor 

tensor([[  0.,  50., 100., 150.,   0.],
        [ 10.,  60., 110., 160.,   0.],
        [ 20.,  70., 120., 170., 250.]], dtype=torch.float64)