-
Notifications
You must be signed in to change notification settings - Fork 7
/
2019-process.html
938 lines (738 loc) · 28 KB
/
2019-process.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
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Process</title>
<link rel="stylesheet" href="reveal.js/css/reset.css">
<link rel="stylesheet" href="reveal.js/css/reveal.css">
<!-- <link rel="stylesheet" href="reveal.js/css/theme/black.css"> -->
<link rel="stylesheet" href="reveal.js/css/theme/solarized.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="reveal.js/lib/css/monokai.css">
<style>
/*pre code {*/
/*display: block;*/
/*padding: 0.5em;*/
/*background: #FFFFFF !important;*/
/*color: #000000 !important;*/
/*}*/
.right-img {
margin-left: 10px !important;
float: right;
height: 500px;
}
.todo:before {
content: 'TODO: ';
}
.todo {
color: red !important;
}
code span.line-number {
color: lightcoral;
}
.reveal pre code {
max-height: 1000px !important;
}
img {
border: 0 !important;
box-shadow: 0 0 0 0 !important;
}
.reveal {
-ms-touch-action: auto !important;
touch-action: auto !important;
}
.reveal h2,
.reveal h3,
.reveal h4 {
letter-spacing: 2px;
font-family: 'Amiri', serif;
/* font-family: 'Times New Roman', Times, serif; */
font-weight: bold;
font-style: italic;
letter-spacing: -2px;
text-transform: none !important;
}
.reveal em {
font-weight: bold;
}
.reveal .step-subtitle h1 {
letter-spacing: 1px;
}
.reveal .step-subtitle h2,
.reveal .step-subtitle h3 {
text-transform: none;
font-style: italic;
font-weight: normal;
/* font-weight: 400; */
/* font-family: 'Amiri', serif; */
font-family: 'Lobster', serif;
letter-spacing: 1px;
color: #2aa198;
text-decoration: underline;
}
.reveal .front-page h1,
.reveal .front-page h2 {
font-family: "League Gothic";
font-style: normal;
text-transform: uppercase !important;
letter-spacing: 1px;
}
.reveal .front-page h1 {
font-size: 2.5em !important;
}
.reveal .highlight {
background-color: #D3337B;
color: white;
}
.reveal section img {
background: none;
}
.reveal img.with-border {
border: 1px solid #586e75 !important;
box-shadow: 3px 3px 1px rgba(0, 0, 0, 0.15) !important;
}
.reveal li {
margin-bottom: 8px;
}
/* For li's that use FontAwesome icons as bullet-point */
.reveal ul.fa-ul li {
list-style-type: none;
}
</style>
<!-- Printing and PDF exports -->
<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
var printMode = window.location.search.match(/print-pdf/gi);
link.href = printMode ? 'reveal.js/css/print/pdf.css' : 'reveal.js/css/print/paper.css';
document.getElementsByTagName('head')[0].appendChild(link);
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section data-markdown class="preparation">
<textarea data-template>
### Preparation
</textarea>
</section>
<section data-markdown>
<textarea data-template>
## Deploying Scikit-learn Models
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Objectives
* How to export your model after you are satisfied with it?
* Setting up a common pipeline
* How to serve the model?
* How to monitor quality of your model?
</textarea>
</section>
<section data-markdown>
<textarea data-template>
## Step 1: Preparing and exporting for production
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Rules for bringing ML in production
1. Make sure your pipeline is solid end to end
1. Start with a reasonable objective
1. Add common-sense features in a simple way
<small>
https://developers.google.com/machine-learning/guides/rules-of-ml/
</small>
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Serving Sklearn models
_Caution: Be very sure you have the same pipeline of steps when serving as you had for training and evaluation!_
<small>It might make sense to use: http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html</small>
<small>Same goes for TensorFlow: https://github.com/tensorflow/transform / https://beam.apache.org/</small>
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Version together
1. Code for Cleaning and Trained Model
1. Trained Model
1. Serving Code
1. Training Data if size permits (consider https://dvc.org/)
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### After training
* Serialize Main Model using Pickle
* Make sure you also serialze your Encoders (LabelEncoder, OneHotEncoder, StandardScaler, etc.)
* If you need different in/out combinations, train multiple models
_Caution: Make sure you Serialize your models using the exact same versions of software as in production (this might be harder than you think)._
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Notebook and exercise: Preparation and Export
* let's go through the notebook together
* We will learn about the Pipeline and ColumnTransformer API
* your favorite model and download it
https://colab.research.google.com/github/djcordhose/ml-workshop/blob/master/notebooks/process/export-pipeline.ipynb
</textarea>
</section>
<section data-markdown>
<textarea data-template>
## Step 2: Serving your model
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Server Environment
* most likely Linux
* Consider using Production Web Server (nginx, Apache httpd, etc.) when serving of HTTPS
* Anaconda 3.x distribution (https://www.anaconda.com/distribution/) or equivalent
* Only controlled update of versions
* Keep development and production versions in sync
* Consider using Docker (https://www.docker.com/)
* Possibly shared Docker image (https://hub.docker.com/r/continuumio/anaconda3)
</textarea>
</section>
<section data-markdown class="local">
<textarea data-template>
### Short Demo: Docker Container
* https://hub.docker.com/r/continuumio/anaconda3
* `docker pull continuumio/anaconda3`
* Start container: `docker run -v C:/Users/olive/Development:/mnt/dev -p 8888:8888 -i -t continuumio/anaconda3 /bin/bash`
* Inside docker container
* `cd /mnt/dev/ml-workshop/notebooks`
* `jupyter notebook --ip=0.0.0.0 --allow-root`
* On local machine: open browser on URL indicated
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### For Prediction
* Load / Deserialize all Models using Pickle <em>only once on startup</em>
* Perform all the necessary encoding and decoding steps
* Consider using VM or Docker for consistent installation
* Serve requests sequentially using Flask
* Scale by using multiple instances and load balancers / dedicated ML server per installation
* Log real world predictions (if ok with <a href='https://gdpr-info.eu/'>GDPR</a>)
</textarea>
</section>
<section>
<h3>Running a Flask Server</h3>
<pre><code contenteditable data-trim class="fragment">
@app.route('/predict', methods=['POST'])
def do_predict():
speed = request.json['speed']
age = request.json['age']
miles = request.json['miles']
</code></pre>
<pre><code contenteditable data-trim class="fragment">
predicted_category, probabilities, classes = predict(speed, age, miles)
return jsonify({
'category': predicted_category,
'prediction': probabilities,
'classes': classes
})
</code></pre>
<p><small><a href='http://flask.pocoo.org/'>http://flask.pocoo.org/</a></small></p>
</section>
<section>
<h3>A Sample Call to the Flask Server</h3>
<pre><code contenteditable data-trim class="python fragment">
curl http://localhost:8889/predict -X POST \
-d '{"speed": 100, "age": 47, "miles": 10}'
</code></pre>
<pre><code contenteditable data-trim class="python fragment">
# {
# 'category': 'GREEN',
# 'prediction': [0.0, 0.87, 0.13],
# 'classes': ['RED', 'GREEN', 'YELLOW']
# }</code></pre>
<p><small><a href='https://curl.haxx.se/'>https://curl.haxx.se//</a></small></p>
</section>
<section>
<h3>Prediction Code</h3>
<pre><code contenteditable data-trim class="python fragment">
# loading models only once on startup
model = pickle.load(open('models/dt.model', 'rb'))
y_le = pickle.load(open('models/y_le.model', 'rb'))
speed_std_scale = pickle.load(open('models/speed_std_scale.model', 'rb'))
age_std_scale = pickle.load(open('models/age_std_scale.model', 'rb'))
miles_std_scale = pickle.load(open('models/miles_std_scale.model', 'rb'))
</code></pre>
<pre><code contenteditable data-trim class="python fragment">
# using models for prediction
def predict(speed, age, miles):
sample = [[speed_std_scale.transform([speed])[0],
age_std_scale.transform([age])[0],
miles_std_scale.transform([miles])[0]]]
</code></pre>
<pre><code contenteditable data-trim class="python fragment">
result = model.predict(sample)
result_group = y_le.inverse_transform(result)[0]
prediction = model.predict_proba(sample)[0].tolist()
return result_group, prediction, y_le.classes_.tolist()
</code></pre>
<p><small><a href='https://docs.python.org/3/library/pickle.html'>https://docs.python.org/3/library/pickle.html</a></small></p>
</section>
<section data-markdown>
<textarea data-template>
### Notebook and exercise: Serve your model on Colab
_let's go through the notebook together and let you create your favorite model_
https://colab.research.google.com/github/DJCordhose/ml-workshop/blob/master/notebooks/process/flask-server.ipynb
</textarea>
</section>
<section data-markdown>
<textarea data-template>
## Once you are in production everything changes
</textarea>
</section>
<section data-markdown>
<textarea data-template>
_The key often is generalization: Does the model perform well on the data that it encounters in the real world or only on
the data you used for training?_
_There are ways to get an idea of this quality from the data you already know. But if the
data you see in production are from the same distribution is something you need to monitor constantly. You also need to
notice when the model becomes stale and needs to be updated._ - Oliver Zeigermann
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### New challenge
_make sure your model works on real data_
* What do you do with new incoming data?
* How to monitor the quality of your model?
* Users get used to what you have, good or bad
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### What is your real objective?
<img src='img/googleml/ml-objectives.jpg'>
<small>
https://developers.google.com/machine-learning/guides/rules-of-ml/
</small>
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Check for bias / unfairness
* Your model might perform well for a few users, but badly for others
* Accuracy and loss only show the average
* Some areas might not have properly covered with data samples (including test)
* Curse of High Dimensions
https://developers.google.com/machine-learning/fairness-overview/
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Dealing with Bias / Unfairness
* log real requests
* log matching user behavior
* evaluate those requests (Elastic)
* if you recommend, do users follow your advice?
* if there is probabilty, how good is it?
* do you see bias/unfairness?
* put more emphasis on data that suffers from bias
Always check with <a href='https://gdpr-info.eu/'>GDPR</a>
</textarea>
</section>
<section data-markdown>
<textarea data-template>
#### Pair plots to find blank data spots
<img src='img/insurance/pair-plot.png' height="600">
</textarea>
</section>
<section data-markdown>
<textarea data-template>
#### What about people driving more than 90k miles / year?
<img src='img/insurance/histogram-miles.png' height="600">
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### How to deal with blank spots?
* Relying on ambiguous prediction scores is not enough
* Either restrict range of input
* Or warn user / log request when blank spot is hit
Try to get more data, even incrementally
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Continuity in model predictions
* People who use your model regularly will expect most things to stay the way they know it
* Even if it not totally accurate
* That might mean you can not train a model from scratch even if you have better data or a better model architecture
* Consider mixing more than one model
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### The Turtle Effect
If the user expects a certain pattern to be in the model, they expect it to persist
<img src="img/turtle.png" height="400px">
</textarea>
</section>
<section data-markdown style="font-size: xx-large">
<textarea data-template>
### More resources
* Oliver Zeigermann, M3, 2018: http://bit.ly/m3-ml-quality
* What’s your ML Test Score? A rubric for ML production systems
* <a href='https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/45742.pdf'>PDF</a>
* https://nips.cc/Conferences/2016/Schedule?showEvent=6255
</textarea>
</section>
<section data-markdown>
<textarea data-template>
## Deploying TensorFlow Models
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### You could also use the Flask approach
* In principal you can bring TensorFlow and Keras models into production like described before
* This might be ok for a test installation
* For the typical production setting there are better options
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Deploying to Google Cloud ML
* Takes away the scaling and installation burden
* Requires to convert your Keras model to a TensorFlow model
* You need to define Signatures for input and output
* The generated serving model also works for your local model servers (more on that later)
* Can use CPU or GPU
</textarea>
</section>
<section>
<h3>Preparing a Keras model for serving</h3>
<div class="fragment">
<p>Creating the Signature</p>
<pre><code contenteditable data-trim class="python">
signature = saved_model.signature_def_utils.build_signature_def(
inputs={'inputs': build_tensor_info(model.input)},
outputs={'scores': build_tensor_info(model.output)},
method_name=saved_model.signature_constants.PREDICT_METHOD_NAME)
</code></pre>
<p><small><a href='https://www.tensorflow.org/serving/signature_defs'>https://www.tensorflow.org/serving/signature_defs</a></small></p>
</div>
<div class="fragment">
<p>Creating the builder and save model</p>
<pre><code contenteditable data-trim class="python">
builder = saved_model.builder.SavedModelBuilder("path_to_model")
builder.add_meta_graph_and_variables(
sess, [saved_model.tag_constants.SERVING],
signature_def_map={
saved_model.signature_constants.
DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature
})
builder.save()
</code></pre>
</div>
</section>
<section data-markdown>
<textarea data-template>
### Alternative
1. Turn your Keras Model into a High-Level TensorFlow Estimator Model Model using <em>model\_to\_estimator</em>
1. Freeze the TensorFlow model using <em>freeze\_graph.py</em>
<small>
https://cloud.google.com/blog/products/gcp/new-in-tensorflow-14-converting-a-keras-model-to-a-tensorflow-estimator
<br>
https://www.tensorflow.org/extend/tool_developers/#freezing
<br>
https://towardsdatascience.com/freezing-a-keras-model-c2e26cb84a38
</small>
</textarea>
</section>
<section data-markdown>
<textarea data-template>
### Whichever approach you take, you now have a TensorFlow Model
* You will have a _.pb_ file at this point
* which is a frozen TensorFlow model
</textarea>
</section>
<section>
<h3>Checking our saved model</h3>
<div class="fragment">
<pre><code contenteditable data-trim class="python">
saved_model_cli show --dir tf/1 \
--tag_set serve --signature_def serving_default
</code></pre>
<pre><code contenteditable data-trim class="fragment python">
The given SavedModel SignatureDef contains the following input(s)
inputs['inputs'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 3)
name: hidden1_input:0
The given SavedModel SignatureDef contains the following output(s)
outputs['scores'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 3)
name: softmax/Softmax:0
Method name is: tensorflow/serving/predict
</code></pre>
</div>
<div class="fragment">
<pre><code contenteditable data-trim class="python">
saved_model_cli run --dir tf/1 --signature_def serving_default \
--tag_set serve --input_exprs inputs=[[100.0,47.0,10.0]]
</code></pre>
<pre><code contenteditable data-trim class="fragment python">
Result for output key scores: [[0.0027608 0.8720881 0.12515119]]
</code></pre>
</div>
<p><small><a href='https://www.tensorflow.org/guide/saved_model#cli_to_inspect_and_execute_savedmodel'>https://www.tensorflow.org/guide/saved_model#cli_to_inspect_and_execute_savedmodel</a></small></p>
</section>
<!-- <section data-markdown>
<textarea data-template>
### Screencast: Checking our model
<video controls src="video/U4-M5-tf-check.mp4" type="video/mp4" height="500"></video>
</textarea>
</section> -->
<section>
<h3>Deploying to Google Clound ML</h3>
<div class="fragment">
<p>Copy your model to a Cloud Bucket</p>
<pre><code contenteditable data-trim class="python">
gsutil mb gs://my_bucket
gsutil cp -R tf/1 gs://my_bucket
</code></pre>
<p><small>
Needs Google Cloud SDK:
<a href='https://cloud.google.com/sdk/install'>https://cloud.google.com/sdk/install</a></small></p>
</div>
<div class="fragment">
<p>Deploy from this bucket</p>
<pre><code contenteditable data-trim class="python">
gcloud ml-engine models create "ml_insurance" --enable-logging
gcloud ml-engine versions create "v1" --model "ml_insurance" \
--origin "gs://my_bucket/1"
gcloud ml-engine versions describe "v1" --model "ml_insurance"
</code></pre>
<p><small>
<a href='https://cloud.google.com/ml-engine/docs/tensorflow/deploying-models'>
https://cloud.google.com/ml-engine/docs/tensorflow/deploying-models</a>
<br>
<a href='https://cloud.google.com/ml-engine/docs/tensorflow/prediction-overview#prediction_logging'>
https://cloud.google.com/ml-engine/docs/tensorflow/prediction-overview#prediction_logging</a></small></p>
</div>
</section>
<section>
<h3>Making Predictions</h3>
<div class="fragment">
<p>Input format is a bit special</p>
<pre><code contenteditable data-trim class="python">
# sample_insurance.json
{"inputs": [ 160, 18, 100]}
{"inputs": [ 100, 47, 10]}
{"inputs": [ 90, 20, 20]}
</code></pre>
</div>
<div class="fragment">
<p>Call from Google Cloud Console</p>
<pre><code contenteditable data-trim class="python fragment">
gcloud ml-engine predict --model "ml_insurance" --version "v1" \
--json-instances ./sample_insurance.json
</code></pre>
<pre><code contenteditable data-trim class="python fragment">
SCORES
[0.8658562898635864, 7.318668918511809e-14, 0.13414366543293]
[0.002760800765827298, 0.8720880746841431, 0.12515118718147278]
[5.452934419736266e-05, 0.005952719133347273, 0.9939927458763123]
</code></pre>
</div>
<p><small>
<a href='https://cloud.google.com/ml-engine/docs/tensorflow/online-predict'>https://cloud.google.com/ml-engine/docs/tensorflow/online-predict</a>
</small></p>
</section>
<!-- <section data-markdown>
<textarea data-template>
### Screencast: Deploying to the Google Clound and making predictions
<video controls src="video/U4-M6-cloud.mp4" type="video/mp4" height="500"></video>
</textarea>
</section> -->
<section>
<h3>Making Predictions from Python</h3>
<div class="fragment">
<p>First we need a few more libraries</p>
<pre><code contenteditable data-trim class="python">
pip install google-api-python-client
pip install tensorflow-serving-api
</code></pre>
</div>
<div class="fragment">
<p>Input needs to conform to JSON now</p>
<pre><code contenteditable data-trim class="python">
instances = [{"inputs": [100, 47, 10]}]
predict_json("ml_project", "ml_insurance", instances=instances)
</code></pre>
<pre><code contenteditable data-trim class="python fragment">
[{'scores':
[0.002760800765827298, 0.8720880746841431, 0.12515118718147278]}]
</code></pre>
</div>
<p><small>
<a href='https://cloud.google.com/ml-engine/docs/tensorflow/online-predict'>https://cloud.google.com/ml-engine/docs/tensorflow/online-predict</a>
</small></p>
</section>
<section>
<h3>Python API</h3>
<div class="fragment">
<pre><code contenteditable data-trim class="python">
import googleapiclient.discovery
def predict_json(project, model, instances):
service = googleapiclient.discovery.build('ml', 'v1')
</code></pre>
<pre><code contenteditable class="python fragment"> name = 'projects/{}/models/{}'.format(project, model)
response = service.projects().predict(
name=name,
body={'instances': instances}
).execute()
return response['predictions']</code></pre>
</div>
<p><small>
<a href='https://cloud.google.com/ml-engine/docs/tensorflow/online-predict'>https://cloud.google.com/ml-engine/docs/tensorflow/online-predict</a>
<br>
<a href='https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/ml_engine/online_prediction/predict.py'>
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/ml_engine/online_prediction/predict.py
</a>
</small></p>
</section>
<section>
<h3>TensorFlow Serving REST API</h3>
<div class="fragment">
<p>Starting the Model Server in Rest Mode (needs Linux)</p>
<pre><code contenteditable data-trim>
tensorflow_model_server --rest_api_port=8501 \
--model_name=manning_insurance_1 \
--model_base_path=$(pwd)/tf
</code></pre>
<p><small><a href='https://www.tensorflow.org/serving/api_rest'>https://www.tensorflow.org/serving/api_rest</a></small></p>
</div>
<div class="fragment">
<p>Curling to it</p>
<pre><code contenteditable data-trim class="python">
curl -X POST \
http://localhost:8501/v1/models/manning_insurance_1:predict \
-d '{ "instances": [{"inputs": [ 100.0, 47.0, 10.0]}]}'
# {
# "predictions": [[0.0027608, 0.872088, 0.125151]]
# }</code></pre>
</div>
<p class="fragment"><small>
<em>Note</em>: To make this work from a browser you need a server in between, because
<a href='https://enable-cors.org/'>CORS</a> makes an
<a href='js/serving-sandbox.html'>
OPTION request</a>
that is not implemented by model server</small></p>
</section>
<section data-markdown style="font-size: xx-large">
<textarea data-template>
### Docker Container
* often the runtime environment is pretty complex and needs to scale
* at least we want something that has all the dependencies resolved and just works
* automatically starting a Flask Server or TensorFlow serving is also nice
* if we need a GPU installed on a server
* https://github.com/NVIDIA/nvidia-docker
* https://devblogs.nvidia.com/gpu-containers-runtime/
* but
* only works with NVIDIA GPU
* be careful, if your software requires a GPU make sure the server you run it on has a matching one
</textarea>
</section>
<section>
<h3>Deploying to the Browser</h3>
<div class="fragment">
<p>Converting our Keras Model to TensorFlow.js</p>
<pre><code contenteditable data-trim class="python">
tensorflowjs_converter --input_format keras \
./model/insurance.hdf5 \
./tfjs
</code></pre>
<p><small><a href='https://js.tensorflow.org/tutorials/import-keras.html'>
https://js.tensorflow.org/tutorials/import-keras.html</a></small></p>
</div>
<div class="fragment">
<p>Loading and using directly from the browser</p>
<pre><code contenteditable data-trim class="fragment line-numbers javascript">
const model = await tf.loadModel('tfjs/model.json');
</code></pre>
<pre><code contenteditable data-trim class="fragment line-numbers javascript">
// max speed, age, thousand miles per year
const example = tf.tensor([[100, 47, 10]]);
const prediction = model.predict(example);
console.log(await prediction.data());
//[0.00334801129065454, 0.8710343241691589, 0.12561771273612976]
</code></pre>
<p><small>
<a href='js/tensorflow-sandbox/load_manning_model.html' target="_blank">
https://djcordhose.github.io/ai/js/tensorflow-sandbox/load_manning_model.html</a></small>
</small></p>
</div>
</section>
</div>
</div>
<script src="reveal.js/js/reveal.js"></script>
<script src="lib/jquery-2.2.4.js"></script>
<script>
$('section:not([data-background])').attr('data-background', "background/white.jpg");
</script>
<script>
const isLocal = window.location.hostname.indexOf('localhost') !== -1 ||
window.location.hostname.indexOf('127.0.0.1') !== -1;
if (isLocal && !printMode) {
} else {
// only applies to public version
$('.todo').remove();
$('.preparation').remove();
$('.local').remove();
}
Reveal.addEventListener( 'ready', function( event ) {
// applies to all versions
$('code').addClass('line-numbers');
$('.fragments li').addClass('fragment')
// make all links open in new tab
$('a').attr('target', '_blank')
if (isLocal && !printMode) {
// only applies to presentation version
Reveal.configure({ controls: false });
} else {
// only applies to public version
$('.fragment').removeClass('fragment');
}
} );
</script>
<script>
// More info about config & dependencies:
// - https://github.com/hakimel/reveal.js#configuration
// - https://github.com/hakimel/reveal.js#dependencies
Reveal.initialize({
controls: true,
progress: false,
history: true,
center: true,
width: 1100,
math: {
mathjax: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js',
config: 'TeX-AMS_HTML-full' // See http://docs.mathjax.org/en/latest/config-files.html
},
dependencies: [
{ src: 'reveal.js/plugin/markdown/marked.js' },
{ src: 'reveal.js/plugin/markdown/markdown.js' },
{ src: 'reveal.js/plugin/notes/notes.js', async: true },
{ src: 'reveal.js/plugin/highlight/highlight.js', async: true },
{ src: 'lib/js/line-numbers.js' },
{ src: 'reveal.js/plugin/math/math.js', async: true }
]
});
</script>
</body>
</html>