일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- Numpy data I/O
- 최대가능도 추정법
- 표집분포
- Python 특징
- boolean & fancy index
- 정규분포 MLE
- BOXPLOT
- Python 유래
- 가능도
- subplot
- unstack
- python 문법
- seaborn
- Operation function
- 카테고리분포 MLE
- scatter
- Python
- 딥러닝
- Numpy
- groupby
- type hints
- dtype
- Comparisons
- VSCode
- namedtuple
- 부스트캠프 AI테크
- ndarray
- Array operations
- pivot table
- linalg
- Today
- Total
또르르's 개발 Story
[Stage 1 - 02] Data Processing 본문
1️⃣ Goal
[BaseLine 작성] (추가 : 3/29, 기간 : 3/29 ~ 3/29)- [Data Processing]
- Face Recognition (추가 : 3/29)
- Cross-validation 사용 (추가 : 3/29)
- 데이터 불균형 해소 (추가 : 3/30)
- Data Augumentation (추가 : 3/30)
- Generator의 초당 Batch 처리량 측정 및 향상 (추가 : 3/30) - [Model]
- ResNet 152층 시도 (추가 : 3/29)
- Efficient Net 시도 (추가 : 3/29)
- YOLO 시도 (추가 : 3/31)
- Pre-trained 모델에 Fine-tuning 하기 (추가 : 3/29)
- Model의 초당 Batch 처리량 측정 및 향상 (추가 : 3/30) - [Training]
- 앙상블 시도 (추가 : 3/29)
- Hyperparameter 변경 (추가 : 3/29, 기간 : 3/29 ~)
- Learning Schedular 사용 (추가 : 3/29)
- Model의 초당 Batch 처리량 측정 (추가 : 3/30) - [Deploy]
- Python 모듈화 (추가 : 3/30)
2️⃣ Learning
[Stage 1 - 이론] Data Processing
1️⃣ Data Augumentation 라이브러리 torchvision.transforms - RandomCrop : 랜덤으로 crop을 해서 input으로 넣는 방법 - Flip : 상하 또는 좌우로 반전 / 하지만 flip은 사진을 거꾸로 찍는 사람은 거의 없으..
dororo21.tistory.com
[Stage 1 - 이론] Model
1️⃣ Model 정의 1) nn.Modules nn.Modules를 상속받아서 사용하면 model 객체 자체를 print (오른쪽 위) 하거나 modules() 함수를 사용 (오른쪽 아래)해서 모듈의 구조를 파악할 수 있습니다. 또한, forward 함..
dororo21.tistory.com
3️⃣ Main Task
1) Face 인식
얼굴 인식은 마스크 때문에 가려지는 부분이 많았기 때문에 눈 인식과 코 인식을 섞어서 사용
haarcascade는 너무 error가 많아서 facenet-pytorch로 도전했습니다.
github.com/timesler/facenet-pytorch
timesler/facenet-pytorch
Pretrained Pytorch face detection (MTCNN) and recognition (InceptionResnet) models - timesler/facenet-pytorch
github.com
facenet-pytorch를 사용하자 얼굴 부분만 crop 해서 나오는 것을 확인했습니다. (추가 : 3/31)
모든 train data들의 path를 불러옵니다.
imgs_path = [filepath for filepath in glob.iglob(f'input/data/train/images/*/*', recursive=True)]
미리 pretrained 되어있는 vggface2를 가져다가 사용합니다.
LFW 정확도가 0.9965를 자랑한다고 써있습니다.

Face Recognition의 강자인 MTCNN을 가져온 후 InceptionResnet의 face model을 평가(eval)용으로만 사용해 분류합니다.
# If required, create a face detection pipeline using MTCNN:
mtcnn = MTCNN()
resnet = InceptionResnetV1(pretrained='vggface2').eval()
새로운 image folder에다가 crop이미지를 저장합니다.
for imgpath in tqdm(imgs_path):
try:
imgpath_split = imgpath.split("/")
img = Image.open(imgpath)
new_path_name = os.path.join("input", "data", "train", "crop_images", imgpath_split[-2],imgpath_split[-1])
# Get cropped and prewhitened image tensor
img_cropped = mtcnn(img, save_path=new_path_name)
# Calculate embedding (unsqueeze to add batch dimension)
img_embedding = resnet(img_cropped.unsqueeze(0))
# Or, if using for VGGFace2 classification
resnet.classify = True
img_probs = resnet(img_cropped.unsqueeze(0))
except:
print(imgpath+" is error")
총 crop 된 데이터는 18456개이며, 약 400개 정도의 data가 face를 못 찾은 것인지 오류가 발생했습니다.
모든 data는 운 좋게도 160x160x3 크기로 crop 되었습니다.
crop_imgs_path = [filepath for filepath in glob.iglob(f'input/data/train/crop_images/*/*', recursive=True)]
>>> print(len(crop_imgs_path))
18456
2) Generator의 초당 Batch 처리량 측정
Face 인식을 통해 얼굴을 crop 한 후, 160x160x3 크기로 일정하게 사용하기 때문에 transform에서 resize를 할 필요가 사라졌습니다.
crop 하기 전 batch/s 속도입니다.
start = time.time()
for batch_in,batch_out in tqdm(train_iter):
pass
>>> print("time : ", time.time()-start)
time : 98.58156418800354
즉, 18,456개 / 98초 = 188 batch/s 입니다.
crop한 후 batch/s 속도입니다.
start = time.time()
for batch_in,batch_out in tqdm(train_iter):
pass
>>> print("time : ", time.time()-start)
time : 21.3472101688385
즉, 18,456개 / 21초 = 878 batch/s 입니다.
4️⃣ Sub Task
1) PIL Image의 Crop과 Save
위에서 facenet을 사용할 때 error가 나서 face crop이 되지 않은 data들은 직접 crop 했습니다.
PIL의 Image에서 제공하는 Crop과 Save를 사용하면 쉽게 Crop 후 저장이 가능합니다.
아래는 전체 코드입니다.
error_imgs_path은 "error가 발생한 img들의 path 리스트"입니다.
imgs = []
area = (120,170,280,330)
for path in error_imgs_path: # error가 생긴 img들의 path
img_name = path.split("/")[-1]
img = Image.open(path)
img = img.crop(area)
img.save("input/data/eval/crop_images/"+img_name, "jpeg")
Crop은 img.crop() 함수를 사용하며, tuple형태의 parameter를 갖습니다.
area=(왼쪽위x축점,왼쪽위y축점,오른쪽아래x축점,오른쪽아래y축점)
Save는 img.save() 함수를 사용하며, 경로+이름 parameter와 확장자(jpeg)를 갖습니다.
5️⃣ Evaluation
날짜 | Data processing | Model | Training | Time | Accuracy | F1 |
3/29 | - ResNet-50 - |
- Hyperparmeter 설정 - |
7h 32m | 61.87% | 0.52% | |
3/31 | - Face Recognition - |
36m | 65.05% | 0.56% |
* F1 Score

1) Face Recognition
Face Recognition은 Facenet을 사용해서 수행했고, 몇 개의 image 확인 결과 crop이 정말 잘 된 것을 알 수 있었습니다.
또한, LFW Accuracy도 0.996 정도로 상당히 높은 정확도를 자랑했습니다.
다만 아쉬운 점은 error가 발생한 image들에 대해서는 부정확하게 crop을 수행했다는 점입니다.
2) Generator의 초당 Batch 처리량 측정
Crop을 하니 확실히 초당 batch 처리량이 빨라지고, transform의 resize를 제거하는 효과를 가졌습니다.
3) 차후 목표
- Efficient-net 시도
Image Classification 최고의 성능을 자랑하기 때문에 Efficient-net의 Pre-train을 사용합니다. - Pre-trained 모델과 fine-tuning 사용하기
'[P Stage 1] Image Classification > 프로젝트' 카테고리의 다른 글
[Stage 1 - 06] 최적의 Hyperparameter 찾기 (0) | 2021.04.05 |
---|---|
[Stage 1 - 05] Remote Server에서 NNI (Auto ML) 사용하기 (0) | 2021.04.04 |
[Stage 1 - 04] Focal Loss (0) | 2021.04.02 |
[Stage 1 - 03] Model & Optimizer (0) | 2021.04.01 |
[Stage 1 - 01] BaseLine 작성 (0) | 2021.03.30 |