Markdown 수식추가 Markdown 추가 네이버 스크립트 구글 스크립트

How to convert from (B, C, W, H) to (B, W, H, C)

 

B : Batch

C : Channel

W : width

H : Height

 

 

tensorpack 예제를 사용하다보니깐 (B, C, W, H)- channel_first 형태를 (B, W, H, C)- channel_last 형태로 바꿔야 하는 과정이 필요로했습니다. 그래서 여러 자료를 찾다가 적절한 방법을 발견했습니다. 바로 tf.transepose라는 함수를 사용하면 됩니다.

 

convert from (BCWH) to (BWHC)

layer = tf.transpose(layer, perm=[0, 2, 3, 1])

 

위에 처럼 사용하면 됩니다.

 

만약, 반대로 해야할 경우는 

 

convert from (BWHC) to (BCWH)

layer = tf.transpose(layer, perm=[0, 3, 1, 2])

 

입니다.

 

참고 자료

 

'공부 > Tensorflow' 카테고리의 다른 글

[Tensorflow] GPU 할당 하는 방법  (2) 2019.08.27
[Tensorflow] tensor scope/name 변경하기  (0) 2019.08.27
  1. Terminal에서 python code를 실행하는 경우 :
$ CUDA_VISIBLE_DEVICES=0 python script.py  
$ CUDA_VISIBLE_DEVICES=1 python script.py  
$ CUDA_VISIBLE_DEVICES=2,3 python script.py  
  1. 소스코드에 직접 python code를 넣는 방법 :
import os

os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   
os.environ["CUDA_VISIBLE_DEVICES"]="0"

참고 자료

 

 대부분 neural network를 구축할 때 scope/name이 충돌나지 않게 구축합니다. 하지만 저같은 tensorflow 초짜들은 그런 거 없이 무조건 구현에 신경을 써서 나중에 Imagenet으로 pre-train한 weight를 쓰고 싶어도 충돌이 일어나 사용하기 힘든 경우가 있었습니다. 저같은 경우에는 먼저 tensorpack의 FasterRCNN 예제에 맞는 network를 구축하고 나아아중에 tensorflow/slim에서 Imagenet을 구축했습니다. 여기서 두 경우가 시간상 멀리 떨어져있어 tensor들의 이름이 대부분 달라서 애를 먹었습니다.

 

 그렇지만 역시 이런 경우를 생각하고 소스코드를 구축한 분들이 있습니다. 밑의 깃허브 주소를 들어가면 소스코드가 존재합니다.

https://gist.github.com/batzner/7c24802dd9c5e15870b4b56e22135c96

 

Small python script to rename variables in a TensorFlow checkpoint

Small python script to rename variables in a TensorFlow checkpoint - tensorflow_rename_variables.py

gist.github.com

사용법에 대해서 조금 설명하면...

파라미터로 checkpoint_dir, replace_from, replace_to, dry_run이 존재합니다.

각각은

 

1. checkpoint_dir

 => 바꾸고 싶은 ckpt 파일의 위치입니다.

2. replace_from

 => 바꾸고 싶은 단어입니다.

3. replace_to

 => relace_from의 단어를 다른 단어로 바뀔 내용입니다.

4. dry_run

 => 입력되는 것은 없지만 이 파라미터를 넣을 경우 실질적으로 바뀌지는 않습니다. 즉, 어떻게 바뀌는지 확인만 하는 것입니다.

 

ex) 

python change.py --checkpoin_dir=model.ckpt --replace_from weights --replace_to W --dry_run

 

※ 저만 그런지는 모르겠지만 'tf.train.get_checkpoint_state' 가 되지 않았습니다. 그래서 저게 많이 쓰이질 않아서 line 34에서 checkpoint.model_checkpoint_path 부분을 저장하고 싶은 위치에 파일이름을 적었습니다. ex) change.ckpt

 

 

여러 tensor 이름들을 변경해야할 경우 저는 shell script를 만들어서 실행했습니다.

 

 

 

 마지막으로, 바뀌거나 바꾸는 중이거나 처음 상태에서 tensor들의 이름을 알고 싶을 때 손쉽게 볼 수 있는 함수가 존재합니다.

 

 밑의 코드는그것을 이용한 소스코드 입니다.


import tensorflow as tf
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--load', help='load a model for evaluation.', required=True)

args = parser.parse_args()

variables = tf.contrib.framework.list_variables(args.load)   # Tensorflow Model Zoo 에서 제공하는 ckeckpoint file

for i, v in enumerate(variables):
    print("{}. name : {} \n    shape : {}".format(i, v[0], v[1]))

--load를 통해 원하는 ckpt 파일을 넣어서 확인하면 됩니다.

 

ex) 

python print.py --load change.ckpt

 

참고 자료

 

+ Recent posts