Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import numpy as np 

2from numpy.linalg import LinAlgError 

3from .blas import get_blas_funcs 

4from .lapack import get_lapack_funcs 

5 

6__all__ = ['LinAlgError', 'LinAlgWarning', 'norm'] 

7 

8 

9class LinAlgWarning(RuntimeWarning): 

10 """ 

11 The warning emitted when a linear algebra related operation is close 

12 to fail conditions of the algorithm or loss of accuracy is expected. 

13 """ 

14 pass 

15 

16 

17def norm(a, ord=None, axis=None, keepdims=False, check_finite=True): 

18 """ 

19 Matrix or vector norm. 

20 

21 This function is able to return one of seven different matrix norms, 

22 or one of an infinite number of vector norms (described below), depending 

23 on the value of the ``ord`` parameter. 

24 

25 Parameters 

26 ---------- 

27 a : (M,) or (M, N) array_like 

28 Input array. If `axis` is None, `a` must be 1D or 2D. 

29 ord : {non-zero int, inf, -inf, 'fro'}, optional 

30 Order of the norm (see table under ``Notes``). inf means NumPy's 

31 `inf` object 

32 axis : {int, 2-tuple of ints, None}, optional 

33 If `axis` is an integer, it specifies the axis of `a` along which to 

34 compute the vector norms. If `axis` is a 2-tuple, it specifies the 

35 axes that hold 2-D matrices, and the matrix norms of these matrices 

36 are computed. If `axis` is None then either a vector norm (when `a` 

37 is 1-D) or a matrix norm (when `a` is 2-D) is returned. 

38 keepdims : bool, optional 

39 If this is set to True, the axes which are normed over are left in the 

40 result as dimensions with size one. With this option the result will 

41 broadcast correctly against the original `a`. 

42 check_finite : bool, optional 

43 Whether to check that the input matrix contains only finite numbers. 

44 Disabling may give a performance gain, but may result in problems 

45 (crashes, non-termination) if the inputs do contain infinities or NaNs. 

46 

47 Returns 

48 ------- 

49 n : float or ndarray 

50 Norm of the matrix or vector(s). 

51 

52 Notes 

53 ----- 

54 For values of ``ord <= 0``, the result is, strictly speaking, not a 

55 mathematical 'norm', but it may still be useful for various numerical 

56 purposes. 

57 

58 The following norms can be calculated: 

59 

60 ===== ============================ ========================== 

61 ord norm for matrices norm for vectors 

62 ===== ============================ ========================== 

63 None Frobenius norm 2-norm 

64 'fro' Frobenius norm -- 

65 inf max(sum(abs(x), axis=1)) max(abs(x)) 

66 -inf min(sum(abs(x), axis=1)) min(abs(x)) 

67 0 -- sum(x != 0) 

68 1 max(sum(abs(x), axis=0)) as below 

69 -1 min(sum(abs(x), axis=0)) as below 

70 2 2-norm (largest sing. value) as below 

71 -2 smallest singular value as below 

72 other -- sum(abs(x)**ord)**(1./ord) 

73 ===== ============================ ========================== 

74 

75 The Frobenius norm is given by [1]_: 

76 

77 :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}` 

78 

79 The ``axis`` and ``keepdims`` arguments are passed directly to 

80 ``numpy.linalg.norm`` and are only usable if they are supported 

81 by the version of numpy in use. 

82 

83 References 

84 ---------- 

85 .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, 

86 Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15 

87 

88 Examples 

89 -------- 

90 >>> from scipy.linalg import norm 

91 >>> a = np.arange(9) - 4.0 

92 >>> a 

93 array([-4., -3., -2., -1., 0., 1., 2., 3., 4.]) 

94 >>> b = a.reshape((3, 3)) 

95 >>> b 

96 array([[-4., -3., -2.], 

97 [-1., 0., 1.], 

98 [ 2., 3., 4.]]) 

99 

100 >>> norm(a) 

101 7.745966692414834 

102 >>> norm(b) 

103 7.745966692414834 

104 >>> norm(b, 'fro') 

105 7.745966692414834 

106 >>> norm(a, np.inf) 

107 4 

108 >>> norm(b, np.inf) 

109 9 

110 >>> norm(a, -np.inf) 

111 0 

112 >>> norm(b, -np.inf) 

113 2 

114 

115 >>> norm(a, 1) 

116 20 

117 >>> norm(b, 1) 

118 7 

119 >>> norm(a, -1) 

120 -4.6566128774142013e-010 

121 >>> norm(b, -1) 

122 6 

123 >>> norm(a, 2) 

124 7.745966692414834 

125 >>> norm(b, 2) 

126 7.3484692283495345 

127 

128 >>> norm(a, -2) 

129 0 

130 >>> norm(b, -2) 

131 1.8570331885190563e-016 

132 >>> norm(a, 3) 

133 5.8480354764257312 

134 >>> norm(a, -3) 

135 0 

136 

137 """ 

138 # Differs from numpy only in non-finite handling and the use of blas. 

139 if check_finite: 

140 a = np.asarray_chkfinite(a) 

141 else: 

142 a = np.asarray(a) 

143 

144 # Only use optimized norms if axis and keepdims are not specified. 

145 if a.dtype.char in 'fdFD' and axis is None and not keepdims: 

146 

147 if ord in (None, 2) and (a.ndim == 1): 

148 # use blas for fast and stable euclidean norm 

149 nrm2 = get_blas_funcs('nrm2', dtype=a.dtype) 

150 return nrm2(a) 

151 

152 if a.ndim == 2 and axis is None and not keepdims: 

153 # Use lapack for a couple fast matrix norms. 

154 # For some reason the *lange frobenius norm is slow. 

155 lange_args = None 

156 # Make sure this works if the user uses the axis keywords 

157 # to apply the norm to the transpose. 

158 if ord == 1: 

159 if np.isfortran(a): 

160 lange_args = '1', a 

161 elif np.isfortran(a.T): 

162 lange_args = 'i', a.T 

163 elif ord == np.inf: 

164 if np.isfortran(a): 

165 lange_args = 'i', a 

166 elif np.isfortran(a.T): 

167 lange_args = '1', a.T 

168 if lange_args: 

169 lange = get_lapack_funcs('lange', dtype=a.dtype) 

170 return lange(*lange_args) 

171 

172 # Filter out the axis and keepdims arguments if they aren't used so they 

173 # are never inadvertently passed to a version of numpy that doesn't 

174 # support them. 

175 if axis is not None: 

176 if keepdims: 

177 return np.linalg.norm(a, ord=ord, axis=axis, keepdims=keepdims) 

178 return np.linalg.norm(a, ord=ord, axis=axis) 

179 return np.linalg.norm(a, ord=ord) 

180 

181 

182def _datacopied(arr, original): 

183 """ 

184 Strict check for `arr` not sharing any data with `original`, 

185 under the assumption that arr = asarray(original) 

186 

187 """ 

188 if arr is original: 

189 return False 

190 if not isinstance(original, np.ndarray) and hasattr(original, '__array__'): 

191 return False 

192 return arr.base is None