Potato
μ•ˆλ…•ν•˜μ„Έμš”, κ°μž‘λ‹ˆλ‹€?πŸ₯” ^___^ 😺 github λ°”λ‘œκ°€κΈ° πŸ‘‰πŸ»

AI study/λ”₯λŸ¬λ‹ ν”„λ ˆμž„μ›Œν¬

[Pytorch] νŒŒμ΄ν† μΉ˜ 기초 - ν…μ„œ 속성 μ‚΄νŽ΄λ³΄κΈ° / ν…μ„œ μ—°μ‚°

감자 πŸ₯” 2021. 7. 16. 10:28
λ°˜μ‘ν˜•

-- λ³Έ ν¬μŠ€νŒ…μ€ νŒŒμ΄ν† μΉ˜λ‘œ λ°°μš°λŠ” μžμ—°μ–΄ 처리 (ν•œλΉ›λ―Έλ””μ–΄) 책을 μ°Έκ³ ν•΄μ„œ μž‘μ„±λœ κΈ€μž…λ‹ˆλ‹€.
-- μ†ŒμŠ€μ½”λ“œ ) https://github.com/rickiepark/nlp-with-pytorch

 

0. ν…μ„œμ˜ νƒ€μž…, 크기, 값을 λ‚˜νƒ€λ‚΄λŠ” ν•¨μˆ˜ μž‘μ„±

ν™•μ‹€ν•œ νƒ€μž…, 크기의 λ³€ν™”λ₯Ό ν™•μΈν•˜κΈ° μœ„ν•΄ μ•„λž˜μ™€ 같은 헬퍼 ν•¨μˆ˜λ₯Ό μž‘μ„±ν•œλ‹€.

def describe(x):
    print("νƒ€μž…: {}".format(x.type()))
    print("크기: {}".format(x.shape))
    print("κ°’: {}".format(x))

 

1. ν…μ„œμ˜ νƒ€μž…κ³Ό 크기 (속성)

ν…μ„œμ—λŠ” FloatTensor, LongTensor, DoubleTensor λ“± λ‹€μ–‘ν•œ ν˜•νƒœμ˜ ν…μ„œκ°€ μ‘΄μž¬ν•œλ‹€. λͺ¨λ“  ν…μ„œλ₯Ό 닀루기 μ „μ—λŠ” μ–Έμ œλ‚˜ ν…μ„œμ˜ 속성을 μ‚΄νŽ΄λ³΄κ³  μž‘μ—…μ„ μˆ˜ν–‰ν•˜λŠ” 것이 ꡉμž₯히 μ€‘μš”ν•˜λ‹€. 

import torch
x = torch.FloatTensor([[1,2,3], [4,5,6]])
describe(x)

1.1 ν…μ„œ νƒ€μž… λ³€κ²½ν•˜κΈ°

# μ•žμ— ν˜•μ„±λœ floattensor ν˜•νƒœμ˜ ν…μ„œλ₯Ό, longtensor둜 λ³€κ²½ν•œλ‹€
x = x.long()
describe(x)

#floatTensor둜 λ³€κ²½
x = x.float()
describe(x)

1.2 ν…μ„œ 크기 ν™•μΈν•˜κΈ° (shape, size())

- shape, size() λ₯Ό μ‚¬μš©ν•˜μ—¬ ν…μ„œμ˜ 크기λ₯Ό μ‚΄νŽ΄λ³Ό 수 μžˆλ‹€. 두 개의 λ©”μ„œλ“œλŠ” 같은 것이닀.

x.shape
x.size()

 

2. ν…μ„œ μ—°μ‚°

2.1 ν…μ„œμ— 일정 κ°’ λ”ν•˜κΈ° (add)

- ν…μ„œ 생성

x = torch.randn(2,3)
describe(x)

- add μ—°μ‚° μˆ˜ν–‰

# x에 xλ₯Ό λ”ν•˜λŠ” μ—°μ‚°
describe(torch.add(x,x))

# x에 νŠΉμ • 수λ₯Ό λ”ν•˜λŠ” μ—°μ‚°
describe(torch.add(x,10))

- add연산을 μ‚¬μš©ν•˜μ§€ μ•Šκ³  + λ₯Ό ν™œμš©ν•  수 도 μžˆλ‹€.

describe(x + 100)

2.2 νŠΉμ • κ°’λ§ŒνΌ μ¦κ°€ν•˜λŠ” ν…μ„œλ‘œ μƒμ„±ν•˜κΈ° (arange)

- arangeν•¨μˆ˜λŠ” 0λΆ€ν„° μ‹œμž‘ν•΄μ„œ 1μ”© μ¦κ°€λ˜μ–΄ μ§€μ •λœ κ°’ μ΄μ „κΉŒμ§€ 1μ”© μ¦κ°€ν•˜λŠ” ν…μ„œλ₯Ό λ§Œλ“œλŠ” ν•¨μˆ˜μ΄λ‹€.

x = torch.arange(1,6)
describe(x)

x = torch.arange(6)
describe(x)

- veiw λ©”μ„œλ“œλŠ” λ™μΌν•œ 데이터λ₯Ό κ³΅μœ ν•˜λŠ” μƒˆλ‘œμš΄ ν…μ„œλ₯Ό λ§Œλ“œλŠ” λ©”μ„œλ“œ

x = x.view(2,3)
describe(x)

2.3 ν…μ„œ sum ν™œμš©ν•˜κΈ° (axis, dim)

axis의 κ°œλ…μ„ μ•Œμ•„μ•Όν•œλ‹€.

- dim =0 μ΄λΌλŠ” λ§€κ°œλ³€μˆ˜λ₯Ό μΆ”κ°€ν•΄μ£Όμ—ˆκΈ° λ•Œλ¬Έμ—, col κΈ°μ€€μœΌλ‘œ sum을 ν•˜κ²Œ λœλ‹€. tensor의 ν˜•νƒœλŠ” 2row 3col ν˜•νƒœμ˜€κ³  col κΈ°μ€€μœΌλ‘œ λ”ν–ˆμœΌλ‹ˆκΉŒ sumν•œ tensor sizeλŠ” 3으둜 좜λ ₯λœλ‹€. (κ²°κ³Ό μ•„λž˜)

# tensorμ—μ„œλŠ” axis, dim λ‘κ°€μ§€λ‘œ μ‚¬μš©ν•˜κ³€ ν•œλ‹€.
describe(torch.sum(x, dim = 0))

- axis (dim) = 1둜 ν–ˆμ„ λ•ŒλŠ” rowκΈ°μ€€μœΌλ‘œ μ—°μ‚°λ˜μ–΄ size 2인 tensorκ°€ 좜λ ₯λœλ‹€. (μ•„λž˜)

describe(torch.sum(x, dim = 1))

- dim, axis λ§€κ°œλ³€μˆ˜ 없이 sumν•˜κ²Œ 되면, tensor λ‚΄μ˜ λͺ¨λ“  값을 λ”ν•œ 값이 좜λ ₯λœλ‹€.

# dim 없이 sum을 ν•˜λ©΄ λͺ¨λ“  값을 ν•©μΉœ 값이 λ‚˜μ˜¨λ‹€.
describe(torch.sum(x))

2.4 ν…μ„œ ν–‰λ ¬ κ³±μ…ˆ (mm)

 

2.5 ν…μ„œ μ—­ν–‰λ ¬ κ΅¬ν•˜κΈ° (inverse, pinverse)

 

2.6 ν…μ„œ λŒ€κ°ν•© κ΅¬ν•˜κΈ° (trace)

 

 

λ°˜μ‘ν˜•