Caffe2 - Python API
A deep learning, cross platform ML framework
compute_statistics_for_blobs.py
1 from __future__ import absolute_import
2 from __future__ import division
3 from __future__ import print_function
4 from __future__ import unicode_literals
5 
6 from caffe2.python import core, schema
7 from caffe2.python.modeling.net_modifier import NetModifier
8 
9 import numpy as np
10 
11 
13  """
14  This class modifies the net passed in by adding ops to compute statistics
15  for certain blobs. For each blob in the list, its min, max, mean and standard
16  deviation will be computed.
17 
18  Args:
19  blobs: list of blobs to compute norm for
20  logging_frequency: frequency for printing norms to logs
21  """
22 
23  def __init__(self, blobs, logging_frequency):
24  self._blobs = blobs
25  self._logging_frequency = logging_frequency
26  self._field_name_suffix = '_summary'
27 
28  def modify_net(self, net, init_net=None, grad_map=None, blob_to_device=None,
29  modify_output_record=False):
30 
31  for blob_name in self._blobs:
32  blob = core.BlobReference(blob_name)
33  if not net.BlobIsDefined(blob):
34  raise Exception('blob {0} is not defined in net {1}'.format(
35  blob, net.Name()))
36 
37  cast_blob = net.Cast(blob, to=core.DataType.FLOAT)
38  stats_name = net.NextScopedBlob(prefix=blob + self._field_name_suffix)
39  stats = net.Summarize(cast_blob, stats_name, to_file=0)
40  net.Print(stats, [], every_n=self._logging_frequency)
41 
42  if modify_output_record:
43  output_field_name = str(blob) + self._field_name_suffix
44  output_scalar = schema.Scalar((np.float, (1,)), stats)
45 
46  if net.output_record() is None:
47  net.set_output_record(
48  schema.Struct((output_field_name, output_scalar))
49  )
50  else:
51  net.AppendOutputRecordField(
52  output_field_name,
53  output_scalar)
54 
55  def field_name_suffix(self):
56  return self._field_name_suffix