[8주차 - Day2] monthly project2

2023. 6. 22. 15:00BOOTCAMP/프로그래머스 인공지능 데브코스

Problem 1. 데이터셋 다운로드 분석하기

 

# 깃허브에서 데이터셋 다운로드하기
! git clone https://github.com/ndb796/Scene-Classification-Dataset
# 폴더 안으로 이동 % cd Scene-Classification-Dataset
# 깃허브에서 데이터셋 다운로드하기
!git clone https://github.com/ndb796/Scene-Classification-Dataset
# 폴더 안으로 이동
%cd Scene-Classification-Dataset
Cloning into 'Scene-Classification-Dataset'... remote: Enumerating objects: 24303, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 24303 (delta 0), reused 6 (delta 0), pack-reused 24297
Receiving objects: 100% (24303/24303), 364.74 MiB | 26.63 MiB/s, done. Resolving deltas: 100% (40/40), done. Checking out files: 100% (24341/24341), done. /content/Scene-Classification-Dataset

 데이터셋 설명

  • 장면(scene) 데이터셋은 24,335개의 다양한 자연 경치(scene) 이미지로 구성되어 있습니다.
  • 총 6개의 클래스(class)로 구성됩니다.
0. 빌딩(buildings)
1. 숲(forests)
2. 빙하(glacier)
3. 산(mountains)
4. 바다(sea)
5. 거리(street)
  • 각 이미지는 150 X 150 크기를 가집니다.
import os
import pandas as pd

path = 'train-scene classification/'

# 전체 이미지 개수 출력하기
file_list = os.listdir(path + 'train/')
print('전체 이미지의 개수:', len(file_list))

# 학습 이미지 확인하기
dataset = pd.read_csv(path + 'train.csv')
print('학습 이미지의 개수:', len(dataset))
print('학습 이미지별 클래스 정보')
dataset.head()

전체 이미지의 개수: 24335

학습 이미지의 개수: 17034

학습 이미지별 클래스 정보

 

Problem 2. 클래스별 학습 이미지 개수 출력하기

클래스별 학습 이미지의 개수를 구하세요.

  • pandas 라이브러리의 데이터프레임(DataFrame)을 이용하면 매우 간단한 코드로 구현할 수 있습니다.
  • 예를 들어 label 컬럼(column)의 값이 3인 데이터의 개수는 다음과 같이 확인 가능합니다.
my_frame [my_frame.label == 3]
총 학습 이미지의 수는 17034개, 클래스의 개수는 6개입니다.
클래스 0: 2628
클래스 1: 2745
클래스 2: 2957
클래스 3: 3037
클래스 4: 2784
클래스 5: 2883
import matplotlib.pyplot as plt
import seaborn as sns

plt.rcParams['figure.figsize'] = (8.0, 6.0) # 그림의 기본 크기 설정

# 각 클래스별 개수 출력
print('클래스 0의 개수:', len(dataset[dataset.label == 0]))
print('클래스 1의 개수:', len(dataset[dataset.label == 1]))
print('클래스 2의 개수:', len(dataset[dataset.label == 2]))
print('클래스 3의 개수:', len(dataset[dataset.label == 3]))
print('클래스 4의 개수:', len(dataset[dataset.label == 4]))
print('클래스 5의 개수:', len(dataset[dataset.label == 5]))

# 각 클래스에 따른 학습 이미지의 개수를 출력하기
fig, ax = plt.subplots(figsize = (10, 4)) # 그림 크기 설정
sns.countplot(x ='label', data=dataset)
plt.xlabel("Class Label")
plt.ylabel("Number of Samples")
plt.show()

클래스 0의 개수: 2628

클래스 1의 개수: 2745

클래스 2의 개수: 2957

클래스 3의 개수: 3037

클래스 4의 개수: 2784

클래스 5의 개수: 2883

특정한 이미지를 불러와 화면에 출력하기

  • PIL 라이브러리로 특정한 경로의 이미지를 불러와 numpy 객체로 만들 수 있습니다.
img = np.asarray(Image.open(이미지 경로))
  • Numpy 객체는 matplotlib를 이용해 간단히 시각화할 수 있습니다.
plt.imshow(img)
plt.show()
  • 원본 이미지의 크기가 너무 크므로, 모든 이미지를 64 X 64 X 3의 크기로 변경합니다.
from skimage.transform import resize
from PIL import Image
import numpy as np

img = Image.open(path + 'train/' + file_list[0])
img = np.asarray(img)
img = resize(img, (64, 64, 3))
print('이미지의 해상도:', img.shape)

# 이미지 출력하기
plt.imshow(img)
plt.show()

이미지의 해상도: (64, 64, 3)

Problem 3. 학습/검증 데이터셋 구성하기

  • 이미지는 별도의 폴더 안에 존재합니다.
  • 모든 이미지를 읽어 와 전체 이미지 데이터를 Numpy 객체로 구성할 필요가 있습니다.
  • 다음과 같이 X_train, y_train, X_test, y_test 변수의 shape이 구성되도록 소스코드를 작성하세요.
for index, row in train_dataset.iterrows():
      print(index, row['image_name'], row ['label'])
import time


######### 학습 데이터셋 #########
start_time = time.time() # 시작 시간

# 학습 데이터셋 구성하기
X_train = []
y_train = []

# 데이터 정보를 하나씩 확인하며
for index, row in train_dataset.iterrows():
    # 이미지 정보를 배열에 담기
    img = Image.open(path + 'train/' + row['image_name'])
    img = np.asarray(img)
    img = resize(img, (64, 64, 3))
    X_train.append(img)
    y_train.append(row['label']) # 레이블 정보를 배열에 담기

X_train = np.asarray(X_train) # Numpy 객체로 변환
y_train = np.asarray(y_train) # Numpy 객체로 변환

print("소요된 시간(초 단위):", time.time() - start_time) # 실행 시간

######### 검증 데이터셋 #########
start_time = time.time() # 시작 시간

# 검증 데이터셋 구성하기
X_val = []
y_val = []

# 데이터 정보를 하나씩 확인하며
for image_name, label in zip(val_dataset['image_name'], val_dataset['label']):
    # 이미지 정보를 배열에 담기
    img = Image.open(path + 'train/' + image_name)
    img = np.asarray(img)
    img = resize(img, (64, 64, 3))
    X_val.append(img)
    y_val.append(label) # 레이블 정보를 배열에 담기

X_val = np.asarray(X_val) # Numpy 객체로 변환
y_val = np.asarray(y_val) # Numpy 객체로 변환

print("소요된 시간(초 단위):", time.time() - start_time) # 실행 시간
소요된 시간(초 단위): 74.47658967971802
소요된 시간(초 단위): 17.42264461517334

 

데이터셋 구성 확인하기

print('학습 이미지:', X_train.shape)
print('학습 레이블:', y_train.shape)
print('검증 이미지:', X_val.shape)
print('검증 레이블:', y_val.shape)
학습 이미지: (13627, 64, 64, 3)
학습 레이블: (13627,)
검증 이미지: (3407, 64, 64, 3)
검증 레이블: (3407,)