apache mxnet으로 배워보는 딥러닝(deep learning) - 김무현 (aws 솔루션즈아키텍트)

Post on 23-Jan-2018

467 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

김무현 솔루션즈아키텍트, AWS

2017년 11월 1일

Apache MXNet으로 배워보는 딥러닝

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

강연 중 질문하는 법

자신이 질문한 내역이 표시되며, 전체 공개로 답변된 내용은 검은색,

질문자 본인에게만 공개로 답변된 내용은 붉은 색으로 돌아옵니다.

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

순서

• 머신러닝/딥러닝이란

• 딥러닝과 관련된 Amazon AI 서비스들

• 이미지 분석에 사용되는 Convolutional Neural Network

• Apache MXNet 101

• Fashion MNIST 분석 예제

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

인공지능, 머신러닝, 딥러닝

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Supervised Learning

Input

Label

Machine Learning Algorithm

래프라도

Prediction

고양이

학습 데이터

?Label

래프라도

모델 조정

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Unsupervised Learning

Input

Machine

Learning

AlgorithmPrediction

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

학습 과정 – 데이터를 학습, 검증, 테스트용으로 나누기

All Labeled Dataset

Training Data

70% 30%

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

학습 과정 – 학습 데이터를 이용한 Learning

All Labeled Dataset

Training Data

70% 30%

TrainingTrial

Model

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

학습 과정 – 성능 검증을 위한 테스트 데이터

All Labeled Dataset

Training Data

70% 30%

TrainingTrial

Model

Test

Data

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

학습 과정 – 학습된 모델 검증

All Labeled Dataset

Training Data

70% 30%

Training

Test

Data

Evaluation

Result

Trial

Model

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

학습 과정 – 성능 검증 측정

All Labeled Dataset

Training Data

70% 30%

Training

Test

Data

Evaluation

Result

Trial

ModelAccuracy

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

왜 딥러닝 최근 유명해졌을까요?

Fast Compute

Ubiquitous Data

Advanced Learning Algorithms

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

딥러닝과 관련된 Amazon AI 서비스들

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Amazon AI 모든 개발자에게 머신러닝 능력을 제공

More in2017

Infrastructure CPU

Engines MXNet TensorFlow Caffe Theano Pytorch CNTK

ServicesAmazon Polly

Platforms

IoT

Speech

Mobile

Amazon ML

Spark &EMR

Kinesis Batch ECS

GPU

More in2017

Chat

Amazon LexAmazon Rekognition

Vision

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

NVIDIA Tesla V100 GPU 지원 Amazon EC2 P3

• 5,120개의 CUDA 코어, 640개의 Tensor 코어

• 각 GPU가 최대 300GBps의 데이터 속도로 실행되는 NVIDIA NVLink 2.0을통해 서로 연결

• 최대 2.7GHz로 실행되는 맞춤형 Intel Xeon E5-2686v4 프로세서

• 혼합 부동 소수 – 125 TFLOPS / 단일 부동 소수(FP32) – 15.7 TFLOPS /더블 부동 소수(FP64) – 7.8 TFLOPS

모델 GPU개수

GPU 메모리 NVIDIANVLink

vCPU 개수

주메모리 네트워크대역폭

EBS 대역폭

p3.2xlarge 1 16 GiB N/A 8 61 GiB Up to 10 Gbps 1.5 Gbps

p3.8xlarge 4 64 GiB 200 GBps 32 244 GiB 10 Gbps 7 Gbps

p3.16xlarge 8 128 GiB 300 GBps 64 488 GiB 25 Gbps 14 Gbps

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

AWS Deep Learning AMI

CUDA 9EC2 P3

CUDA 8

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

AWS Deep Learning AMI https://aws.amazon.com/amazon-ai/amis/details/

Amazon Linux, Ubuntu

많이 사용하는 딥러닝프레임워크

Apache MXNet, Tensorflow, Caffe2, torch, Keras, Keras 2, theano, Caffe, CNTK, PyTorch

딥러닝에 필요한 라이브러리들

Python2, Python3, Jupyter notebok, Anaconda2/3, Matplotlib, scikit-image, cpplint, pylint, pandas, graphviz 등

Intel Math Kernel Library (Apache MXNet)

NVIDIA CUDA, CUDA Deep Neural Network library (cuDNN)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Deep Learning으로 무엇을 해볼까요?

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

딥러닝의 Hello World – MNIST 데이터셋

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Fashion-MNIST https://github.com/zalandoresearch/fashion-mnist

• Zalando’s article 이미지들

• 60,000개의 학습 데이터

• 10,000개의 테스트 데이터

• 28 x 28, 회색 이미지

• 10개 카테고리

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

딥러닝에 적용한 아이디어 - 뉴런

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

인공 뉴런

출력 뉴런

연결 가중치

• 입력학습 데이터 X에 대한 백터

• 출력입력에 대한 Linear function 결과값

• 비선형성 (Nonlinearity)출력을 원하는 범위의 값으로변화시키는 것. 예, 분류의 경우 [0,1]확률값이 필요

• 학습가중치 w와 Bias b 를 찾는 과정

x1 x2 xn

w1 w2wn

…….입력 뉴런

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Deep Neural Network

hidden layersInput layer

output

Add Non Linearity to output of hidden layer

To transform output into continuous range

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

딥러닝에서의 Training

0.4 0.3

0.2 0.9

...

back propogation (gradient descent)

X1 != X

0.4 ± 𝛿 0.3 ± 𝛿

newweights

newweights

0

1

0

1

1

.

.

-

-

X

input

label

...

X1

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

딥러닝 모델

0.2

-0.1

...

0.7

Input Output

1 1 1

1 0 1

0 0 03

mx.sym.Pooling(data, pool_type="max", kernel=(2,2), stride=(2,2)

lstm.lstm_unroll(num_lstm_layer, seq_len, len, num_hidden, num_embed)

4 2

2 0 4=Max

1

3

...

4

0.2

-0.1

...

0.7

mx.sym.FullyConnected(data, num_hidden=128)

2

mx.symbol.Embedding(data, input_dim, output_dim = k)

Queen

4 2

2 0 2=Avg

Input Weights

cos(w, queen) = cos(w, king) - cos(w, man) + cos(w, woman)

mx.sym.Activation(data, act_type="xxxx")

"relu"

"tanh"

"sigmoid"

"softrelu"

Neural Art

Face Search

Image Segmentation

Image Caption

“People Riding Bikes”

Bicycle, People,

Road, Sport

Image Labels

Image

Video

Speech

Text

“People Riding Bikes”

Machine Translation

“Οι άνθρωποι

ιππασίας ποδήλατα”

Events

mx.model.FeedForward model.fit

mx.sym.SoftmaxOutput

Anatomy of a Deep Learning Model

mx.sym.Convolution(data, kernel=(5,5), num_filter=20)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Convolutional Neural Network에서 사용되는 레이어 종류

Convolutional Layer Activation Layer Pooling Layer

패턴을 검출하는 필터 역할 비선형 구조를 적용 배열 크기(행,열)를 줄임

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

일반 Neural Network와 Convolutional Network

이미지 출처: http://cs231n.github.io/convolutional-networks/

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

이미지에서 패턴을 찾는 Convolutional Layer

이미지 출처: http://cs231n.github.io/convolutional-networks/

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Convolutional Neural Network를 적용한 이미지 분류

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

LeNet-5

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

AlexNet

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

GoogLeNet

Convolution Pooling Softmax Other

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

VGG

Image Credit : https://www.cs.toronto.edu/~frossard/post/vgg16/

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

ResNet

Image Credit : https://arxiv.org/pdf/1512.03385.pdf

• Residual 학습 개념 사용• Layer 수: 18, 34, 50, 101, 152

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

이제 구현해 볼까요?

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

딥러닝 구현을 위한 프레임워크가 필요합니다

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Deep Learning 프레임워크들

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Apache MXNet

• 자원을 효율적으로 활용함

• 작은 메모리의 GPU와 느린 네트워크를 고려

• 클라우드에서 학습하고, 어디에나 배포

• 속도

• 노드와 GPU 개수가 증가하는 것과 비례한 성능 향상

• 단일 노드에서도 높은 효율 (C++ Backend)

• 프로그램밍 기능

• 명령형(Imperative)과 선언형(Declarative) 프로그램밍 혼합

• 다양한 프로그램 언어 지원

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

MXNet 특징 - GPU 개수 증가에 따른 확장성

Number of GPUs

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Gluon

유연한 딥러닝을 위한 쉬운 프로그래밍 인터페이스

• 친숙한 API

• 다이나믹 네트워크

• 알고리즘으로 네트워크 정의

• 학습을 위한 고속 연산자

Introducing Gluon: a new library for machine learning from AWS and Microsoft

https://aws.amazon.com/blogs/aws/introducing-gluon-a-new-library-for-machine-learning-from-aws-and-microsoft/

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Apache MXNet 구성 요소

NDArray

• 명령형 프로그래밍 (Imperative)

• CPU와 GPU에서 다차원 배열(Tensor) 연산을 수행

Symbol

• 선언형 프로그래밍 (Declarative)

• Neural Network 그래프 정의 및 최적화를 위한 자동 미분 수행

Module

• Neural Network 학습 및 예측 수행

Iterators

• 데이터 로딩

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

NDArray – mxnet.ndarray

• 다차원 배열(텐서)에 대한 수학 연산을 위한 핵심 자료 구조

• 고정 크기의 동일한 데이터 타입의 다차원 배열

• NumPy와 차이점

• CPU, GPU 및 여러 GPU 환경에서 연산을 수행

• 여러 연산을 가용한 하드웨어에 걸쳐서 병렬로 수행

0 1 2

3 4 5

2 X 3 배열

1번째 Axis 2번째 Axis

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

NDArray – 주요 Attribute들

• ndarray.shape: 배열의 차원값

• ndarray.dtype: 원소의 데이터 타입 (numpy 타입 객체)

• ndarray.size: 배열의 총 원소 개수

• ndarray.context: 형열이 저장된 디바이스 (CPU, GPU)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Symbol – mxnet.symbol

Symbol을 이용한 선언형(declarative) 프로그래밍 방법은,

1) 입력과 출력에 대한 Placeholder을 이용해서 연산 그래프 정의

2) NDArray 변수들을 Placeholder에 바인딩한 후, 그래프 연산을 수행

최적화된 연산 수행 (예, 메모리 재사용을 통한 적은 메모리 사용)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Symbol – 기본 사용법

import mxnet as mx

a = mx.sym.Variable('a')

b = mx.sym.Variable('b')

c = a + b

d = a * b

e = mx.sym.dot(a, b)

mx.viz.plot_network(symbol=c)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Apache MXNet – Symbol 패키지

Convolution

Activation

Pooling

Flatten

FullyConnected

SoftmaxOutput

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Symbol – 기본 Neural Network 구성하기

net = mx.sym.Variable('data')

net = mx.sym.FullyConnected(data=net, name='fc1',

num_hidden=128)

net = mx.sym.Activation(data=net, name='relu1',

act_type="relu")

net = mx.sym.FullyConnected(data=net, name='fc2',

num_hidden=10)

net = mx.sym.SoftmaxOutput(data=net, name='out')

mx.viz.plot_network(net, shape={'data':(100,200)})

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Module – mxnet.module

• 정의된 네트워크를 학습 시키고, 학습된 네트워크를 이용해서 예측을 수행

• 상위 레벨 및 중간 레벨 인터페이스 제공

학습 수행 순서

• 학습 데이터 입력

• 모델 파라메터 초기화

• 네트워크를 따라 Forward, Backward 수행

• Gradient들을 기반으로 weight 값 조정

• 모델 체크포인트 …

bind

init_params

init_optimizer

metric.create

forward

update_metric

backward

update

fit

중간 레벨 인터페이스 상위 레벨 인터페이스

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Module – 모델 정의

# create a module

mod = mx.mod.Module(

symbol=net,

context=mx.cpu(),

data_names=['data'],

label_names=['softmax_label'])

• symbol: Neural Network 정의

• context: 어떤 디바이스에서 수행할 것인지 (CPU, GPU, 여러 GPU들)

• data_names: 입력 데이터 변수 이름들

• label_names: 입력 label 변수 이름들

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Module – 여러 GPU 사용하기

# Single GPU

module = mx.module.Module(

context=mx.gpu(0))

# Train on multiple GPUs

module = mx.module.Module(

context=[mx.gpu(i) for i in range(N)], ...)

• Data parallelism을 기본 지원

• 여러개의 GPU를 사용하도록 간단히 설정 가능

examples

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Module – 중간 레벨 인터페이스 활용 예제

# 주어진 입력 데이터 및 label 모양(shape)에 따라 메모리 할당

mod.bind(data_shapes=train_iter.provide_data, label_shapes=train_iter.provide_label)

# uniform random number를 사용해서 파라메터 초기화 수행

mod.init_params(initializer=mx.init.Uniform(scale=.1))

# 학습 속도(learning rate) 0.1 값으로 학습에 SGD 사용

mod.init_optimizer(optimizer='sgd', optimizer_params=(('learning_rate', 0.1), ))

# 정확도(accuracy)를 메트릭으로 사용

metric = mx.metric.create('acc')

# 트레이닝 을 5 epoch 수행

for epoch in range(5):

train_iter.reset()

metric.reset()

for batch in train_iter:

mod.forward(batch, is_train=True) # 예측값 계산

mod.update_metric(metric, batch.label) # 예측 정확도 누적

mod.backward() # gradients 계산

mod.update() # 파라메터 업데이트

print('Epoch %d, Training %s' % (epoch, metric.get()))

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Module – 상위 레벨 인터페이스

• 학습: 중간 레벨 인터페이스를 하나 하나 수행하지 않고, module.fit API 호출

• 예측: module.predict API 제공

# fit the module

mod.fit(train_iter,

eval_data=val_iter,

optimizer='sgd',

optimizer_params={'learning_rate':0.1},

eval_metric='acc',

num_epoch=8)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Module – 모델 저장 및 읽어오기

• 학습이 완료된 모델은 파일로 저장하고,

checkpoint = mx.callback.do_checkpoint(model_prefix)

• 필요할 때 저장된 모델을 읽어서 예측에 사용sym, arg_params, aux_params = mx.model.load_checkpoint(model_prefix, 3)

• 모델 체크포인트 파일

• 네트워크 정의: .json

• 학습된 파라메터값들: .params

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

이제 정말 구현해 볼까요?

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

MXNet을 이용한 Convolutional Layer 구현 방법

mxnet.symbol.Convolution()

mxnet.symbol.Activation()

mxnet.symbol.Pooling()

mxnet.symbol.flatten()

mxnet.symbol.FullyConnected()

mxnet.symbol.SoftmaxOutput()

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Convolution Layer 예제

import mxnet as mx

data = mx.sym.Variable(‘data’)

conv1 = mx.sym.Convolution(data=data, kernel=(5,5), num_filter=30)

act1 = mx.sym.Activation(data=conv1, act_type=‘relu’)

pool1 = mx.sym.Pooling(data=act1, pool_type=‘max’, kernel=(2,2))

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

3D 배열을 1D 배열로 변환

fc0 = mx.sym.Flatten(pool2)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Fully Connected Layer 정의

fc1 = mx.sym.FullyConnected(data=fc0, num_hidden=500)

act3 = mx.sym.Activation(data=fc1, act_type=‘relu’)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

마지막 카테고리 판별을 위한 Output 레이어 정의

fc3 = mx.sym.FullyConnected(data=fc2, num_hidden=500)

output_layer = mx.sym.SoftmaxOutput(data=fc3, name=’softmax’)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

MXNet을 이용한 Fashion-MNIST 분석 예제https://github.com/sunilmallya/dl-twitch-seriesE3_image_recognition_clothing_detector.ipynb

$ ssh –i mysecurekey.pem –L 8888:localhost:8888 ubuntu@EC2-IP

$ git clone https://github.com/sunilmallya/dl-twitch-series.git$ cd dl-twitch-series$ jupyter notebook

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

딥러닝에 대해서 더 알고 싶으시면

AWS AI (https://aws.amazon.com/ko/amazon-ai)

AWS AI Blog (https://aws.amazon.com/blogs/ai)

Deep Learning - The Straight Dope (http://gluon.mxnet.io)

Apache MXNet (http://mxnet.incubator.apache.org)

Gluon (http://mxnet.incubator.apache.org/gluon)

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

AWS re:Invent 2017 – 머신러닝https://aws.amazon.com/blogs/ai/your-guide-to-machine-learning-at-reinvent-2017/

50개 이상의 breakout 세션

핸즈온 워크샵, 랩

Deep-dive Chalk Talk

주목할 만한 이벤트들

• Robocar Rally 2017

• Deep Learning Summit

• Deep Learning on AWS

• Computer Vision Language & Speech

© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

질문에 대한 답변 드립니다.

발표자료/녹화영상 제공합니다.http://bit.ly/awskr-webinar

더 나은 세미나를 위해여러분의 의견을 남겨 주세요!

top related