-
TensorFlow 기초 1 - TensorFlow에서의 상수 선언(constant) 및 사칙연산, type 변환TensorFlow 2022. 11. 28. 12:28
vector : 1-d tensor 1차원 배열
matrix : 2-d tensor 2차원 배열import tensorflow as tf import os # SSE 및 AVX 등의 경고는 소스를 빌드 하면 없어지지만, 명시적으로 경고 없애기 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' print("즉시 실행 모드: ", tf.executing_eagerly()) print("GPU ", "사용 가능" if tf.test.is_gpu_available() else "사용 불가능") print(tf.__version__) # 2.11.0
위의 코드로 GPU가 사용 가능한지 사용 불가능한지 확인 할 수 있다.
# 상수 선언 print(1, type(1)) print(tf.constant(1), type(tf.constant(1))) # scala : 0-d tensor print(tf.constant([1])) # vector : 1-d tensor 1차원 배열 print(tf.constant([[1]])) # matrix : 2-d tensor 2차원 배열 print(tf.rank(tf.constant(1)), ' ', tf.rank(tf.constant([1])), ' ', tf.rank(tf.constant([[1]]))) print() a = tf.constant([1, 2]) # 창조 선언 b = tf.constant([3, 4]) c = a + b print(c) c = tf.add(a, b) # 더하기 print(c) print() # d = tf.constant([3]) # Broadcasting d = tf.constant([[3]]) # Broadcasting e = c + d print(e) print(1 + 2) # 파이썬에서의 연산 print(tf.constant([1]) + tf.constant([2])) # tensorflow에서의 연산 print() print(7) print(tf.convert_to_tensor(7, dtype = tf.float32)) # 파이썬의 상수를 tensor로 바꿔줄 수 있는 함수 print(tf.cast(7, dtype = tf.float32)) print(tf.constant(7.0)) print(tf.constant(7, dtype = tf.float32)) # 36~ 39 라인은 같은 방법이다. print() # numpy의 ndarray와 tensor 사이에 type 변환 import numpy as np arr = np.array([1, 2]) print(arr, type(arr)) print(arr + 5) tfarr = tf.add(arr, 5) # ndarray가 자동으로 tensor로 변환 print(tfarr) print(tfarr.numpy()) # tensor를 ndarray로 강제 변환 print(np.add(tfarr, 3)) # tensor를 ndarray로 자동 변환 print(list(tfarr.numpy())) <console> 즉시 실행 모드: True GPU 사용 불가능 2.11.0 1 <class 'int'> tf.Tensor(1, shape=(), dtype=int32) <class 'tensorflow.python.framework.ops.EagerTensor'> tf.Tensor([1], shape=(1,), dtype=int32) tf.Tensor([[1]], shape=(1, 1), dtype=int32) tf.Tensor(0, shape=(), dtype=int32) tf.Tensor(1, shape=(), dtype=int32) tf.Tensor(2, shape=(), dtype=int32) tf.Tensor([4 6], shape=(2,), dtype=int32) tf.Tensor([4 6], shape=(2,), dtype=int32) tf.Tensor([[7 9]], shape=(1, 2), dtype=int32) 3 tf.Tensor([3], shape=(1,), dtype=int32) 7 tf.Tensor(7.0, shape=(), dtype=float32) tf.Tensor(7.0, shape=(), dtype=float32) tf.Tensor(7.0, shape=(), dtype=float32) tf.Tensor(7.0, shape=(), dtype=float32) [1 2] <class 'numpy.ndarray'> [6 7] tf.Tensor([6 7], shape=(2,), dtype=int32) [6 7] [ 9 10] [6, 7]
파이썬의 상수를 tensor로 바꿔줄 수 있는 함수가 존재한다.
numpy의 ndarray와 tensor 사이에 type 변환 가능하다.
'TensorFlow' 카테고리의 다른 글
TensorFlow 기초 5 - 사칙연산, 관계연산, 논리연산, 차원 축소, 차원 확대, one-hot, argmax (1) 2022.11.28 TensorFlow 기초 4 - 사칙연산, tf.constant(), tf.Variable(), autograph 기능 (0) 2022.11.28 TensorFlow 기초 3 - TF의 구조 (Graph로 설계된 내용은 Session에 실행) (0) 2022.11.28 TensorFlow 기초 2 - 변수, 값 치환, 누적(+=) (0) 2022.11.28 TensorFlow 설치 (0) 2022.11.28