본문으로 건너뛰기
실습하기

텐서 연산 이해하기

텐서플로우에서 데이터를 표현하는 기본 단위인 텐서(Tensor)를 활용하면 덧셈, 뺄셈, 곱셈과 같은 기본적인 사칙 연산부터 행렬 곱셈, 차원 변경까지 다양한 연산을 수행할 수 있습니다.

이번 수업에서는 기본적인 텐서 연산을 수행하는 방법을 살펴보겠습니다.


1. 기본 연산 (덧셈, 뺄셈, 곱셈, 나눗셈)

텐서 간 기본적인 사칙연산을 수행할 수 있습니다.

텐서 연산 예시
import tensorflow as tf

# 2개의 1차원 텐서 생성
tensor_a = tf.constant([1, 2, 3])
tensor_b = tf.constant([4, 5, 6])

# 기본 연산 수행
add_result = tf.add(tensor_a, tensor_b) # 덧셈

diff_result = tf.subtract(tensor_a, tensor_b) # 뺄셈

mul_result = tf.multiply(tensor_a, tensor_b) # 곱셈

div_result = tf.divide(tensor_a, tensor_b) # 나눗셈

print("덧셈 결과:", add_result)
# 덧셈 결과: tf.Tensor([5 7 9], shape=(3,), dtype=int32)

print("뺄셈 결과:", diff_result)
# 뺄셈 결과: tf.Tensor([-3 -3 -3], shape=(3,), dtype=int32)

print("곱셈 결과:", mul_result)
# 곱셈 결과: tf.Tensor([ 4 10 18], shape=(3,), dtype=int32)

print("나눗셈 결과:", div_result)
# 나눗셈 결과: tf.Tensor([0.25 0.4 0.5], shape=(3,), dtype=float64)

2. 행렬 곱셈 (Matrix Multiplication)

신경망에서 입력 데이터와 가중치 사이의 연산은 행렬 곱셈을 통해 수행됩니다.

예를 들어 신경망의 각 층(Layer)에서 입력 벡터(Input Vector)와 가중치 행렬을 곱한 후, 활성화 함수를 적용하여 출력을 생성할 때 행렬 곱셈 연산이 사용됩니다.

행렬 곱셈을 수핼할 때는 tf.matmul()을 사용합니다.

행렬 곱셈 예시
# 2x3 행렬과 3x2 행렬 생성
matrix_a = tf.constant([[1, 2, 3], [4, 5, 6]])
matrix_b = tf.constant([[7, 8], [9, 10], [11, 12]])

# 행렬 곱셈 수행
matmul_result = tf.matmul(matrix_a, matrix_b)
print("행렬 곱셈 결과:", matmul_result)
# 행렬 곱셈 결과: tf.Tensor(
# [[ 58 64]
# [139 154]], shape=(2, 2), dtype=int32)

3. 차원 변경 (Reshape & Transpose)

딥러닝 모델에서는 데이터를 특정 형태로 변환해야 할 때가 많습니다.

tf.reshape()tf.transpose()를 사용하여 텐서의 형태를 변경할 수 있습니다.

# 1차원 텐서를 2x3 행렬로 변환
reshaped_tensor = tf.reshape(tf.constant([1, 2, 3, 4, 5, 6]), (2, 3))
print("변형된 텐서:", reshaped_tensor)
# 변형된 텐서: tf.Tensor(
# [[1 2 3]
# [4 5 6]], shape=(2, 3), dtype=int32)

# 행렬 전치
transposed_tensor = tf.transpose(reshaped_tensor)
print("전치된 텐서:", transposed_tensor)
# 전치된 텐서: tf.Tensor(
# [[1 4]
# [2 5]
# [3 6]], shape=(3, 2), dtype=int32)

이외에도 다음과 같은 다양한 텐서 연산을 수행할 수 있습니다.

  • 축 기준 연산 : 특정 차원을 따라 합계(sum), 평균(mean), 최대값(max), 최소값(min)을 계산

  • 브로드캐스팅 : 작은 텐서를 더 큰 텐서에 자동으로 확장하여 연산을 수행하는

  • tf.where() : 특정 조건에 따라 값을 선택

다음 수업에서는 지금까지 배운 내용을 바탕으로 간단한 퀴즈를 풀어보겠습니다.

다음 내용이 궁금하다면?

코드프렌즈 PLUS 멤버십 가입 or 강의를 등록해 주세요!