본문 바로가기
인공지능

MNIST 데이터 읽기

by judy@ 2023. 7. 3.

mnist 데이터는 yann 교수님의 페이지에서 다운로드 가능한데, png 등이 아니라 ubyte 형식의 데이터이다. python-mnist 라이브러리를 사용하면 간단하게 데이터를 array 형태로 로드할 수 있어서 이를 사용하여 로드해본다

 

목차

     

    1. 파일 다운로드

    http://yann.lecun.com/exdb/mnist/ 이 링크에서 아래와 같이 파란 상자 안의 링크를 눌러 데이터를 다운받는다.

     

    2. 사용할 라이브러리 임포트

    # 설치 명령어
    !pip install numpy matplotlib python-mnist
    
    # 임포트
    import numpy as np
    import matplotlib.pyplot as plt
    
    from mnist import MNIST

     

    3. 데이터 로드

    mndata = MNIST('../data/mnist/') # '../data/mnist/' 부분은 다운받은 파일이 들어있는 디렉토리의 경로로 설정
    
    train_images, train_labels = mndata.load_training()
    test_images, test_labels = mndata.load_testing()
    
    train_images, train_labels
    # Outputs
    ([[0,
       0,
    ...
       0,
       0,
       0],
      ...],
     array('B', [5, 0, 4, 1, 9, 2, 1, 3, 1, 4, 3, 5, 3, 6, 1, 7, ...

     

    4. numpy array로 변환

    로드한 데이터는 리스트 형태로 바로 사용할 수 없음

     

    train_images = np.array(train_images).reshape((-1, 28, 28))
    train_labels = np.array(train_labels)
    test_images = np.array(test_images).reshape((-1, 28, 28))
    test_labels = np.array(test_labels)
    
    train_images.shape, train_labels.shape, test_images.shape, test_labels.shape

     

    5. 이미지와 레이블 확인해보기

    idx = 0
    
    plt.title(train_labels[0])
    plt.imshow(train_images[0], cmap='gray')
    plt.show()

     

    반응형