Chapter 3 / Artificial Neural Net
Binary Classification
Tensors
Type
e.g.
Scalar
1
Vector (Rank 1 tensor)
[1 2 3]
Matrix (Rank 2 tensor)
[[1, 2 ], [3, 4]]
Tensor (Rank n tensor)
[[[1,2,3]]]
Tensor๋ฅผ ๋ง๋ค ๋๋
tensor์ members
Attribute
Desc.
size() : method
ํ ์ ํํ ๋ฆฌํด
shape : property
ํ ์ ํํ ํ๋กํผํฐ(ndarray.shape?)
ndimension() : method
ํ ์ ๋ญํฌ ๋ฆฌํด
view(*list) : method
np.reshape()
tensor์ ๊ฐํ ์ ์๋ ์กฐ์๋ค
method
Desc.
torch.unsqueeze(tensor, n)
n ๋ญํฌ ์์น์์ ๋ญํฌ 1 ๋๋ ค ๋ฆฌํด
torch.squeeze(tensor)
๋ญํฌ 1 ์ค์ด๊ธฐ
์ฐ์ฐ๋ค
method
Desc.
torch.mm(a,b)
= matmul()
torch.cat(tensors, dim)
dim ๊ธฐ์ค์ผ๋ก tensor๋ฅผ concat
torch.dist(a,b)
a, b ํ ์ ์ฌ์ด์ ๊ฑฐ๋ฆฌ
Autograd
Gradient Descent ์๋ ๊ตฌํ
Gradient ์ ์ฉ ๋ฐฉ๋ฒ - ํ ์ ์ ์ธ ์ ๋ค์๊ณผ ๊ฐ์ด requires_grad ๋ฅผ True๋ก ์ค์ ํ๋ฉด tensor.grad์ gradient๋ฅผ ์ ์ฅ
์์(backward())
๊ฐ๋จํ GD
ANN
๊ฐ์ค์น ํ๋ ฌ์ ์ด์ ์ธต์ ๋ฒกํฐ๋ฅผ ๊ณฑํ๊ณ bias๋ฅผ ๋ํ๊ณ ๋น์ ํํ๋ฅผ ์ํด ํ์ฑํํจ์ ์ ์ฉ
torch.nn.Linear( in, out)
์ผ๋ก wx+b, torch.nn.ReLU()
๋ก ReLU, torch.nn.Sigmoid()
๋ก ์๊ทธ๋ชจ์ด๋ ํ์ฑํ ํจ์ ์ ์ฉ
torch.nn.BCELoss()
๋ก Binary Cross Entropy loss๋ฅผ ๊ณ์ฐํ๋ ๊ฐ์ฒด๋ฅผ ์์ฑ, torch.optim.SGD(parameters,lr)
๋ก ํด๋น ํ๋ผ๋ฏธํฐ๋ฅผ ๋์์ผ๋ก ํ๋ optimizer๋ฅผ ์์ฑ.
model.eval()
๊ณผ model.train()
์ ๊ฐ๊ฐ ์คํ ๋ชจ๋์ ํ์ต ๋ชจ๋๋ฅผ ์ค์์นญํ ์ ์๋ค.
optimizer.zero_grad()
๋ฅผ ์ด์ฉํด gradient๋ฅผ 0์ผ๋ก ์ฌ์ค์ ํด ์๋ก์ด gradient๋ฅผ ๊ณ์ฐํ ์ ์๋๋ก ํจ.
train ๋ชจ๋๋ก ๋ณ๊ฒฝํ ํ,
๋ชจ๋ธ์ ๋ฐ์ดํฐ๋ฅผ ๋ฃ์ด output๊ณ์ฐ, loss๋ฅผ ๊ณ์ฐ, loss๋ฅผ backpropagation, optimizer์ผ๋ก parameter์ ์ ์ฅ๋ gradient๋ฅผ ์ด์ฉํด ์ต์ ํ - ๋ฅผ ๋ฐ๋ณตํ๋ค.
3์ฅ์ ANN์ XOR ์ด์ง ๋ถ๋ฅ๋ผ๊ณ ๋ณผ ์ ์๋ค. ํ๋์ linear ๊ตฌ๋ถ์ผ๋ก ๋ถ๋ฅํ ์ ์์ด ์ฌ๋ฌ ์ธต์ ์ฌ์ฉํ๋ค.
BCE
Binary Cross Entropy๋ Cross Entropy์ ํน์ํ ๊ฒฝ์ฐ(ํ๋ฅ ๋ถํฌํจ์๊ฐ scalar๊ฐ์ด๊ณ , ์ด์ง์ผ๋ก ๋ถ๋ฅํ ๋) ์ด๋ค. Cross Entropy๋ ๋์ผํ Event Space(์ฌ๊ธฐ์ Sample Space์ ์์๊ฐ 2๊ฐ๋ผ ๋ณผ ์ ์์ผ๋ฏ๋ก Event Space๋ {O, X})์์ ๋ค๋ฅธ ๋ ํ๋ฅ ๋ถํฌ(์ฌ๊ธฐ์ ๋ฐ์ดํฐ์ ๋ถํฌ์ ์์ธก์ ๋ถํฌ)์ ์ ๋ณด๋ ์ฐจ์ด๋ฅผ ๊ณ์ฐํ๋ค.
3์ฅ์ ๋ชจ๋ธ์์ ์์ธกํ๋ ๊ฒ์ ๋ ํด๋์ค ์ค ํ๋์ ํด๋์ค์ ๋ํด ์ํ ํ๋ฅ ์ด๋ฏ๋ก ํ๋์ ํ๋ฅ ๊ฐ์ ๊ฐ์ง๋ฉฐ ํ๋ฅ ์ง๋ํจ์๋ y, 1-y ๋ก ๊ฐ ํด๋์ค์ ํ ๋น๋๋ค๊ณ ๋ณผ ์ ์๋ค. ๊ทธ๋ฌ๋ฉด BCE๋
y๋ ์ฐธ๊ฐ(์ฃผ์ด์ง ๋ฐ์ดํฐ), \hat y๋ ์์ธก๊ฐ์ด๋ค.
Reuse Parameter/Model
๋ชจ๋ธ ํ์ต ํ ํ๋ผ๋ฏธํฐ๋ฅผ ์ ์ฅํ๋ค๊ฐ ๋ค์ ์ฌ์ฉํ ์ ์๋ค. torch.save(model.statedict(),'filename')
์ผ๋ก ์ ์ฅ ํ, model.load_state_dict(torch.load('filename'))
์ผ๋ก restore ํ ์ ์๋ค.
Last updated
Was this helpful?