TensorFlow.js란?

TensorFlow.js는 Google이 개발한 머신러닝 라이브러리인 TensorFlow의 JavaScript 버전입니다. 브라우저와 Node.js 환경에서 모두 실행되며, 별도의 서버 없이 클라이언트 사이드에서 머신러닝 모델을 학습하고 예측할 수 있습니다.

TensorFlow.js의 주요 특징

  • 브라우저 기반 실행: 서버 없이 브라우저에서 바로 실행
  • GPU 가속: WebGL/WebGPU를 통한 하드웨어 가속 지원
  • 모델 호환성: Python TensorFlow 모델 변환 지원
  • 오프라인 작동: 학습된 모델을 브라우저 캐시에 저장하여 오프라인에서도 사용 가능

1. TensorFlow.js 설치

프로젝트 설정

# 새 프로젝트 생성
npm init -y

# TensorFlow.js 설치
npm install @tensorflow/tfjs

HTML에서 직접 사용

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>

2. 기본 개념 이해

텐서(Tensor)

텐서는 TensorFlow.js의 기본 데이터 구조입니다. 다차원 배열로 생각할 수 있습니다.

// 0차원 텐서 (스칼라)
const scalar = tf.scalar(5);

// 1차원 텐서 (벡터)
const vector = tf.tensor1d([1, 2, 3, 4]);

// 2차원 텐서 (행렬)
const matrix = tf.tensor2d([[1, 2], [3, 4]]);

// 3차원 텐서
const tensor3d = tf.tensor3d([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]);

텐서 연산

const a = tf.tensor1d([1, 2, 3]);
const b = tf.tensor1d([4, 5, 6]);

// 덧셈
const sum = a.add(b); // [5, 7, 9]

// 곱셈
const product = a.mul(b); // [4, 10, 18]

// 행렬 곱셈
const matA = tf.tensor2d([[1, 2], [3, 4]]);
const matB = tf.tensor2d([[5, 6], [7, 8]]);
const matMul = matA.matMul(matB);

3. 첫 번째 모델: 선형 회귀

선형 회귀는 가장 기본적인 머신러닝 알고리즘으로, 데이터의 패턴을 직선으로 찾습니다.

async function linearRegression() {
  // 1. 모델 생성
  const model = tf.sequential();
  
  // 2. 레이어 추가
  model.add(tf.layers.dense({
    units: 1,
    inputShape: [1]
  }));

  // 3. 모델 컴파일
  model.compile({
    optimizer: tf.train.sgd(0.01),
    loss: 'meanSquaredError'
  });

  // 4. 학습 데이터 준비
  const xs = tf.tensor1d([1, 2, 3, 4, 5]);
  const ys = tf.tensor1d([2, 4, 6, 8, 10]);

  // 5. 모델 학습
  await model.fit(xs, ys, {
    epochs: 100,
    callbacks: {
      onEpochEnd: (epoch, logs) => {
        console.log(`Epoch ${epoch}: loss = ${logs.loss.toFixed(4)}`);
      }
    }
  });

  // 6. 예측
  const prediction = model.predict(tf.tensor1d([6]));
  prediction.print(); // 약 12 예상

  // 메모리 정리
  xs.dispose();
  ys.dispose();
  prediction.dispose();
}

linearRegression();

4. 웹 애플리케이션 통합

간단한 예측 앱

<!DOCTYPE html>
<html>
<head>
  <title>TensorFlow.js 선형 회귀</title>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
</head>
<body>
  <h1>선형 회귀 예측</h1>
  <input type="number" id="inputValue" placeholder="값 입력">
  <button onclick="predict()">예측</button>
  <p id="result"></p>

  <script>
    let model;

    async function trainModel() {
      // 모델 생성 및 학습
      model = tf.sequential();
      model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
      model.compile({ optimizer: tf.train.sgd(0.01), loss: 'meanSquaredError' });

      const xs = tf.tensor1d([1, 2, 3, 4, 5]);
      const ys = tf.tensor1d([2, 4, 6, 8, 10]);

      await model.fit(xs, ys, { epochs: 100 });

      document.getElementById('result').textContent = '모델 학습 완료!';
    }

    function predict() {
      const input = document.getElementById('inputValue').value;
      if (!input) return;

      const prediction = model.predict(tf.tensor1d([parseFloat(input)]));
      const result = prediction.dataSync()[0];

      document.getElementById('result').textContent = `예측 결과: ${result.toFixed(2)}`;
      prediction.dispose();
    }

    trainModel();
  </script>
</body>
</html>

5. Web Worker 사용

머신러닝 연산은 메인 스레드를 차단할 수 있습니다. Web Worker를 사용하여 백그라운드에서 연산을 처리하세요.

// worker.js
importScripts('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js');

self.onmessage = async function(e) {
  const { data } = e.data;
  
  // 백그라운드에서 모델 학습
  const model = tf.sequential();
  model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
  model.compile({ optimizer: tf.train.sgd(0.01), loss: 'meanSquaredError' });
  
  const xs = tf.tensor1d(data.x);
  const ys = tf.tensor1d(data.y);
  
  await model.fit(xs, ys, { epochs: 100 });
  
  self.postMessage({ trained: true });
  
  xs.dispose();
  ys.dispose();
};
// main.js
const worker = new Worker('worker.js');

worker.postMessage({
  data: {
    x: [1, 2, 3, 4, 5],
    y: [2, 4, 6, 8, 10]
  }
});

worker.onmessage = function(e) {
  console.log('모델 학습 완료!');
};

6. 성능 최적화

GPU 가속

TensorFlow.js는 기본적으로 WebGL을 사용하여 GPU 가속을 제공합니다.

// WebGL 사용 (기본값)
tf.setBackend('webgl');

// WebGPU 사용 (최신 브라우저)
tf.setBackend('webgpu');

// CPU 사용 (디버깅용)
tf.setBackend('cpu');

메모리 관리

// 텐서 생성 시 자동 메모리 관리
tf.tidy(() => {
  const a = tf.tensor1d([1, 2, 3]);
  const b = tf.tensor1d([4, 5, 6]);
  const sum = a.add(b);
  return sum.dataSync(); // tidy 내부의 텐서는 자동으로 메모리 해제
});

// 수동 메모리 해제
const tensor = tf.tensor1d([1, 2, 3]);
// 사용 후
tensor.dispose();

7. 모델 저장 및 로드

모델 저장

async function saveModel(model) {
  await model.save('localstorage://my-model');
  // 또는
  await model.save('indexeddb://my-model');
}

모델 로드

async function loadModel() {
  const model = await tf.loadLayersModel('localstorage://my-model');
  return model;
}

8. 실전 팁

  1. 데이터 정규화: 학습 데이터를 0-1 사이로 정규화하면 학습 속도가 빨라집니다.
  2. 배치 크기: 큰 데이터셋에서는 배치 학습을 사용하세요.
  3. 학습률: 너무 높으면 발산, 너무 낮으면 학습이 느려집니다.
  4. 과적합 방지: 검증 데이터를 사용하여 과적합을 감시하세요.

결론

TensorFlow.js를 사용하면 복잡한 서버 인프라 없이도 브라우저에서 머신러닝을 구현할 수 있습니다. 이를 통해 개인정보 보호, 오프라인 작동, 빠른 응답 속도 등 다양한 이점을 누릴 수 있습니다.

다음 단계로는 더 복잡한 모델(신경망, CNN, RNN)을 구현해보고, 실제 프로젝트에 적용해보세요!