텐서플로우에서 array index를 문자열로 변환하는 방법
조대협 (http://bcho.tistory.com)
예전에, 얼굴 인식 모델을 만들때, 라벨 숫자로 하지 않고 사람 이름 문자열로 했다가 이 문자열의 배열 인덱스를 구하는 것을 구현하지 못해서 라벨을 다시 숫자로 데이타를 재생성한 적이 있었다. 텐서플로우에서 텐서는 파이썬의 일반 자료형이 아니기 때문에, 파이썬의 배열등을 사용하지 못해서 생기는 문제였는데, 포기하고 있다가 다른 코드를 보던중에, 이 부분을 해결해주는 코드를 찾아서, 정리해놓는다.
tf.contrib.lookup 에 이를 지원하기 위한 함수들이 정의되어 있다.
https://www.tensorflow.org/api_docs/python/tf/contrib/lookup
배열 인덱스로 문자열로 리턴하기
코드를 보자
import tensorflow as tf
table = tf.contrib.lookup.index_to_string_table_from_tensor(
tf.constant(['Jessica','Jolie','Kidman','Sulyun'])
)
sess = tf.InteractiveSession()
# Initialize Table
tf.tables_initializer().run()
p1 = table.lookup(tf.to_int64(3))
print p1.eval()
p2 = table.lookup(tf.to_int64([0,2]))
print p2.eval()
tf.contrib.lookup.index_to_string_from_tensor() 메서드를 이용하여, index를 string으로 lookup 하기 위한 테이블을 생성한다. 이 때 테이블에 들어가는 배열은 tf.constant로 정의해서 전달한다.
다음 이렇게 정의된 테이블을 사용하기 위해서는 테이블을 초기화 해줘야 한다. 초기화는
tf.tables_initializer().run()
Sulyun ['Jessica' 'Kidman']
문자열로 배열 인덱스 구하기
반대로 문자열로 배열의 인덱스를 리턴할 수 도 있다. 함수는 tf.contrib.lookup.index_table_from_tensor()를 이용하여, 문자열이 들어간 배열을 tf.constant 형태로 넘기면 되고, 찾을때는 마찬가지로 lookup() 함수를 이용하면 된다.
import tensorflow as tf
table = tf.contrib.lookup.index_table_from_tensor(
mapping = tf.constant(['Jessica','Jolie','Kidman','Sulyun'])
)
sess = tf.InteractiveSession()
tf.tables_initializer().run()
p1 = table.lookup(tf.constant('Kidman'))
print p1.eval()
p2 = table.lookup(tf.constant(['Jessica','Sulyun','Soho']))
print p2.eval()
'빅데이타 & 머신러닝 > 머신러닝' 카테고리의 다른 글
Wide and deep network 모델 활용하기 (0) | 2017.07.20 |
---|---|
텐서플로우에서 모델 export시 그래프를 다시 그리는 이유 (1) | 2017.06.26 |
얼굴 인식 모델을 만들어보자 #4 -클라우드를 이용하여 학습 시키기 (0) | 2017.06.22 |
얼굴 인식 모델을 만들어보자 #3 - 학습된 모델로 예측하기 (2) | 2017.06.19 |
연예인 얼굴 인식 모델을 만들어보자 - #2. CNN 모델을 만들고 학습시켜 보자 (15) | 2017.06.15 |