본문 바로가기
AI

[Tensorflow] Tensorflow 기본 개념, keras 란?

by 은구잇 2021. 12. 17.
728x90

1. 텐서란?

 

텐서는 다차원 배열(Multi-dimensional Array) 입니다.

텐서는 백터와 행렬을 일반화 한것이면 3차원 이상으로 확장할 수 있습니다.

TensorFlow의 가장 중요한 객체이며 텐서의 연산으로 진행할 수 있습니다.

2. 텐서의 차원 - Rank

 

텐서의 랭크 확인하는 방법.

 

<코드>

import tensorflow as tf

 

scalar = tf.constant(1)

vector = tf.constant([1,2,3])

matrix = tf.constant([1,2,3],[4,5,6],[7,8,9])

tensor = tf.constant([[[1, 2, 3], [4, 5, 6], [7, 8, 9],[10, 11, 12]],
                      [[1, 2, 3], [4, 5, 6], [7, 8, 9],[10, 11, 12]]])

 

랭크를 순서대로 출력해보면 0, 1, 2, 3 차원을 확인 할 수 있다.

tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)

 

3. 텐서에서 사용하는 메서드

 

import tensorflow as tf

 

# tf.zeros -> 모든 요소가 0인 텐서를 만들기

a = tf.zeros(1)

b = tf.zeros([2])

c = tf.zeros([2,3])

 

# tf.ones() 도 동일하게 사용.

# tf.range() 사용

 

# tf.linspace() : 주어진 범위를 균일한 간격으로 나누는 것.

a = tf.linspace(0,1,3)

 

4. 텐서의 자료형과 형태   dtype, shape

 

d = tf.constant([1., 2.])
e = tf.constant([[1, 2., 3]])
f = tf.constant([[1, 2], [3, 4]])

print(d.dtype, d.shape)
print(e.dtype, e.shape)
print(f.dtype, f.shape)

 

<dtype: 'float32'> (2,)
<dtype: 'float32'> (1, 3)
<dtype: 'int32'> (2, 2)

 

5. Numpy 호환성

텐서는 Numpy 어레이와 비슷하지만 gpu를 사용할 수 있음.

 

a = tf.constant([1,2,3])

a.numpy()   <- numpy 어레이로 변환.