개요

  • 이번부터 쓰는 글은 Tensorflow-models 중 hand-pose-detection 을 자사 제품 내에서 구현한 후, 그와 관련된 AI 이론을 정리한 내용임
  • 이번 글 출처: 학부 강의 내용, 필기, 구글링, 필요하다면 이하에서 출처 명시했음

 


 

1. 서

 

의미

  • hidden layer가 2개 이상인 이유
    : 풀고자 하는 문제를 세부 문제로 나누고, 그 문제를 다시 세세부 문제로 나누기 때문
    (ex) 사람의 얼굴인가 → 오른쪽 위에 눈이 있는가 → 위에 눈썹이 있는가, 가운데에 눈동자가 있는가, 아래에 속눈썹이 있는가

 

Support vector machine과의 비교
  • SVM (Support Vector Machine)
    • 머신러닝 분야 중 하나로 ①패턴 인식, 자료 분석을 위한 지도 학습 모델 분류와 ②회귀 분석을 위해 사용됨
    • SVM의 패턴 인식 순서
      1. 2개 카테고리 중 어느 하나에 속한 데이터 집합이 주어졌을 때,
      2. 그것을 바탕으로 비확률적 이진 선형분류모델을 만듦. 이 모델은 새로운 데이터가 둘 중 어떤 카테고리에 속하는지 판단함
      3. 해당 모델은 데이터가 분포된 공간에서 선을 그어 경계를 표현함. 그리고 SVM 알고리즘은 그 중 가장 큰 폭을 가진 경계를 찾음
    • 예시 : 이진 분류를 한다면 밑 사진처럼 직선(linear decision boundary)을 그어 구분하는 것
      -> 출처: https://sanghyu.tistory.com/7

  • 비교
  SVM (D)NN
공통점 - hidden feature 를 사용
- hidden space 위에서 linear decision boundary를 이용하여 분류
 
차이점
: 학습 대상
feature mapping은 고정,
linear decision boundary만 학습
linear decision boundary + feature mapping 도 함께 학습

 


 

2. 모형 

 

모수의 학습 방법 
: 목적 함수 및 함수 구조를 기반으로 최적화 알고리즘 설명
  1. 기울기 강화 알고리즘 (Gradient Descent algorithm; GD)
  • 특정 목적 함수 L(θ)를 최소화하는 θ을 한 번에 찾기 힘든 경우에 사용하는 대표적인 반복 알고리즘.
  • 목적 함수 의미

  • GD의 아이디어

  • 구체적인 알고리즘 내용

 


 

   2. 역전파 알고리즘 (Back propagation algorithm)

  • 의미
    • 미분값이 위에서 아래로 계산되어짐 (Back propagation)
    • DNN 모수들의 (b, w) gradient를 구하는 알고리즘
    • 목적 함수 L(θ)을 최소화하기 위해 gradient descent algorithm을 사용한 결과,
      NN의 특수한 형태 때문에 ∂L(θ) / ∂θ(l+1)의 계산에 필요한 값을 알고 있으면, ∂L(θ) / ∂θ(l)가 자동적으로 계산됨.
      (여기서 θ(l)은 l층에서의 모수)
  • 수식으로 의미 이해

  • 예제
    • 문제: Calculate gradient 에 있는 수식을 도출하는게 목적!
     

 


 

  3. Stochastic gradient descent method (SGD)

  • 기본 용어 정리
    • Batch : 학습 데이터 전체
    • Mini-batch : 학습 데이터의 일부, 즉 batch에서 sampling 한 것
    • Epoch : 반복적인 학습 알고리즘을 사용할 때 모든 학습 데이터를 한 번 씩 사용하는 것을 의미
      (ex: 10000개의 학습 데이터가 존재하고, 매번 50개의 데이터(i.e. 50개의 mini-batch)를 이용하여 모수를 학습할 때, 이 알고리즘을 200번을 반복하면 1 epoch, 400번을 반복하면 2 epochs라고 함.)
      → 즉 1 에폭당 학습 데이터 10000개를 한 바퀴 도는 느낌
  • 의미
    • Stochastic gredient descent algorithm을 사용한 method
    • 아이디어 및 업데이트 방법

  • 장점
    • 계산량↓: 업데이트 할 때 모든 batch를 사용할 때보다 적은 계산을 필요로 함
    • 정확성↑: 수렴성이 이론적으로 보장 (Bottou, 1998 and Murata, 1998)
  • gredient descent algorithm과의 차이
    • 핵심
      • Gradient Descent (GD): mini batch 사용하지 않고 학습 → 에폭이 1인 SGD 느낌
      • Stochastic Gradient Descent (SGD): mini batch 를 샘플링하여 학습 → 파생적으로 에폭의 개념 나오게 됨
    • 수식
          - GD

                  - SGD 

  •     그림
                 

 


 

2. 학습률 (learning rate) 의 선택

의미
  • 목적 함수의 최댓값 또는 최솟값을 향해 이동하면서 각 반복에서 단계 크기를 결정하는 스칼라
  • 학습률은 머신러닝 및 통계학에서 사용되는 용어
  • 최적화 알고리즘의 조정 매개변수
  • εt∶ t 시점의 학습률

 

특징
  • 학습률이 지나치게 크거나 작으면 좋은 추정값을 얻을 수 없음. 목적 함수가 목적지로 발산 or 도달하지 못하기 때문임
  • 따라서 학습이 진행될수록 비교적 큰 학습률 → t가 증가함에 따라 학습률을 줄여나가는 것이 바람직함
  • 이론적으로는 εt ∝1/t이면 (비례하다면), 역전파 알고리즘을 사용하였을 때 손실 함수가 국소적인 최소값으로 수렴한다는 사실이 알려져 있음. (Bottou et al., 2018)

 


 

3. 한계

Vanishing gradients problem
  • 모수에 대한 gradient 값이 아래층으로 내려갈수록 작아지는 현상.
    = 즉, hidden layer 쌓을수록 추정 값 정확도↓ (=성능↓)
  • 그 결과 아래층의 모수가 초기 값과 크게 다르지 않은 값을 가진 채 학습이 종료.
    = 즉, 안 좋은 모수를 갖는 추정 값으로 수렴함
  • 따라서, 때때로 DNN이 NN 보다 성능이 나쁜 경우 발생함
  • 원인: 역전파 알고리즘이 좋지 않은 추정값을 제공 (bad local minima).

 

Running time
  • 일반적으로 DNN은 1개의 hidden layer를 가지는 NN보다 더 많은 수의 모수를 필요로 함
  • 더 많은 수의 모수를 추정하기 위해 보다 더 많은 시간 소요됨

 

보완책: 사전 학습 (Pre-training)
  • 2006년 G.E.Hinton 교수가 처음으로 제안: Hinton and Salakhutdinov (2006), Hinton et al (2006)
  • 입력 변수만 사용하여 모수를 추정하는 기법 (Pre-training) → 추청된 모수를 학습 시 초기값으로 사용 (Training)
    → 이 방법이 이전 방법과 다른 이유: 기존 training은 입력 값, 출력 값을 모두 이용하여 학습
  • 효과: 역전파 알고리즘의 한계 해결
    • 결과가 해의 초기값에 의존
      = 즉 아래층에 있는 모수들은 초기 값과 크게 다르지 않음
    • 그러나 좋은 해의 초기값을 찾기 어려움
  • 예시: Erhan et al., 2010 and Larochelle et al., 2007
    • 왼쪽 그래프: hidden layer 1층, 오른쪽 그래프: hidden layer 4층
    • hidden layer의 개수가 늘어날수록 pre-training 한 layer의 효과가 더 커짐
      = 즉 데이터의 test error 가 작아짐

 


 

4. Advanced of deep learning

하드웨어의 발전: GPU의 사용
  • 딥러닝에서 필요한 계산들을 대부분 병렬처리 가능
  • 따라서 CPU로 계산할 때보다 훨씬 빠른 계산 가능
    + 훨씬 많은 hidden layer와 모수들을 가지는 복잡한 모형 설계하여 활용 가능

 

새로운 활성 함수의 개발: ReLU (Rectified Linear Units; Nair and Hinton (2010))
  • 우수성
    • 기존의 활성함수 (예: sigmoid or tanh)는 그 특성상 모수를 추정하는데 어려움
      (어려움: vanishing gradient)
    • Piece-wise 선형 함수를 활성함수로 사용
      → vanishing gradient 문제 해결, 속도 향상, 사전 학습 불필요해짐
  • sigmoid 함수와 비교

  • 이후에 ReLU를 응용하여 LeakyReLU (Mass et al., 2013), PReLU (He et al., 2015), ELU (Clevert et al., 2015) 등 많은 활성 함수가 제안됨.

 

Regularization method 개발
  1. Drop out
    • 매번 역전파를 할 때마다 노드의 절반을 끄고 (=drop out) 학습
      → 최종 결과를 낼 떄에는 각 층 결과값에 1/2를 곱하는 방법
    • 효과: 노드 간 상관관계↓, 독립성↑
    • 원인: fully connected neural network을 학습할 때, 같은 층의 노드간에 높은 상관관계 발생
      → 입력값이 조금만 바뀌어도 모든 네트워크에 큰 변화가 생길 수 있음
  2. Batch normalization
    • 매번 mini batch를 이용하여 학습할 떄마다 노드들을 정규화함
    • 효과: 적은 에폭 학습을 하여도 기존보다 좋은 성능 (ex. 보다 높은 accuracy)를 얻을 수 있게 됨
    • 원인: 은닉 노드 각각의 분포 및 scale이 상이 → 성능이 좋지 않음
  3. Data augmentation (데이터 증강)
    • Random crop, RGB perturbation, image reflection 등으로 학습 데이터를 대량 확보하는 것
    • 심지어 Sequential data에서도 data의 순서를 바꾸어 학습 데이터를 늘림.
    • 효과: 모델이 정확한 예측을 하기 위한 재료가 다수 확보됨
      → 보다 정확한 예측 가능
    • 원인: 학습 대상 데이터의 양이 지나치게 적은 경우, 학습이 제대로 되기 어려움
  4. Residual learning architecture (잔차 학습 아키텍처)
    • Networks에서 이웃하지 않은 layer 사이에도 connection을 추가
    • 효과: Vanishing problem 해결

 


 

5. Advanced of learning algorithms

SGD 방법의 단점
  1. 학습률 εk의 scale에 따라 성능이 크게 좌우됨.
    = 손실 함수들마다 좋은 성능을 보장하는 학습률 scale이 달라 선택이 어려움

  2. 이전 gradient 정보들은 무시하고 현 시점의 gradient만을 사용하여 업데이트
      → 수렴 속도가 느릴 수 있음

  3. 시점 k에서 모든 gradient에 미리 정해 놓은 학습률 εk를 곱해주어 업데이트.
      → 손실함수가 특정 모수들의 방향에 대해서 민감하게 변할 경우에 수렴하지 않을 수 있음.
      → 안장점*에 빠질 가능성이 높음.

      * 안장점 (Saddle point)
      - 다변수 함수에서 특정한 형태의 극값.
        = 한 쪽 방향에서 보면 극댓값, 다른 쪽 방향에서 보면 극솟값
      - 예시 : 이차항이 마이너스인 이차함수
        -> 안장점 (이자 극댓값)에서 한 방향에서는 곡면이 상승, 다른 방향에서는 하강

        - 머신러닝에서의 안장점 
          > 신경망 모형(NN)을 학습시킬 때 최적화 알고리즘이 안장점에 도달한 경우,
            여기서 멈추지 않고 전역 최소점 (global minimum) 또는 국소 최소점 (local minimum) 에 도달할 수 있도록 설계해야함
            ( ∵ 최적화 알고리즘의 목표 = 목적함수(손실함수) 최소화)
          > 따라서 이것이 머신러닝 또는 딥러닝의 성능을 결정지음

 

SGD with momentum
  • 현 시점의 gradient 업데이트 방향이 이전 시점의 gradient 정보에 영향을 받는 방법
    = 즉 현재 및 과거 시점의 gradient 크기에(g) 영향을 받아서 모수들(θ) 각각의 학습률이(ε) 결정됨
  • Goodfellow, I., et al. (2016) Deep Learning : 모멘텀을 수식으로 증명

  • 이는 “이전 gradient 정보들은 무시하고 현 시점의 gradient만을 사용하여 업데이트” 하는 SGD의 1번 단점을 보완한 것

 

adam
  • ①accumulated squared gradient를 weighted average로 업데이트 함 (두 번째 빨간 박스)
    + ②현 시점의 gradient 업데이트 방향이 이전 시점의 gradient 정보에 영향을 받아 결정됨 (첫 번째 빨간 박스)
    = ①RMSProp* + ②momentum
    • RMSProp (Tieleman and Hinton, 2012)
      • AdaGrad*와는 다르게 accumulated squared gradient를 누적 합으로 업데이트 하지 않고, weighted average로 업데이트 함.
        = 즉 AdaGrad의 단점 보완
      • Goodfellow, I., et al. (2016) Deep Learning : RMSProp을 수식으로 증명
        : 빨간 박스 수식 = weighted average

               * AdaGrad
                 : 현재 및 과거 시점의 gradient의 크기에 영향을 받아서 (첫 번째 빨간 박스)
                → 모수들 각각의 학습률이 결정됨 ( i.e. adaptive learning rate) (두 번째 빨간 박스)

                  - 학습률이 미리 정해져 있지 않고, 합리적인 방법을 통해 결정된다는 점에서 SGD의 단점 중 1번, 3번이 해결됨 
                  - Goodfellow, I., et al. (2016) Deep Learning : AdaGrad을 수식으로 증명
                  - 한계 - 지속적인 업데이트가 진행됨에 따라 accumulated squared gradient의 r의 값이 너무 커져서 업데이트가 몇 차례 진행 되지 않아 모수의 추정값이 도중에 수렴해 버림

  • Goodfellow, I., et al. (2016) Deep Learning : Adam을 수식으로 증명
    • 현재까지 나온 최적화 방법론들 중 일반적으로 빠르게 좋은 추정 값을 찾아 주는 알고리즘.
    • Convex loss function 뿐만 아니라 non-convex loss function (예: 딥러닝 모델에서의 손실함수) 에서 매우 좋은 성능을 제공.

개요

  • handpose, face, pose - detection의 model type은 모두 CNN
  • = 즉 모델의 전반적인 구조, 학습하여 결과를 도출하는 방식이 모두 CNN을 근본으로 하고, 모델 아키텍처도 advanced CNN 의 양상을 띄고 있음
  • 따라서 이번 글에서는 CNN이 포함된 큰 카테고리인 DNN을 설명하기 위해 NN (Neural Network)을 먼저 설명하고, 다음 글에서 DNN에 대해 설명할 것임
  • 구체적인 CNN에 대해서는 face-detection 시리즈에서 설명할 예정임.

 


 

1. 의미

  • 인공 신경망 모형 (Artificial Neural Network): 일반적으로 artificial은 떼고 말함
  • 뇌 구조 (신경망)을 모방하여 만든 수학적 모형
    = 즉 인간의 뇌가 문제를 해결하는 방식과 유사하게 구현
  • 머신러닝의 한 분야

 


 

2. 함수 구조

수식

그림

 

용어 설명
  • 활성 함수 (activation function) 
    • 인공 신경망에서 입력 신호의 가중치 합을 출력 신호로 변환하는 함수 
    • 특징: 비선형성 (non-linearity) -> 입력에 대한 비선형 변환을 통해 신경망이 다양한 종류의 복잡한 함수를 학습
    • 활성 함수의 형태

  • 은닉층 (hidden layer)
    : 입력층 (input layer)과 출력층 (output layer) 사이에 위치하는 모든 층
  • 완전 연결 계층 (fully connected layer)
    : 한 층(layer)의 모든 뉴런이 그 다음 층(layer)의 모든 뉴런과 연결된 상태

 


 

3. 이론적 성질

논문 원문
  • Universal approximator (Cybenko, 1989 and Homik et al, 1989)
  • Theorem 2 of Cybenko (1989)

 

해석

N을 충분히 키울 수 있으면 (여기서는 무한대로 표현됨), 모든 계층의 모든 x에 대하여 f(x)는 실제 함수의 합인 G(x)와 정밀도 ϵ (0보다 큰 아주 작은 값)만큼 가깝게 표현 가능
<-> N을 충분히 키울 수 있으면, Neural network를 표현한 f(x)는 다양한 함수 형태로 표현될 수 있음 
<-> t가 +-무한대로 가면, 활성함수 (여기서는 sigmoid)가 +-1로 감 

개요

 


 

1. 모델 설명 | Used to

모델 설명
  • 모델명: MediaPipe BlazePose GHUM 3D
  • 구체적인 설명
Lite (3MB size), Full (6 MB size) and Heavy (26 MB size) models, to estimate the full 3D body pose of an individual in videos captured by a smartphone or web camera.
Optimized for on-device, real-time fitness applications: Lite model runs ~44 FPS on a CPU via XNNPack TFLite and ~49 FPS via TFLite GPU on a Pixel 3. Full model runs ~18 FPS on a CPU via XNNPack TFLite and ~40 FPS via TFLite GPU on a Pixel 3.
Heavy model runs ~4FPS on a CPU via XNNPack TFLite and ~19 FPS via TFLite GPU on a Pixel 3.

 

Used to
Applications
3D full body pose estimation for single-person videos on mobile, desktop and in browser.

Domain & Users
 - Augmented reality
 - 3D Pose and gesture recognition
 - Fitness and repetition counting
 - 3D pose measurements (angles / distances)

Out-of-scope applications
Multiple people in an image.
 - People too far away from the camera (e.g. further than 14 feet/4 meters)
 - Head is not visible Applications requiring metric accurate depth
 - Any form of surveillance or identity recognition is explicitly out of scope and not enabled by this technology

 


 

2. Model type 및 Model architecture

모델 카드 인용
Convolutional Neural Network: MobileNetV2-like with customized blocks for real-time performance.

 

Model type: CNN

 

Model architecture : MobileNetV2

 


 

3. input, output

Inputs
Regions in the video frames where a person has been detected.
Represented as a 256x256x3 array with aligned human full body part, centered by mid-hip in vertical body pose and rotation distortion of (-10, 10) . Channels order: RGB with values in [0.0, 1.0].

Output(s)
33x5 array corresponding to (x, y, z, visibility, presence).
 - X, Y coordinates are local to the region of interest and range from [0.0, 255.0].
 - Z coordinate is measured in "image pixels" like the X and Y coordinates and represents the distance relative to the plane of the subject's hips, which is the origin of the Z axis. Negative values are between the hips and the camera; positive values are behind the hips.
Z coordinate scale is similar with X, Y scales but has different nature as obtained not via human annotation, by fitting synthetic data (GHUM model) to the 2D annotation. Note, that Z is not metric but up to scale.
 - Visibility is in the range of [min_float, max_float] and after user-applied sigmoid denotes the probability that a keypoint is located within the frame and not occluded by another bigger body part or another object.
 - Presence is in the range of [min_float, max_float] and after user-applied sigmoid denotes the probability that a keypoint is located within the frame.
[
  {
    score: 0.8,
    keypoints: [
      {x: 230, y: 220, score: 0.9, score: 0.99, name: "nose"},
      {x: 212, y: 190, score: 0.8, score: 0.91, name: "left_eye"},
      ...
    ],
    keypoints3D: [
      {x: 0.65, y: 0.11, z: 0.05, score: 0.99, name: "nose"},
      ...
    ],
    segmentation: {
      maskValueToLabel: (maskValue: number) => { return 'person' },
      mask: {
        toCanvasImageSource(): ...
        toImageData(): ...
        toTensor(): ...
        getUnderlyingType(): ...
      }
    }
  }
]

 


 

4. evaluation metric

pose의 metric : PDJ
  • average Percentage of Detected Joints: 감지된 부위의 평균 비율 오차
We consider a keypoint to be correctly detected if predicted visibility for it matches ground truth and the absolute 2D Euclidean error between the reference and target keypoint normalized by the 2D torso diameter projection
is smaller than 20%.
This value was determined during development as the maximum value that does not degrade accuracy in classifying pose / asana based solely on the key points without perceiving the original RGB image. The model is providing 3D coordinates, but the z-coordinate is obtained from synthetic data, so for a fair comparison with human annotations, only 2D coordinates are employed.

 

evaluation results
  • geographical
Evaluation across 14 regions of heavy, full and lite models on smartphone back-facing camera photos dataset results an average performance of 94.2% +/- 1.3% stdev with a range of [91.4%, 96.2%] across regions for the heavy model, an average performance of 91.8% +/- 1.4% stdev with a range of [89.2%, 94.0%] across regions for the full model and an average performance of 87.0% +/-2.0% stdev with a range of [83.2%, 89.7%] across regions for the lite model.
Comparison with our fairness criteria yields a maximum discrepancy between average and worst performing regions of 4.8% for the heavy, 4.8% for the full and 6.5% for the light model.
  • skin tone and gender
Evaluation on smartphone back-facing camera photos dataset results in an average performance of 93.6% with a range of [89.3%, 95.0%] across all skin tones for the heavy model, an average performance of 91.1% with a range of [85.9%, 92.9%] across all skin tones for the full model and an average performance of 86.4% with a range of [80.5%, 87.8%] across regions for the lite model. The maximum discrepancy between worst and best performing categories is 5.7% for the heavy model, 7.0% for the full model and 7.3% for the lite model.
Evaluation across gender yields an average performance of 94.8% with a range of [94.2%, 95.3%] for the heavy model, an average performance of 92.3% with a range of [91.2%, 93.4%] for the full model, and an average of 83.7% with a range of [86.0%, 89.1%] for the lite model.
The maximum discrepancy is 1.1% for the heavy model, 2.2% for the full model and 3.1% for the lite model.

개요

 


 

1. 모델 설명 | Used to

모델 설명
  • 모델명: MediaPipe Attention Mesh
  • 구체적인 설명
A lightweight model for real-time prediction of 3D facial surface landmarks from video captured by a front-facing smartphone camera.
Designed for applications like AR makeup, eye tracking and AR puppeteering that rely on highly accurate landmarks for eye (+ iris) and lips regions predicted by the model. Runs at over 50 FPS on Pixel 2 phone.

 

Used to
  • 특정 신원에 대한 얼굴 또는 얼굴 특징에 대해서는 저장할 수 없음에 주의
Applications
 - Detection of human facial surface landmarks from monocular video.
 - Optimized for videos captured on front-facing cameras of smartphones.
 - Well suitable for mobile AR (augmented reality) applications.

Domain & Users
 - The primary intended application is AR entertainment.
 - Intended users are people who use augmented reality for entertainment purposes.

Out-of-scope applications
Not appropriate for:
 - This model is not intended for human life-critical decisions.
 - Predicted face landmarks do not provide facial recognition or identification and do not store any unique face representation.

 


 

2. Model type 및 Model architecture

모델 카드 인용
MobileNetV2 - like with customized blocks for real-time performance and an attention mechanism to refine lips and eye regions and to predict irises.

 

Model type: CNN

 

Model architecture
  • face-landmarks-detection 에서는 detector-model과 landmark-model이라고 하지 않고, 각각을 sub model이라고 칭함
  • 입, 눈, 눈동자를 제외한 박스 안에 있는 얼굴 부위 탐지 및 좌표 예측: MobileNetV2
  • 입, 눈, 눈동자의 탐지 및 좌표 예측: attention mechanism
    • 특히 이 메커니즘에서 spatial transformer 모듈이 사용됨
    • 이 모듈은 아핀 변환 행렬(affine transformation matrix)에 의해 조절되고, 사용자가 박스 안의 keypoint를 당기고 회전하고 바꾸고 왜곡할 수 있게 함
attention mechanism
An attention mechanism pulls out visual features of a given region of interest by sampling a grid of 2D points in the feature space and extracting the features under the sampled points. This allows to train architectures end-to-end and to enrich the features that are used by the attention mechanism.

spatial transformer
Specifically, we use a spatial transformer module which is controlled by an affine transformation matrix and allows us to zoom, rotate, translate, and skew the sampled grid of points.

 


 

3. input, output

Inputs
Image of cropped face with 25% margin on each side and size 192x192 px.

Output(s)
 - Facial surface represented as 468 3D landmarks flatened into a 1D tensor: (x1, y1, z1), (x2, y2, z2), ... x- and y-coordinates follow the image pixel coordinates;
z-coordinates are relative to the face center of mass and are scaled proportionally to the face width.
 - Lips refined region surface represented as 80 2D landmarks (inner and outer contours and an intermediate line) flattened into a 1D tensor.
 - Eye with eyebrow refined region surface (x2) represented as 71 2D landmarks (eye and eyebrow contours with surrounding areas) flattened into a 1D tensor.
 - Iris refined region surface (x2) represented as 5 2D landmarks (1 for pupil center and 4 for iris contour) flattened into a 1D tensor.
 - Face flag indicating the likelihood of the face being present in the input image. Used in tracking mode to detect that the face was lost and the face detector should be applied to obtain a new face position. Face probability threshold is set at 0.5 by default and can be adjusted.
[
  {
    box: {
      xMin: 304.6476503248806,
      xMax: 502.5079975897382,
      yMin: 102.16298762367356,
      yMax: 349.035215984403,
      width: 197.86034726485758,
      height: 246.87222836072945
    },
    keypoints: [
      {x: 406.53152857172876, y: 256.8054528661723, z: 10.2, name: "lips"},
      {x: 406.544237446397, y: 230.06933367750395, z: 8},
      ...
    ],
  }
]

 


 

4. evaluation metric

face의 metric : IOD MAE
  • 양쪽 눈 사이의 거리의 평균 오차
  • IOD (Normalization by Interocular Distance)
Normalization by interocular distance (IOD) is applied to unify the scale of the samples.
IOD is calculated as the distance between the eye centers (which are estimated as the centers of segments connecting eye corners) and is taken as 100%.
To accommodate head rotations, 3D IOD from the ground truth is employed.
  • MAE (Mean Absolute Error normalized by interocular distance) : handpose와 동일
Mean absolute error is calculated as the pixel distance between ground truth and predicted face mesh.
The model provides 3D coordinates, but as the z screen coordinates as well as metric world coordinates are obtained from synthetic data, so for a fair comparison with human annotations, only 2D screen coordinates MNAE are employed.

 

evaluation results
  • 구체적인 내용
Comparison with fairness goal of 2.56% IOD MAE discrepancy across 17 regions:
 - Tracking mode: from 2.73% to 3.95% (difference of 1.22%)
 - Reacquisition mode: from 3.01% to 4.28% (difference of 1.27%)

Comparison with our fairness criteria yields a maximum discrepancy between best and worst performing regions of 1.22% for the tracking mode and 1.27% for the reacquisition mode.
We therefore consider the models performing well across groups.
  • Tracking mode and Reacquisition mode
  Tracking mode Reacquisition mode
발동 상황 메인 모드
 = 대부분의 얼굴 감지 가능한 일반적인 상황
 = 이전 프레임에서 높은 정확도의 얼굴 정보를 얻을 수 있을 때
이전 프레임에서 얼굴 정보를 얻을 수 없을 때
 = 첫 번째 프레임 or 얼굴 추적 정보가 없어졌을 때
이용하는 툴 the Mdiapipe Python Solution API for face mesh BlazeFace Detector
Tracking mode
The main mode that takes place most of the time and is based on obtaining a highly accurate face crop from the prediction on the previous frame (frames 2, 3, ... on the image below). Underneath we utilize the MediaPipe Python Solution API for Face Mesh and run the pipeline for several frames on the same image before measuring the tracking accuracy (thus the crop region is determined from the model predictions as in a video stream).

Reacquisition mode
Takes place when there is no information about the face from previous frames. It happens either on the first frame (image below) or on the frames where the face tracking is lost. In this case, an external face detector is being run over the whole frame. We used BlazeFace Detector for the evaluation of the reacquisition mode.

 

개요

 

Model Card Hand Tracking (Lite_Full) with Fairness Oct 2021.pdf

 

drive.google.com

 

 


 

0. Model card 란?

의미
  • 모델의 다양한 속성, 성능 등을 공유하여 개발자로 하여금 선택의 기회를 넓혀주기 위한 문서
  • 구글에서 발표한 Model Cards for Model Reporting 논문에 기반한 것

 

목적
  • 머신러닝 모델의 유스케이스 명료화 
  • 머신러닝 모델의 적용 오류 상황 최소화
In order to clarify the intended use cases of machine learning models and minimize their usage in contexts for which they are not well suited, we recommend that released models be accompanied by documentation detailing their performance characteristics

 

포함된 내용
  • 다양한 평가 기준: 문화적 차이, 지역, 성별 등
  • 모델 사용 방법
  • 구체적인 성능 평가 과정
  • 여타 관련 요소
Model cards are short documents accompanying trained machine learning models that provide
benchmarked evaluation in a variety of conditions, such as across different cultural, demographic, or phenotypic groups (e.g., race, geographic location, sex, Fitzpatrick skin type [15]) and intersectional groups (e.g., age and race, or sex and Fitzpatrick skin type) that are relevant to the intended application domains.
Model cards also disclose the context in which models are intended to be used, details of the performance evaluation procedures, and other relevant information.

 


 

1. 모델 설명 | Used to 

모델명 : MediaPipe Hands (Lite / Full)
  • 구체적인 설명
Hand tracking neural network pipelines: Lite and Full, to predict 2D and 3D hand landmarks on an image / video sequence.
Both pipelines consist of:
 - Hand detector model, which locates hand region
 - Hand tracking model, which predict 2D keypoints, 3D world keypoints, handedness on a cropped area around hand
 - MediaPipe graph, with hand tracking logic.
  • mediapipe와 tfjs 차이
    • hand-pose-detection 모델을 로드하여 옵션을 설정하다 보면, mediapipe 옵션과 tfjs 옵션이 구분되어 있음을 알 수 있음. 그러나 양자의 차이가 헷갈려서 이하에서 정리함
    • 이하 내용은 handpose, face, pose-detection 에서 동일함
  mediapipe tfjs
공통점 머신러닝 모델을 웹 또는 기타 플랫폼에서 실행하기 위한 도구  
차이점 - Google에서 개발한 크로스 플랫폼 프레임워크
- 머신러닝 모델을 비롯한 다양한 타입의 계산 그래프를 구축하고 실행
- Tensorflow의 웹 버전
: Tensorflow 모델을 웹 브라우저 상에서 실행할 수 있게 해줌
미리 구축된 다양한 머신러닝 솔루션(예: 얼굴 인식, 손동작 인식 등)을 제공 → 사용자는 쉽게 복잡한 머신러닝 기능을 구현 JavaScript를 사용하여 직접 모델을 구축하고 학습시키는 데에초점
C++, Python, JavaScript 등 다양한 언어를 지원
→ 데스크톱, 모바일, 웹 등 다양한 플랫폼에서 실행
웹 브라우저 또는 Node.js 환경에서 실행

 


 

Used to
Application
Predicting landmarks within the crop of prominently displayed hands in images or videos captured by a smartphone camera.

Domain & Users
Mobile AR (augmented reality) Mobile AR (augmented reality) applications. Gesture recognition Hand control

Out-of-scope applications not appropriate for:
 - Counting the number of hands in a crowd
 - Predicting hand landmarks with gloves or occlusions. For example when the hand is holding objects or there is decoration on the hand including jewelry, tattoo and henna.
 - Any form of surveillance or identity recognition is explicitly out of scope and not enabled by this technology.

 


 

2. model type | model architecture

개요
  • 총 2가지의 모델로 구성되어 있음. ①detector ②landmark (tracking) 모델
  • 따라서 model type은 양자 모두 CNN (Convolutional Neural Network)로 모두 동일하지만, model architecture는 그 양상이 상이함
  • 즉 모델 아키텍처는 2단계 (detector model 실행 → tracking model 실행)로 이루어져 있는 셈
Two step neural network pipeline with single-shot detector and following regression model running on the cropped region.
  • 위의 사실은 face, pose - detection 이 동일하지만, detector 모델과 tracking 모델 정보를 별도로 제공하는건 handpose가 동일함

 


 

model type: CNN

 


 

model architecture
  • detector model: SSD (Single-Shot Detector model) -> 손 (모양)을 탐지
  • tracker model: Regression model -> 탐지한 손 (모양)의 좌표를 예측

 


3. input, output

  • detector model
Inputs
A frame of video or an image, represented as a 192 x 192 x 3 tensor. Channels order: RGB with values in [0.0, 1.0].

Output(s)
A float tensor 2016 x 18 of predicted embeddings representing anchors transformation which are further used in Non Maximum Suppression algorithm.
  • tracking model (landmark model)
Inputs
A crop of a frame of video or an image, represented as a 224 x 224 x 3 tensor. Channels order: RGB with values in [0.0, 1.0].

Output(s)
A float scalar represents the presence of a hand in the given input image. 21 3-dimensional screen landmarks represented as a 1 x 63 tensor and normalized by image size. This output should only be considered valid when the presence score is higher than a threshold. A float scalar represents the handedness of the predicted hand. This output should only be considered valid when the presence score is higher than a threshold. 21 3-dimensional metric scale world landmarks represented as a 1 x 63 tensor. Predictions are based on the GHUM hand model. This output should only be considered valid when the presence score is higher than a threshold.
  • 결론적으로 사용자 입장에서의 input, output은 다음과 같음
Inputs
A video stream or an image of arbitrary size. Channels order: RGB with values in [0.0, 1.0].

Output(s)
List of detected hands, each containing 21 3-dimensional screen landmarks A float scalar represents the handedness probability of the predicted hand. 21 3-dimensional metric scale world landmarks. Predictions are based on the GHUM hand model.
[
  {
    score: 0.8,
    handedness: ‘Right’,
    keypoints: [
      {x: 105, y: 107, name: "wrist"},
      {x: 108, y: 160, name: "pinky_finger_tip"},
      ...
    ],
    keypoints3D: [
      {x: 0.00388, y: -0.0205, z: 0.0217, name: "wrist"},
      {x: -0.025138, y: -0.0255, z: -0.0051, name: "pinky_finger_tip"},
      ...
    ]
  }
]

 


4. evaluation metric

의미
  • 모델 성능을 측정하는 방법 (Model Performance Measures)
  • 이 방법은 ‘fairness evaluation’ 임. 즉 모델이 여러 집단(ex. 피부색, 성별, 거주 지역)에 대해 동일하게 잘 동작하는지 확인하는 절차임
    -> handpose의 경우, 다양한 지역 / 피부색 / 성별 인구에 대해 모델 작동을 테스트 했음
  • 따라서 metric = 언급한 집단 별로 차이가 있을 법한 수치를 계산하는 것임
  • 위의 내용은 handpose, face, pose-detection 모두에도 적용되는 내용임

 


handpose의 metric : MNAE (Mean of Normalized Absolute Error by palm size)
  • 손바닥 크기의 평균 오차
  • Normalization by palm size
Normalization by palm size is applied to unify the scale of the samples. Palm size is calculated as the distance between the wrist and the first joint (MCP) of the middle finger.
  • Mean absolute error
Mean absolute error is calculated as the pixel distance between ground truth and predicted hand landmarks.
The model provides 3D coordinates, but as the z screen coordinates as well as metric world coordinates are obtained from synthetic data, so for a fair comparison with human annotations, only 2D screen coordinates MNAE are employed.

 


evaluation results
  • 해석 방법
    • MNAE의 범위, 평균, 오차 범위 / MNAE와 stdev와의 차이 / 각 집단의 카테고리별 차이 등을 통계적으로 해석하여 밑과 같은 결론 도출
    • 결론적으로 fairness results를 해석하는 것과 동일함
    • 위 사실은 face, pose - detection 모두 동일함
  • geographical
Evaluation across 14 regions on the validation dataset yields an average performance of 12.02% +/- 1.6% stdev with a range of [8.43%, 13.42%] across regions for the lite model and an average performance of 10.09% +/- 1.73% stdev with a range of [6.10%, 13.00%] across regions for the full model.
We found that per-joint MNAE is the smallest at the base of each finger, and gets larger toward the fingertip. We conjecture that the prediction is easier around the palm which is more rigid than the fingers. We also found that the normalized absolute error is larger for blurry or occluded joints.
The findings are consistent across all regions. We didn’t find any error pattern with regard to the regions.
  • skin tone
Evaluation across 6 skin tone types on the validation dataset yields an average performance of 5.67% +/- 0.94% stdev with a range of [4.88%, 7.25%] across types for lite model and an average performance of 5.08% +/- 0.72% stdev with a range of [4.53%, 6.21%] across types for full model.
  • gender
Evaluation across genders on the validation dataset yields an average performance of 5.67% with a range of [5.29%, 6.05%] for lite model and an average performance of 5.09% with a range of [4.80%, 5.38%] for full model.
Our findings are the same as in geographical fairness evaluation results above. We didn’t find any error pattern with regard to the skin tone types or the gender.

개요

  • 회사에서 Tensorflow.js 의 모델 중 hand-pose-detection, face-landmarks-detection, pose-detection을 이용하여 자사 제품에 구현하는 프로젝트 진행
  • 각 모델의 model card를 보니 model type이 모두 CNN 이었음
  • CNN은 딥러닝에 포함되는 개념이므로, 딥러닝 및 이를 포함하는 머신러닝 의미까지 정리할 필요가 있다고 생각함
  • 참고로 머신러닝, 딥러닝은 모두 인공지능에 포함하는 개념
  • 이하 내용의 출처: 학부 시절 강의 자료를 각색하고, 구글링한 것을 바탕으로 하고, 특별하게 참고한 내용이 있을 경우 링크 걸었음

 


 

1. 머신러닝 (Machine-learning)

의미
  • “기계가 일일이 코드로 명시하지 않은 동작을 데이터로부터 학습하여 실행할 수 있도록 하는 알고리즘을 개발하는 연구 분야” (미국 컴퓨터과학자 아서 사무엘, 1959)
    = 즉 머신러닝은 1. 학습하여 2. 예측 (=기계가 일일이 코드로 명시하지 않은 동작을 실행) 하는 것 까지임
  • 종류는 1. 지도 학습 2. 비지도 학습 3. 강화 학습이 있음.

 

종류
  1. 지도 학습 (Supervised learning)
    • 사람이 각각의 input(x)에 대해 label(y)을 달아 놓은 (=지도) 데이터를 컴퓨터가 학습 (하여 예측)
    • label(y)이 이산적: 분류(classification) 문제, label(y)이 연속적: 회귀(regression) 문제
  2. 비지도 학습 (Unsupervised learning)
    • 사람없이 컴퓨터가 스스로 label(y)이 없는 데이터에 대해 학습
    • 즉 y값 없이 x값 만을 이용하여 학습
  3. 강화 학습 (Reinforcement learning)
    • 현재의 상태(State)에서 어떤 행동(Action)을 취하는 것이 최적인지를 학습
      = 행동을 취할 때마다 외부 환경에서 보상이 주어지는데, 이러한 보상을 최대화 하는 방향 (=강화)으로 학습
    • 예시: 알파고
  4. 내가 지금까지 구현한 모델과 경험해본 프로젝트는 (e.g. 이미지 분류, 자연어 처리, object-detection) 지도 학습에 속함

 

구성 요소
  1. 데이터
    • 내가 알고 있는 입력값 x와 출력값 y가 있는 그 데이터
      = 즉 함수에 넣을 수 있는 입력값과 그 결과

  2. 모형 (Model)
    • 입력값(x)과 목표값(y) 사이의 관계를 나타내는 식
    • 모형의 몇 개의 모수(parameter)로 대표될 수 있음 → 예시: 선형함수의 경우 기울기, y절편
    • 예시: 통계학 모형에서 사용되는 모형들이 모두 예시가 될 수 있음
    • 로지스틱 회귀모형 (Logistic regression model)
      : 이하 예시는 활성 함수 중 하나인 sigmoid function
      • 그래프 (로지스틱 회귀 함수 그림)
      • 추정된 모형 예시
       
  3. 목적 함수 (Objective function or Loss function)
    • 모수 성능 평가 척도
    • 목적 함수가 작을수록 모형이 데이터를 잘 설명
    • 종류: 오차 제곱 함수(MSE), 교차 엔트로피(Cross Entrophy), 로지스틱 손실 함수(Logistic Loss)등
    • 예시
      : 어떤 봉지에 물건을 담을 때 크기와 무게를 고려하여 담은 물건의 총액이 가장 크도록 담고 싶음
      → 목적 함수: 담는 물건의 총액
    • 오차 제곱 함수(Mean Squared Error)
      • 예측값과 실제값 사이 거리를 제곱하여 계산
      • 산식 : MSE = E의 값이 작을수록 알고리즘 성능이 좋음
      • 한계: 학습 속도가 느림
        • ∵ sigmoid의 도함수의 가로축에 해당하는 wx+b가 커질수록 기울기가 작아짐
        • 따라서 오류(error)가 더 큰 쪽의 gredient가 작아짐
          → 직접 산식으로 확인 https://brave-greenfrog.tistory.com/101
    • 교차 엔트로피(Cross Entrophy)
      • 예측값과 실제값 사이의 거리를 제곱하여 계산
      • 산식 (이진 분류의 경우)
        • 이때 p = sigmoid(wx+b)
        • 교차 엔트로피 l를 가중치 w로 미분하면 x(p-y)가 도출되고, bias로 미분하면 p-y가 도출됨
      • 오류(error)가 커질수록 → gradient가 더 크게 계산됨
      • 따라서 오류가 보다 큰 부분의 가중치를 많이 수정하게 되어, 더 빠른 속도로 학습이 이루어짐. 즉 MSE의 한계 보완
       
    • 로지스틱 손실 함수 (Logistic Loss function)
      : 분류 문제를 해결하기 위한 목적 함수  

    • 산식 (이진 분류의 경우) 주의할 점
      • 목적 함수 = 손실 함수 or 손실 함수 외의 함수
        -> 인공지능이 분류 문제를 푸는 경우가 많아 just 손실 함수라고 표현됨. 그러나 손실 함수는 목적 함수의 일부임을 명심!
  4. 최적화 알고리즘 (Optimization algorithm)
    • 목적 함수를 최소화 (= 최적화) 하는 모수를 찾기 위한 알고리즘
    • 예시: Gradient Descent algorithm (GD), Newton Raphson method, EM algorithm 등
    • 다양한 알고리즘 예시가 있지만 딥러닝에서는 주로 GD 기반의 최적화 알고리즘을 사용함

 

결론
  • 딥러닝 ⊂ 기계 학습
  • 양자 차이점: 사용 모형
    → 기계 학습: 인공 신경망, 딥러닝: 심층 인공 신경망 사용
    • 인공신경망(artificial neural network)
      • 머신러닝에서 연구되고 있는 학습 모델 중 하나.
      • 주로 패턴 인식에 쓰이는 기술, 인간의 뇌의 뉴런과 시냅스의 연결을 프로그램으로 재현하는 것
      • 딥러닝(Deep Learning)은 심층 인공 신경망 (Deep neural networks)을 기초로 해서 발전
      • 딥러닝의 등장으로 인공지능 분야가 크게 발전

 


 

2. 딥러닝 (Deep-learning)

의미
  • Deep Neural Network(DNN, 심층인공신경망)을 모형으로 사용하는 머신 러닝
    = 즉 DNN을 모형으로 기계가 학습하여 예측하는 것
    = DNN을 모형으로 기계가 일일히 코드로 명시하지 않은 동작을 데이터로부터 학습하여 실행할 수 있도록 하는 알고리즘을 개발하는 연구 분야
  • DNN
    : 2개 이상의 중간층을 가지고 있는 신경망 모형

 

응용 분야
  • 이미지 분석: 이미지 인식, 압축, 복원, 생성 등
    → 내가 수행한 handpose, face, pose - detection 프로젝트도 여기에 속함
  • 언어 분석: 구글 번역기, 챗봇
  • 음성 분석 : 인공지능 스피커, STT(Speech to Text)
  • 강화 학습 분야: 알파고, 무인자동차

 

기타
  • 딥러닝 모형을 구현할 수 있는 컴퓨팅 환경
    • Hardware: GPU or TPU
    • Python 프로그램: Tensorflow, Keras, Pytorch 등의 모듈
    • 개별 PC에서는 복잡
  • 딥러닝 개발 환경 : 구글 Colaboratory (Colab)!

 


3. 통계학과 인공지능 (머신러닝, 딥러닝) 의 관계

  • 인공지능, 머신러닝에서 가장 먼저 드는 사례가 선형 회귀 분석임. 또한 머신러닝 개념 및 구성 요소를 설명할 때 모수, 최적화 등 통계학의 개념이 자주 등장함. 따라서 양자의 관계에 대해 궁금해짐
  • 현재의 인공지능 방법론은 통계, 예측, 데이터 분석, 딥러닝, 머신러닝, 자연어 처리 등 여러 방법론을 복합적으로 활용함
  • “1987년부터 인공지능이 통계 등 과학적인 방법론을 채택했다”
    (인공지능, 현대적 접근 (Artificial Intelligence A Modern Approach, 3rd edition 25p)
구분 머신러닝 통계학
모델명 지도 학습 (예측 모델) 선형회귀분석
x, y 입력 x, 레이블 y 독립변수 x, 종속변수 y
파라미터 구하는 방법 학습 회귀식 추정
특징 정확한 ‘예측’에 집중 (ex. 영화 평가 예측의 정확도 구하기) 사람들의 ‘선택 이유’에 집중 (ex. 사람들이 그 영화를 영화관에서 보는 이유 분석)

 

문제 인식

  • 정지 버튼을 누르면 캔버스에 그려졌던 손, 얼굴, 포즈의 keypoints와 path가 남아있는 현상
  • 사수께서 clearRect() 함수가 정상적으로 적용되지 않았다고 알려주심

 


 

cleatRect() 함수 사용법

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 200, 100);
ctx.clearRect(40, 40, 50, 50);
  • 결과물 : 빨간색 context 내부에 설정한 크기의 사각형의 색이 지워졌음

  • 그러나 이 코드가 개별 detector 함수에 들어가면 안 됨 (∵ 향후 다른 detector 함수와 함께 실행하였을 때 오류 가능성)
  • 따라서 detector 관련 코드를 모두 관리하는 detector-manager 코드에서 clearRect() 함수를 적용해야 함

 


 

해결법

  • draw 하여 캔버스에 비디오를 그리기 전에 clearRect 하여 이전의 캔버스를 지워야함
  • 지속적으로 렌더링되어 캔버스에 이미지가 그려지기 때문
if (result) {
  if (dt.drawBox) {
      dt.context.clearRect(0,0,Detector.DIMENSIONS[0],Detector.DIMENSIONS[1]);
      dt.detector.draw(dt.canvas);
      this._renderer.updateBitmapSkin(dt.skinId, dt.canvas, 1);
  } 
} else {
  if (dt.drawBox && hasResult) {
      dt.context.clearRect(0,0,Detector.DIMENSIONS[0],Detector.DIMENSIONS[1]);
      this._renderer.updateBitmapSkin(dt.skinId,dt.canvas,1);
  }
}

문제 인식

  • 일렉트론으로 구현해보았을 때는 이하 코드처럼 라이브 비디오 자체를 매개변수로 예측하였음.
const hands = await detector.estimateHands(camera.video, { flipHorizontal: false });
  • 그러나 자사 소프트웨어 기존 코드에서는 estimate 함수의 매개변수가 이미지임. 따라서 기존 방식을 따라 가야 했음

 


 

1. Tensorflow.js 공식 깃헙

  • 매개변수의 확인 → 이미지와 비디오 둘 다 가능!
  • 따라서 이미지로 estimate 함수 사용하여 일렉트론으로 구현해보고자 함
// 이미지
const result = await detector.estimateHands(image, {
  staticImageMode: true
} as handPoseDetection.MediaPipeHandsTfjsEstimationConfig);

// 비디오
const hands = await detector.estimateHands(video, null /* config */);

 


 

2. 일렉트론으로 구현 

  • 핵심 로직
    1. ctx.drawImage(video, 0, 0, canvas.width, canvas.height) 
      : 웹 캠에서 받아온 비디오 현재 프레임을 캔버스에 표시
    2. ctx.getImageData(0, 0, canvas.width, canvas.height)
      : 캔버스의 이미지 데이터를 가져옴 (캡처)
  • 핵심 코드 
_captureImageData(video) {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = video.videoWidth;  
  canvas.height = video.videoHeight;
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);  
  return ctx.getImageData(0, 0, canvas.width, canvas.height);
}

// estimate 함수에 적용
const detector = createDetector(SupportedModels.MediapipeHands);
const imageData = HandposeDetector.captureImageData(video);
const result = await detector.estimateHands(imageData);

 


 

해결법 (요약)

  • GUI 프로젝트 코드에 이미 video → image 로 바꾸는 로직이 작성되어 있었음
// drawImage()
if (lastUpdate + cacheTimeout < now) {
  try {
      if (mirror) {
          context.scale(-1, 1);
          context.translate(width * -1, 0);
      }
      context.drawImage(this._element,
          // source x, y, width, height
          0, 0, elementDimension.width, elementDimension.height,
          // dest x, y, width, height
          0, 0, width, height
      );
      context.setTransform(1, 0, 0, 1, 0, 0);
      workspace.lastUpdate = now;
  } catch {
      return null;
  }
}

// getImageData()
if (formatCache.lastUpdate + cacheTimeout < now) {
	if (format === CameraProvider.FORMAT_IMAGE_DATA) {
	    formatCache.lastData = context.getImageData(0, 0, width, height);
}

 

  • 나는 이미 정해져 있는 detect 함수의 매개변수인 imageData를 가져와 처리함
detect(imageData) {
	return new Promise((resolve, reject) => {   
    this._detector.estimateHands(imageData).then(result => {
        this._result = result;
        console.log(`this._result: `, this._result);

        this._result.forEach((res) => {
            console.log(`${res.handedness} hand keypoints:`);
            res.keypoints.forEach((keypoint, i) => {
                let x = keypoint.x - 320;
                let y = keypoint.y - 240;
                console.log(`Keypoint ${i}: [${x}, ${y}]`);
            })
        })
        resolve(this._result);
    }).catch(e => {
        reject(e);
    });
	})
}

 

 

 

개요

 


 

1. npm install 해야 할 최소한의 모듈

<!-- 둘이 set-->
npm install @tensorflow-models/hand-pose-detection --legacy-peer-deps
npm install @mediapipe/hands --legacy-peer-deps

<!-- 위의 핵심 라이브러리를 실행할 수 있도록 하기 위한 peer dependency-->
npm install @tensorflow/tfjs --legacy-peer-deps
npm install @tensorflow/tfjs-converter --legacy-peer-deps
npm install @tensorflow/tfjs-core --legacy-peer-deps
  • 추가적으로 필요하다고 여겨지는 @tensorflow/tfjs-backend-webgl @tensorflow/tfjs-backend-wasm @tensorflow/tfjs-backend-webgpu 은 이하 peer dependency 에 이미 포함되어 있음
  • 특히 webgl을 tf.setBackend(’webgl’) 식으로 설정할 필요도 없음. 아래 설치하고 핵심 라이브러리를 require 하면 자동 설정됨
  • 주의할 점 : peer dependency 충돌 해결하는 글 보러 가기

이하 글의 코드와 글의 근본적인 출처는 Tensorflow-models 공식 깃헙입니다!

 

개요

  • 이하에서는 이번 프로젝트에서 구현한 hand-pose-detection, face-landmarks-detection, pose-detection 모델을 로딩하는 방법을 정리하였음.
  • 위 모델들을 로딩한다는 것 = createDetector() 함수를 실행한다는 것 
  • 이하 방법은 model loading 시리즈 2편인 npm install 해야하는 최소한의 모듈 글을 참고해서 코드를 짜야 보다 효율적임
  • 또한 createDetector() 함수를 오프라인으로 저장한 모델과 함께 사용하는 경우, 버전을 제대로 맞추지 않는다면 quantization 오류를 계에에에에속 맞닥뜨릴 것임. 따라서 해당 오류를 해결한 글과 함께 보길 권장함 

 


 

1. CDN

  • CDN 이란 
    • Contents Delivery Network : 콘텐츠 전송 네트워크
    • 콘텐츠를 임시 저장 서버에 옮겼다가 수요가 있을 때 콘텐츠를 전달
  • 핵심 코드 : 이하 코드는 Tensorflow-models 공식 깃헙에서 demo 코드로 명시한 방법
<!-- Require the peer dependencies of hand-pose-detection. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-core"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-converter"></script>

<!-- You must explicitly require a TF.js backend if you're not using the TF.js union bundle. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-webgl"></script>

<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/hand-pose-detection"></script>

 


 

2. npm install + require( 또는 import )

  • npm 모듈 설치 
npm install @tensorflow-models/hand-pose-detection
npm install @tensorflow/tfjs-core, @tensorflow/tfjs-converter
npm install @tensorflow/tfjs-backend-webgl
  • require (또는 import)
// require
const {createDetector,SupportedModels} = require("@tensorflow-models/hand-pose-detection");

// import
import * as handPoseDetection from '@tensorflow-models/hand-pose-detection';
import * as tf from '@tensorflow/tfjs-core';
// Register WebGL backend.
import '@tensorflow/tfjs-backend-webgl';
  • 그러나 위의 1번, 2번 방법은 온라인 환경에서만 정상 작동한다는 단점이 있음. 이를 보완하는 방법으로 모델을 오프라인으로 저장해서 불러오는 3번이 있음

 


 

3. 오프라인 저장 

  • 모델을 오프라인 저장 해야 하는 이유
    1. CORS 에러 (Cross-Origin Resource Sharing)
      • 웹 브라우저가 다른 도메인, 프로토콜, 포트에서 실행되는 웹페이지에서 리소스를 요청할 때 발생
      • 따라서 모델을 오프라인 저장하지 않고, localhost:5050 에서 localhost:8888 로 model.json을 요청한다면,
        웹 브라우저가 포트 번호가 달라 다른 출처(origin)으로 간주하고 CORS 정책에 따라 요청 차단함
      • CORS에 대해 보다 전문적으로 설명한 글 보러 가기 
 

CORS

 

ko.javascript.info

       2. 자사 소프트웨어 특성 상 인터넷이 끊어져도 제품 사용할 수 있어야 함
          : 그러나 CDN 방식과 npm install 방식은 온라인 상태여야만 Tensorflow-models의 npm 모듈 사용 가능

 

 

Find Pre-trained Models | Kaggle

Use and download pre-trained models for your machine learning projects.

www.kaggle.com

       

        2. createDetector() 함수의 옵션 지정 : detectorModelUrl, landmarkModelUrl 모델 저장 장소 지정

_createDetector() {
  const model = SupportedModels.MediaPipeHands;
  const detector = createDetector(model, {
      runtime: "tfjs",
      modelType: "lite",
      maxHands: 2, // or 2~10.
      flipHorizontal: false,
      staticImageMode: false,
      detectorModelUrl:
          "/static/tensorflow-models/tfjs-model_handpose_3d_detector_lite_1/model.json",
      landmarkModelUrl:
          "/static/tensorflow-models/tfjs-model_handpose_3d_landmark_lite_1/model.json",
  });
  return detector;
}

 

      3. 비동기로 모델 로딩

if (!this._detector) {
    this._createDetector().then(detector => {
        this._detector = detector;
        console.log("model loading success!, detector: ", this._detector);
    })
}

 

      4. 모델 로딩 결과 : <pending> → 펼치면 “fulfilled” 출력되어야 함

+ Recent posts