Python(Colab) 파이토치(Pytorch) + 딥러닝 + CNN 사용해보기
2023. 6. 21. 22:47ㆍ파이썬/머신러닝 및 딥러닝
1. 기초설정
import torch
import torch.nn as nn
import torch.optim as optim
2. 데이터 설정
# 예제 데이터 준비
# 배치 크기 / 채널 / 세로 / 가로
inputs = torch.Tensor(1,1,28,28)
print(inputs.shape)

3. 컨볼루젼2d 사용
conv1 = nn.Conv2d(in_channels=1,out_channels=32,kernel_size=3, padding='same')
out1 = conv1(inputs)
print(out1.shape)

해석
첫번째 ) 1개 입력 데이터 / 32개 출력 데이터 / 필터 사이즈 (3,3) / padding으로 주위가 0(black) 설정
두번째) 예시 데이터를 컨볼루전에 대입
세번째) 결과 모양 출력 (padding설정으로 크기가 줄지 않았다.)
4. pooling하기
pool= nn.MaxPool2d(kernel_size=2)
out2 = pool(out1)
print(out2.shape)

해석
첫번째) maxpooling(필터별 각 최대값만 저장)하는 모델을 형성한다. (필터는 2*2)
두번째) 모델에 cov2d를 적용했던 데이터 적용
세번째) 결과 확인 2*2 필터로 핵심적인 feature만 추출했기 때문에 사이즈 감소
5. 두번째 컨볼루젼
conv2 = nn.Conv2d(in_channels=32,out_channels=64,kernel_size=3, padding='same')
out3 = conv2(out2)
print(out3.shape)

해석
첫번째) pooling한 데이터의 채널이 32개 임으로 input이 32개
두번째 ) 32개 입력 데이터 / 64개 출력 데이터 / 필터 사이즈 (3,3) / padding으로 주위가 0(black) 설정
세번째) 예시 데이터를 컨볼루전에 대입
네번째) 결과 모양 출력 (padding설정으로 크기가 줄지 않았다.)
6. 두번째 pooling
pool= nn.MaxPool2d(kernel_size=2)
out4 = pool(out3)
print(out4.shape)

해석
첫번째) maxpooling(필터별 각 최대값만 저장)하는 모델을 형성한다. (필터는 2*2)
두번째) 모델에 2번쨰 cov2d를 적용했던 데이터 적용
세번째) 결과 확인 2*2 필터로 핵심적인 feature만 추출했기 때문에 사이즈 감소
7. fc 모델에 넣기 전 평탄화 (선형회귀 모델에 넣기 위해)
flatten = nn.Flatten()
out5 = flatten(out4)
out5.shape # 64 * 7 * 7

해석
Batch_size 1 X Channel 64 X Row 7 X Col 7 = 3136
8. 선형회귀 모델에 넣기 (fc Layer 역할)
fc = nn.Linear(3136,10)
out6 = fc(out5)
print(out6.shape)

해석
선형회귀 모델에 3136개의 input을 넣고 10개의 ouput을 받겠다.
728x90
'파이썬 > 머신러닝 및 딥러닝' 카테고리의 다른 글
Python(Colab) 파이토치(Pytorch) + 딥러닝 + 전이학습 (Alien vs predator) (0) | 2023.06.24 |
---|---|
Python(Colab) 파이토치(Pytorch) + 딥러닝 + CNN + 손글씨 데이터 (0) | 2023.06.21 |
Python(Colab) 파이토치(Pytorch) + 딥러닝 + CNN기초(이미지) (2) | 2023.06.21 |
Python(Colab) 파이토치(Pytorch) + 활성화 함수 (1) | 2023.06.21 |
Python(Colab) 파이토치(Pytorch) + 딥러닝 해보기 (0) | 2023.06.20 |