반응형




다음 깃허브에 있는 텐서플로우 2.0 예제코드를 분석해보려합니다.

https://github.com/aymericdamien/TensorFlow-Examples/tree/master/tensorflow_v2 




최초작성 2019. 8. 28

최종작성 2019. 9. 1




우선 다음 명령을 사용하여 텐서플로우 RC를 설치하세요.

이후 글 작성시점과 텐서플로우 2.0 설치하는 방법이 달라질 수 있으니 텐서플로우 홈페이지(https://www.tensorflow.org)를 꼭 확인해보세요.


pip install tensorflow==2.0.0-rc0 






1. Hello World 문자열 출력해보기



텐서플로우 2.0에서는 tf.Graph, tf.Session를 사용하는 대신 Eager execution를 사용하는 것을 권장하는 것 같습니다. 

또한 tf.Session을 사용하여 텐서 값을 출력하는 대신 numpy() 메소드를 사용하면 넘파이 배열로 변환해줍니다. 



첫번째 예제를 파이썬 인터프리터에서 실행시켜 보았습니다.



텐서플로우 모듈을 임포트합니다.


>>> import tensorflow as tf



"hello world" 문자열을 가지는 상수 오퍼레이션을 생성합니다. 

변수 tensor_a는 상수 오퍼레이션의 출력인 텐서를 가리키게 됩니다. 

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 메시지는 무시해도 됩니다.


>>> tensor_a = tf.constant('hello world')
2019-08-28 12:45:24.610172: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports
instructions that this TensorFlow binary was not compiled to use: AVX2



tensor_a를 출력합니다. 텐서플로우 1.x와  달리 좀 바뀌었네요.

텐서플로우 2.0에서는 오퍼레이션을 실행하는 순간 연산이 수행되기 때문에 텐서 정보에 이미 오퍼레이션 실행결과가 numpy 속성에 보여집니다.


>>> tensor_a
<tf.Tensor: id=0, shape=(), dtype=string, numpy=b'hello world'>



numpy() 메소드를 사용하여 텐서의 값을 넘파이 데이터 타입으로 변환하여 출력해볼 수 있습니다. 


>>> tensor_a.numpy()
b'hello world'




변수 tensor_a가 가리키는 텐서의 타입과 numpy() 메소드 사용시 타입을 출력해봅니다.


>>> type(tensor_a) 
<class 'tensorflow.python.framework.ops.EagerTensor'>

>>> type(tensor_a.numpy())
<class 'bytes'>



bytes 클래스를 str 클래스로 변환합니다.

문자열 앞에 보이던 b가 사라집니다. 


>>> tensor_a.numpy().decode('utf-8')
'hello world'

>>> type(tensor_a.numpy().decode('utf-8'))
<class 'str'>



텐서값으로 한글을 사용한 경우입니다. 


>>> tensor_a = tf.constant("안녕")

>>> tensor_a.numpy()               
b'\xec\x95\x88\xeb\x85\x95'

>>> tensor_a.numpy().decode('utf-8')
'안녕'






2. 간단한 수학 연산하는 방법


텐서플로우 2.0을 사용하여 산술연산과 행렬연산을 하는 방법을 다루고 있습니다.









문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts