Beispiel #1
0
def build_net(graph: nx.DiGraph):
    try:
        if not hasattr(os.environ, 'GLOG_minloglevel'):
            os.environ['GLOG_minloglevel'] = '2'
        import caffe
        log.info('Partial inference via the framework is available')
    except ImportError:
        log.warning(
            'pyCaffe is not available. Partial inference via the framework is not '
            + 'possible')
        return

    try:
        net = caffe.Net(graph.proto_path, graph.caffemodel_path, caffe.TEST)
    except Exception as err:
        raise Error(
            'Error happened while constructing caffe.Net in the Caffe fallback function: {}. '
            + refer_to_faq_msg(12), str(err)) from err

    inputs_node_name = find_inputs(graph)

    reshape_flag = False
    for i in inputs_node_name:
        new_input_shape = graph.node[i]['shape'].astype(int)
        top_node = get_node_top(graph, i)
        caffe_shape = list(net.blobs[top_node].shape)
        if not np.all(caffe_shape == new_input_shape):
            net.blobs[top_node].reshape(*[int(x) for x in new_input_shape])
            reshape_flag = True

    if reshape_flag:
        net.reshape()

    try:
        net.forward()
    except KeyError as err:
        log.error('Error happened in Caffe net.forward: {}.'.format(str(err)))
        log.error(
            'It may point to the known bug in pycaffe when top and name of the layer do not match.'
        )
        log.error('Please make sure that the latest pycaffe is used.')
        raise Error(
            'Cannot infer shapes due to exception in Caffe: {}. ' +
            refer_to_faq_msg(13), str(err)) from err
    except Exception as err:
        raise Error(
            'Cannot infer shapes in Caffe net.forward due to exception: {}.' +
            refer_to_faq_msg(13), str(err)) from err

    graph.__setattr__('caffe_net', net)