Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
import numpy as np
2
import json
3
4
from keras.utils.data_utils import get_file
5
from keras import backend as K
6
7
CLASS_INDEX = None
8
CLASS_INDEX_PATH = 'https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json'
9
10
11
def preprocess_input(x, dim_ordering='default'):
12
if dim_ordering == 'default':
13
dim_ordering = K.image_dim_ordering()
14
assert dim_ordering in {'tf', 'th'}
15
16
if dim_ordering == 'th':
17
x[:, 0, :, :] -= 103.939
18
x[:, 1, :, :] -= 116.779
19
x[:, 2, :, :] -= 123.68
20
# 'RGB'->'BGR'
21
x = x[:, ::-1, :, :]
22
else:
23
x[:, :, :, 0] -= 103.939
24
x[:, :, :, 1] -= 116.779
25
x[:, :, :, 2] -= 123.68
26
# 'RGB'->'BGR'
27
x = x[:, :, :, ::-1]
28
return x
29
30
31
def decode_predictions(preds):
32
global CLASS_INDEX
33
assert len(preds.shape) == 2 and preds.shape[1] == 1000
34
if CLASS_INDEX is None:
35
fpath = get_file('imagenet_class_index.json',
36
CLASS_INDEX_PATH,
37
cache_subdir='models')
38
CLASS_INDEX = json.load(open(fpath))
39
indices = np.argmax(preds, axis=-1)
40
results = []
41
for i in indices:
42
results.append(CLASS_INDEX[str(i)])
43
return results
44
45