MCPcopy Create free account
hub / github.com/NVIDIA/TensorRT / TensorFlowInfer

Class TensorFlowInfer

samples/python/efficientnet/compare_tf.py:29–85  ·  view source on GitHub ↗

Implements TensorFlow inference of a saved model, following the same API as the TensorRTInfer class.

Source from the content-addressed store, hash-verified

27
28
29class TensorFlowInfer:
30 """
31 Implements TensorFlow inference of a saved model, following the same API as the TensorRTInfer class.
32 """
33
34 def __init__(self, saved_model_path):
35 gpus = tf.config.experimental.list_physical_devices("GPU")
36 for gpu in gpus:
37 tf.config.experimental.set_memory_growth(gpu, True)
38
39 self.model = tf.saved_model.load(saved_model_path)
40 self.pred_fn = self.model.signatures["serving_default"]
41
42 # Setup I/O bindings
43 self.inputs = []
44 fn_inputs = self.pred_fn.structured_input_signature[1]
45 for i, input in enumerate(list(fn_inputs.values())):
46 self.inputs.append(
47 {
48 "index": i,
49 "name": input.name,
50 "dtype": np.dtype(input.dtype.as_numpy_dtype()),
51 "shape": input.shape.as_list(),
52 }
53 )
54 self.outputs = []
55 fn_outputs = self.pred_fn.structured_outputs
56 for i, output in enumerate(list(fn_outputs.values())):
57 self.outputs.append(
58 {
59 "index": i,
60 "name": output.name,
61 "dtype": np.dtype(output.dtype.as_numpy_dtype()),
62 "shape": output.shape.as_list(),
63 }
64 )
65
66 def input_spec(self):
67 return self.inputs[0]["shape"], self.inputs[0]["dtype"]
68
69 def output_spec(self):
70 return self.outputs[0]["shape"], self.outputs[0]["dtype"]
71
72 def infer(self, batch, top=1):
73 # Process I/O and execute the network
74 input = {self.inputs[0]["name"]: tf.convert_to_tensor(batch)}
75 output = self.pred_fn(**input)
76 output = output[self.outputs[0]["name"]].numpy()
77
78 # Read and process the results
79 classes = np.argmax(output, axis=1)
80 scores = np.max(output, axis=1)
81 top = max(top, output.shape[1])
82 top_classes = np.flip(np.argsort(output, axis=1), axis=1)[:, 0:top]
83 top_scores = np.flip(np.sort(output, axis=1), axis=1)[:, 0:top]
84
85 return classes, scores, [top_classes, top_scores]
86

Callers 1

mainFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected