tensorlayer tricks
1.0.0
딥 러닝 연구가 세상을 계속 개선하는 동안, 우리는 매일 Tensorlayer가있는 알고리즘을 구현하기 위해 많은 트릭을 사용합니다.
다음은 Tensorlayer를 사용하는 트릭에 대한 요약입니다. 실제로 유용한 트릭을 찾으면 풀 요청을 열어 문서에 추가하십시오. 우리가 그것이 합리적이고 확인 되었다면, 우리는 그것을 병합 할 것입니다.
git clone https://github.com/zsdonghao/tensorlayer.git 엑시 처리하여 전체 저장소를 다운로드 한 다음 tensorlayer 폴더를 프로젝트에 복사 할 수 있습니다.pip 설치를 사용하려면 마스터 버전을 설치하는 것이 좋습니다.is_fix True 로 설정하고 매개 변수를 재사용하여 교육/테스트를위한 다른 그래프를 작성하십시오. 다른 그래프에 대해 다른 batch_size 와 노이즈 확률을 설정할 수도 있습니다. 이 방법은 Gaussiannoiselayer, Batchnormlayer 등을 사용할 때 가장 좋습니다. 예를 들어 있습니다. def mlp ( x , is_train = True , reuse = False ):
with tf . variable_scope ( "MLP" , reuse = reuse ):
net = InputLayer ( x , name = 'in' )
net = DropoutLayer ( net , 0.8 , True , is_train , name = 'drop1' )
net = DenseLayer ( net , n_units = 800 , act = tf . nn . relu , name = 'dense1' )
net = DropoutLayer ( net , 0.8 , True , is_train , name = 'drop2' )
net = DenseLayer ( net , n_units = 800 , act = tf . nn . relu , name = 'dense2' )
net = DropoutLayer ( net , 0.8 , True , is_train , name = 'drop3' )
net = DenseLayer ( net , n_units = 10 , act = tf . identity , name = 'out' )
logits = net . outputs
net . outputs = tf . nn . sigmoid ( net . outputs )
return net , logits
x = tf . placeholder ( tf . float32 , shape = [ None , 784 ], name = 'x' )
y_ = tf . placeholder ( tf . int64 , shape = [ None , ], name = 'y_' )
net_train , logits = mlp ( x , is_train = True , reuse = False )
net_test , _ = mlp ( x , is_train = False , reuse = True )
cost = tl . cost . cross_entropy ( logits , y_ , name = 'cost' )여기에 더.
train_vars = tl . layers . get_variables_with_name ( 'MLP' , True , True )
train_op = tf . train . AdamOptimizer ( learning_rate = 0.0001 ). minimize ( cost , var_list = train_vars ) layers = tl . layers . get_layers_with_name ( network , "MLP" , True )데이터 세트가 크면 데이터로드 및 데이터 확대가 바닥이되어 교육 속도가 느려집니다. 데이터 처리 속도를 높이려면 다음과 같습니다.
데이터 크기가 컴퓨터의 메모리에 공급 될 정도로 작고 데이터 확대는 간단합니다. 쉽게 디버깅하려면 다음을 수행 할 수 있습니다.
tl.models 사용 x = tf . placeholder ( tf . float32 , [ None , 224 , 224 , 3 ])
# get the whole model
vgg = tl . models . VGG16 ( x )
# restore pre-trained VGG parameters
sess = tf . InteractiveSession ()
vgg . restore_params ( sess )
# use for inferencing
probs = tf . nn . softmax ( vgg . outputs ) x = tf . placeholder ( tf . float32 , [ None , 224 , 224 , 3 ])
# get VGG without the last layer
vgg = tl . models . VGG16 ( x , end_with = 'fc2_relu' )
# add one more layer
net = tl . layers . DenseLayer ( vgg , 100 , name = 'out' )
# initialize all parameters
sess = tf . InteractiveSession ()
tl . layers . initialize_global_variables ( sess )
# restore pre-trained VGG parameters
vgg . restore_params ( sess )
# train your own classifier (only update the last layer)
train_params = tl . layers . get_variables_with_name ( 'out' ) x1 = tf . placeholder ( tf . float32 , [ None , 224 , 224 , 3 ])
x2 = tf . placeholder ( tf . float32 , [ None , 224 , 224 , 3 ])
# get VGG without the last layer
vgg1 = tl . models . VGG16 ( x1 , end_with = 'fc2_relu' )
# reuse the parameters of vgg1 with different input
vgg2 = tl . models . VGG16 ( x2 , end_with = 'fc2_relu' , reuse = True )
# restore pre-trained VGG parameters (as they share parameters, we don’t need to restore vgg2)
sess = tf . InteractiveSession ()
vgg1 . restore_params ( sess ) import tensorflow as tf
import tensorlayer as tl
from keras . layers import *
from tensorlayer . layers import *
def my_fn ( x ):
x = Dropout ( 0.8 )( x )
x = Dense ( 800 , activation = 'relu' )( x )
x = Dropout ( 0.5 )( x )
x = Dense ( 800 , activation = 'relu' )( x )
x = Dropout ( 0.5 )( x )
logits = Dense ( 10 , activation = 'linear' )( x )
return logits
network = InputLayer ( x , name = 'input' )
network = LambdaLayer ( network , my_fn , name = 'keras' )
... > >> captions = [ "one two , three" , "four five five" ] # 2个 句 子
> >> processed_capts = []
> >> for c in captions :
> >> c = tl . nlp . process_sentence ( c , start_word = "<S>" , end_word = "</S>" )
> >> processed_capts . append ( c )
> >> print ( processed_capts )
... [[ '<S>' , 'one' , 'two' , ',' , 'three' , '</S>' ],
... [ '<S>' , 'four' , 'five' , 'five' , '</S>' ]] > >> tl . nlp . create_vocab ( processed_capts , word_counts_output_file = 'vocab.txt' , min_word_count = 1 )
... [ TL ] Creating vocabulary .
... Total words : 8
... Words in vocabulary : 8
... Wrote vocabulary file : vocab . txttl.nlp.create_vocab 에서 만든 txt 어휘 파일에서 어휘 객체를 만듭니다. > >> vocab = tl . nlp . Vocabulary ( 'vocab.txt' , start_word = "<S>" , end_word = "</S>" , unk_word = "<UNK>" )
... INFO : tensorflow : Initializing vocabulary from file : vocab . txt
... [ TL ] Vocabulary from vocab . txt : < S > < / S > < UNK >
... vocabulary with 10 words ( includes start_word , end_word , unk_word )
... start_id : 2
... end_id : 3
... unk_id : 9
... pad_id : 0그런 다음 다음과 같이 Word를 ID 또는 Vice 구절에 매핑 할 수 있습니다.
> >> vocab . id_to_word ( 2 )
... 'one'
> >> vocab . word_to_id ( 'one' )
... 2
>> > vocab . id_to_word ( 100 )
... '<UNK>'
> >> vocab . word_to_id ( 'hahahaha' )
... 9 > >> sequences = [[ 1 , 1 , 1 , 1 , 1 ],[ 2 , 2 , 2 ],[ 3 , 3 ]]
> >> sequences = tl . prepro . pad_sequences ( sequences , maxlen = None ,
... dtype = 'int32' , padding = 'post' , truncating = 'pre' , value = 0. )
... [[ 1 1 1 1 1 ]
... [ 2 2 2 0 0 ]
... [ 3 3 0 0 0 ]]sequence_length 에 공급하십시오. > >> data = [[ 1 , 2 , 0 , 0 , 0 ], [ 1 , 2 , 3 , 0 , 0 ], [ 1 , 2 , 6 , 1 , 0 ]]
> >> o = tl . layers . retrieve_seq_length_op2 ( data )
> >> sess = tf . InteractiveSession ()
> >> tl . layers . initialize_global_variables ( sess )
> >> print ( o . eval ())
... [ 2 3 4 ]tl.files.load_and_assign_npz 사용하여 복원하십시오.tl.files.load_and_assign_npz_dict 사전으로 저장하십시오. 키는 매개 변수 이름입니다.tl.files.load_ckpt 사용하여 복원합니다. TL은 다른 TF 래퍼와 상호 작용할 수 있습니다. 즉, 다른 래퍼가 구현 한 코드 나 모델을 찾으면 사용할 수 있습니다!
BatchNormLayer 의 decay Default는 0.9이며 대형 데이터 세트의 경우 0.999로 설정됩니다.