numpy_5 数学函数与逻辑函数

广播

广播(Broadcasting)机制描述了 numpy 如何在算术运算期间处理具有不同形状的数组,让较小的数组在较大的数组上“广播”,以便它们具有兼容的形状。
广播的规则:

  1. 若两个数组的维度数dim不相同,那么小维度数组的形状将会在左边补1;
  2. 若shape维度不匹配,但是有维度是1,那么可以扩展维度是1的维度匹配另一个数组;
  3. 若shape维度不匹配,但是没有任何一个维度是1,则匹配引发错误。
import numpy as np
x = np.array([0.0, 10.0, 20.0, 30.0])
y = np.array([1.0, 2.0, 3.0])
h = x[:, np.newaxis]
print(h)
# [[ 0.]
#  [10.]
#  [20.]
#  [30.]]
print(y)
# [1. 2. 3.]
z=h+y
print(z)
# [[ 1.  2.  3.]
#  [11. 12. 13.]
#  [21. 22. 23.]
#  [31. 32. 33.]]

数学函数

算术运算

numpy.add(x1, x2, *args, **kwargs) # x1 + x2
numpy.subtract(x1, x2, *args, **kwargs) # x1 - x2
numpy.multiply(x1, x2, *args, **kwargs) # x1乘x2
numpy.divide(x1, x2, *args, **kwargs) # x1 / x2
numpy.floor_divide(x1, x2, *args, **kwargs) # x1 // x2
numpy.power(x1, x2, *args, **kwargs) # x1的x2次幂

应用时注意广播原则;运算为元素级(两两相同位置的数进行运算)。

numpy.sqrt(x, *args, **kwargs) # 开方,等价于numpy.power(x, 0.5)
numpy.square(x, *args, **kwargs) # 平方,等价于numpy.power(x, 2)

三角函数

numpy.sin(x, *args, **kwargs)
numpy.cos(x, *args, **kwargs)
numpy.tan(x, *args, **kwargs)
numpy.arcsin(x, *args, **kwargs)
numpy.arccos(x, *args, **kwargs)
numpy.arctan(x, *args, **kwargs)

它们对数组中的各个元素逐一进行操作。

注:通用函数

通用函数(universal function)通常叫作ufunc,它对数组中的各个元素逐一进行操作。这表明,通用函数分别处理输入数组的每个元素,生成的结果组成一个新的输出数组,输出数组的大小跟输入数组相同。
三角函数等很多数学运算符合通用函数的定义,例如,计算平方根的sqrt()函数、用来取对数的log()函数和求正弦值的sin()函数。

指数和对数

numpy.exp(x, *args, **kwargs) # e的x次幂
numpy.log(x, *args, **kwargs) # ln(x)
numpy.exp2(x, *args, **kwargs) # 2的x次幂
numpy.log2(x, *args, **kwargs) # 以2为底数的log
numpy.log10(x, *args, **kwargs) # lg(x)
注意:log(exp(x)) = x

加法和乘法函数

numpy.sum(a[, axis=None, dtype=None, out=None, …]) #直接求和
numpy.cumsum(a, axis=None, dtype=None, out=None) # 累加和
numpy.prod(a[, axis=None, dtype=None, out=None, …]) #直接乘
numpy.cumprod(a, axis=None, dtype=None, out=None) # 累乘
numpy.diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue) #差值
a:输入矩阵;n:可选,代表要执行几次差值;axis:默认是最后一维(例如二维的话则axis=1)
The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively(递归的).

通过不同的 axis,numpy 会沿着不同的方向进行操作:
二维数组:不设置(None)——对所有的元素操作;如果axis=0,则沿着纵轴进行操作;axis=1,则沿着横轴进行操作。
多维数组:设axis=i,则 numpy 沿着第i个下标变化的方向进行操作。

差值样例:

import numpy as np
A = np.arange(2, 14).reshape((3, 4))
A[1, 1] = 8
print(A)
# [[ 2  3  4  5]
#  [ 6  8  8  9]
#  [10 11 12 13]]
print(np.diff(A))
# [[1 1 1]
#  [2 0 1]
#  [1 1 1]]
print(np.diff(A,n=2))
# [[ 0  0]
#  [-2  1]
#  [ 0  0]]
print(np.diff(A, axis=0))
# [[4 5 4 4]
#  [4 3 4 4]]
print(np.diff(A, n=2,axis=0))
# [[ 0 -2  0  0]]
注:聚合函数

聚合函数 是指对一组值(比如一个数组)进行操作,返回一个单一值作为结果的函数。因而,求数组所有元素之和的函数就是聚合函数。ndarray类实现了多个这样的函数。

四舍五入

numpy.around(a, decimals=0, out=None) # 四舍五入—将数组舍入到给定的小数位数
numpy.ceil(x, *args, **kwargs) # 向上取整
numpy.floor(x, *args, **kwargs) # 向下取整(直接去掉小数部分)

杂项

1.numpy.clip(a, a_min, a_max, out=None, **kwargs) # 裁剪(限制)数组中的值

import numpy as np
x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
y = np.clip(x, a_min=20, a_max=30)
print(y)
# [[20 20 20 20 20]
#  [20 20 20 20 20]
#  [21 22 23 24 25]
#  [26 27 28 29 30]
#  [30 30 30 30 30]]

2.numpy.absolute(x, *args, **kwargs) # 取绝对值
numpy.abs(x, *args, **kwargs) # 取绝对值的速记写法

3.numpy.sign(x, *args, **kwargs) # 返回数字符号的逐元素指示

import numpy as np
x = np.arange(-5, 5)
print(x)
#[-5 -4 -3 -2 -1  0  1  2  3  4]
print(np.sign(x))
#[-1 -1 -1 -1 -1  0  1  1  1  1]

4.numpy.mod(arr,3) # arr % 3

import numpy as np
a=np.array([[ 2, 15, 13,  9],
       [ 9, 17,  2, 14],
       [ 4,  2, 11, 19]])
# mod <=> x % 3
print(np.mod(a, 3))
# [[2 0 1 0]
#  [0 2 2 2]
#  [1 2 2 1]]
# mod 运算可以指定多个被除数
print(np.mod(a, a-5))
# array([[-1,  5,  5,  1],
#        [ 1,  5, -1,  5],
#        [ 0, -1,  5,  5]])

逻辑函数

真值测试

numpy.all(a, axis=None, out=None, keepdims=np._NoValue) # 判断给定轴向上的所有元素是否都为True

numpy.any(a, axis=None, out=None, keepdims=np._NoValue)# 判断给定轴向上是否有一个元素为True

零为False,其他情况为True——不是数字(NaN),正无穷大和负无穷大的值都是’True’,因为它们不等于零。
如果axis为None,返回单个布尔值True或False

import numpy as np
a = np.array([[3,0,5],[0,2,3],[1,3,4]])
print(a)
print(np.all(a, axis=1))  # [False False  True]
print(np.any(a, axis=1))  # [ True  True  True]

逻辑运算

numpy.logical_not(x, *args, **kwargs) # 计算非x元素的真值。
numpy.logical_and(x1, x2, *args, **kwargs) # 计算x1 AND x2元素的真值。
numpy.logical_or(x1, x2, *args, **kwargs) # 逐元素计算x1 OR x2的真值
numpy.logical_xor(x1, x2, *args, **kwargs) # 异或运算(同为0(False),异为1(True))

对照

numpy.greater(x1, x2, *args, **kwargs) # Return the truth value of (x1 > x2)
numpy.greater_equal(x1, x2, *args, **kwargs# Return the truth value of (x1 >= x2)
numpy.equal(x1, x2, *args, **kwargs) # Return (x1 == x2)
numpy.not_equal(x1, x2, *args, **kwargs) # Return (x1 != x2)
numpy.less(x1, x2, *args, **kwargs) # Return the truth value of (x1 < x2)
numpy.less_equal(x1, x2, *args, **kwargs) # Return the truth value of (x1 =< x2)
(注意广播规则的应用)

numpy.allclose()函数: 比较两个数组在一个公差内按元素方向是否相等。
numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
判断是否为True的计算依据:
np.absolute(a - b) <= (atol + rtol * absolute(b))
参数
a, b:要比较的输入数组。
rtol:float,相对公差参数。
atol:float,绝对公差参数。
equal_nan:将NaNs比较为相等——在同一个地方,且 equal_nan=True ;若inf在两个数组中位于同一位置且符号相同,则将它们视为相等。
返回布尔值:如果两个数组在给定的公差内相等,则返回“真”;否则返回“假”。

与类似函数的对比分析:

  1. numpy.array_equal(arr1,arr2):此逻辑函数检查两个数组是否具有相同的形状和元素。
  2. numpy.isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False)
    numpy.allclose() 等价于 numpy.all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))。
import numpy as np
x = np.isclose([1e10, 1e-7], [1.00001e10, 1e-8])
print(x)  # [ True False]
x = np.allclose([1e10, 1e-7], [1.00001e10, 1e-8])
print(x)  # False
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值