본문 바로가기

Learn/TensorFlow

TensorFlow 학습 #6 상수와 텐서보드

반응형

2020/09/05 - [Learn/TensorFlow] - TensorFlow 학습 #5 텐서플로우 연산구조

 

TensorFlow 학습 #5 텐서플로우 연산구조

2020/09/04 - [Learn/TensorFlow] - TensorFlow 학습 #4 - 설치 및 실행 TensorFlow 학습 #4 - 설치 및 실행 2020/08/26 - [Learn/TensorFlow] - TensorFlow 학습 #3 - 머신 러닝 TensorFlow 학습 #3 - 머신 러닝..

javart.tistory.com


TensorFlow

자료형

상수

 상수형 텐서를 이용하는 방법에 대한 매뉴얼이 있다. 

 

상수 생성의 파라미터

// value - 상수 값
// dtype - 결과 텐서의 유형
// shape - 결과 텐서의 선택적 차원
// name - 텐서의 선택적 이름
tf.constant(value, dtype=None, shape=None, name='Const')
//여기선 그래프에서 Const로 나타난다.

 

복잡해 보여도 전 글을 보면 알겠지만 기본적으론 value만 사용해도 된다. 즉,  dtype은 넣지 않아도 value의 형태에 따라 알아서 유추된다.

 

파이썬 리스트를 통해 1차원 텐서 생성

a = tf.constant([1,2,3,4,5,6])

 

float64로 캐스팅 요청

tf.constant([1,2,3,4,5,6], dtype=tf.float64)

 

shape의 경우 텐서의 차원을 선택하는데 필요하다. 그리고 차원(공간)보다 값의 양이 적으면 확장되어 채워진다.

tf.constant(0, shape=(2, 3))
// [0,0,0]
// [0,0,0]

 

모든 원소 값이 0인 텐서 생성법

import tensorflow as tf
node1 = tf.zeros([2,3], dtype=tf.int32)
tf.print(node1 )

//[[0 0 0]
// [0 0 0]]

모든 원소 값이 1인 텐서 생성법

import tensorflow as tf
node1 = tf.ones([2,3], dtype=tf.int32)
tf.print(node1 )
//[[1 1 1]
// [1 1 1]]

 

난수 값 생성하기

 - 회귀, 분류 등에서 기울기 등의 값을 임의로 생성해야 할 때 사용할 수 있다.

tf.random_normal([2,3], seed=1234)

채워져 있는 값 생성

tf.fill([2,3],9)
//[[9 9 9]
// [9 9 9]]

n부터 m까지의 값을 i개로 채우기

tf.linspace(10.0 , 15.0, 3, name="linesp")
//[10. 12.5 15.]

 

n부터  m까지의 값을 i 만큼 증가시켜 만들기

tf.range(10, 20, 3) 
// start, limit, delta
//[10 13 16 19]

0부터 n까지 i 만큼 증가시켜 만들기

tf.range(10, delta=2)
[0 2 4 6 8]

연산 해보기

 1.x 버전 때의 텐서플로우 사칙연산

import tensorflow as tf

node1=tf.constant([[4,5]])
print(node1)
//Tensor("Const_:0", shape=(1, 2), dtype=int32)

node2=tf.constant([[2],[3]])
print(node2)
//Tensor("Const_1:0", shape=(2, 1),
//dtype=int32

sess = tf.Session()
result_add=sess.run(node1+node2)
result_sub=sess.run(node1-node2)
result_mul=sess.run(node1*node2)
result_div=sess.run(node1/node2)

print(result_add)
//4+2=6 5+2=7
//4+3=7 5+3=8

print(resut_sub)
//4-2=2 5-2=3
//4-3=1 5-3=2

print(result_mul)
//4*2=8 5*2=10
//4*3=12 5*3=15
print(result_div)
//4/2=2 5/2=2.5
//4/3=1.33 5/3=1.6
sess.close()

 

2.x 버전에서의 텐서플로우 사칙연산

 더이상 세션을 일일이 제어할 필요는 없다.

import tensorflow as tf

n1 = tf.constant([[4,5]])
n2 = tf.constant([[2],[3]])

tf.print(n1+n2)
tf.print(n1-n2)
tf.print(n1*n2)
tf.print(n1/n2)

 

텐서보드

텐서보드 기록하기

 자세한 사항안 이곳에서 확인해보면 된다.

writer = tf.summary.create_file_writer("/tmp/mylogs")
with writer.as_default():
  for step in range(100):
    # other model code would go here
    tf.summary.scalar("my_metric", 0.5, step=step)
    writer.flush()

 

 

텐서보드 살펴보기

 아나콘다를 실행하고 텐서플로우를 설치한 가상환경을 활성화한다

아래 명령어를 통해 저장한 경로로 이동한다.

 : cd /d 'path'

아래 명령어를 통해 텐서보드를 실행한다.

 :(tensorflow) 'path' > tensorboard --logdir='파일'

브라우저에서 localhost:6006을 입력해 접속한다.

 

반응형