m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

290 lines
10 KiB

7 months ago
  1. """
  2. Array methods which are called by both the C-code for the method
  3. and the Python code for the NumPy-namespace function
  4. """
  5. import warnings
  6. from contextlib import nullcontext
  7. from numpy.core import multiarray as mu
  8. from numpy.core import umath as um
  9. from numpy.core.multiarray import asanyarray
  10. from numpy.core import numerictypes as nt
  11. from numpy.core import _exceptions
  12. from numpy._globals import _NoValue
  13. from numpy.compat import pickle, os_fspath
  14. # save those O(100) nanoseconds!
  15. umr_maximum = um.maximum.reduce
  16. umr_minimum = um.minimum.reduce
  17. umr_sum = um.add.reduce
  18. umr_prod = um.multiply.reduce
  19. umr_any = um.logical_or.reduce
  20. umr_all = um.logical_and.reduce
  21. # Complex types to -> (2,)float view for fast-path computation in _var()
  22. _complex_to_float = {
  23. nt.dtype(nt.csingle) : nt.dtype(nt.single),
  24. nt.dtype(nt.cdouble) : nt.dtype(nt.double),
  25. }
  26. # Special case for windows: ensure double takes precedence
  27. if nt.dtype(nt.longdouble) != nt.dtype(nt.double):
  28. _complex_to_float.update({
  29. nt.dtype(nt.clongdouble) : nt.dtype(nt.longdouble),
  30. })
  31. # avoid keyword arguments to speed up parsing, saves about 15%-20% for very
  32. # small reductions
  33. def _amax(a, axis=None, out=None, keepdims=False,
  34. initial=_NoValue, where=True):
  35. return umr_maximum(a, axis, None, out, keepdims, initial, where)
  36. def _amin(a, axis=None, out=None, keepdims=False,
  37. initial=_NoValue, where=True):
  38. return umr_minimum(a, axis, None, out, keepdims, initial, where)
  39. def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
  40. initial=_NoValue, where=True):
  41. return umr_sum(a, axis, dtype, out, keepdims, initial, where)
  42. def _prod(a, axis=None, dtype=None, out=None, keepdims=False,
  43. initial=_NoValue, where=True):
  44. return umr_prod(a, axis, dtype, out, keepdims, initial, where)
  45. def _any(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
  46. # Parsing keyword arguments is currently fairly slow, so avoid it for now
  47. if where is True:
  48. return umr_any(a, axis, dtype, out, keepdims)
  49. return umr_any(a, axis, dtype, out, keepdims, where=where)
  50. def _all(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
  51. # Parsing keyword arguments is currently fairly slow, so avoid it for now
  52. if where is True:
  53. return umr_all(a, axis, dtype, out, keepdims)
  54. return umr_all(a, axis, dtype, out, keepdims, where=where)
  55. def _count_reduce_items(arr, axis, keepdims=False, where=True):
  56. # fast-path for the default case
  57. if where is True:
  58. # no boolean mask given, calculate items according to axis
  59. if axis is None:
  60. axis = tuple(range(arr.ndim))
  61. elif not isinstance(axis, tuple):
  62. axis = (axis,)
  63. items = nt.intp(1)
  64. for ax in axis:
  65. items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)]
  66. else:
  67. # TODO: Optimize case when `where` is broadcast along a non-reduction
  68. # axis and full sum is more excessive than needed.
  69. # guarded to protect circular imports
  70. from numpy.lib.stride_tricks import broadcast_to
  71. # count True values in (potentially broadcasted) boolean mask
  72. items = umr_sum(broadcast_to(where, arr.shape), axis, nt.intp, None,
  73. keepdims)
  74. return items
  75. # Numpy 1.17.0, 2019-02-24
  76. # Various clip behavior deprecations, marked with _clip_dep as a prefix.
  77. def _clip_dep_is_scalar_nan(a):
  78. # guarded to protect circular imports
  79. from numpy.core.fromnumeric import ndim
  80. if ndim(a) != 0:
  81. return False
  82. try:
  83. return um.isnan(a)
  84. except TypeError:
  85. return False
  86. def _clip_dep_is_byte_swapped(a):
  87. if isinstance(a, mu.ndarray):
  88. return not a.dtype.isnative
  89. return False
  90. def _clip_dep_invoke_with_casting(ufunc, *args, out=None, casting=None, **kwargs):
  91. # normal path
  92. if casting is not None:
  93. return ufunc(*args, out=out, casting=casting, **kwargs)
  94. # try to deal with broken casting rules
  95. try:
  96. return ufunc(*args, out=out, **kwargs)
  97. except _exceptions._UFuncOutputCastingError as e:
  98. # Numpy 1.17.0, 2019-02-24
  99. warnings.warn(
  100. "Converting the output of clip from {!r} to {!r} is deprecated. "
  101. "Pass `casting=\"unsafe\"` explicitly to silence this warning, or "
  102. "correct the type of the variables.".format(e.from_, e.to),
  103. DeprecationWarning,
  104. stacklevel=2
  105. )
  106. return ufunc(*args, out=out, casting="unsafe", **kwargs)
  107. def _clip(a, min=None, max=None, out=None, *, casting=None, **kwargs):
  108. if min is None and max is None:
  109. raise ValueError("One of max or min must be given")
  110. # Numpy 1.17.0, 2019-02-24
  111. # This deprecation probably incurs a substantial slowdown for small arrays,
  112. # it will be good to get rid of it.
  113. if not _clip_dep_is_byte_swapped(a) and not _clip_dep_is_byte_swapped(out):
  114. using_deprecated_nan = False
  115. if _clip_dep_is_scalar_nan(min):
  116. min = -float('inf')
  117. using_deprecated_nan = True
  118. if _clip_dep_is_scalar_nan(max):
  119. max = float('inf')
  120. using_deprecated_nan = True
  121. if using_deprecated_nan:
  122. warnings.warn(
  123. "Passing `np.nan` to mean no clipping in np.clip has always "
  124. "been unreliable, and is now deprecated. "
  125. "In future, this will always return nan, like it already does "
  126. "when min or max are arrays that contain nan. "
  127. "To skip a bound, pass either None or an np.inf of an "
  128. "appropriate sign.",
  129. DeprecationWarning,
  130. stacklevel=2
  131. )
  132. if min is None:
  133. return _clip_dep_invoke_with_casting(
  134. um.minimum, a, max, out=out, casting=casting, **kwargs)
  135. elif max is None:
  136. return _clip_dep_invoke_with_casting(
  137. um.maximum, a, min, out=out, casting=casting, **kwargs)
  138. else:
  139. return _clip_dep_invoke_with_casting(
  140. um.clip, a, min, max, out=out, casting=casting, **kwargs)
  141. def _mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
  142. arr = asanyarray(a)
  143. is_float16_result = False
  144. rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
  145. if rcount == 0 if where is True else umr_any(rcount == 0, axis=None):
  146. warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)
  147. # Cast bool, unsigned int, and int to float64 by default
  148. if dtype is None:
  149. if issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
  150. dtype = mu.dtype('f8')
  151. elif issubclass(arr.dtype.type, nt.float16):
  152. dtype = mu.dtype('f4')
  153. is_float16_result = True
  154. ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
  155. if isinstance(ret, mu.ndarray):
  156. ret = um.true_divide(
  157. ret, rcount, out=ret, casting='unsafe', subok=False)
  158. if is_float16_result and out is None:
  159. ret = arr.dtype.type(ret)
  160. elif hasattr(ret, 'dtype'):
  161. if is_float16_result:
  162. ret = arr.dtype.type(ret / rcount)
  163. else:
  164. ret = ret.dtype.type(ret / rcount)
  165. else:
  166. ret = ret / rcount
  167. return ret
  168. def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
  169. where=True):
  170. arr = asanyarray(a)
  171. rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
  172. # Make this warning show up on top.
  173. if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None):
  174. warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
  175. stacklevel=2)
  176. # Cast bool, unsigned int, and int to float64 by default
  177. if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
  178. dtype = mu.dtype('f8')
  179. # Compute the mean.
  180. # Note that if dtype is not of inexact type then arraymean will
  181. # not be either.
  182. arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where)
  183. # The shape of rcount has to match arrmean to not change the shape of out
  184. # in broadcasting. Otherwise, it cannot be stored back to arrmean.
  185. if rcount.ndim == 0:
  186. # fast-path for default case when where is True
  187. div = rcount
  188. else:
  189. # matching rcount to arrmean when where is specified as array
  190. div = rcount.reshape(arrmean.shape)
  191. if isinstance(arrmean, mu.ndarray):
  192. arrmean = um.true_divide(arrmean, div, out=arrmean, casting='unsafe',
  193. subok=False)
  194. else:
  195. arrmean = arrmean.dtype.type(arrmean / rcount)
  196. # Compute sum of squared deviations from mean
  197. # Note that x may not be inexact and that we need it to be an array,
  198. # not a scalar.
  199. x = asanyarray(arr - arrmean)
  200. if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
  201. x = um.multiply(x, x, out=x)
  202. # Fast-paths for built-in complex types
  203. elif x.dtype in _complex_to_float:
  204. xv = x.view(dtype=(_complex_to_float[x.dtype], (2,)))
  205. um.multiply(xv, xv, out=xv)
  206. x = um.add(xv[..., 0], xv[..., 1], out=x.real).real
  207. # Most general case; includes handling object arrays containing imaginary
  208. # numbers and complex types with non-native byteorder
  209. else:
  210. x = um.multiply(x, um.conjugate(x), out=x).real
  211. ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where)
  212. # Compute degrees of freedom and make sure it is not negative.
  213. rcount = um.maximum(rcount - ddof, 0)
  214. # divide by degrees of freedom
  215. if isinstance(ret, mu.ndarray):
  216. ret = um.true_divide(
  217. ret, rcount, out=ret, casting='unsafe', subok=False)
  218. elif hasattr(ret, 'dtype'):
  219. ret = ret.dtype.type(ret / rcount)
  220. else:
  221. ret = ret / rcount
  222. return ret
  223. def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
  224. where=True):
  225. ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
  226. keepdims=keepdims, where=where)
  227. if isinstance(ret, mu.ndarray):
  228. ret = um.sqrt(ret, out=ret)
  229. elif hasattr(ret, 'dtype'):
  230. ret = ret.dtype.type(um.sqrt(ret))
  231. else:
  232. ret = um.sqrt(ret)
  233. return ret
  234. def _ptp(a, axis=None, out=None, keepdims=False):
  235. return um.subtract(
  236. umr_maximum(a, axis, None, out, keepdims),
  237. umr_minimum(a, axis, None, None, keepdims),
  238. out
  239. )
  240. def _dump(self, file, protocol=2):
  241. if hasattr(file, 'write'):
  242. ctx = nullcontext(file)
  243. else:
  244. ctx = open(os_fspath(file), "wb")
  245. with ctx as f:
  246. pickle.dump(self, f, protocol=protocol)
  247. def _dumps(self, protocol=2):
  248. return pickle.dumps(self, protocol=protocol)