Sacred + Omniboard

Sacred 기본 소개: 2020/02/21 - [AI&BigData/MLOps] - Sacred - 머신러닝 실험관리 도구

  • Omniboard는 Sacred를 위한 웹 대시보드
  • MongoDB를 연결해 Sacred의 실험 들과 각 실험들의 메트릭, 로그 들의 의 가시화를 도와줌
  • React, Node.js, Express, Bootstrap으로 작성됨

특징들

  • 실험의 관리
    • 모든 실험들이 tablular format으로 리스트 됨(정렬, 리오더, 리사이징 가능한 컬럼)
    • 가장 마지막 실험의 설정을 자동으로 불러올 수 있음
    • 선택한 컬럼의 show/hide 가능
    • 메트릭 컬럼 추가 가능(예: minimum validation loss, maximum training accuracy 등)
    • 커스텀 컬럼 추가 가능
    • 각 실험에 태그나 노트를 추가 가능
    • 모든 컬럼을 정렬, 필터링 가능
  • 실험의 드릴다운
    • 메트릭 그래프를 보여줌
    • 콘솔 결과를 보여줌
    • 모든 런타임 라이브러리
    • 소스코드를 보거나 다운로드
    • 아티팩트(실행에 의해 생성된 파일)를 보거나 다운로드
    • 호스트의 하드웨어 스펙(예: OS 버전, CPU/GPU 디바이스 정보, 드라이버 버전 등)을 보여줌
    • git 해쉬, 버전 컨트롤 정보를 보여줌
  • 실험의 비교
    • 다중의 실험의 메트릭들을 하나의 그래프에서 비교
    • 두개의 실험들의 캡쳐된 결과를 비교
    • 두개의 실험들의 소스파일을 비교
    • 두개의 실험의 설정값을 비교

테스트

소스코드

  • tensorflow 2.0 튜토리얼 fashion mnist classification 소스코드를 기반으로 변경

  • 소스코드 github주소

      import os
      import numpy as np
    
      import tensorflow as tf
      from tensorflow import keras
    
      from sacred import Experiment
      from sacred.observers import MongoObserver
    
      ex = Experiment('fashion_mnist')
      ex.observers.append(MongoObserver.create(url='localhost:27017',
                                              db_name='sacred_omniboard'))
    
      @ex.config
      def get_config():
          num_epochs = 5
          hidden_size = 128
          num_classes = 10
    
      @ex.capture
      def set_model_path(seed):
          model_dir = os.getcwd()
          model_filename = 'model/my_model_{}.h5'.format(seed)
          model_path = os.path.join(model_dir, model_filename)
    
          return model_path
    
      def write_logs(ex, logs):
          #print(logs)
          ex.log_scalar('loss', logs.get('loss'))
          ex.log_scalar('val_loss', logs.get('val_loss'))
          ex.log_scalar('accuracy', logs.get('accuracy'))
          ex.log_scalar('val_accuracy', logs.get('val_accuracy'))
    
      @ex.capture
      def create_model(hidden_size, num_classes):
          # create model
          model = keras.Sequential([
                                      keras.layers.Flatten(input_shape = (28, 28)),
                                      keras.layers.Dense(hidden_size, activation='relu'),
                                      keras.layers.Dense(num_classes, activation='softmax')
          ])
    
          model.compile(optimizer='adam',
                      loss='sparse_categorical_crossentropy',
                      metrics=['accuracy'])
    
          model.summary()
    
          return model
    
      @ex.capture
      def train(num_epochs):
          print(tf.__version__)
    
          # data load
          fashion_mnist = keras.datasets.fashion_mnist
          (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
    
          '''
          print("type(train_images): {}".format(type(train_images)))
          print("train_images.shape: {}, train_labels.shape: {}".format(train_images.shape, train_labels.shape))
          print("train_images.shape: {}, train_labels.shape: {}".format(test_images.shape, test_images.shape))
          '''
    
          class_names = ['T-shirts/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
                          'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
    
          # data preprocessing
          train_images = train_images / 255.0
          test_images = test_images / 255.0    
    
          # create model
          model = create_model()
    
          # callback
          cp_callback = keras.callbacks.LambdaCallback(
              on_epoch_end = lambda epoch, logs: write_logs(ex, logs)
          )
    
          # training        
          model.fit(train_images, train_labels, epochs=num_epochs,
                      validation_data = (test_images, test_labels),
                      callbacks = [cp_callback])
    
          # model save
          model_path = set_model_path()
          model.save(model_path)
    
          # add artifact: content_type - mimetype
          ex.add_artifact(filename=model_path, content_type='application/x-hdf5')
    
          # evaluate
          test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
          print("test_loss: {}, test acc: {}".format(test_loss, test_acc))
    
      @ex.automain
      def run():
          train()

실행하기

  • omniboard 설치

      npm install -g omniboard
  • 코드 작성 후 테스트 스텝

    1. MongoDB 서비스 시작

    2. 코드를 작성(sacred mongodb observer를 사용하여 데이터를 저장)

    3. 코드를 실행

    4. Omniboard 시작

       omniboard -m hostname:port:database
    5. 웹 브라우저에서 http://localhost:9000 주소로 접속

스크린샷

  • omniboard list view
  • Metrics Plot
  • Captured Out
  • Experiment Details
  • Host Info
  • Run Info
  • Aritifacts
  • Source Files
  • Config

참고문서

'AI&BigData > MLOps' 카테고리의 다른 글

AutoML 도구 Microsoft NNI  (0) 2020.03.02
Sacred - 머신러닝 실험관리 도구  (1) 2020.02.21