딥러닝

[딥러닝] 딥러닝 다중분류 모델 만들기 (3가지 동물 분류) 전처리

퓨어맨 2022. 7. 22. 13:48
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
# os : 파일 및 폴더 처리에 관련된 라이브러리
import os
# 각 폴더별 경로 지정
duck_dir = '오리/'
raccoon_dir = '너구리/'
platypus_dir = '오리너구리/'
# os.listdir : 해당 경로에 있는 파일명들을 리스트로 순서대로 저장
duck_fnames = os.listdir(duck_dir)
raccoon_fnames = os.listdir(Raccoon_dir)
platypus_fnames = os.listdir(platypus_dir)
# os.path.join : 폴더 경로와 파일명을 결합
test_path = os.path.join(duck_dir, duck_fnames[50])
# 이미지를 로딩하는 함수(데이터로드, 파일 오픈 및 사이즈 조정, 배열로 변경)
def load_images(folder_path, file_names, img_size_shape=(224,224)) :
    images = []
    
    for i in file_names :
        # 폴더 경로 + 파일명 합치기
        path = os.path.join(folder_path, i)
        # 파일 오픈 및 크기조정
        img = Image.open(path).resize(img_size_shape).convert('RGB')
        # numpy 배열로 변경후에 리스트에 저장
        images.append(np.array(img))
     
    # 리스트 자체도 numpy 배열로 변경해서 반환
    return np.array(images)
train_duck = load_images(duck_dir, duck_fnames)
train_raccoon = load_images(raccoon_dir, raccoon_fnames)
train_platypus = load_images(platypus_dir, platypus_fnames)

 

print(train_duck.shape)
print(train_raccoon.shape)
print(train_platypus.shape)
(400, 224, 224, 3)
(400, 224, 224, 3)
(400, 224, 224, 3)

 

plt.imshow(train_raccoon[1]);

 

X = np.concatenate([train_duck, train_raccoon, train_platypus])
y = np.array ([0]*400 + [1]*400 + [2]*400)

 

print(X.shape)
print(y.shape)
(1200, 224, 224, 3)
(1200,)

 

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.2,
                                                    random_state=11
                                                   )
                                                   
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
(960, 224, 224, 3)
(960,)
(240, 224, 224, 3)
(240,)

 

 

NPZ파일로 변환(Numpy Zip)

  • 압축된 배열 파일로 데이터를 변환
np.savez_compressed('animals.npz',   # 저장될 폴더 경로 및 파일명 설정
                    X_train = X_train,
                    X_test = X_test,
                    y_train = y_train,
                    y_test = y_test
                   )