-
TensorFlow 기초 4 - 사칙연산, tf.constant(), tf.Variable(), autograph 기능TensorFlow 2022. 11. 28. 16:43
# tf.constant() : 텐서(일반적으로 상수)를 직접 기억 # tf.Variable() : 텐서가 저장된 주소를 참조 import tensorflow as tf import numpy as np from imageio.plugins._freeimage import FIMultipageBitmap node1 = tf.constant(3, tf.float32) node2 = tf.constant(4.0) print(node1) print(node2) imsi = tf.add(node1, node2) # 덧셈 print(imsi) print() node3 = tf.Variable(3, dtype=tf.float32) node4 = tf.Variable(4.0) print(node3) print(node4) node4.assign_add(node3) # 덧셈 누적 print(node4) print() a = tf.constant(5) b = tf.constant(10) c = tf.multiply(a, b) # 곱하기 print(c) result = tf.cond(a < b, lambda:tf.add(10, c), lambda:tf.square(a)) print('result :', result.numpy()) print('---함수 관련 : autograph 기능 (Graph 객체 환경에서 작업하도록 함)---') v = tf.Variable(1) @tf.function def find_next_func(): # autograph 기능을 사용하면 함사가 텐서 타입으로 자동으로 변환된다. v.assign(v + 1) if tf.equal(v % 2, 0): v.assign(v + 10) find_next_func() print(v.numpy()) print(type(find_next_func)) # <class 'function'> or polymorphic_function.Function print('^^^^ func1 ^^^^') def func1(): # 1부터 3까지 증가 imsi = tf.constant(0) su = 1 for _ in range(3): # imsi = tf.add(imsi, su) # imsi = imsi + su imsi += su return imsi kbs = func1() print(kbs.numpy(), ' ', np.array(kbs)) print('^^^^ func2 ^^^^') imsi = tf.constant(0) @tf.function def func2(): # 1부터 3까지 증가 # imsi = tf.constant(0) global imsi su = 1 for _ in range(3): # imsi = tf.add(imsi, su) # imsi = imsi + su imsi += su return imsi mbc = func2() print(mbc.numpy(), ' ', np.array(mbc)) print('^^^^ func3 ^^^^') imsi = tf.Variable(0) # auto Graph에서는 tf.Variable()은 함수 밖에 선언해야 된다. @tf.function def func3(): # imsi = tf.Variable(0) su = 1 for _ in range(3): # imsi = tf.add(imsi, su) # imsi = imsi + su # imsi += su imsi.assign_add(su) # 이것만 가능 return imsi sbs = func3() print(sbs.numpy(), ' ', np.array(sbs)) print('---구구단 출력---') @tf.function def gugu1(dan): su = 0 # su = tf.constant(0) for _ in range(9): su = tf.add(su, 1) # print(su.numpy()) # err : auto graph에서는 tensor 연산에만 집중한다. # print('{}*{}={:2}'.format(dan, su, dan * su)) # err gugu1(3) print() # @tf.function def gugu2(dan): for i in range(1, 10): reslut = tf.multiply(dan, i) # 원소 곱하기, tf.matmul() : 행렬곱 print('{}*{}={:2}'.format(dan, i, reslut)) gugu2(3) <console> 2022-11-28 16:30:21.708035: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. tf.Tensor(3.0, shape=(), dtype=float32) tf.Tensor(4.0, shape=(), dtype=float32) tf.Tensor(7.0, shape=(), dtype=float32) <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=3.0> <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=4.0> <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=7.0> tf.Tensor(50, shape=(), dtype=int32) result : 60 ---함수 관련 : autograph 기능 (Graph 객체 환경에서 작업하도록 함)--- 12 <class 'tensorflow.python.eager.polymorphic_function.polymorphic_function.Function'> ^^^^ func1 ^^^^ 3 3 ^^^^ func2 ^^^^ 3 3 ^^^^ func3 ^^^^ 3 3 ---구구단 출력--- 3*1= 3 3*2= 6 3*3= 9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27
tf.constant() : 텐서(일반적으로 상수)를 직접 기억
tf.Variable() : 텐서가 저장된 주소를 참조autograph 기능을 사용하면 함사가 텐서 타입으로 자동으로 변환된다.
auto Graph에서는 tf.Variable()은 함수 밖에 선언해야 된다.
tf.Variable()은 tf.add(), imsi +su, +=su 가 에러를 발생하므로 imsi.assign_add(su) 함수를 써야된다.
auto graph에서는 tensor 연산에만 집중한다. 다른 것(numpy, {} format 등) 이 들어오면 err를 발생시킨다.
'TensorFlow' 카테고리의 다른 글
TensorFlow 기초 6 - Keras 모델 기본 개념, 케라스 모델링 순서 (0) 2022.11.29 TensorFlow 기초 5 - 사칙연산, 관계연산, 논리연산, 차원 축소, 차원 확대, one-hot, argmax (1) 2022.11.28 TensorFlow 기초 3 - TF의 구조 (Graph로 설계된 내용은 Session에 실행) (0) 2022.11.28 TensorFlow 기초 2 - 변수, 값 치환, 누적(+=) (0) 2022.11.28 TensorFlow 기초 1 - TensorFlow에서의 상수 선언(constant) 및 사칙연산, type 변환 (0) 2022.11.28