TensorFlow

TensorFlow 기초 4 - 사칙연산, tf.constant(), tf.Variable(), autograph 기능

코딩탕탕 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를 발생시킨다.