Skip to content
98 changes: 98 additions & 0 deletions Image Classifier.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
## 📕 이미지 분류 정리 (Pytorch)
---
### torchvision
: data loaders for common datasets such as ImageNet, CIFAR10, MNIST

code - `torchvision.datasets` and `torch.utils.data.DataLoader`

### steps
1. Load and normalize the CIFAR10 training and test datasets using torchvision
2. Define a Convolutional Neural Network
3. Define a loss function
4. Train the network on the training data
5. Test the network on the test data

### 중요 코드 정리
#### 1. Load and normalize CIFAR10
```
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=2)
```
#### 2. Define a Convolutional Neural Network - 3-channel images
```
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = torch.flatten(x, 1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
```


#### 3. Define a loss function - Cross-Entropy loss와 SGD with momentum
```
import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
```


#### 4. Train the network on the training data
```
for epoch in range(2): # loop over the dataset multiple times

running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data

# zero the parameter gradients
optimizer.zero_grad()

# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()

# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
running_loss = 0.0

print('Finished Training')
```

#### 5. Test the network on the test data
```
correct = 0
total = 0
# since we're not training, we don't need to calculate the gradients for our outputs
with torch.no_grad():
for data in testloader:
images, labels = data
# calculate outputs by running images through the network
outputs = net(images)
# the class with the highest energy is what we choose as prediction
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()

print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')
```
59 changes: 59 additions & 0 deletions Transfer Learning.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
## 📕 전이학습 정리 (Pytorch)

### TRANSFER LEARNING 이란?
작은 데이터셋으로도 CNNs 학습을 시킬 수 있는 방법.

매우 큰 데이터셋(예. 100가지 분류에 대해 120만개의 이미지가 포함된 ImageNet)에서 합성곱 신경망(ConvNet)을 미리 학습한 후, 이 합성곱 신경망을 관심있는 작업 을 위한 초기 설정 또는 고정된 특징 추출기(fixed feature extractor)로 사용한다.

### 시나리오 2가지
1. fine tuning - 사전 학습된 모델을 새로운 문제에 적용하기 위해 일부 가중치를 조절하는 학습 과정
2. 고정된 특징 추출기로써의 합성곱 신경망- 마지막에 완전히 연결 된 계층을 제외한 모든 신경망의 가중치를 고정. 이 마지막의 완전히 연결된 계층은 새로운 무작위의 가중치를 갖는 계층으로 대체되어 이 계층만 학습.

### 중요한 코드 정리
#### 합성곱 신경망 미세조정(finetuning)
```
model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
# 여기서 각 출력 샘플의 크기는 2로 설정합니다.
# 또는, nn.Linear(num_ftrs, len (class_names))로 일반화할 수 있습니다.
model_ft.fc = nn.Linear(num_ftrs, 2)

model_ft = model_ft.to(device)

criterion = nn.CrossEntropyLoss()

# 모든 매개변수들이 최적화되었는지 관찰
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

# 7 에폭마다 0.1씩 학습률 감소
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)

# 학습 및 평가
model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
num_epochs=25)
```
#### 고정된 특징 추출기로써의 합성곱 신경망
```
model_conv = torchvision.models.resnet18(pretrained=True)
for param in model_conv.parameters():
param.requires_grad = False

# 새로 생성된 모듈의 매개변수는 기본값이 requires_grad=True 임
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)

model_conv = model_conv.to(device)

criterion = nn.CrossEntropyLoss()

# 이전과는 다르게 마지막 계층의 매개변수들만 최적화되는지 관찰
optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)

# 7 에폭마다 0.1씩 학습률 감소
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)

# 학습 및 평가
model_conv = train_model(model_conv, criterion, optimizer_conv,
exp_lr_scheduler, num_epochs=25)

```
Binary file added Week_17_논문리뷰.pdf
Binary file not shown.
Binary file added Week_18_논문리뷰.pdf
Binary file not shown.
Binary file added cs231n_2017_lecture10.pdf
Binary file not shown.
Binary file added cs231n_2017_lecture11.pdf
Binary file not shown.
Binary file added cs231n_2017_lecture13.pdf
Binary file not shown.
Binary file added cs231n_2017_lecture14.pdf
Binary file not shown.
Binary file added cs231n_2017_lecture9.pdf
Binary file not shown.
66 changes: 66 additions & 0 deletions lecture02.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
### 1. `Image Classsification`
: input 이미지가 주어졌을때, 주어진 카테고리 레이블에 알맞게 분류하는가 ex) 고양이사진 -> 고양이

#### Problem
- Semantic Gap : 컴퓨터가 보는 것, 즉 pixel values와 실제 대상과는 큰 차이가 있음

#### Challenges
- Viewpoint variation : 대상이 그대로일때, 카메라 구도가 조금만 바뀌어도 pixel은 모두 바뀐다.
- Illumination : 조명
- Deformation : 포즈, 위치 등의 변화
- Occlusion : 대상의 일부만 보일 때
- Background Clutter : 배경색과 겹쳐 보일 때 (보호색)
- Intraclass variation : 다른 모양, 사이즈, 색상, 나이,,등 클래스 내의 다양성이 존재

#### 시도한 방법
: edges를 찾아서 corners를 찾고 ... 이 방법을 각 카테고리마다 반복

💥 문제점1. super brittle

💥 문제점2. scalable approach가 아님. 종류 하나하나씩 다 해야함.

#### Data-Driven Approach
: 머신러닝을 통해 이미지를 학습하여 모델을 만들고, 그 모델을 통해 에측 및 평가

### 2. `Nearest Neighbor `
: train에서 데이터와 레이블을 모두 기억하고 predict에서 학습 이미지와 가장 유사한 것의 라벨로 예측한다.


→ '유사'하다고 어떻게 비교하는가?
: L1 거리를 사용하여 이미지 사이의 행렬의 거리를 계산

- 숫자들 사이의 크기가 비슷하다면 사진도 비슷할 것
- 사진의 숫자들을 모두 빼고 절댓값을 씌움 -> L1거리
- 이 방법을 사진의 모든 픽셀에 똑같이 적용, 그 후 나온 수를 모두 더해주면 두 사진 사이의 다른 정도가 나옴


💥 문제점. train 시간은 빠르지만, test 시간이 오래걸림. 모든 사진들을 다 빼주면서 계산해야하기 때문에

### 3. `K-Nearest Neighbor`
: 주변 k개를 봤을 때 가장 비슷한 것이 정답
(k=1일 때, Nearest Neighbor과 같음)

#### Distance Metric
: L1(Manhatten distance) - 다이아몬드
L2(Euclidean distance) - 원

#### Hyperparameters
: k, distance 처럼 직접 정해야하는 값. 초모수
- train/validation/test로 나눔
- train 데이터 셋에서 훈련된 값을 validation 데이터 셋으로 확인하며 하이퍼파라미터를 바꿔주고 test로 테스트하기
- 🔺 데이터셋, 문제 마다 모두 다름.

#### Cross-Validation
: fold로 데이터를 나누어서 돌아가면서 validation으로 놓고 평균값으로 최종 하이퍼파라미터를 설정함

#### 실무적으론..
→ Nearest Neighbor 와 K-Nearest Neighbor는 사용되지 않음
- predict 과정이 굉장히 오래 걸림
- 차원이 넓어질수록 필요한 데이터 수가 굉장히 많아짐

### 4. `Linear Classification`
- 이미지 숫자들 (32*32*3), weight → 10개 카테고리에 대한 점수
- 💥문제점. 카테고리마다 하나의 결과밖에 내지 못함.



48 changes: 48 additions & 0 deletions lecture04.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
## Lec4 - Introduction to Neural Networks
---

### Backpropagation과 Neural Network


- 임의의 복잡한 함수를 통해 어떻게 analytic gradient를 계산할까?
- computational graph를 사용해서 함수를 표현하게 됨으로써 backpropagation이라고 부르는 기술을 사용할 수 있게 된다.

`backpropagation`

: gradient를 얻기위해 computational graph 내부의 모든 변수에 대해 chain rule을 재귀적으로 사용

`forward pass`

: 입력값을 받아서 loss값을 구하기까지 계산해 가는 과정

`backward pass`

: forward pass가 끝난 이후 역으로 미분해가며 기울기 값들을 구해가는 과정

#### Patterns in Backward Flow
![image](https://user-images.githubusercontent.com/63354176/160359745-b469e38e-9a5d-4bcb-a349-f5882a1f4a9a.png)

#### Modularized implementation
![image](https://user-images.githubusercontent.com/63354176/160360260-d03fb655-a2ca-4304-b80c-7241176d6bcf.png)

- forward pass : 인자 값은 x와 y, 리턴 값 z=x*y
- backward pass : loss 값 L을 z로 미분한 값을 인자로, 리턴 값은 L을 x, y로 미분한 값

![image](https://user-images.githubusercontent.com/63354176/160360618-9a9b132d-f072-4f9d-8d4d-774717031bc2.png)
- dx = self.y * dz
- dy = self.x * dz

----
## Neural Networks
![image](https://user-images.githubusercontent.com/63354176/160360940-facb46f0-a1e8-44c1-8572-a773ccdfc4c0.png)

하나만 말고, 다른 W 레이어 두 개를 지나게 만들자! `f=W2*max(0, W1x)`

((뒤에 내용은 아직 이해가 잘 안돼서 나중에 추가하겠습니다))

레이어를 2개, 3개 ... 여러개를 씌우게 되는 것 = 인공 신경망
![image](https://user-images.githubusercontent.com/63354176/160361709-56c70eb1-760d-4755-898a-d0923d55c169.png)

`fully-connected layer`

: 중간중간에 모든 노드가 다음의 모든 노드에 영향을 끼치는 레이어
39 changes: 39 additions & 0 deletions lecture05.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
## Lec5 - Convolutional Neural Networks

### History of CNN

- 1957년: 최초로 perceptron을 구현, 가중치 W를 업데이트하는 update rule
- 1960년: Multilayer Perceptron Network인 Adaline/Madaline
- 1986년: backpropagation, 신경망 학습 시작. But 다시 암흑기
- 2006년: Deep Learning, 초기화에는 RBM, hidden Layer에서 가중치가 학습.
- 2012년: ImageNet 분류-> AlexNet

### Fast-forward to today: CNNs
이미지 분류, 이미지 검색, detection과 segmentation, 자율주행, face recognition, pose recognition,...
- Image captioning: 사진을 보고 이미지에 대한 설명을 하는 것 (CNN+RNN)

### Convolutional Neural Networks

#### convolution Layer
convolve filter을 이용해 인풋의 이미지 특징을 뽑아냄(depth는 같아야함)
- w_T*x+b
=> 28*28*1 의 activation map => 하나의 층 생성 => ... 반복 => 이미지 특징 추출

#### conv-> ReLU->pooling-> ...
여기서 ReLU는 0 이하 값들을 전부 0으로 만들어 검정색이 됨

#### activation map 과정
N: input size
F: filter 크기
output size = (N-F)/stride + 1
=> stride를 거칠수록 사이즈가 작아지는 문제 => `Padding`

#### 중간 summary
input size는 32, 64,128 ...
filter가 3이고 stride가 1이면 padding은 1
filter가 5이고 stride가 1이면 padding은 2

### Pooling
: 큰 특징값을 유지하면서 이미지 사이즈를 줄여주는 것 (주로 max pooling)