[AutoML][AutoKeras] [OSS] AutoKeras로 자동학습(AutoML) 하기

최근 회사 업무를 하면서 AutoML을 조사할 일이 있었는데, AutoKeras가 작년말 정식 Release 되었다는 것을 알았다. AutoKeras는 Texas A&M에서 만든 것으로 많은 AutoML솔루션들이 Table 데이터 처리를 위한 최적의 머신러닝 모델을 찾아주는 것에 반해, Google AutoML과 마찬가지로 비정형 데이터까지 모델링 해 준다.

 

 

AutoKeras는 무엇보다 설치가 간단하다. 기존에 사용하던 머신에 AutoKeras 패키지만 설치해 주면 잘 동작한다(설치조건: Tensorflow 2.1, Python 3.6). GPU 설정은 공통된 부분이고, 요즘은 AWS SageMaker나 GCP AI Platform에서 설정되어 나오니 크게 신경쓰지 않아도 된다.

pip install autokeras


AutoML을 가능하게 한 3가지 요소는 1) Auto Feature Engineering 2) Neural Search Architecture 3) Hyper Parameter Tuning으로 각각에 대한 설명은 인터넷에 많이 공개되어 있다. (원리를 잘 몰라서 설명을...)

간단한 예제를 통해 얼마나 결과를 잘 뽑아주는 지 비교해 보았다. 간단한 Table Data로는 큰 차이를 볼 수 없기에, IMDB 영화 평가를 Sentiment Analysis하는 예제를 수행해 보았다. 특별히 모델링이라고 할 것도 없고, TextClassifier를 만들고, fit 한 것이 전부다. AutoKeras 홈페이지에는 fit 할 때 epochs을 따로 주지 않아 1,000으로 디폴트 설정되는데 너무 오래 걸려서 15번만 하게 바꾸었다.

import numpy as np
import tensorflow as tf

import autokeras as ak


def imdb_raw():
    max_features = 20000
    index_offset = 3  # word index offset

    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(
        num_words=max_features,
        index_from=index_offset)
    x_train = x_train
    y_train = y_train.reshape(-1, 1)
    x_test = x_test
    y_test = y_test.reshape(-1, 1)

    word_to_id = tf.keras.datasets.imdb.get_word_index()
    word_to_id = {k: (v + index_offset) for k, v in word_to_id.items()}
    word_to_id["<PAD>"] = 0
    word_to_id["<START>"] = 1
    word_to_id["<UNK>"] = 2

    id_to_word = {value: key for key, value in word_to_id.items()}
    x_train = list(map(lambda sentence: ' '.join(
        id_to_word[i] for i in sentence), x_train))
    x_test = list(map(lambda sentence: ' '.join(
        id_to_word[i] for i in sentence), x_test))
    x_train = np.array(x_train, dtype=np.str)
    x_test = np.array(x_test, dtype=np.str)
    return (x_train, y_train), (x_test, y_test)


# Prepare the data.
(x_train, y_train), (x_test, y_test) = imdb_raw()
print(x_train.shape)  # (25000,)
print(y_train.shape)  # (25000, 1)
print(x_train[0][:50])  # <START> this film was just brilliant casting <UNK>

# Initialize the TextClassifier
clf = ak.TextClassifier(max_trials=3, epochs=15)
# Search for the best model.
clf.fit(x_train, y_train)
# Evaluate on the testing data.
print('Accuracy: {accuracy}'.format(clf.evaluate(x_test, y_test)))


결과는 20분쯤 뒤에 나왔고 (AWS g4dn.2xlarge), 69.3% 정도의 정확도를 보였다. (Confusion Matrix로 좀 더 세밀하게 평가해야 하지만, 일단 AutoML을 소개하는 정도여서)

Accuracy: [0.6931472323129854, 0.5]


AutoML이 아닌 Keras로 LSTM 모델을 통해 평가하여 비교해 보았다. (소스는 Keras 홈페이지에서)

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

from __future__ import print_function

from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding
from keras.layers import LSTM
from keras.datasets import imdb

max_features = 20000
# cut texts after this number of words (among top max_features most common words)
maxlen = 80
batch_size = 32

print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')

print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)

print('Build model...')
model = Sequential()
model.add(Embedding(max_features, 128))
model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))

# try using different optimizers and different optimizer configs
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

print('Train...')
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=15,
          validation_data=(x_test, y_test))
score, acc = model.evaluate(x_test, y_test,
                            batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)


15분 정도 소요됐고 AutoKeras보다 10% 정도 더 나은 결과를 보여줬다. 꽤 큰 차이이긴 하지만, AutoKeras 학습 시 Epochs을 대폭 줄여서 실행한 원인이 클 것이다. 도메인과 AI 모델링에 전문성을 갖고 있다면 굳이 자원을 과다하게 사용해 가며 AutoML을 사용할 필요는 없지만, 단지 데이터를 불러오는 것으로도 나쁘지 않은 결과를 얻을 수 있어 나 같은 초중급 분석가가 활용하기엔 괜찮아 보인다.

Test accuracy: 0.81112


컨설팅회사 캡제미나이는 AutoML 솔루션을 평가하면서 현재 가지고 있는 공통적 약점을 정리하였다.
https://www.capgemini.com/gb-en/2020/02/automatic-machine-learning/

  • Unsupervised Learning: as unsupervised learning does not rely on labelled datasets, there is no clear measure of success that can be used to assess the quality of results to compare algorithms directly.
  • Complex Data Types: most AutoML systems initially designed to work with structured, tabular or relational data, then further extended to handle unstructured data such as text and images. However, by now, network data and web data are still not included in any AutoML products.
  • Feature Engineering Embedded with Domain Knowledge: some AutoML systems offer automatic feature engineering such as DataRobot, H2O Driverless AI, but none of them could incorporate domain knowledge into the ML process.

현업이 바로 이용하기에 가장 큰 허들은 세번째 Domain Data와 결합되지 않는 Feature Engineering 일 듯 싶다. 그렇다 하더라도, 데이터 분석이나 통계에 경험이 있는 현업 종사자들이 AI 모델링을 배우지 않은 상태에서 일부 전처리만으로 비교적 최적 결과를 얻어낼 수 있다는 건 충분히 매력적일 것이다.

[출처] https://magoker.tistory.com/27

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86449
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78884
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95640
46 [데이터분석 & 데이터 사이언스] 수많은 데이터 사이언티스트들이 직장을 떠나는 이유는 무엇인가? file 졸리운_곰 2025.03.09 903
45 [데이터분석][파이썬][python] 한글 글꼴 사용 (matplotlib) 졸리운_곰 2024.04.18 1360
44 [데이터분석 & 데이터 사이언스] 데이터에 관한 꼭 알아야 할 오해와 진실 12가지 졸리운_곰 2024.01.17 1315
43 [데이터분석][파이썬][python] Awesome Dash Awesome file 졸리운_곰 2021.07.10 2340
42 [데이터분석][파이썬][python] ???? Introducing Dash ???? file 졸리운_곰 2021.07.10 1608
41 [dataset] (한글) 욕설 감지 데이터셋 file 졸리운_곰 2021.05.12 1559
40 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1763
39 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1605
38 [데이터분석][데이터 사이언스][python][Dash] Python, Dash 및 Plotly를 사용하여 COVID-19 사례 데이터 시각화 file 졸리운_곰 2021.03.28 1501
37 [데이터분석][머신러닝] When not to use machine learning or AI Adventures in wishful thinking, nonstationarity, and pattern-finding / 기계 학습 또는 AI를 사용하지 않아야하는 경우 희망찬 사고, 비정상 성, 패턴 찾기의 모험 file 졸리운_곰 2021.03.28 21622
36 [MSA][머신러닝] 쿠버네티스 기반의 End2End 머신러닝 플랫폼 Kubeflow #1 - 소개 file 졸리운_곰 2021.03.21 1136
35 [데이터사이언스] 데이터 과학자를위한 3 가지 훌륭한 디자인 패턴, 3 Great Design Patterns for Data Scientists file 졸리운_곰 2021.03.04 782
34 [데이터분석] 시계열 데이터에 AI를 사용하는 이유는 무엇입니까? file 졸리운_곰 2021.02.28 1193
33 [데이터분석] AI 예측 및 이상 탐지를위한 시계열 데이터 전처리 file 졸리운_곰 2021.02.28 1031
32 [데이터분석] bitcoin analysis 비트 코인 시계열 데이터에 대한 AI 이상 탐지 file 졸리운_곰 2021.02.27 1592
31 [데이터분석 & 데이터 사이언스] How To Create a Data Science Portfolio Website file 졸리운_곰 2021.02.14 1824
30 [데이터수집4] 오픈 API 데이터 수집 (소셜미디어 데이터 수집) file 졸리운_곰 2020.06.12 1951
29 [데이터수집3] 관계형 데이터베이스 데이터 수집 file 졸리운_곰 2020.06.12 1319
28 [데이터수집2] 분산시스템 로그 수집 (빅데이터 수집) file 졸리운_곰 2020.06.12 1493
27 [데이터수집1] 웹 크롤링, 웹 스크래핑 file 졸리운_곰 2020.06.12 1804
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED