-
Notifications
You must be signed in to change notification settings - Fork 1
/
tensorflowTest.py
2720 lines (1992 loc) · 102 KB
/
tensorflowTest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # CPU Only Mode
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ["CUDA_VISIBLE_DEVICES"] = "1,2"
$ CUDA_VISIBLE_DEVICES=0 python my_script.py # Uses GPU 0.
$ CUDA_VISIBLE_DEVICES=2,3 python my_script.py # Uses GPU 2,3
============
import os
# 0(debug), 1(info), 2(warning), 3(Error)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # warning log 필터링. -----> import tensorflow보다 앞에 배치.
import tensorflow as tf #
===========
error:
WARNING:tensorflow:Entity <bound method Dense.call of <tensorflow.python.layers.core.Dense object at 0x000001BECB4B9080>>
could not be transformed and will be executed as-is. Please report this to the AutgoGraph team.
When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: converting <bound method Dense.call of <tensorflow.python.layers.core.Dense object at 0x000001BECB4B9080>>:
AssertionError: Bad argument number for Name: 3, expecting 4
https://github.com/tensorflow/autograph/issues/1
pip install --user gast==0.2.2
==================
with tf.variable_scope('hccho1'):
x = tf.placeholder(tf.float32,shape=[2,3])
x = tf.convert_to_tensor(np.random.randn(2,3).astype(np.float32))
x = tf.convert_to_tensor(np.array([[-0.6587036 , 0.67638916, -0.07040939],[ 0.02193491, -0.13528223, 1.2818061 ]], dtype=np.float32))
y = tf.layers.dense(x,units=10)
with tf.variable_scope('hccho2'):
z = tf.layers.batch_normalization(y)
loss = tf.reduce_mean(z)
# optimization관련 op를 만들때도 scope가 있어야 한다. 그렇지 않으면,
# optimization 관련 variable이 위에 있는 scope를 찾아가서 붙는다.
with tf.variable_scope('hccho3'): # optimization관련 op를 만들때도 scope가 있어야 한다.
train_op = tf.train.AdamOptimizer(0.001).minimize(loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='hccho1') +tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='hccho2')
print(sess.run(z))
saver = tf.train.Saver(var_list)
saver.restore(sess,'c:\\a\\model.ckpt')
print(sess.run(z))
saver = tf.train.Saver(var_list)
saver.save(sess, 'c:\\a\\model.ckpt')
######################################################################
# remove warning
# TensorFlow에서는 5가지의 로깅 타입을 제공하고 있습니다. ( DEBUG, INFO, WARN, ERROR, FATAL ) INFO가 설정되면, 그 이하는 다 출력된다.
tf.logging.set_verbosity(tf.logging.ERROR)
# TF 1.14
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
모두 출력하지 않게...
import logging
logging.getLogger('tensorflow').disabled = True
######################################################################
tf.shape(x) --> op
x.get_shape().as_list() --> list. 이 경우는 [None,3] 이런 식으로 될 수도 있다.
######################################################################
np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])
######################################################################
def print_variable_summary():
import pprint
variables = sorted([[v.name, v.get_shape()] for v in tf.global_variables()])
pprint.pprint(variables)
######################################################################
# 아래의 api는 어떻게 사용하는지 한번 정리해야 겠다~~
tf.scatter_update
tf.gether
tf.gather_nd
tf.scatter_add
tf.sequence_mask
tf.sequence_mask([1, 3, 2], 5) # [[True, False, False, False, False],
# [True, True, True, False, False],
# [True, True, False, False, False]]
tf.boolean_mask([0,1,2,3], [True,False,True,False]) ==> [0,2] (True에 해당하는 값마 추출)
tf.slice
######################################################################
w0= np.array([[[ 4, 3, 6, 7],
[ -5, 5, 0, -6],
[ -4, 9, -6, 1]],
[[ -7, 1, -3, -1],
[ -6, 16, 10, 12],
[ 6, 5, 8, -15]]]).astype(np.float32)
weights0 = tf.get_variable('weights0', shape=w0.shape)
weights1 = tf.get_variable('weights1', shape=w0.shape,initializer=tf.constant_initializer(w0))
weights3 = tf.get_variable('weights3', initializer=w0)
weights2 = tf.Variable(w0, name='weights2')
def get_network_size():
print ('network size: {:,}'.format(np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])))
def test1():
import tensorflow as tf
print( tf.__version__)
hello = tf.constant("Hello, TensorFlow!")
sess = tf.Session()
print( sess.run(hello))
def test2():
import tensorflow as tf
node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0)
node3 = tf.add(node1,node2)
sess = tf.Session()
print(node1 , "\n", node2,"\n", node3)
print( sess.run(node3) )
def test22():
import tensorflow as tf
nodes={}
nodes['1'] = tf.constant(3.0, tf.float32)
nodes['2'] = tf.constant(4.0)
nodes['3'] = tf.add(nodes['1'],nodes['2'])
sess = tf.Session()
print(nodes['1'] , "\n", nodes['2'],"\n", nodes['3'])
print( sess.run(nodes['3']) )
sess.close()
def test3():
import tensorflow as tf
x=1
y = x+9
print(y)
x = tf.constant(1, name = 'x')
y = tf.Variable(x+9, name = 'y')
print(x,y)
model = tf.global_variables_initializer()
with tf.Session() as session:
session.run(model)
print(session.run(y))
def testOneHot():
import tensorflow as tf
import numpy as np
Y1=np.array([[2],[4]])
Y2=tf.one_hot(Y1,5) # shape=(2,1,5)
Y3=tf.reshape(Y2,[-1,5]) # shape=(2,5)
sess = tf.Session()
print(sess.run(Y2), sess.run(Y3))
def testPlaceholde():
import tensorflow as tf
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
#result_node = a + b
result_node = tf.add(a,b)
sess = tf.Session()
print(sess.run(result_node, feed_dict={a: 3.5, b: 2.7}))
print(sess.run(result_node, feed_dict={a: [1,2], b: [2,5]}))
def testLinearRegression():
import tensorflow as tf
x_train = [1,2,3]
y_train = [1,2,3]
W = tf.Variable(tf.random_normal([1]),name='Weight')
b = tf.Variable(tf.random_normal([1]),name='bias')
hypothesis = x_train * W + b
cost = tf.reduce_mean(tf.square(hypothesis - y_train))
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01)
train = optimizer.minimize(cost)
#
grad1 = tf.gradients(cost,[W,b]) # gradiend 값만
grad2 = optimizer.compute_gradients(cost,[W,b]) # gradient와 trainable variable이 쌍으로.
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(4000):
sess.run(train)
if i%100 ==0:
print(i,sess.run(cost), sess.run(W), sess.run(b))
def testLinearRegression2():
import tensorflow as tf
x_train = tf.placeholder(tf.float32)
y_train = tf.placeholder(tf.float32)
W = tf.Variable(tf.random_normal([1]),name='Weight')
b = tf.Variable(tf.random_normal([1]),name='bias')
hypothesis = x_train * W + b
cost = tf.reduce_mean(tf.square(hypothesis - y_train))
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1)
train = optimizer.minimize(cost)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
#merged = tf.merge_all_summaries()
#writer = tf.summary.FileWriter("/tmp/test_logs", sess.graph)
for i in range(2000):
cost_, W_, b_, train_ = sess.run([cost,W,b,train], feed_dict={x_train: [1,2,3], y_train: [10,20,30]})
if i%100 ==0:
print(i,cost_, W_, b_)
# Test our model
print(sess.run(hypothesis, feed_dict={x_train: [6.0, 5.4]}))
=================================================
import tensorflow as tf
import numpy as np
def test_gpu():
c = []
for d in ['/gpu:0']: # ['/gpu:1','/gpu:2']
with tf.device(d):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3])
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2])
c.append(tf.matmul(a, b))
with tf.device('/cpu:0'):
sum = tf.add_n(c)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print (sess.run(sum))
test_gpu()
===============================================================
def optimization_test():
def myfun(x):
return tf.reduce_sum(x*x-2*x)
vector = tf.Variable(7., 'vector')
loss = myfun(vector)
#optimizer = tf.contrib.opt.ScipyOptimizerInterface(loss, options={'maxiter': 100, 'disp': True})
optimizer = tf.contrib.opt.ScipyOptimizerInterface(loss,method='L-BFGS-B', options={'maxiter': 100, 'disp': True})
with tf.Session() as session:
session.run(tf.global_variables_initializer())
optimizer.minimize(session)
print(session.run(vector))
def RNN_test()
import tensorflow as tf
import numpy as np
tf.reset_default_graph()
h = [1, 0, 0, 0]; e = [0, 1, 0, 0]
l = [0, 0, 1, 0]; o = [0, 0, 0, 1]
mode = 1
x_data = np.array([[h, e, l, l, o],[e, o, l, l, l],[l, l, e, e, l]], dtype=np.float32)
batch_size = len(x_data)
hidden_size = 2
if mode == 0:
cell = rnn.BasicRNNCell(num_units=hidden_size)
#cell = rnn.BasicLSTMCell(num_units=hidden_size, state_is_tuple=True)
else:
cells = []
for _ in range(3):
#cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_dim)
cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size,state_is_tuple=True)
cells.append(cell)
cell = tf.contrib.rnn.MultiRNNCell(cells)
initial_state = cell.zero_state(batch_size, tf.float32)
# output에 FC layer를 추가하여 원하는 size로 변환해 준다. 필요 없으면 빼도 됨
cell = tf.contrib.rnn.OutputProjectionWrapper(cell, 4)
outputs, _states = tf.nn.dynamic_rnn(cell,x_data,initial_state=initial_state,dtype=tf.float32)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(outputs))
print(sess.run(_states))
sess.close()
def embedding():
tf.reset_default_graph()
x_data = np.array([[0, 3, 1, 2, 4],[1, 3, 1, 2, 3],[2, 4, 0, 2, 4]], dtype=np.int32) # (batch_size,seq_length)
input_dim = 5; embedding_dim = 6;
init = np.arange(input_dim*embedding_dim).reshape(input_dim,-1) # sample initialization
sess = tf.InteractiveSession()
with tf.variable_scope('test',reuse=tf.AUTO_REUSE) as scope:
embedding = tf.get_variable("embedding", initializer=init) # shape=(input_dim, embedding_dim)
inputs = tf.nn.embedding_lookup(embedding, x_data) # shape=(batch_size, seq_length, embedding_dim)
sess.run(tf.global_variables_initializer())
print(embedding)
print("inputs",inputs)
print(sess.run(embedding))
print(sess.run(inputs))
def test_legacy_seq2seq():
tf.reset_default_graph()
x_data = np.array([[0, 3, 1, 2, 4],[1, 3, 1, 2, 3],[2, 4, 0, 2, 4]], dtype=np.int32)
init = np.arange(30).reshape(5,-1)
print("data shape: ", x_data.shape)
sess = tf.InteractiveSession()
batch_size = len(x_data)
hidden_dim =6
num_layers = 2
seq_length = x_data.shape[1]
with tf.variable_scope('test',reuse=tf.AUTO_REUSE) as scope:
# Make rnn
cells = []
for _ in range(num_layers):
cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_dim)
cells.append(cell)
cell = tf.contrib.rnn.MultiRNNCell(cells)
embedding = tf.get_variable("embedding", initializer=init.astype(np.float32),dtype = tf.float32)
inputs = tf.nn.embedding_lookup(embedding, x_data)
initial_state = cell.zero_state(batch_size, tf.float32) # num_layers tuple. batch x hidden_dim
inputs = tf.split(inputs,seq_length,1)
inputs = [tf.squeeze(input_,[1]) for input_ in inputs]
outputs, last_state = tf.contrib.legacy_seq2seq.rnn_decoder(inputs,initial_state,cell)
sess.run(tf.global_variables_initializer())
print("initial_state: ", sess.run(initial_state))
print("\n\noutputs: ",outputs)
print(sess.run(outputs)) #seq_length, batch_size, hidden_dim
print("\n\nlast_state: ",last_state) # last_state이 마지막 값은 output의 마지막과 같은 값
print(sess.run(last_state)) # num_layers, batch_size, hidden_dim
def test_seq2seq():
import numpy as np
import tensorflow as tf
from tensorflow.python.layers.core import Dense
tf.reset_default_graph()
vocab_size = 5
SOS_token = 0
EOS_token = 4
x_data = np.array([[SOS_token, 3, 1, 2, 3, 2],[SOS_token, 3, 1, 2, 3, 1],[SOS_token, 1, 3, 2, 2, 1]], dtype=np.int32)
y_data = np.array([[1,2,0,3,2,EOS_token],[3,2,3,3,1,EOS_token],[3,1,1,2,0,EOS_token]],dtype=np.int32)
print("data shape: ", x_data.shape)
sess = tf.InteractiveSession()
output_dim = vocab_size
batch_size = len(x_data)
hidden_dim =6
num_layers = 2
seq_length = x_data.shape[1]
embedding_dim = 8
state_tuple_mode = True
init_state_flag = 0
init = np.arange(vocab_size*embedding_dim).reshape(vocab_size,-1)
train_mode = True
with tf.variable_scope('test',reuse=tf.AUTO_REUSE) as scope:
# Make rnn
cells = []
for _ in range(num_layers):
#cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_dim)
cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_dim,state_is_tuple=state_tuple_mode)
cells.append(cell)
cell = tf.contrib.rnn.MultiRNNCell(cells)
#cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_dim)
embedding = tf.get_variable("embedding", initializer=init.astype(np.float32),dtype = tf.float32)
inputs = tf.nn.embedding_lookup(embedding, x_data) # batch_size x seq_length x embedding_dim
Y = tf.convert_to_tensor(y_data)
if init_state_flag==0:
initial_state = cell.zero_state(batch_size, tf.float32) #(batch_size x hidden_dim) x layer 개수
else:
if state_tuple_mode:
h0 = tf.random_normal([batch_size,hidden_dim]) #h0 = tf.cast(np.random.randn(batch_size,hidden_dim),tf.float32)
initial_state=(tf.contrib.rnn.LSTMStateTuple(tf.zeros_like(h0), h0),) + (tf.contrib.rnn.LSTMStateTuple(tf.zeros_like(h0), tf.zeros_like(h0)),)*(num_layers-1)
else:
h0 = tf.random_normal([batch_size,hidden_dim]) #h0 = tf.cast(np.random.randn(batch_size,hidden_dim),tf.float32)
initial_state = (tf.concat((tf.zeros_like(h0),h0), axis=1),) + (tf.concat((tf.zeros_like(h0),tf.zeros_like(h0)), axis=1),) * (num_layers-1)
if train_mode:
helper = tf.contrib.seq2seq.TrainingHelper(inputs, np.array([seq_length]*batch_size))
else:
helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embedding, start_tokens=tf.tile([SOS_token], [batch_size]), end_token=EOS_token)
output_layer = Dense(output_dim, name='output_projection')
decoder = tf.contrib.seq2seq.BasicDecoder(cell=cell,helper=helper,initial_state=initial_state,output_layer=output_layer)
# maximum_iterations를 설정하지 않으면, inference에서 EOS토큰을 만나지 못하면 무한 루프에 빠진다.
outputs, last_state, last_sequence_lengths = tf.contrib.seq2seq.dynamic_decode(decoder=decoder,output_time_major=False,impute_finished=True,maximum_iterations=10)
weights = tf.ones(shape=[batch_size,seq_length])
loss = tf.contrib.seq2seq.sequence_loss(logits=outputs.rnn_output, targets=Y, weights=weights)
sess.run(tf.global_variables_initializer())
print("initial_state: ", sess.run(initial_state))
print("\n\noutputs: ",outputs)
o = sess.run(outputs.rnn_output) #batch_size, seq_length, outputs
o2 = sess.run(tf.argmax(outputs.rnn_output,axis=-1))
print("\n",o,o2) #batch_size, seq_length, outputs
print("\n\nlast_state: ",last_state)
print(sess.run(last_state)) # batch_size, hidden_dim
print("\n\nlast_sequence_lengths: ",last_sequence_lengths)
print(sess.run(last_sequence_lengths)) # [seq_length]*batch_size
print("kernel(weight)",sess.run(output_layer.trainable_weights[0])) # kernel(weight)
print("bias",sess.run(output_layer.trainable_weights[1])) # bias
if train_mode:
p = sess.run(tf.nn.softmax(outputs.rnn_output)).reshape(-1,output_dim)
print("loss: {:20.6f}".format(sess.run(loss)))
print("manual cal. loss: {:0.6f} ".format(np.average(-np.log(p[np.arange(y_data.size),y_data.flatten()]))) )
def test_bidirectional():
import tensorflow as tf
import numpy as np
tf.reset_default_graph()
x_data = np.array([[0, 3, 1],[1, 0, 0]], dtype=np.int32)
x_data = np.expand_dims(x_data,2).astype(np.float32)
#cell_f = tf.contrib.rnn.BasicRNNCell(num_units=2)
#cell_b = tf.contrib.rnn.BasicRNNCell(num_units=2)
cell_f = tf.contrib.rnn.BasicLSTMCell(num_units=2)
cell_b = tf.contrib.rnn.BasicLSTMCell(num_units=2)
(encoder_fw_outputs, encoder_bw_outputs),(encoder_fw_final_state, encoder_bw_final_state) = tf.nn.bidirectional_dynamic_rnn(cell_fw=cell_f,cell_bw=cell_b,inputs=x_data,dtype=tf.float32)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print("\nencoder_fw_outputs: ", sess.run(encoder_fw_outputs))
print("\nencoder_bw_outputs: ", sess.run(encoder_bw_outputs))
print("\nencoder_fw_final_state: ", sess.run(encoder_fw_final_state))
print("\nencoder_bw_final_state: ", sess.run(encoder_bw_final_state))
"""
BasicRNNCell:
encoder_fw_outputs:
[[[ 0. 0. ], [-0.37422162,0.9775176 ],[-0.6056877 0.57990843]]
[[-0.13036166 0.63284284], [-0.41194066 -0.16159871],[ 0.3657935 0.44170365]]]
encoder_bw_outputs:
[[[ 0.3409077 -0.8065934 ], [-0.43896067 -0.98964894], [-0.22973818 -0.58141154]]
[[-0.22973818 -0.58141154], [ 0. 0. ], [ 0. 0. ]]]
encoder_fw_final_state:
[[-0.6056877 0.57990843],[ 0.3657935 0.44170365]]
encoder_bw_final_state:
[[ 0.3409077 -0.8065934 ],[-0.22973818 -0.58141154]]
BasicLSTMCell:
encoder_fw_outputs:
[[[ 0. 0. ],[ 0.13082808 -0.10455302],[ 0.13346125 -0.10499903]]
[[ 0.04281872 -0.03912188], [ 0.03448014 -0.02246729],[ 0.02988851 -0.009888 ]]]
encoder_bw_outputs:
[[[-0.04539058 -0.2564498 ], [-0.00913273 -0.5504859 ],[-0.01013058 -0.18332982]]
[[-0.01013058 -0.18332982], [ 0. 0. ],[ 0. 0. ]]]
encoder_fw_final_state:
LSTMStateTuple(c=array([[ 0.23159406, -0.27031744],[ 0.059204 , -0.02017506]], dtype=float32),
h=array([[ 0.13346125, -0.10499903],[ 0.02988851, -0.009888 ]], dtype=float32))
encoder_bw_final_state:
LSTMStateTuple(c=array([[-0.08561244, -0.71315455],[-0.02546103, -0.3122089 ]], dtype=float32),
h=array([[-0.04539058, -0.2564498 ],[-0.01013058, -0.18332982]], dtype=float32))
"""
=======================
def get_info_from_checkpoint():
import tensorflow as tf
tf.reset_default_graph()
from tensorflow.contrib.framework.python.framework import checkpoint_utils # tf 2.x from tensorflow.python.training import checkpoint_utils
checkpoint_dir = 'D:\\hccho\\cs231n-Assignment\\assignment3\\save-sigle-layer\\model.ckpt-1000000.ckpt' # 구체적으로 명시
#checkpoint_dir = 'D:\\hccho\\cs231n-Assignment\\assignment3\\save-sigle-layer # 디렉토리만 지정 ==> 가장 최근
var_list = checkpoint_utils.list_variables(checkpoint_dir) # tf.train.list_variables(checkpoint_dir)
"""
with open('var_list.txt', 'w') as f:
for item in var_list:
f.write("%s\n" % item[0])
"""
#sess = tf.Session()
for v in var_list:
print(v) # tuple(variable name, [shape])
vv = checkpoint_utils.load_variable(checkpoint_dir, v[0])
print(vv) #values
def init_from_checkpoint():
#ckpt로 부터 특정 값만 뽑아내어, 선언한 변수 초기화 하기.
from tensorflow.contrib.framework.python.framework import checkpoint_utils
checkpoint_dir = 'D:\\hccho\\Tacotron-2-hccho\\ver1\\logdir-tacotron2\\moon+son_2019-02-27_00-21-42\\model.ckpt-56000' # 구체적으로 명시
#checkpoint_dir = 'D:\\hccho\\cs231n-Assignment\\assignment3\\save-sigle-layer' # 디렉토리만 지정 ==> 가장 최근
var_list = checkpoint_utils.list_variables(checkpoint_dir)
#1 직접 선언한 variable을 ckpt로부터 값 불러와 초기화
vv = checkpoint_utils.load_variable(checkpoint_dir, var_list[50][0]) # var_list[50][0]<--name, var_list[50][1]<-- shape
w = tf.get_variable('var1', shape=vv.shape)
tf.train.init_from_checkpoint(checkpoint_dir,{var_list[50][0]: w}) # var_list[50]에 있는 값이 w로 할당된다. sess.run(tf.global_variables_initializer()) 해야 값이 할당된다.
#2 tf.layers.dense로 간접적으로 선언된 variable을 ckpt로부터 값 불러와 초기화
vv2 = checkpoint_utils.load_variable(checkpoint_dir, var_list[141][0])
X = np.arange(3*16).reshape(3,16).astype(np.float32) # var_list[141]의 shape확인 후, 잡았다.
Y = tf.layers.dense(tf.convert_to_tensor(X),units=2048,name='hccho')
tf.train.init_from_checkpoint(checkpoint_dir,{var_list[141][0]: 'hccho/kernel'})
graph = tf.get_default_graph()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
ww,kk = sess.run([w,graph.get_tensor_by_name('hccho/kernel:0')])
print(np.allclose(ww,vv))
print(np.allclose(kk,vv2))
=======================
참고: tensorflow 2.x ----> tf.train.list_variables, from tensorflow.python.training import checkpoint_utils
https://www.tensorflow.org/guide/checkpoint
saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="resnet_v2_50"))
variables_in_checkpoint = tf.train.list_variables('.\\ckpt\\resnet_v2_50.ckpt') # ---> key,shape만. 값은 없음.
-----
import tensorflow as tf # tensorflow 2.x
from tensorflow.python.training import checkpoint_utils
# 디렉토리, 파일 preface 모두 가능
#ckpt_dir_or_file = r'D:\hccho\TF2\RnnEncoderDecoder\saved_model_mid'
ckpt_dir_or_file = r'D:\hccho\TF2\RnnEncoderDecoder\saved_model_mid\model_ckpt-7030'
var_list = tf.train.list_variables(ckpt_dir_or_file)
for v in var_list:
print(v) # tuple(variable name, [shape])
vv = checkpoint_utils.load_variable(ckpt_dir_or_file, v[0])
print(vv) #values
----
=======================
Bahdanau attention weight
encoder_hidden_size = 300 = context vector size
decoder_hidden_size = 110
BahdanauAttention_depth = 99
attention_layer_size=77
[<tf.Variable 'embed/embeddings:0' shape=(103, 100) dtype=float32_ref>,
<tf.Variable 'rnn/gru_cell/gates/kernel:0' shape=(400, 600) dtype=float32_ref>,
<tf.Variable 'rnn/gru_cell/gates/bias:0' shape=(600,) dtype=float32_ref>,
<tf.Variable 'rnn/gru_cell/candidate/kernel:0' shape=(400, 300) dtype=float32_ref>,
<tf.Variable 'rnn/gru_cell/candidate/bias:0' shape=(300,) dtype=float32_ref>,
<tf.Variable 'decode/memory_layer/kernel:0' shape=(300, 99) dtype=float32_ref>,
<tf.Variable 'decode/decoder/output_projection_wrapper/attention_wrapper/bahdanau_attention/query_layer/kernel:0' shape=(110, 99) dtype=float32_ref>, ==> decoder_hidden_size x BahdanauAttention_depth
<tf.Variable 'decode/decoder/output_projection_wrapper/attention_wrapper/bahdanau_attention/attention_v:0' shape=(99,) dtype=float32_ref>,
==> context weight 계산
<tf.Variable 'decode/decoder/output_projection_wrapper/attention_wrapper/gru_cell/gates/kernel:0' shape=(287, 220) dtype=float32_ref>, ==> (input 100 + decoder_hidden_size 110 + attention_layer_size 77) x 2*decoder hidden
<tf.Variable 'decode/decoder/output_projection_wrapper/attention_wrapper/gru_cell/gates/bias:0' shape=(220,) dtype=float32_ref>,
<tf.Variable 'decode/decoder/output_projection_wrapper/attention_wrapper/gru_cell/candidate/kernel:0' shape=(287, 110) dtype=float32_ref>,
<tf.Variable 'decode/decoder/output_projection_wrapper/attention_wrapper/gru_cell/candidate/bias:0' shape=(110,) dtype=float32_ref>,
<tf.Variable 'decode/decoder/output_projection_wrapper/attention_wrapper/attention_layer/kernel:0' shape=(410, 77) dtype=float32_ref>, None이 아닐 때, ==> tf.contrib.seq2seq.AttentionWrapper 에서 (encoder_hidden_size : decoder_hidden_size) ==>attention_layer_size ==> attention
<tf.Variable 'decode/decoder/output_projection_wrapper/kernel:0' shape=(77, 103) dtype=float32_ref>, ==> outprojectionwrapper 또는 out_layer를 통해, attention(output)의 크기를 원하는 크기를 바꾼다.
<tf.Variable 'decode/decoder/output_projection_wrapper/bias:0' shape=(103,) dtype=float32_ref>]
======================
# tf.layers.dense 의 input tensor가 3차원일 때:
# 예: input.shape (2,3,4) x units = 5 ==> (2,3,5)가 만들어지고, weight는 (4,5) size 이다
# 즉, 4개의 숫자들 간의 계산으로 새로운 5개의 숫자를 만들어낸다. 첫번째, 두번째 index들 간의 계산은 이루어지지 않는다.
# (batch_size, Time Length, embedding_dim)으로 해석하면, batch나 Time간의 계산은 되지 않고, embedding만 연산된다.
# https://github.com/tensorflow/tensorflow/issues/8175
def dense_test():
tf.reset_default_graph()
A0 = np.arange(24).reshape(2,3,4).astype(np.float32)
A = tf.convert_to_tensor(A0)
init = np.arange(20).reshape(4,5).astype(np.float32)
x = tf.layers.dense(A,5,kernel_initializer=tf.constant_initializer(init),activation=None)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
graph = tf.get_default_graph()
xx = sess.run(x)
w = sess.run(graph.get_tensor_by_name('dense/kernel:0'))
#w = sess.run('dense/kernel:0') <----- 이렇게 해도된다. tensor이름만 으로도 된다.
print(xx)
print(w)
======================
def tf_binary_image()
import skimage.io as io
import matplotlib.pyplot as plt
cat_img = io.imread('cat.jpeg') # integer numpy array, (194, 260, 3)
cat_string = cat_img.tostring() # b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\ ....'
reconstructed_cat_1d = np.fromstring(cat_string, dtype=np.uint8) # array([255, 255, 255, ..., 255, 255, 255], dtype=uint8)
reconstructed_cat_img = reconstructed_cat_1d.reshape(cat_img.shape)
print(np.allclose(cat_img, reconstructed_cat_img))
with tf.gfile.FastGFile('cat.jpeg', 'rb') as f:
cat_img2 = f.read() # b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\
cat_img2 = tf.image.decode_jpeg(cat_img2, channels=3)
cat_img2 = tf.image.resize_images(cat_img2, size=cat_img.shape[:-1])
sess = tf.Session()
cat_img2 = sess.run(cat_img2).astype(np.uint8)
# numerical 문제로 같은 값은 아니다.
print(np.mean([cat_img, cat_img2],axis=(1,2,3)))
io.imshow(np.concatenate([cat_img,cat_img2],axis=1))
plt.show()
#############################################################
def TFRecord_reading1():
# tfrecord 파일에 있는 data를 thread에 넣어 놓고 sess.run 할 때마다 뽑아 사용하기
# tfrecord에서binary data가 저장되어 있는데, tf.image.decode_jpeg로 이용해서 0~255 사이 값으로 변환한다.
from skimage import io
from matplotlib import pyplot as plt
filename = 'D:\\hccho\\CycleGAN-TensorFlow-master\\data\\tfrecords\\apple.tfrecords'
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example, features={'image/file_name': tf.FixedLenFeature([], tf.string), 'image/encoded_image': tf.FixedLenFeature([], tf.string),})
image_buffer = features['image/encoded_image']
file_name_buffer = features['image/file_name']
image = tf.image.decode_jpeg(image_buffer, channels=3)
image = tf.image.resize_images(image, size=(256, 256))
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image = image/127.5 -1.0
image.set_shape([256, 256, 3])
# image와 file_name_buffer를 같이 shuffle_batch로 해야, data쌍이 맞다.
images,file_names = tf.train.shuffle_batch( [image,file_name_buffer], batch_size=5, num_threads=8, capacity=1500, min_after_dequeue=100 )
sess = tf.Session()
# 이부분이 반드시 있어야 됨.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
sess.run(tf.global_variables_initializer())
a,z=sess.run([images,file_names]) # images, file_names가 쌍으로
b=sess.run(images) # images만 사용해도, 내부적으로는 file_names도 소모
print(a.shape,b.shape)
print(np.mean([a[0],b[0]],axis=(1,2,3)))
print(z)
io.imshow(np.concatenate(a,axis=1))
plt.show()
########################
a,z=sess.run([images,file_names]) # images, file_names가 쌍으로
print(z)
io.imshow(np.concatenate(a,axis=1))
plt.show()
#############################################################
def TFRecord_reading2():
# tfrecord 파일에서 전체 data 뽑아내기
# tfrecord에서binary data가 저장되어 있는데, tf.image.decode_jpeg로 이용해서 0~255 사이 값으로 변환한다.
filename = 'D:\\hccho\\CycleGAN-TensorFlow-master\\data\\tfrecords\\apple.tfrecords'
record_iterator = tf.python_io.tf_record_iterator(path=filename)
reconstructed_images = []
reconstructed_file_names = []
for string_record in record_iterator:
example = tf.train.Example()
example.ParseFromString(string_record)
image_buffer = example.features.feature['image/encoded_image'].bytes_list.value[0] # binary data
image = tf.image.decode_jpeg(image_buffer, channels=3) # binary data가 tensor로 변환된다.
image = tf.image.resize_images(image, size=(256, 256))
reconstructed_images.append(image)
file_name_buffer = example.features.feature['image/file_name'].bytes_list.value[0] # tensor 아님
reconstructed_file_names.append(file_name_buffer)
print(len(reconstructed_images))
sess = tf.Session()
x = sess.run(reconstructed_images[101]) # 0.0~255.0 사이의 float값
print(x.shape, reconstructed_file_names[101])
io.imshow(x/127.5 -1.0)
plt.show()
#############################################################
def TFRecord_reading3():
import skimage.io as io
import matplotlib.pyplot as plt
def mydecode(serialized_example):
features = tf.parse_single_example(serialized_example, features={'image/file_name': tf.FixedLenFeature([], tf.string), 'image/encoded_image': tf.FixedLenFeature([], tf.string),})
image_buffer = features['image/encoded_image']
file_name_buffer = features['image/file_name']
image = tf.image.decode_jpeg(image_buffer, channels=3)
image = tf.image.resize_images(image, size=(256, 256))
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image = image/127.5 -1.0
image.set_shape([256, 256, 3])
return image,file_name_buffer
# tf.data.TFRecordDataset 이용하는 방식인데, 위에서 만든 example인 TFRecord_reading1()과 유사
# 이 방식은 Coordinator 없이 iterator를 이용
filename = 'D:\\hccho\\CycleGAN-TensorFlow-master\\data\\tfrecords\\apple.tfrecords'
my_dataset = tf.data.TFRecordDataset(filename)
my_dataset = my_dataset.map(mydecode)
my_dataset = my_dataset.repeat()
my_dataset = my_dataset.shuffle(buffer_size=100)
iterator = tf.data.Iterator.from_structure(my_dataset.output_types, my_dataset.output_shapes)
init_op = iterator.make_initializer(my_dataset)
next_element = iterator.get_next()
with tf.Session() as sess:
sess.run(init_op)
x,y = sess.run(next_element)
io.imshow(x)
plt.title(y)
plt.show()
x,y = sess.run(next_element)
io.imshow(x)
plt.title(y)
plt.show()
#############################################################
#### tfrecord 파일 관련 error메시지.
- 파일 이름이 잘못되었을 때:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 129: invalid start byte
- example = tf.parse_single_example(record, name_to_features) 에서 name_to_features에 해당하는 dict를 잘못 설정했을 때.
tensorflow.python.framework.errors_impl.InvalidArgumentError: Key: segment_ids. Can't parse serialized Example.
#############################################################
# train_input, train_target <----- numpy array
buffer_size = 32
dataset = tf.data.Dataset.from_tensor_slices((train_input, train_target)) # 여기의 argument가 mapping_fn의 argument가 된다.
dataset = dataset.shuffle(buffer_size=buffer_size*10)
dataset = dataset.batch(buffer_size,drop_remainder=False)
for i,(x,y) in enumerate(dataset):
if i% 300 == 0:
print(x.shape,y.shape)
print('='*10)
for i,(x,y) in enumerate(dataset):
if i% 1000 == 0:
print(x.shape,y.shape)
#############################################################
def shuffle_batch():
# shuffle_batch를 이용하는 또 다른 방식
# 전체 data를 tf.train.slice_input_producer에 넣어 처리
myDataX = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1],[0,0,1],[0,1,1],[1,0,1],[1,1,1],[0,0,1],[0,1,1],[1,0,1],[1,1,1]]).astype(np.float32)
myDataY = np.array([[0,1,2,3,4,5,6,7,8,9,10,11]]).astype(np.float32).T
X = tf.convert_to_tensor(myDataX, tf.float32)
Y = tf.convert_to_tensor(myDataY, tf.float32)
# Create Queues
input_queues = tf.train.slice_input_producer([X, Y])
batch_size= 4
x, y = tf.train.shuffle_batch(input_queues,num_threads=8,batch_size=batch_size, capacity=batch_size*64,
min_after_dequeue=batch_size*32, allow_smaller_final_batch=False)
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(20):
print(sess.run([x,y]))
coord.request_stop()
coord.join(threads)
print('Done')
#############################################################
def data_gen():
batch_size = 2
def g():
while True:
a = np.random.randn(batch_size,3).astype(np.float32)
#b = np.random.randint(10, size=(batch_size,1))
b = a.astype(np.int32)
yield a,b
#dataset = tf.data.Dataset.from_generator(g, (tf.float32, tf.int32))
dataset = tf.data.Dataset.from_generator(g, (tf.float32, tf.int32), (tf.TensorShape([None,3]), tf.TensorShape([None,3])))
iterator = dataset.make_one_shot_iterator()
X,Y = iterator.get_next()
sess = tf.Session()
for i in range(5):
x,y = sess.run([X,Y])
print(i, x,y)
#################
# batch마다 가장 긴 data를 기준으로 padding ===> batch마다 길이가 달라진다.
def variable_length_data_gen():
batch_size = 2
samples = ['너 오늘 아주 이뻐 보인다',
'나는 오늘 기분이 더러워',
'끝내주는데, 좋은 일이 있나봐',
'나 좋은 일이 생겼어',
'아 오늘 진짜 너무 많이 정말로 짜증나',
'환상적인데, 정말 좋은거 같아']
labels = np.array([[1], [0], [1], [1], [0], [1]])
okt = Okt()
samples2 = [okt.morphs(x) for x in samples]
tokenizer2 = preprocessing.text.Tokenizer(num_words = 17, oov_token="<UKN>") # oov: out of vocabulary ---> 0: pad, 1: <UNK>, ... num_words-1,
tokenizer2.fit_on_texts(samples2+['SOS','EOS'])
print(tokenizer2.word_index)
sequences2 = tokenizer2.texts_to_sequences(samples2)
print(sequences2)
sos_id = tokenizer2.word_index['sos']
eos_id = tokenizer2.word_index['eos']
def g():
data_len= len(sequences2)
while True:
sample_ids = np.random.choice(data_len,batch_size, replace=False)
sample_sequence = np.array(sequences2)[sample_ids]
sample_sequence = [[sos_id]+s+[eos_id] for s in sample_sequence]
sequence_length = [len(s) for s in sample_sequence]
max_len = np.max(sequence_length)
sample_sequence = preprocessing.sequence.pad_sequences(sample_sequence, maxlen=max_len, padding='post')
sample_label = labels[sample_ids].reshape(-1)
yield {'text': sample_sequence,'length': sequence_length}, sample_label
dataset = tf.data.Dataset.from_generator(g, ({'text': tf.int32, 'length': tf.int32}, tf.int32), ({'text': tf.TensorShape([batch_size, None]),'length': tf.TensorShape([batch_size]) }, tf.TensorShape([batch_size])))
iterator = dataset.make_one_shot_iterator()
X,Y = iterator.get_next()
sess = tf.Session()
for i in range(5):
x,y = sess.run([X,Y])
print(i, x,y)
#############################################################
from konlpy.tag import Kkma,Okt
def Make_Batch():
# 이 example도 data가 simple할 때는 가능하지만, mini batch별로 조작을 어떻게 해야하는지??? ---> dataset.batch, dataset.mpa순서 조정으로
from tensorflow.keras import preprocessing
samples = ['너 오늘 아주 이뻐 보인다',
'나는 오늘 기분이 더러워',
'끝내주는데, 좋은 일이 있나봐',
'나 좋은 일이 생겼어',
'아 오늘 진짜 너무 많이 정말로 짜증나',
'환상적인데, 정말 좋은거 같아']
label = [[1], [0], [1], [1], [0], [1]]
MAX_LEN = 5
tokenizer = preprocessing.text.Tokenizer(oov_token="<UKN>") # oov: out of vocabulary
tokenizer.fit_on_texts(samples+['SOS','EOS']) # 0에는 아무것도 할당되어 있지 않다.
print(tokenizer.word_index)
word_to_index = tokenizer.word_index
word_to_index['PAD'] = 0
index_to_word = dict(map(reversed, word_to_index.items()))
print('word_to_index(pad): ', word_to_index)
print('index_to_word', index_to_word)
if False:
# inference에 사용하기 위해 vocab를 저장해 두어야 한다.
if (not (os.path.exists('vocab.pickle'))):
with open('vocab.pickle', 'wb') as f:
pickle.dump({'word_to_index': word_to_index, 'index_to_word': index_to_word}, f)
sequences = tokenizer.texts_to_sequences(samples) # 역변환: tokenizer.sequences_to_texts(sequences)
'''
[[5, 2, 6, 7, 8],
[9, 2, 10, 11],
[12, 3, 4, 13],
[14, 3, 4, 15],
[16, 2, 17, 18, 19, 20, 21],
[22, 23, 24, 25]]
'''