상세 컨텐츠

본문 제목

1.딥러닝 데이터 표현과 연산

본문

딥러닝 데이터 표현과 연산

  • 데이터 표현을 위한 기본 구조로 텐서(tensor)를 사용
  • 텐서는 데이터를 담기위한 컨테이너(container)로서 일반적으로 수치형 데이터를 저장
 

 

 

텐서(Tensor)

  • Rank: 축의 개수
  • Shape: 형상(각 축에 따른 차원 개수)
  • Type: 데이터 타입
import numpy as np
import tensorflow as tf
 

0D Tensor(Scalar)

  • 하나의 숫자를 담고 있는 텐서(tensor)
  • 축과 형상이 없음
t0= tf.constant(1)
print(t0)
 
출력
tf.Tensor(1, shape=(), dtype=int32)

1D Tensor(Vector)

  • 값들을 저장한 리스트와 유사한 텐서
  • 하나의 축이 존재
t1=tf.constant([1,2,3])
print(t1)
print(tf.rank(t1))
출력
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)

2D Tensor(Matrix)

  • 행렬과 같은 모양으로 두개의 축이 존재
  • 일반적인 수치, 통계 데이터셋이 해당
  • 주로 샘플(samples)과 특성(features)을 가진 구조로 사용
t2= tf.constant([[1,2,3],
                [4,5,6],
                [7,8,9]])
print(t2)
print(tf.rank(t2))
출력
tf.Tensor(
[[1 2 3]
 [4 5 6]
 [7 8 9]], shape=(3, 3), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
코드텍스트
 
 

3D Tensor

  • 큐브(cube)와 같은 모양으로 세개의 축이 존재
  • 데이터가 연속된 시퀀스 데이터나 시간 축이 포함된 시계열 데이터에 해당
  • 주식 가격 데이터셋, 시간에 따른 질병 발병 데이터 등이 존재
  • 주로 샘플(samples), 타임스텝(timesteps), 특성(features)을 가진 구조로 사용
t3= tf.constant([[[1,2,3],
                  [4,5,6],
                  [7,8,9]],
                  [[1,2,3],
                   [4,5,6],
                   [7,8,9]],
                [[1,2,3],
                [4,5,6],
                [7,8,9]]])
print(t3)
print(tf.rank(t3))
 
출력
tf.Tensor( [[[1 2 3] [4 5 6] [7 8 9]] [[1 2 3] [4 5 6] [7 8 9]] [[1 2 3] [4 5 6] [7 8 9]]], shape=(3, 3, 3), dtype=int32) tf.Tensor(3, shape=(), dtype=int32)
 

텐서 데이터 타입

  • 텐서의 기본 dtype
    • 정수형 텐서: int32
    • 실수형 텐서: float32
    • 문자열 텐서: string
  • int32, float32, string 타입 외에도 float16, int8 타입 등이 존재
  • 연산시 텐서의 타입 일치 필요
  • 타입변환에는 tf.cast() 사용
i=tf.constant(2)
 
출력

<tf.Tensor: shape=(), dtype=int32, numpy=2>

f=tf.constant(2.)
f
 
출력
<tf.Tensor: shape=(), dtype=float32, numpy=2.0>
s=tf.constant('sdf')
print(s)
 
출력
tf.Tensor(b'sdf', shape=(), dtype=string)
 

텐서 연산

print(tf.constant(2)+tf.constant(2))
print(tf.constant(2)-tf.constant(2))
print(tf.add(tf.constant(2),tf.constant(2)))
print(tf.subtract(tf.constant(2),tf.constant(2)))
 
출력
 
tf.Tensor(4, shape=(), dtype=int32) tf.Tensor(0, shape=(), dtype=int32) tf.Tensor(4, shape=(), dtype=int32) tf.Tensor(0, shape=(), dtype=int32)
 
print(tf.constant(2)*tf.constant(2))
print(tf.constant(2)/tf.constant(2))
print(tf.multiply(tf.constant(2),tf.constant(2)))
print(tf.divide(tf.constant(2),tf.constant(2)))

출력

tf.Tensor(4, shape=(), dtype=int32) tf.Tensor(1.0, shape=(), dtype=float64) tf.Tensor(4, shape=(), dtype=int32) tf.Tensor(1.0, shape=(), dtype=float64)

관련글 더보기