numpy 分母为零的处理办法

numpy 分母为零的处理办法

如果使用for循环逐项处理数据,就丧失了numpy数组运算的优势。有以下2法可以避免for循环。

法一

利用numpy.divide,不为0的项正常除,为0的项赋一个默认值。

numpy.divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'true_divide'>

2个关键参数:初始化一个结果数组out,在where数组为真的地方,就会执行除法,结果存到out的对应位置,在where数组为假的地方,不操作,保持out原来的值。

  • out ndarray, None, or tuple of ndarray and None, optional

    A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where array_like, optional

    This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

示例

>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)

# If you don't pass `out` the indices where (b == 0) will be uninitialized!
>>> c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
>>> print(c)
[ 0.   0.   0.   1.   1.5]

法二

感谢@~华仔呀的方法:numpy中np.finfo用法

"""
np.finfo使用方法
    eps是一个很小的非负数
    除法的分母不能为0的,不然会直接跳出显示错误。
    使用eps将可能出现的零用eps来替换,这样不会报错。
"""
import numpy as np
 
x = np.array([1, 2, 3], dtype=float)
eps = np.finfo(x.dtype).eps  # eps = 2.220446049250313e-16 type = <class 'numpy.float64'>
print(eps, type(eps))
height = np.array([0, 2, 3], dtype=float)
height = np.maximum(height, eps) #一旦height中出现0,就用eps进行替换
print(height)   #[2.22044605e-16 2.00000000e+00 3.00000000e+00]
dy = x / height
print(dy)   #[4.50359963e+15 1.00000000e+00 1.00000000e+00]

参考

  1. How to return 0 with divide by zero
  2. numpy中np.finfo用法
  • 11
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个 Python 的实现,主要使用了 numpy 库进行矩阵计算和归一化处理: ```python import numpy as np # 假设原始矩阵 A 和 B 的大小为 m 行 n 列 m, n = 10, 8 # 生成随机矩阵 A 和 B A = np.random.rand(m, n) B = np.random.rand(m, n) # 对矩阵 A 进行归一化处理,正向指标越大越好,使用最大值归一化 max_values = np.max(A, axis=0) A_norm = A / max_values # 对矩阵 B 进行归一化处理,负向指标越小越好,使用最小值归一化 min_values = np.min(B, axis=0) B_norm = min_values / B # 将矩阵 A、B 中的所有元素都大于等于 1 A_norm = A_norm + 1 B_norm = B_norm + 1 # 将矩阵 A、B 转化为相同阶数的方阵,这里假设为 m x m 的方阵 A_square = np.zeros((m, m)) B_square = np.zeros((m, m)) for i in range(m): for j in range(m): if i < n and j < n: A_square[i][j] = A_norm[i][j] B_square[i][j] = B_norm[i][j] elif i == j: A_square[i][j] = 1 B_square[i][j] = 1 # 计算矩阵 A 和 B 相互作用的增长值,避免分母的情况下加上一个小的数值 eps = 1e-6 C = np.dot(A_square, B_square) D = np.dot(B_square, A_square) growth = (C - D) / (D + eps) ``` 以上代码中,我们使用了两种不同的归一化方法,分别是最大值归一化和最小值归一化,根据正向指标和负向指标的不同选择不同的方法。在将矩阵 A、B 转化为方阵时,我们使用了一个简单的方法,即将原始矩阵填充到对角线上,其余部分填充为 0。最后计算相互作用的增长值时,为避免分母的情况,我们加上了一个小的数值 eps。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值