-
Notifications
You must be signed in to change notification settings - Fork 269
/
index.html
1019 lines (956 loc) · 45.2 KB
/
index.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.9.2" />
<title>ktrain API documentation</title>
<meta name="description" content="" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Package <code>ktrain</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">from .version import __version__
from . import imports as I
from .core import ArrayLearner, GenLearner, get_predictor, load_predictor, release_gpu_memory
from .vision.learner import ImageClassLearner
from .text.learner import BERTTextClassLearner, TransformerTextClassLearner
from .text.ner.learner import NERLearner
from .graph.learner import NodeClassLearner, LinkPredLearner
from .data import Dataset, TFDataset, SequenceDataset
from . import utils as U
__all__ = ['get_learner', 'get_predictor', 'load_predictor', 'release_gpu_memory',
'Dataset', 'TFDataset', 'SequenceDataset']
def get_learner(model, train_data=None, val_data=None,
batch_size=U.DEFAULT_BS, eval_batch_size=U.DEFAULT_BS,
workers=1, use_multiprocessing=False):
"""
```
Returns a Learner instance that can be used to tune and train Keras models.
model (Model): A compiled instance of keras.engine.training.Model
train_data (tuple or generator): Either a:
1) tuple of (x_train, y_train), where x_train and
y_train are numpy.ndarrays or
2) Iterator
val_data (tuple or generator): Either a:
1) tuple of (x_test, y_test), where x_testand
y_test are numpy.ndarrays or
2) Iterator
Note: Should be same type as train_data.
batch_size (int): Batch size to use in training. default:32
eval_batch_size(int): batch size used by learner.predict
only applies to validaton data during training if
val_data is instance of utils.Sequence.
default:32
workers (int): number of cpu processes used to load data.
This is ignored unless train_data/val_data is an instance of
tf.keras.preprocessing.image.DirectoryIterator or tf.keras.preprocessing.image.DataFrameIterator.
use_multiprocessing(bool): whether or not to use multiprocessing for workers
This is ignored unless train_data/val_data is an instance of
tf.keras.preprocessing.image.DirectoryIterator or tf.keras.preprocessing.image.DataFrameIterator.
```
"""
# check arguments
if not isinstance(model, I.Model):
raise ValueError('model must be of instance Model')
U.data_arg_check(train_data=train_data, val_data=val_data)
if type(workers) != type(1) or workers < 1:
workers =1
# check for NumpyArrayIterator
if train_data and not U.ondisk(train_data):
if workers > 1 and not use_multiprocessing:
use_multiprocessing = True
wrn_msg = 'Changed use_multiprocessing to True because NumpyArrayIterator with workers>1'
wrn_msg +=' is slow when use_multiprocessing=False.'
wrn_msg += ' If you experience issues with this, please set workers=1 and use_multiprocessing=False.'
I.warnings.warn(wrn_msg)
# verify BERT
is_bert = U.bert_data_tuple(train_data)
if is_bert:
maxlen = U.shape_from_data(train_data)[1]
msg = """For a GPU with 12GB of RAM, the following maxima apply:
sequence len=64, max_batch_size=64
sequence len=128, max_batch_size=32
sequence len=256, max_batch_size=16
sequence len=320, max_batch_size=14
sequence len=384, max_batch_size=12
sequence len=512, max_batch_size=6
You've exceeded these limits.
If using a GPU with <=12GB of memory, you may run out of memory during training.
If necessary, adjust sequence length or batch size based on above."""
wrn = False
if maxlen > 64 and batch_size > 64:
wrn=True
elif maxlen > 128 and batch_size>32:
wrn=True
elif maxlen>256 and batch_size>16:
wrn=True
elif maxlen>320 and batch_size>14:
wrn=True
elif maxlen>384 and batch_size>12:
wrn=True
elif maxlen > 512 and batch_size>6:
wrn=True
if wrn: I.warnings.warn(msg)
# return the appropriate trainer
if U.is_iter(train_data):
if U.is_ner(model=model, data=train_data):
learner = NERLearner
elif U.is_imageclass_from_data(train_data):
learner = ImageClassLearner
elif U.is_nodeclass(data=train_data):
learner = NodeClassLearner
elif U.is_nodeclass(data=train_data):
learner = LinkPredLearner
elif U.is_huggingface(data=train_data):
learner = TransformerTextClassLearner
else:
learner = GenLearner
else:
if is_bert:
learner = BERTTextClassLearner
else: # vanilla text classifiers use standard ArrayLearners
learner = ArrayLearner
return learner(model, train_data=train_data, val_data=val_data,
batch_size=batch_size, eval_batch_size=eval_batch_size,
workers=workers, use_multiprocessing=use_multiprocessing)
# keys
# currently_unsupported: unsupported or disabled features (e.g., xai graph neural networks have not been implemented)
# dep_fix: a fix to address a problem in a dependency</code></pre>
</details>
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="ktrain.core" href="core.html">ktrain.core</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.data" href="data.html">ktrain.data</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.graph" href="graph/index.html">ktrain.graph</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.imports" href="imports.html">ktrain.imports</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.lroptimize" href="lroptimize/index.html">ktrain.lroptimize</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.models" href="models.html">ktrain.models</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.predictor" href="predictor.html">ktrain.predictor</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.preprocessor" href="preprocessor.html">ktrain.preprocessor</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.tabular" href="tabular/index.html">ktrain.tabular</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.text" href="text/index.html">ktrain.text</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.utils" href="utils.html">ktrain.utils</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.version" href="version.html">ktrain.version</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ktrain.vision" href="vision/index.html">ktrain.vision</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="ktrain.get_learner"><code class="name flex">
<span>def <span class="ident">get_learner</span></span>(<span>model, train_data=None, val_data=None, batch_size=32, eval_batch_size=32, workers=1, use_multiprocessing=False)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>Returns a Learner instance that can be used to tune and train Keras models.
model (Model): A compiled instance of keras.engine.training.Model
train_data (tuple or generator): Either a:
1) tuple of (x_train, y_train), where x_train and
y_train are numpy.ndarrays or
2) Iterator
val_data (tuple or generator): Either a:
1) tuple of (x_test, y_test), where x_testand
y_test are numpy.ndarrays or
2) Iterator
Note: Should be same type as train_data.
batch_size (int): Batch size to use in training. default:32
eval_batch_size(int): batch size used by learner.predict
only applies to validaton data during training if
val_data is instance of utils.Sequence.
default:32
workers (int): number of cpu processes used to load data.
This is ignored unless train_data/val_data is an instance of
tf.keras.preprocessing.image.DirectoryIterator or tf.keras.preprocessing.image.DataFrameIterator.
use_multiprocessing(bool): whether or not to use multiprocessing for workers
This is ignored unless train_data/val_data is an instance of
tf.keras.preprocessing.image.DirectoryIterator or tf.keras.preprocessing.image.DataFrameIterator.
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_learner(model, train_data=None, val_data=None,
batch_size=U.DEFAULT_BS, eval_batch_size=U.DEFAULT_BS,
workers=1, use_multiprocessing=False):
"""
```
Returns a Learner instance that can be used to tune and train Keras models.
model (Model): A compiled instance of keras.engine.training.Model
train_data (tuple or generator): Either a:
1) tuple of (x_train, y_train), where x_train and
y_train are numpy.ndarrays or
2) Iterator
val_data (tuple or generator): Either a:
1) tuple of (x_test, y_test), where x_testand
y_test are numpy.ndarrays or
2) Iterator
Note: Should be same type as train_data.
batch_size (int): Batch size to use in training. default:32
eval_batch_size(int): batch size used by learner.predict
only applies to validaton data during training if
val_data is instance of utils.Sequence.
default:32
workers (int): number of cpu processes used to load data.
This is ignored unless train_data/val_data is an instance of
tf.keras.preprocessing.image.DirectoryIterator or tf.keras.preprocessing.image.DataFrameIterator.
use_multiprocessing(bool): whether or not to use multiprocessing for workers
This is ignored unless train_data/val_data is an instance of
tf.keras.preprocessing.image.DirectoryIterator or tf.keras.preprocessing.image.DataFrameIterator.
```
"""
# check arguments
if not isinstance(model, I.Model):
raise ValueError('model must be of instance Model')
U.data_arg_check(train_data=train_data, val_data=val_data)
if type(workers) != type(1) or workers < 1:
workers =1
# check for NumpyArrayIterator
if train_data and not U.ondisk(train_data):
if workers > 1 and not use_multiprocessing:
use_multiprocessing = True
wrn_msg = 'Changed use_multiprocessing to True because NumpyArrayIterator with workers>1'
wrn_msg +=' is slow when use_multiprocessing=False.'
wrn_msg += ' If you experience issues with this, please set workers=1 and use_multiprocessing=False.'
I.warnings.warn(wrn_msg)
# verify BERT
is_bert = U.bert_data_tuple(train_data)
if is_bert:
maxlen = U.shape_from_data(train_data)[1]
msg = """For a GPU with 12GB of RAM, the following maxima apply:
sequence len=64, max_batch_size=64
sequence len=128, max_batch_size=32
sequence len=256, max_batch_size=16
sequence len=320, max_batch_size=14
sequence len=384, max_batch_size=12
sequence len=512, max_batch_size=6
You've exceeded these limits.
If using a GPU with <=12GB of memory, you may run out of memory during training.
If necessary, adjust sequence length or batch size based on above."""
wrn = False
if maxlen > 64 and batch_size > 64:
wrn=True
elif maxlen > 128 and batch_size>32:
wrn=True
elif maxlen>256 and batch_size>16:
wrn=True
elif maxlen>320 and batch_size>14:
wrn=True
elif maxlen>384 and batch_size>12:
wrn=True
elif maxlen > 512 and batch_size>6:
wrn=True
if wrn: I.warnings.warn(msg)
# return the appropriate trainer
if U.is_iter(train_data):
if U.is_ner(model=model, data=train_data):
learner = NERLearner
elif U.is_imageclass_from_data(train_data):
learner = ImageClassLearner
elif U.is_nodeclass(data=train_data):
learner = NodeClassLearner
elif U.is_nodeclass(data=train_data):
learner = LinkPredLearner
elif U.is_huggingface(data=train_data):
learner = TransformerTextClassLearner
else:
learner = GenLearner
else:
if is_bert:
learner = BERTTextClassLearner
else: # vanilla text classifiers use standard ArrayLearners
learner = ArrayLearner
return learner(model, train_data=train_data, val_data=val_data,
batch_size=batch_size, eval_batch_size=eval_batch_size,
workers=workers, use_multiprocessing=use_multiprocessing)</code></pre>
</details>
</dd>
<dt id="ktrain.get_predictor"><code class="name flex">
<span>def <span class="ident">get_predictor</span></span>(<span>model, preproc, batch_size=32)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>Returns a Predictor instance that can be used to make predictions on
unlabeled examples. Can be saved to disk and reloaded as part of a
larger application.
Args
model (Model): A compiled instance of keras.engine.training.Model
preproc(Preprocessor): An instance of TextPreprocessor,ImagePreprocessor,
or NERPreprocessor.
These instances are returned from the data loading
functions in the ktrain vision and text modules:
ktrain.vision.images_from_folder
ktrain.vision.images_from_csv
ktrain.vision.images_from_array
ktrain.text.texts_from_folder
ktrain.text.texts_from_csv
ktrain.text.ner.entities_from_csv
batch_size(int): batch size to use. default:32
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_predictor(model, preproc, batch_size=U.DEFAULT_BS):
"""
```
Returns a Predictor instance that can be used to make predictions on
unlabeled examples. Can be saved to disk and reloaded as part of a
larger application.
Args
model (Model): A compiled instance of keras.engine.training.Model
preproc(Preprocessor): An instance of TextPreprocessor,ImagePreprocessor,
or NERPreprocessor.
These instances are returned from the data loading
functions in the ktrain vision and text modules:
ktrain.vision.images_from_folder
ktrain.vision.images_from_csv
ktrain.vision.images_from_array
ktrain.text.texts_from_folder
ktrain.text.texts_from_csv
ktrain.text.ner.entities_from_csv
batch_size(int): batch size to use. default:32
```
"""
# check arguments
if not isinstance(model, Model):
raise ValueError('model must be of instance Model')
if not isinstance(preproc, (ImagePreprocessor,TextPreprocessor, NERPreprocessor, NodePreprocessor, LinkPreprocessor, TabularPreprocessor)):
raise ValueError('preproc must be instance of ktrain.preprocessor.Preprocessor')
if isinstance(preproc, ImagePreprocessor):
return ImagePredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, TextPreprocessor):
#elif type(preproc).__name__ == 'TextPreprocessor':
return TextPredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, NERPreprocessor):
return NERPredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, NodePreprocessor):
return NodePredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, LinkPreprocessor):
return LinkPredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, TabularPreprocessor):
return TabularPredictor(model, preproc, batch_size=batch_size)
else:
raise Exception('preproc of type %s not currently supported' % (type(preproc)))</code></pre>
</details>
</dd>
<dt id="ktrain.load_predictor"><code class="name flex">
<span>def <span class="ident">load_predictor</span></span>(<span>fpath, batch_size=32, custom_objects=None)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>Loads a previously saved Predictor instance
Args
fpath(str): predictor path name (value supplied to predictor.save)
From v0.16.x, this is always the path to a folder.
Pre-v0.16.x, this is the base name used to save model and .preproc instance.
batch_size(int): batch size to use for predictions. default:32
custom_objects(dict): custom objects required to load model.
This is useful if you compiled the model with a custom loss function, for example.
For models included with ktrain as is, this is populated automatically
and can be disregarded.
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def load_predictor(fpath, batch_size=U.DEFAULT_BS, custom_objects=None):
"""
```
Loads a previously saved Predictor instance
Args
fpath(str): predictor path name (value supplied to predictor.save)
From v0.16.x, this is always the path to a folder.
Pre-v0.16.x, this is the base name used to save model and .preproc instance.
batch_size(int): batch size to use for predictions. default:32
custom_objects(dict): custom objects required to load model.
This is useful if you compiled the model with a custom loss function, for example.
For models included with ktrain as is, this is populated automatically
and can be disregarded.
```
"""
# load the preprocessor
preproc = None
try:
preproc_name = os.path.join(fpath, U.PREPROC_NAME)
with open(preproc_name, 'rb') as f: preproc = pickle.load(f)
except:
try:
preproc_name = fpath +'.preproc'
#warnings.warn('could not load .preproc file as %s - attempting to load as %s' % (os.path.join(fpath, U.PREPROC_NAME), preproc_name))
with open(preproc_name, 'rb') as f: preproc = pickle.load(f)
except:
raise Exception('Failed to load .preproc file in either the post v0.16.x loction (%s) or pre v0.16.x location (%s)' % (os.path.join(fpath, U.PREPROC_NAME), fpath+'.preproc'))
# load the model
model = _load_model(fpath, preproc=preproc, custom_objects=custom_objects)
# preprocessing functions in ImageDataGenerators are not pickable
# so, we must reconstruct
if hasattr(preproc, 'datagen') and hasattr(preproc.datagen, 'ktrain_preproc'):
preproc_name = preproc.datagen.ktrain_preproc
if preproc_name == 'resnet50':
preproc.datagen.preprocessing_function = pre_resnet50
elif preproc_name == 'mobilenet':
preproc.datagen.preprocessing_function = pre_mobilenet
elif preproc_name == 'inception':
preproc.datagen.preprocessing_function = pre_inception
else:
raise Exception('Uknown preprocessing_function name: %s' % (preproc_name))
# return the appropriate predictor
if not isinstance(model, Model):
raise ValueError('model must be of instance Model')
if not isinstance(preproc, (ImagePreprocessor, TextPreprocessor, NERPreprocessor, NodePreprocessor, LinkPreprocessor, TabularPreprocessor)):
raise ValueError('preproc must be instance of ktrain.preprocessor.Preprocessor')
if isinstance(preproc, ImagePreprocessor):
return ImagePredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, TextPreprocessor):
return TextPredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, NERPreprocessor):
return NERPredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, NodePreprocessor):
return NodePredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, LinkPreprocessor):
return LinkPredictor(model, preproc, batch_size=batch_size)
elif isinstance(preproc, TabularPreprocessor):
return TabularPredictor(model, preproc, batch_size=batch_size)
else:
raise Exception('preprocessor not currently supported')</code></pre>
</details>
</dd>
<dt id="ktrain.release_gpu_memory"><code class="name flex">
<span>def <span class="ident">release_gpu_memory</span></span>(<span>device=0)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>Relase GPU memory allocated by Tensorflow
Source:
https://stackoverflow.com/questions/51005147/keras-release-memory-after-finish-training-process
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def release_gpu_memory(device=0):
"""
```
Relase GPU memory allocated by Tensorflow
Source:
https://stackoverflow.com/questions/51005147/keras-release-memory-after-finish-training-process
```
"""
from numba import cuda
K.clear_session()
cuda.select_device(device)
cuda.close()
return</code></pre>
</details>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="ktrain.Dataset"><code class="flex name class">
<span>class <span class="ident">Dataset</span></span>
</code></dt>
<dd>
<div class="desc"><pre><code>Base class for custom datasets in ktrain.
If subclass of Dataset implements a method to to_tfdataset
that converts the data to a tf.Dataset, then this will be
invoked by Learner instances just prior to training so
fit() will train using a tf.Dataset representation of your data.
Sequence methods such as __get_item__ and __len__
must still be implemented.
The signature of to_tfdataset is as follows:
def to_tfdataset(self, train=True)
See ktrain.text.preprocess.TransformerDataset as an example.
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class Dataset:
"""
```
Base class for custom datasets in ktrain.
If subclass of Dataset implements a method to to_tfdataset
that converts the data to a tf.Dataset, then this will be
invoked by Learner instances just prior to training so
fit() will train using a tf.Dataset representation of your data.
Sequence methods such as __get_item__ and __len__
must still be implemented.
The signature of to_tfdataset is as follows:
def to_tfdataset(self, train=True)
See ktrain.text.preprocess.TransformerDataset as an example.
```
"""
# required: used by ktrain.core.Learner instances
def nsamples(self):
raise NotImplemented
# required: used by ktrain.core.Learner instances
def get_y(self):
raise NotImplemented
# optional: to modify dataset between epochs (e.g., shuffle)
def on_epoch_end(self):
pass
# optional
def ondisk(self):
"""
```
Is data being read from disk like with DirectoryIterators?
```
"""
return False
# optional: used only if invoking *_classifier functions
def xshape(self):
"""
```
shape of X
Examples:
for images: input_shape
for text: (n_example, sequence_length)
```
"""
raise NotImplemented
# optional: used only if invoking *_classifier functions
def nclasses(self):
"""
```
Number of classes
For classification problems: this is the number of labels
Not used for regression problems
```
"""
raise NotImplemented</code></pre>
</details>
<h3>Subclasses</h3>
<ul class="hlist">
<li><a title="ktrain.data.SequenceDataset" href="data.html#ktrain.data.SequenceDataset">SequenceDataset</a></li>
<li><a title="ktrain.data.TFDataset" href="data.html#ktrain.data.TFDataset">TFDataset</a></li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="ktrain.Dataset.get_y"><code class="name flex">
<span>def <span class="ident">get_y</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_y(self):
raise NotImplemented</code></pre>
</details>
</dd>
<dt id="ktrain.Dataset.nclasses"><code class="name flex">
<span>def <span class="ident">nclasses</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>Number of classes
For classification problems: this is the number of labels
Not used for regression problems
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def nclasses(self):
"""
```
Number of classes
For classification problems: this is the number of labels
Not used for regression problems
```
"""
raise NotImplemented</code></pre>
</details>
</dd>
<dt id="ktrain.Dataset.nsamples"><code class="name flex">
<span>def <span class="ident">nsamples</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def nsamples(self):
raise NotImplemented</code></pre>
</details>
</dd>
<dt id="ktrain.Dataset.on_epoch_end"><code class="name flex">
<span>def <span class="ident">on_epoch_end</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def on_epoch_end(self):
pass</code></pre>
</details>
</dd>
<dt id="ktrain.Dataset.ondisk"><code class="name flex">
<span>def <span class="ident">ondisk</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>Is data being read from disk like with DirectoryIterators?
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def ondisk(self):
"""
```
Is data being read from disk like with DirectoryIterators?
```
"""
return False</code></pre>
</details>
</dd>
<dt id="ktrain.Dataset.xshape"><code class="name flex">
<span>def <span class="ident">xshape</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>shape of X
Examples:
for images: input_shape
for text: (n_example, sequence_length)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def xshape(self):
"""
```
shape of X
Examples:
for images: input_shape
for text: (n_example, sequence_length)
```
"""
raise NotImplemented</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ktrain.SequenceDataset"><code class="flex name class">
<span>class <span class="ident">SequenceDataset</span></span>
<span>(</span><span>batch_size=32)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>Base class for custom datasets in ktrain.
If subclass of Dataset implements a method to to_tfdataset
that converts the data to a tf.Dataset, then this will be
invoked by Learner instances just prior to training so
fit() will train using a tf.Dataset representation of your data.
Sequence methods such as __get_item__ and __len__
must still be implemented.
The signature of to_tfdataset is as follows:
def to_tfdataset(self, training=True)
See ktrain.text.preprocess.TransformerDataset as an example.
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class SequenceDataset(Dataset, Sequence):
"""
```
Base class for custom datasets in ktrain.
If subclass of Dataset implements a method to to_tfdataset
that converts the data to a tf.Dataset, then this will be
invoked by Learner instances just prior to training so
fit() will train using a tf.Dataset representation of your data.
Sequence methods such as __get_item__ and __len__
must still be implemented.
The signature of to_tfdataset is as follows:
def to_tfdataset(self, training=True)
See ktrain.text.preprocess.TransformerDataset as an example.
```
"""
def __init__(self, batch_size=32):
self.batch_size = batch_size
# required by keras.utils.Sequence instances
def __len__(self):
raise NotImplemented
# required by keras.utils.Sequence instances
def __getitem__(self, idx):
raise NotImplemented
return False</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li><a title="ktrain.data.Dataset" href="data.html#ktrain.data.Dataset">Dataset</a></li>
<li>tensorflow.python.keras.utils.data_utils.Sequence</li>
</ul>
<h3>Subclasses</h3>
<ul class="hlist">
<li><a title="ktrain.data.MultiArrayDataset" href="data.html#ktrain.data.MultiArrayDataset">MultiArrayDataset</a></li>
<li><a title="ktrain.graph.sg_wrappers.LinkSequenceWrapper" href="graph/sg_wrappers.html#ktrain.graph.sg_wrappers.LinkSequenceWrapper">LinkSequenceWrapper</a></li>
<li><a title="ktrain.graph.sg_wrappers.NodeSequenceWrapper" href="graph/sg_wrappers.html#ktrain.graph.sg_wrappers.NodeSequenceWrapper">NodeSequenceWrapper</a></li>
<li><a title="ktrain.tabular.preprocessor.TabularDataset" href="tabular/preprocessor.html#ktrain.tabular.preprocessor.TabularDataset">TabularDataset</a></li>
<li><a title="ktrain.text.ner.preprocessor.NERSequence" href="text/ner/preprocessor.html#ktrain.text.ner.preprocessor.NERSequence">NERSequence</a></li>
<li><a title="ktrain.text.preprocessor.TransformerDataset" href="text/preprocessor.html#ktrain.text.preprocessor.TransformerDataset">TransformerDataset</a></li>
</ul>
<h3>Inherited members</h3>
<ul class="hlist">
<li><code><b><a title="ktrain.data.Dataset" href="data.html#ktrain.data.Dataset">Dataset</a></b></code>:
<ul class="hlist">
<li><code><a title="ktrain.data.Dataset.nclasses" href="data.html#ktrain.data.Dataset.nclasses">nclasses</a></code></li>
<li><code><a title="ktrain.data.Dataset.ondisk" href="data.html#ktrain.data.Dataset.ondisk">ondisk</a></code></li>
<li><code><a title="ktrain.data.Dataset.xshape" href="data.html#ktrain.data.Dataset.xshape">xshape</a></code></li>
</ul>
</li>
</ul>
</dd>
<dt id="ktrain.TFDataset"><code class="flex name class">
<span>class <span class="ident">TFDataset</span></span>
<span>(</span><span>tfdataset, n, y)</span>
</code></dt>
<dd>
<div class="desc"><pre><code>Wrapper for tf.data.Datasets
</code></pre>
<pre><code>Args:
tfdataset(tf.data.Dataset): a tf.Dataset instance
n(int): number of examples in dataset (cardinality, which can't reliably be extracted from tf.data.Datasets)
y(np.ndarray): y values for each example - should be in the format expected by your moddel (e.g., 1-hot-encoded)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class TFDataset(Dataset):
"""
```
Wrapper for tf.data.Datasets
```
"""
def __init__(self, tfdataset, n, y):
"""
```
Args:
tfdataset(tf.data.Dataset): a tf.Dataset instance
n(int): number of examples in dataset (cardinality, which can't reliably be extracted from tf.data.Datasets)
y(np.ndarray): y values for each example - should be in the format expected by your moddel (e.g., 1-hot-encoded)
```
"""
if not isinstance(tfdataset, tf.data.Dataset):
raise ValueError('tfdataset must be a fully-configured tf.data.Dataset with batch_size, etc. set appropriately')
self.tfdataset = tfdataset
self.bs = next(tfdataset.as_numpy_iterator())[-1].shape[0] # extract batch_size from tfdataset
self.n = n
self.y = y
@property
def batch_size(self):
return self.bs
@batch_size.setter
def batch_size(self, value):
if value != self.bs:
warnings.warn('batch_size parameter is ignored, as pre-configured batch_size of tf.data.Dataset is used')
def nsamples(self):
return self.n
def get_y(self):
return self.y
def to_tfdataset(self, train=True):
return self.tfdataset</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li><a title="ktrain.data.Dataset" href="data.html#ktrain.data.Dataset">Dataset</a></li>
</ul>
<h3>Instance variables</h3>
<dl>
<dt id="ktrain.TFDataset.batch_size"><code class="name">var <span class="ident">batch_size</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def batch_size(self):
return self.bs</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ktrain.TFDataset.get_y"><code class="name flex">
<span>def <span class="ident">get_y</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_y(self):
return self.y</code></pre>
</details>
</dd>
<dt id="ktrain.TFDataset.nsamples"><code class="name flex">
<span>def <span class="ident">nsamples</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def nsamples(self):
return self.n</code></pre>
</details>
</dd>
<dt id="ktrain.TFDataset.to_tfdataset"><code class="name flex">
<span>def <span class="ident">to_tfdataset</span></span>(<span>self, train=True)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_tfdataset(self, train=True):
return self.tfdataset</code></pre>
</details>
</dd>
</dl>
<h3>Inherited members</h3>
<ul class="hlist">
<li><code><b><a title="ktrain.data.Dataset" href="data.html#ktrain.data.Dataset">Dataset</a></b></code>:
<ul class="hlist">
<li><code><a title="ktrain.data.Dataset.nclasses" href="data.html#ktrain.data.Dataset.nclasses">nclasses</a></code></li>
<li><code><a title="ktrain.data.Dataset.ondisk" href="data.html#ktrain.data.Dataset.ondisk">ondisk</a></code></li>
<li><code><a title="ktrain.data.Dataset.xshape" href="data.html#ktrain.data.Dataset.xshape">xshape</a></code></li>
</ul>
</li>
</ul>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="ktrain.core" href="core.html">ktrain.core</a></code></li>
<li><code><a title="ktrain.data" href="data.html">ktrain.data</a></code></li>
<li><code><a title="ktrain.graph" href="graph/index.html">ktrain.graph</a></code></li>
<li><code><a title="ktrain.imports" href="imports.html">ktrain.imports</a></code></li>
<li><code><a title="ktrain.lroptimize" href="lroptimize/index.html">ktrain.lroptimize</a></code></li>
<li><code><a title="ktrain.models" href="models.html">ktrain.models</a></code></li>
<li><code><a title="ktrain.predictor" href="predictor.html">ktrain.predictor</a></code></li>
<li><code><a title="ktrain.preprocessor" href="preprocessor.html">ktrain.preprocessor</a></code></li>
<li><code><a title="ktrain.tabular" href="tabular/index.html">ktrain.tabular</a></code></li>
<li><code><a title="ktrain.text" href="text/index.html">ktrain.text</a></code></li>
<li><code><a title="ktrain.utils" href="utils.html">ktrain.utils</a></code></li>
<li><code><a title="ktrain.version" href="version.html">ktrain.version</a></code></li>
<li><code><a title="ktrain.vision" href="vision/index.html">ktrain.vision</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="ktrain.get_learner" href="#ktrain.get_learner">get_learner</a></code></li>
<li><code><a title="ktrain.get_predictor" href="#ktrain.get_predictor">get_predictor</a></code></li>
<li><code><a title="ktrain.load_predictor" href="#ktrain.load_predictor">load_predictor</a></code></li>
<li><code><a title="ktrain.release_gpu_memory" href="#ktrain.release_gpu_memory">release_gpu_memory</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="ktrain.Dataset" href="#ktrain.Dataset">Dataset</a></code></h4>
<ul class="two-column">
<li><code><a title="ktrain.Dataset.get_y" href="#ktrain.Dataset.get_y">get_y</a></code></li>
<li><code><a title="ktrain.Dataset.nclasses" href="#ktrain.Dataset.nclasses">nclasses</a></code></li>
<li><code><a title="ktrain.Dataset.nsamples" href="#ktrain.Dataset.nsamples">nsamples</a></code></li>
<li><code><a title="ktrain.Dataset.on_epoch_end" href="#ktrain.Dataset.on_epoch_end">on_epoch_end</a></code></li>
<li><code><a title="ktrain.Dataset.ondisk" href="#ktrain.Dataset.ondisk">ondisk</a></code></li>
<li><code><a title="ktrain.Dataset.xshape" href="#ktrain.Dataset.xshape">xshape</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ktrain.SequenceDataset" href="#ktrain.SequenceDataset">SequenceDataset</a></code></h4>
</li>