본문 바로가기
프로그래밍/TensorFlow2

텐서와 변수 - 2

by 세인트 워터멜론 2021. 2. 10.

Tensorflow의 텐서는 일정한 데이터 타입(dtype이라고 함)을 가진 다차원 배열이다. numpy의 ndarray과 매우 유사하지만 변경이 불가능하다. 즉, 텐서는 생성된 후에는 변경할 수 없는 상수(constant)다.

 

 

모델에서 텐서를 추출할 수도 있지만 모델에 관계없이 직접 텐서를 생성할 수도 있다. 먼저 몇 가지 Tensorflow 함수를 이용해서 텐서를 생성해 보자. 다음은 tf.constant를 이용한 텐서의 생성 예다.

 

a0 = tf.constant(2)
a1 = tf.constant([1.0, 2.0])
a2 = tf.constant([[1, 2, 3], [4, 5, 6]])
a3 = tf.constant([
    [ [1.0], [2.0] ],
    [ [3.0], [4.0] ],
    [ [5.0], [6.0] ]
    ])

print(a0)
print(a1)
print(a2)
print(a3)

 

프린트해보면 결과는 다음과 같다. a0은 차원이 0인 스칼라 텐서이고 데이터 타입은 int32다.

 

Output:

tf.Tensor(2, shape=(), dtype=int32)

 

a1은 차원이 1인 벡터 텐서이고 데이터 타입은 float32다.

 

Output:

tf.Tensor([1. 2.], shape=(2,), dtype=float32)

 

a2는 차원이 2인 \(2 \times 3\) 행렬 텐서이고 데이터 타입은 int32다.

 

Output:

tf.Tensor(
[[1 2 3]
 [4 5 6]], shape=(2, 3), dtype=int32)

 

a3은 차원이 3인 \(3 \times 2 \times 1\) 텐서이고 데이터 타입은 float32다.

 

Output:

tf.Tensor(
[[[1.]
  [2.]]

 [[3.]
  [4.]]

 [[5.]
  [6.]]], shape=(3, 2, 1), dtype=float32)

 

 

 

tf.ones와 tf.zeros를 이용하여 모든 성분이 0 또는 1인 텐서를 생성할 수도 있다.

 

zero1 = tf.zeros((3,2))
one1 = tf.ones((2,3))

 

.numpy 메쏘드를 사용하면 텐서 데이터를 numpy 배열로 변환할 수 있다.

 

a2_num = a2.numpy()

 

반대로 numpy 배열에서 텐서로 변환할 수도 있다.

 

a2_tensor = tf.constant(a2_num)

 

파이썬에는 상수가 없기 때문에 같은 이름의 b에 값을 두 번 대입할 수 있다.

 

b = tf.constant(5)
print(b)
b = tf.constant(4)
print(b)

 

 

Output:

tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(4, shape=(), dtype=int32)

 

따라서 즉시 실행(eager) 모드에서는 연산 결과만 가지고는 텐서가 그 값을 변경할 수 없는 상수인지 확실히 알 수 없다. 하지만 내부적으로 다른 이름으로 두 상수를 구분하고 있다. 그래프(graph) 모드에서는 이를 확인할 수 있다.

 

with tf.Graph().as_default():
    c = tf.constant(8)
    print(c)
    c = tf.constant(7)
    print(c)

 

 

Output:

Tensor("Const:0", shape=(), dtype=int32)
Tensor("Const_1:0", shape=(), dtype=int32)

 

name 키워드를 이용하여 텐서에 같은 이름 'c'를 부여해도,

 

with tf.Graph().as_default():
    c = tf.constant(8, name='c')
    print(c)
    c = tf.constant(7, name='c')
    print(c)

 

내부적으로 c와 c_1라는 이름으로 두 상수를 구분하고 있다.

 

Output:

Tensor("c:0", shape=(), dtype=int32)
Tensor("c_1:0", shape=(), dtype=int32)

 

어쨌든 텐서는 값을 변경할 수 없으며 새로운 텐서를 생성할 수 있을 뿐이다.

 

 

 

'프로그래밍 > TensorFlow2' 카테고리의 다른 글

tf.reduce_sum 함수  (0) 2021.03.12
텐서와 변수 - 3  (0) 2021.02.11
텐서와 변수 - 1  (0) 2021.02.09
GradientTape로 간단한 CNN 학습하기  (0) 2021.01.11
Model Subclassing API로 간단한 CNN 구현해 보기  (0) 2021.01.11

댓글