def scalar(value): if type(value) == type(1): res = _F.const([value], [], _F.NCHW, _F.int) return res elif type(value) == type(1.): res = _F.const([value], [], _F.NCHW, _F.float) return res else: raise NotImplementedError("not supported data type for creating scalar variable")
def moments(x, axes=[2, 3], shift=None, keep_dims=True): x = _to_var(x) if not isinstance(x, Var): raise RuntimeError("parameter x is not valid") if len(x.shape) != 4 or x.data_format != _F.NC4HW4: raise RuntimeError("parameter x must be 4-D w/ NC4HW4 format") if axes != [2, 3] and axes != (2, 3): raise RuntimeError("parameter axes must be [2, 3] in current implementation") shift = _F.const([0.], [1]) #though it's not used, it's preserved return _F.moments(x, axes, shift, True)
def _to_var(x, to_float=True): if _numpy_supported: if isinstance(x, np.ndarray): # convert numpy ndarray to MNN var if to_float: if x.dtype != np.float32: x = x.astype(np.float32) return _F.const(x, x.shape) if not to_float: if x.dtype != np.int32: x = x.astype(np.int32) return _F.const(x, x.shape, dtype=_F.int) elif isinstance( x, (list, tuple)) and x: # convert list and tuple to MNN Var x = np.array(x) if to_float: if x.dtype != np.float32: x = x.astype(np.float32) return _F.const(x, x.shape) if not to_float: if x.dtype != np.int32: x = x.astype(np.int32) return _F.const(x, x.shape, dtype=_F.int) else: # No numpy support if isinstance(x, _Int): return _F.const(x, [], dtype=_F.int) elif isinstance(x, _Float): return _F.const(x, [], dtype=_F.float) return x
def _to_var(x, to_float=True): if isinstance(x, np.ndarray): if to_float: if x.dtype != np.float32: x = x.astype(np.float32) return _F.const(x, x.shape) if not to_float: if x.dtype != np.int32: x = x.astype(np.int32) return _F.const(x, x.shape, dtype=_F.int) elif isinstance(x, (list, tuple)) and x: x = np.array(x) if to_float: if x.dtype != np.float32: x = x.astype(np.float32) return _F.const(x, x.shape) if not to_float: if x.dtype != np.int32: x = x.astype(np.int32) return _F.const(x, x.shape, dtype=_F.int) elif isinstance(x, _Int): return _F.const(x, [], dtype=_F.int) elif isinstance(x, _Float): return _F.const(x, [], dtype=_F.float) return x