1# Licensed to the Apache Software Foundation (ASF) under one 2# or more contributor license agreements. See the NOTICE file 3# distributed with this work for additional information 4# regarding copyright ownership. The ASF licenses this file 5# to you under the Apache License, Version 2.0 (the 6# "License"); you may not use this file except in compliance 7# with the License. You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, 12# software distributed under the License is distributed on an 13# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14# KIND, either express or implied. See the License for the 15# specific language governing permissions and limitations 16# under the License. 17 18# pylint: disable=missing-docstring 19from __future__ import print_function 20 21import numpy as np 22import mxnet as mx 23try: 24 import cPickle as pickle 25except ImportError: 26 import pickle 27 28 29def extract_feature(sym, args, auxs, data_iter, N, xpu=mx.cpu()): 30 input_buffs = [mx.nd.empty(shape, ctx=xpu) for k, shape in data_iter.provide_data] 31 input_names = [k for k, shape in data_iter.provide_data] 32 args = dict(args, **dict(zip(input_names, input_buffs))) 33 exe = sym.bind(xpu, args=args, aux_states=auxs) 34 outputs = [[] for _ in exe.outputs] 35 output_buffs = None 36 37 data_iter.hard_reset() 38 for batch in data_iter: 39 for data, buff in zip(batch.data, input_buffs): 40 data.copyto(buff) 41 exe.forward(is_train=False) 42 if output_buffs is None: 43 output_buffs = [mx.nd.empty(i.shape, ctx=mx.cpu()) for i in exe.outputs] 44 else: 45 for out, buff in zip(outputs, output_buffs): 46 out.append(buff.asnumpy()) 47 for out, buff in zip(exe.outputs, output_buffs): 48 out.copyto(buff) 49 for out, buff in zip(outputs, output_buffs): 50 out.append(buff.asnumpy()) 51 outputs = [np.concatenate(i, axis=0)[:N] for i in outputs] 52 return dict(zip(sym.list_outputs(), outputs)) 53 54 55class MXModel(object): 56 def __init__(self, xpu=mx.cpu(), *args, **kwargs): 57 self.xpu = xpu 58 self.loss = None 59 self.args = {} 60 self.args_grad = {} 61 self.args_mult = {} 62 self.auxs = {} 63 self.setup(*args, **kwargs) 64 65 def save(self, fname): 66 args_save = {key: v.asnumpy() for key, v in self.args.items()} 67 with open(fname, 'wb') as fout: 68 pickle.dump(args_save, fout) 69 70 def load(self, fname): 71 with open(fname, 'rb') as fin: 72 args_save = pickle.load(fin) 73 for key, v in args_save.items(): 74 if key in self.args: 75 self.args[key][:] = v 76 77 def setup(self, *args, **kwargs): 78 raise NotImplementedError("must override this") 79