![]() |
![]() |
![]() |
![]() |
이 노트북은 텐서플로를 사용하기 위한 입문 튜토리얼입니다. 다음 내용을 다룹니다 :
- 필요한 패키지 임포트
- 텐서(Tensor) 생성 및 사용
- GPU 가속기 사용
tf.data.Dataset
시연
TensorFlow 가져오기
시작하기 위해서 텐서플로 모듈을 임포트합니다. 텐서플로 2.0에서는 즉시 실행(eager execution)이 기본적으로 실행됩니다. 이는 텐서플로를 조금 더 대화형 프론트엔드(frontend)에 가깝게 만들어 줍니다. 세부사항은 나중에 이야기할 것입니다.
import tensorflow as tf
텐서
텐서는 다차원 배열입니다. NumPy ndarray
객체와 유사하게 tf.Tensor
객체에는 데이터 유형과 형상이 있습니다. 또한 tf.Tensor
는 가속기 메모리(예: GPU)에 상주할 수 있습니다. TensorFlow는 tf.Tensor
를 소비하고 생성하는 풍부한 연산 라이브러리를 제공합니다(tf.add, tf.matmul, tf.linalg.inv 등). 이러한 연산은 기본 Python 유형을 자동으로 변환합니다. 예를 들면 다음과 같습니다.
print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.square(5))
print(tf.reduce_sum([1, 2, 3]))
# Operator overloading is also supported
print(tf.square(2) + tf.square(3))
tf.Tensor(3, shape=(), dtype=int32) tf.Tensor([4 6], shape=(2,), dtype=int32) tf.Tensor(25, shape=(), dtype=int32) tf.Tensor(6, shape=(), dtype=int32) tf.Tensor(13, shape=(), dtype=int32)
각각의 tf.Tensor
는 크기와 데이터 타입을 가지고 있습니다.
x = tf.matmul([[1]], [[2, 3]])
print(x)
print(x.shape)
print(x.dtype)
tf.Tensor([[2 3]], shape=(1, 2), dtype=int32) (1, 2) <dtype: 'int32'>
넘파이 배열과 tf.Tensor
의 가장 확연한 차이는 다음과 같습니다:
- 텐서는 가속기 메모리(GPU, TPU와 같은)에서 사용할 수 있습니다.
텐서
는 불변성(immutable)을 가집니다.
넘파이 호환성
텐서와 넘파이 배열 사이의 변환은 다소 간단합니다.
- 텐서플로 연산은 자동으로 넘파이 배열을 텐서로 변환합니다.
- 넘파이 연산은 자동으로 텐서를 넘파이 배열로 변환합니다.
텐서는 .numpy()
메서드(method)를 호출하여 넘파이 배열로 변환할 수 있습니다. 가능한 경우, tf.Tensor
와 배열은 메모리 표현을 공유하기 때문에 이러한 변환은 일반적으로 간단(저렴)합니다. 그러나 tf.Tensor
는 GPU 메모리에 저장될 수 있고, 넘파이 배열은 항상 호스트 메모리에 저장되므로, 이러한 변환이 항상 가능한 것은 아닙니다. 따라서 GPU에서 호스트 메모리로 복사가 필요합니다.
import numpy as np
ndarray = np.ones([3, 3])
print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray, 42)
print(tensor)
print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor, 1))
print("The .numpy() method explicitly converts a Tensor to a numpy array")
print(tensor.numpy())
TensorFlow operations convert numpy arrays to Tensors automatically tf.Tensor( [[42. 42. 42.] [42. 42. 42.] [42. 42. 42.]], shape=(3, 3), dtype=float64) And NumPy operations convert Tensors to numpy arrays automatically [[43. 43. 43.] [43. 43. 43.] [43. 43. 43.]] The .numpy() method explicitly converts a Tensor to a numpy array [[42. 42. 42.] [42. 42. 42.] [42. 42. 42.]]
GPU 가속
대부분의 텐서플로 연산은 GPU를 사용하여 가속화됩니다. 어떠한 코드를 명시하지 않아도, 텐서플로는 연산을 위해 CPU 또는 GPU를 사용할 것인지를 자동으로 결정합니다. 필요시 텐서를 CPU와 GPU 메모리 사이에서 복사합니다. 연산에 의해 생성된 텐서는 전형적으로 연산이 실행된 장치의 메모리에 의해 실행됩니다. 예를 들어:
x = tf.random.uniform([3, 3])
print("Is there a GPU available: "),
print(tf.config.list_physical_devices("GPU"))
print("Is the Tensor on GPU #0: "),
print(x.device.endswith('GPU:0'))
Is there a GPU available: [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')] Is the Tensor on GPU #0: True
장치 이름
Tensor.device
는 텐서를 구성하고 있는 호스트 장치의 풀네임을 제공합니다. 이러한 이름은 프로그램이 실행중인 호스트의 네트워크 주소 및 해당 호스트 내의 장치와 같은 많은 세부 정보를 인코딩하며, 이것은 텐서플로 프로그램의 분산 실행에 필요합니다. 텐서가 호스트의 N
번째 GPU에 놓여지면 문자열은 GPU:<N>
으로 끝납니다.
명시적 장치 배치
텐서플로에서 "배치(replacement)"는 개별 연산을 실행하기 위해 장치에 할당(배치)하는 것입니다. 앞서 언급했듯이, 명시적 지침이 없을 경우 텐서플로는 연산을 실행하기 위한 장치를 자동으로 결정하고, 필요시 텐서를 장치에 복사합니다. 그러나 텐서플로 연산은 tf.device
을 사용하여 특정한 장치에 명시적으로 배치할 수 있습니다. 예를 들어:
import time
def time_matmul(x):
start = time.time()
for loop in range(10):
tf.matmul(x, x)
result = time.time()-start
print("10 loops: {:0.2f}ms".format(1000*result))
# Force execution on CPU
print("On CPU:")
with tf.device("CPU:0"):
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("CPU:0")
time_matmul(x)
# Force execution on GPU #0 if available
if tf.config.list_physical_devices("GPU"):
print("On GPU:")
with tf.device("GPU:0"): # Or GPU:1 for the 2nd GPU, GPU:2 for the 3rd etc.
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("GPU:0")
time_matmul(x)
On CPU: 10 loops: 82.68ms On GPU: 10 loops: 386.59ms
데이터셋
이 섹션에서는 tf.data.Dataset
API를 사용하여 모델에 데이터를 공급하기 위한 파이프라인을 구축합니다. tf.data.Dataset
API는 모델의 훈련 또는 평가 루프에 공급할 단순하고 재사용 가능한 부분을 이용해 성능 기준에 맞는 복잡한 입력 파이프라인을 구축하는 데 사용됩니다.
소스 데이터셋 생성
Dataset.from_tensors
, Dataset.from_tensor_slices
와 같은 팩토리 함수 중 하나를 사용하거나 TextLineDataset
또는 TFRecordDataset
와 같은 파일에서 읽는 객체를 사용하여 소스 데이터세트를 만듭니다. 자세한 내용은 TensorFlow 데이터세트 가이드를 참조하세요.
ds_tensors = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])
# Create a CSV file
import tempfile
_, filename = tempfile.mkstemp()
with open(filename, 'w') as f:
f.write("""Line 1
Line 2
Line 3
""")
ds_file = tf.data.TextLineDataset(filename)
변환 적용
맵(map)
, 배치(batch)
, 셔플(shuffle)
과 같은 변환 함수를 사용하여 데이터셋의 레코드에 적용하세요.
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)
반복
tf.data.Dataset
는 레코드 순회를 지원하는 반복 가능한 객체입니다.
print('Elements of ds_tensors:')
for x in ds_tensors:
print(x)
print('\nElements in ds_file:')
for x in ds_file:
print(x)
Elements of ds_tensors: tf.Tensor([4 1], shape=(2,), dtype=int32) tf.Tensor([ 9 16], shape=(2,), dtype=int32) tf.Tensor([36 25], shape=(2,), dtype=int32) Elements in ds_file: tf.Tensor([b'Line 1' b'Line 2'], shape=(2,), dtype=string) tf.Tensor([b'Line 3' b' '], shape=(2,), dtype=string)