Skip to content
This repository has been archived by the owner on Oct 19, 2023. It is now read-only.

Commit

Permalink
update chapter names
Browse files Browse the repository at this point in the history
  • Loading branch information
keon committed Aug 28, 2019
1 parent 0805d8d commit 04452ec
Show file tree
Hide file tree
Showing 57 changed files with 64 additions and 277 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,5 @@ data/

tmp/
snapshot/

.vscode
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,10 @@

import torch


w = torch.tensor(1.0, requires_grad=True)


a = w*3
l = a**2
l.backward()
print(w.grad)
print('l을 w로 미분한 값은 {}'.format(w.grad))

Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@
import matplotlib.pyplot as plt
import torch.nn.functional as F


n_dim = 2
x_train, y_train = make_blobs(n_samples=80, n_features=n_dim, centers=[[1,1],[-1,-1],[1,-1],[-1,1]], shuffle=True, cluster_std=0.3)
x_test, y_test = make_blobs(n_samples=20, n_features=n_dim, centers=[[1,1],[-1,-1],[1,-1],[-1,1]], shuffle=True, cluster_std=0.3)


def label_map(y_, from_, to_):
y = numpy.copy(y_)
for f in from_:
Expand All @@ -27,7 +25,6 @@ def label_map(y_, from_, to_):
y_test = label_map(y_test, [0, 1], 0)
y_test = label_map(y_test, [2, 3], 1)


def vis_data(x,y = None, c = 'r'):
if y is None:
y = [None] * len(x)
Expand All @@ -41,14 +38,12 @@ def vis_data(x,y = None, c = 'r'):
vis_data(x_train, y_train, c='r')
plt.show()


x_train = torch.FloatTensor(x_train)
print(x_train.shape)
x_test = torch.FloatTensor(x_test)
y_train = torch.FloatTensor(y_train)
y_test = torch.FloatTensor(y_test)


class NeuralNet(torch.nn.Module):
def __init__(self, input_size, hidden_size):
super(NeuralNet, self).__init__()
Expand All @@ -66,19 +61,16 @@ def forward(self, input_tensor):
output = self.sigmoid(linear2)
return output


model = NeuralNet(2, 5)
learning_rate = 0.03
criterion = torch.nn.BCELoss()
epochs = 2000
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)


model.eval()
test_loss_before = criterion(model(x_test).squeeze(), y_test)
print('Before Training, test loss is {}'.format(test_loss_before.item()))


# 오차값이 0.73 이 나왔습니다. 이정도의 오차를 가진 모델은 사실상 분류하는 능력이 없다고 봐도 무방합니다.
# 자, 이제 드디어 인공신경망을 학습시켜 퍼포먼스를 향상시켜 보겠습니다.

Expand All @@ -92,24 +84,20 @@ def forward(self, input_tensor):
train_loss.backward()
optimizer.step()


model.eval()
test_loss = criterion(model(x_test).squeeze(), y_test)
print('After Training, test loss is {}'.format(test_loss.item()))


# 학습을 하기 전과 비교했을때 현저하게 줄어든 오차값을 확인 하실 수 있습니다.
# 지금까지 인공신경망을 구현하고 학습시켜 보았습니다.
# 이제 학습된 모델을 .pt 파일로 저장해 보겠습니다.

torch.save(model.state_dict(), './model.pt')
print('state_dict format of the model: {}'.format(model.state_dict()))


# `save()` 를 실행하고 나면 학습된 신경망의 가중치를 내포하는 model.pt 라는 파일이 생성됩니다. 아래 코드처럼 새로운 신경망 객체에 model.pt 속의 가중치값을 입력시키는 것 또한 가능합니다.

new_model = NeuralNet(2, 5)
new_model.load_state_dict(torch.load('./model.pt'))
new_model.eval()
print('벡터 [-1, 1]이 레이블 1을 가질 확률은 {}'.format(new_model(torch.FloatTensor([-1,1])).item()))

Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,11 @@
import pickle
import matplotlib.pyplot as plt


shp_original_img = (100, 100)
broken_image = torch.FloatTensor( pickle.load(open('./broken_image_t.p', 'rb'),encoding='latin1' ) )


plt.imshow(broken_image.view(100,100))


def weird_function(x, n_iter=5):
h = x
filt = torch.tensor([-1./3, 1./3, -1./3])
Expand All @@ -31,14 +28,11 @@ def weird_function(x, n_iter=5):
h = torch.cat( (h[h.shape[0]//2:],h[:h.shape[0]//2]), 0 )
return h


def distance_loss(hypothesis, broken_image):
return torch.dist(hypothesis, broken_image)


random_tensor = torch.randn(10000, dtype = torch.float)


lr = 0.8
for i in range(0,20000):
random_tensor.requires_grad_(True)
Expand All @@ -50,6 +44,4 @@ def distance_loss(hypothesis, broken_image):
if i % 1000 == 0:
print('Loss at {} = {}'.format(i, loss.item()))


plt.imshow(random_tensor.view(100,100).data)

Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,28 @@
print("Shape:", x.shape)
print("랭크(차원):", x.ndimension())


# 랭크 늘리기
x = torch.unsqueeze(x, 0)
print(x)
print("Size:", x.size())
print("Shape:", x.shape)
print("랭크(차원):", x.ndimension())


# 랭크 줄이기
x = torch.squeeze(x)
print(x)
print("Size:", x.size())
print("Shape:", x.shape) #[3, 3] 2개의 차원에 각 3개의 원소를 가진 텐서
print("랭크(차원):", x.ndimension())


# 랭크의 형태 바꾸기
x = x.view(9)
print(x)
print("Size:", x.size())
print("Shape:", x.shape)
print("랭크(차원):", x.ndimension())


try:
x = x.view(2,4)
except Exception as e:
print(e) #에러 출력

Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,14 @@
print("w:", w)
print("x:", x)


b = torch.randn(5,2, dtype=torch.float)
print("b:", b.size())
print("b:", b)


wx = torch.mm(w,x) # w의 행은 5, x의 열은 2, 즉 shape는 [5, 2]입니다.
print("wx size:", wx.size())
print("wx:", wx)


result = wx + b
print("result size:", result.size())
print("result:", result)

36 changes: 0 additions & 36 deletions 03-파이토치로_구현하는_인공_신경망/broken_image_t.p

This file was deleted.

9 changes: 0 additions & 9 deletions 04-딥러닝으로_패션_아이템_구분하기/README.md

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# 딥러닝으로 패션 아이템 구분하기

Fashion MNIST 데이터셋과 앞서 배운 인공신경망을 이용하여 패션아이템을 구분해봅니다.
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,16 @@
from torchvision import datasets, transforms, utils
from torch.utils import data


%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np


# ## Fashion MNIST 데이터셋

transform = transforms.Compose([
transforms.ToTensor()
])


trainset = datasets.FashionMNIST(
root = './.data/',
train = True,
Expand All @@ -31,7 +29,6 @@
transform = transform
)


batch_size = 16

train_loader = data.DataLoader(
Expand All @@ -43,22 +40,18 @@
batch_size = batch_size
)


dataiter = iter(train_loader)
images, labels = next(dataiter)


# ## 멀리서 살펴보기
img = utils.make_grid(images, padding=0)
npimg = img.numpy()
plt.figure(figsize=(10, 7))
plt.imshow(np.transpose(npimg, (1,2,0)))
plt.show()


print(labels)


CLASSES = {
0: 'T-shirt/top',
1: 'Trouser',
Expand All @@ -77,7 +70,6 @@
index = label.item()
print(CLASSES[index])


# ## 가까이서 살펴보기
idx = 1

Expand All @@ -87,4 +79,3 @@
print(item_npimg.shape)
plt.imshow(item_npimg, cmap='gray')
plt.show()

Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,18 @@
import torch.nn.functional as F
from torchvision import transforms, datasets


USE_CUDA = torch.cuda.is_available()
DEVICE = torch.device("cuda" if USE_CUDA else "cpu")


EPOCHS = 30
BATCH_SIZE = 64


# ## 데이터셋 불러오기

transform = transforms.Compose([
transforms.ToTensor()
])


trainset = datasets.FashionMNIST(
root = './.data/',
train = True,
Expand All @@ -50,7 +46,6 @@
shuffle = True,
)


# ## 뉴럴넷으로 Fashion MNIST 학습하기
# 입력 `x` 는 `[배치크기, 색, 높이, 넓이]`로 이루어져 있습니다.
# `x.size()`를 해보면 `[64, 1, 28, 28]`이라고 표시되는 것을 보실 수 있습니다.
Expand All @@ -72,7 +67,6 @@ def forward(self, x):
x = self.fc3(x)
return x


# ## 모델 준비하기
# `to()` 함수는 모델의 파라미터들을 지정한 곳으로 보내는 역할을 합니다.
# 일반적으로 CPU 1개만 사용할 경우 필요는 없지만,
Expand All @@ -83,7 +77,6 @@ def forward(self, x):
model = Net().to(DEVICE)
optimizer = optim.SGD(model.parameters(), lr=0.01)


# ## 학습하기

def train(model, train_loader, optimizer):
Expand All @@ -97,7 +90,6 @@ def train(model, train_loader, optimizer):
loss.backward()
optimizer.step()


# ## 테스트하기

def evaluate(model, test_loader):
Expand All @@ -122,7 +114,6 @@ def evaluate(model, test_loader):
test_accuracy = 100. * correct / len(test_loader.dataset)
return test_loss, test_accuracy


# ## 코드 돌려보기
# 자, 이제 모든 준비가 끝났습니다. 코드를 돌려서 실제로 훈련이 되는지 확인해봅시다!

Expand All @@ -132,4 +123,3 @@ def evaluate(model, test_loader):

print('[{}] Test Loss: {:.4f}, Accuracy: {:.2f}%'.format(
epoch, test_loss, test_accuracy))

Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,12 @@
import torch.nn.functional as F
from torchvision import transforms, datasets


USE_CUDA = torch.cuda.is_available()
DEVICE = torch.device("cuda" if USE_CUDA else "cpu")


EPOCHS = 50
BATCH_SIZE = 64


# ## 데이터셋에 노이즈 추가하기
# ![original.png](./assets/original.png)
# ![horizontalflip.png](./assets/horizontalflip.png)
Expand All @@ -43,7 +40,6 @@
])),
batch_size=BATCH_SIZE, shuffle=True)


# ## 뉴럴넷으로 Fashion MNIST 학습하기
# 입력 `x` 는 `[배치크기, 색, 높이, 넓이]`로 이루어져 있습니다.
# `x.size()`를 해보면 `[64, 1, 28, 28]`이라고 표시되는 것을 보실 수 있습니다.
Expand Down Expand Up @@ -73,7 +69,6 @@ def forward(self, x):
x = self.fc3(x)
return x


# ## 모델 준비하기
# `to()` 함수는 모델의 파라미터들을 지정한 곳으로 보내는 역할을 합니다.
# 일반적으로 CPU 1개만 사용할 경우 필요는 없지만,
Expand All @@ -84,7 +79,6 @@ def forward(self, x):
model = Net(dropout_p=0.2).to(DEVICE)
optimizer = optim.SGD(model.parameters(), lr=0.01)


# ## 학습하기

def train(model, train_loader, optimizer):
Expand All @@ -97,7 +91,6 @@ def train(model, train_loader, optimizer):
loss.backward()
optimizer.step()


# ## 테스트하기
def evaluate(model, test_loader):
model.eval()
Expand All @@ -118,7 +111,6 @@ def evaluate(model, test_loader):
test_accuracy = 100. * correct / len(test_loader.dataset)
return test_loss, test_accuracy


# ## 코드 돌려보기
# 자, 이제 모든 준비가 끝났습니다. 코드를 돌려서 실제로 훈련이 되는지 확인해봅시다!

Expand All @@ -128,4 +120,3 @@ def evaluate(model, test_loader):

print('[{}] Test Loss: {:.4f}, Accuracy: {:.2f}%'.format(
epoch, test_loss, test_accuracy))

Loading

0 comments on commit 04452ec

Please sign in to comment.