파이썬 이것저것/파이썬 딥러닝 관련

[Python] 딥러닝 텐서플로(TensorFlow)

agingcurve 2022. 7. 14. 22:38
반응형

유연하고, 효율적이며, 확장성 있는 딥러닝 프레임워크 대형 클러스터 컴퓨터부터 스마트폰까지 다양한 디바이스에서 동작한다.

 

 

텐서

텐서는 1-D, 2-D, 3-D 데이터는 텐서로 만들어서 다차원 배열로 만들어짐

텐서(Tensor) + 플로우(Flow)

 

텐서는 1-D, 2-D, 3-D 데이터는 텐서로 만들어서 다차원 배열로 만들어 진다. 텐서를 통해서 여러가지 사칙연산을 진행한다고 했을 때, 이에 대한 Output을 만듬 예를 들면, Input Tensor와 Feature Flow는 output까지 가는것을 볼 수 있다.

 

 

딥러닝에서 데이터를 의미하는 텐서(tensor)와 데이터 플로우 그래프를 따라 연산이 수행되는 형태(Flow)의 합

 

 

 

상수텐서

 

value : 반환되는 상수값 shape : Tensor의 차원 dtype : 반환되는 Tensor 타입 name : 텐서 이름

import tensorflow as tf
# 상수형 텐서 생성
tensor_a = tf.constant(value, dtype=None, shape=None, name=None)

 

import tensorflow as tf
# 모든 원소 값이 0인 텐서 생성
tensor_b = tf.zeros(shape, dtype=tf.float32, name=None)
# 모든 원소 값이 1인 텐서 생성
tensor_c = tf.ones(shape, dtype=tf.float32, name=None)

 

시퀀스 텐서 

 

start : 시작 값 stop : 끝 값 num : 생성할 데이터 개수 name : 텐서의 이름

import tensorflow as tf
tf.constant(value, dtype= None, shape= None, name= ‘Const’)
텐서플로우 기초 사용법
import tensorflow as tf
# start에서 stop까지 증가하는 num 개수 데이터를 가진 텐서 생성
tensor_d = tf.linspace(start, stop, num, name=None)

 

변수 텐서

 

initial_value : 초기 값 dtype : 반환되는 Tensor 타입 name : 텐서의 이름

import tensorflow as tf
# 변수형 텐서 생성
tensor_f = tf.Variable(initial_value=None, dtype= None, name= None )

 

상수 텐서 및 수식 정의

 

import tensorflow as tf
tf.constant(value, dtype= None, shape= None, name= ‘Const’)
텐서플로우 기초 사용법
import tensorflow as tf
# 상수 텐서 생성
a = tf.constant([1,0],dtype=tf.float32)
# 수식 정의
def forward(x):
return W * x + b

 

 

텐서데이터 생성 파이썬으로 구현하기

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

'''
1. 상수 텐서를 생성하는 constant_tensors 함수를 완성

   Step01. 5의 값을 가지는 (1,1) shape의 8-bit integer 텐서를 만들기
   
   Step02. 모든 원소의 값이 0인 (3,5) shape의 16-bit integer 텐서를 만들기
   
   Step03. 모든 원소의 값이 1인 (4,3) shape의 8-bit integer 텐서를 만들기
'''

def constant_tensors():
    
    t1 = tf.constant(5, shape = (1,1), dtype = tf.int8)
    
    t2 = tf.zeros(shape = (3,5), dtype=tf.int16)
    
    t3 = tf.ones(shape = (4,4), dtype=tf.int8)
    
    return t1, t2, t3

'''
2. 시퀀스 텐서를 생성하는 sequence_tensors 함수를 완성

   Step01. 1.5에서 10.5까지 증가하는 3개의 텐서를 만들기
   
   Step02. 2.5에서 20.5까지 증가하는 5개의 텐서를 만들기
'''

def sequence_tensors():
    
    seq_t1 = tf.range(1.5, 11, 4.5)
    
    seq_t2 = tf.range(2.5, 21, 4.5)
    
    return seq_t1, seq_t2

'''
3. 변수를 생성하는 variable_tensor 함수를 완성

   Step01. 값이 100인 변수 텐서를 만들기
   
   Step02. 모든 원소의 값이 1인 (2,2) shape의 변수 텐서를 만들기
           이름도 'W'로 지정
   
   Step03. 모든 원소의 값이 0인 (2,) shape의 변수 텐서를 만들기
           이름도 'b'로 지정
'''

def variable_tensor():
    
    var_tensor = tf.Variable(initial_value = 100)
    
    W = tf.Variable(tf.ones(shape=(2,2)), name = "W")
    
    b = tf.Variable(tf.zeros(shape = (2,), name = "b")
    
    return var_tensor, W, b

def main():
    
    t1, t2, t3 = constant_tensors()
    
    seq_t1,seq_t2 = sequence_tensors()
    
    var_tensor, W, b = variable_tensor()
    
    constant_dict = {'t1':t1, 't2':t2, 't3':t3}
    
    sequence_dict = {'seq_t1':seq_t1, 'seq_t2':seq_t2}
    
    variable_dict = {'var_tensor':var_tensor, 'W':W, 'b':b}
    
    for key, value in constant_dict.items():
        print(key, ' :', value.numpy())
    
    print()
    
    for key, value in sequence_dict.items():
        print(key, ' :', value.numpy())
        
    print()
    
    for key, value in variable_dict.items():
        print(key, ' :', value.numpy())

if __name__ == "__main__":
    main()

 

텐서 계산기를 구현

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

def main():
    
    a = tf.constant(10, dtype = tf.int32)
    b = tf.constant(3, dtype = tf.int32)
    
    add = tf.add(a, b)
    sub = tf.subtract(a, b)
    mul = tf.multiply(a, b)
    div = tf.truediv(a, b)
    
    tensor_dict = {'add':add, 'sub':sub, 'mul':mul, 'div':div}
    
    for key, value in tensor_dict.items():
        print(key, ' :', value.numpy(), '\n')
    
    return add, sub, mul, div

if __name__ == "__main__":
    main()