1import warnings 2 3import numpy 4import six 5 6import chainer 7from chainer.backends import cuda 8 9 10def as_vec(x): 11 warnings.warn( 12 'chainer.utils.array.as_vec is deprecated. Please refer to ' 13 'numpy.ravel or other array backend functions to flatten ndarrays.', 14 DeprecationWarning) 15 if x.ndim == 1: 16 return x 17 return x.ravel() 18 19 20def as_mat(x): 21 warnings.warn( 22 'chainer.utils.array.as_mat is deprecated. Please refer to ' 23 'numpy.reshape or other array backend functions to reshape ndarrays.', 24 DeprecationWarning) 25 if x.ndim == 2: 26 return x 27 return x.reshape(len(x), -1) 28 29 30def empty_like(x): 31 warnings.warn( 32 'chainer.utils.array.empty_like is deprecated. Please refer to ' 33 'numpy.empty_like or other array backend functions to initialize ' 34 'empty arrays.', 35 DeprecationWarning) 36 if cuda.available and isinstance(x, cuda.ndarray): 37 return cuda.cupy.empty_like(x) 38 else: 39 return numpy.empty_like(x) 40 41 42def size_of_shape(shape): 43 size = 1 44 for i in shape: 45 size *= i 46 47 # should not return long in Python 2 48 return int(size) 49 50 51def sum_to(x, shape): 52 if x.shape == shape: 53 return x 54 if isinstance(x, chainer.Variable): 55 raise TypeError( 56 'chainer.utils.sum_to does not support Variable input. ' 57 'Use chainer.functions.sum_to instead.') 58 ndim = len(shape) 59 lead = x.ndim - ndim 60 lead_axis = tuple(six.moves.range(lead)) 61 axis = tuple([i + lead for i, sx in enumerate(shape) if sx == 1]) 62 y = x.sum(lead_axis + axis, keepdims=True) 63 if lead > 0: 64 y = y.squeeze(lead_axis) 65 return y 66