Learning
레슨 1 / 8·15분

텐서와 연산

TensorFlow.js는 브라우저와 Node.js에서 머신러닝 모델을 학습하고 실행할 수 있는 JavaScript 라이브러리입니다. 핵심 데이터 구조인 텐서(Tensor)는 다차원 배열을 나타내며, GPU 가속을 활용한 수학 연산을 제공합니다.

텐서 생성

javascript
import * as tf from '@tensorflow/tfjs';

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

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

// 스칼라 (단일 값)
const scalar = tf.scalar(3.14);

// 특수 텐서
const zeros = tf.zeros([2, 3]);   // 2x3 영행렬
const ones = tf.ones([3, 3]);     // 3x3 단위값 행렬

// shape와 dtype 확인
console.log(matrix.shape);  // [2, 2]
console.log(matrix.dtype);  // 'float32'

텐서 연산

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

// 요소별 연산
const sum = a.add(b);        // [5, 7, 9]
const product = a.mul(b);    // [4, 10, 18]

// 행렬 곱
const m1 = tf.tensor2d([[1, 2], [3, 4]]);
const m2 = tf.tensor2d([[5, 6], [7, 8]]);
const matMul = m1.matMul(m2);
matMul.print();
// [[19, 22],
//  [43, 50]]

// 텐서 값을 JavaScript 배열로 변환
const data = await sum.data();
console.log(data);  // Float32Array [5, 7, 9]

메모리 관리

javascript
// 텐서는 GPU 메모리를 사용하므로 수동 해제가 필요합니다
const tensor = tf.tensor([1, 2, 3]);
// 사용 후 메모리 해제
tensor.dispose();

// tf.tidy()로 자동 메모리 관리 (권장)
const result = tf.tidy(() => {
  const x = tf.tensor([1, 2, 3]);
  const y = tf.tensor([4, 5, 6]);
  // tidy 블록 안에서 생성된 중간 텐서는 자동 해제
  // 반환된 텐서만 유지됨
  return x.add(y);
});

result.print();  // [5, 7, 9]
// result는 나중에 직접 dispose() 해야 합니다
💡

tf.tidy() 안에서는 중간 계산에 사용된 텐서가 자동으로 해제됩니다. 메모리 누수를 방지하려면 항상 tf.tidy()를 사용하세요. 단, tf.tidy() 내부에서는 비동기 코드를 사용할 수 없습니다.