我正在从规范化数组中访问X和Y值。但是当我使用for循环将一个方程应用于规范化数组的每个bin时,想要用0排除值。我收到0值的错误。
normed = array([[ 0.0003, 0.0026, 0.0149, 0.0288, 0.0328, 0.0174, 0.0036,
0.0004, 0. , 0. ],
[ 0.0001, 0.0024, 0.0103, 0.0244, 0.0321, 0.0211, 0.0064,
0.0006, 0. , 0. ],
[ 0.0003, 0.0012, 0.0072, 0.0235, 0.0325, 0.0246, 0.0079,
0.0012, 0. , 0. ],
[ 0. , 0.0008, 0.0065, 0.0182, 0.0346, 0.0274, 0.0124,
0.002 , 0.0004, 0. ],
[ 0. , 0.0005, 0.0033, 0.0155, 0.0302, 0.0327, 0.0153,
0.0032, 0.0003, 0. ],
[ 0. , 0.0002, 0.0025, 0.0121, 0.0283, 0.0342, 0.0184,
0.0054, 0.0004, 0. ],
[ 0. , 0.0001, 0.0016, 0.008 , 0.0253, 0.0318, 0.0219,
0.0084, 0.001 , 0.0002],
[ 0. , 0. , 0.0008, 0.0056, 0.0198, 0.0316, 0.0296,
0.0108, 0.0018, 0.0002],
[ 0. , 0.0001, 0.0007, 0.0035, 0.0169, 0.0329, 0.0318,
0.0163, 0.0039, 0.0006],
[ 0. , 0. , 0.0001, 0.0022, 0.0107, 0.0253, 0.0329,
0.0171, 0.004 , 0.0011]])
Px = normed.sum(axis=0)
array([ 0.0007, 0.0079, 0.0479, 0.1418, 0.2632, 0.279 , 0.1802,
0.0654, 0.0118, 0.0021])
def funct():
CEnt = 0
for i in range(0,10):
if i > 0:
for j in range(0,10):
if j > 0:
CEnt += normed[i][j]*np.log2(Px/(normed[i][j]))
return CEnt
当我打印funct()时,我得到了错误:[nan nan nan nan nan nan nan nan nan] RuntimeWarning:在true_divide中遇到的除以零 RuntimeWarning:在乘法中遇到无效值
如何使用CEnt方程编写for循环来遍历数组中的100个bin,同时排除0值?非常感谢....
答案 0 :(得分:0)
您将索引与零进行比较而不是实际值。 以下代码将忽略零。
import numpy as np
from numpy import array
normed = array([[ 0.0003, 0.0026, 0.0149, 0.0288, 0.0328, 0.0174, 0.0036,
0.0004, 0. , 0. ],
[ 0.0001, 0.0024, 0.0103, 0.0244, 0.0321, 0.0211, 0.0064,
0.0006, 0. , 0. ],
[ 0.0003, 0.0012, 0.0072, 0.0235, 0.0325, 0.0246, 0.0079,
0.0012, 0. , 0. ],
[ 0. , 0.0008, 0.0065, 0.0182, 0.0346, 0.0274, 0.0124,
0.002 , 0.0004, 0. ],
[ 0. , 0.0005, 0.0033, 0.0155, 0.0302, 0.0327, 0.0153,
0.0032, 0.0003, 0. ],
[ 0. , 0.0002, 0.0025, 0.0121, 0.0283, 0.0342, 0.0184,
0.0054, 0.0004, 0. ],
[ 0. , 0.0001, 0.0016, 0.008 , 0.0253, 0.0318, 0.0219,
0.0084, 0.001 , 0.0002],
[ 0. , 0. , 0.0008, 0.0056, 0.0198, 0.0316, 0.0296,
0.0108, 0.0018, 0.0002],
[ 0. , 0.0001, 0.0007, 0.0035, 0.0169, 0.0329, 0.0318,
0.0163, 0.0039, 0.0006],
[ 0. , 0. , 0.0001, 0.0022, 0.0107, 0.0253, 0.0329,
0.0171, 0.004 , 0.0011]])
Px = normed.sum(axis=0)
def funct():
CEnt = 0
for line in normed:
for value in line:
if value > 0:
CEnt += value*np.log2(Px/(value))
return CEnt
print(funct())
循环(对于这个10x10阵列)与此相同:
def funct():
CEnt = 0
for i in range(10):
for j in range(10):
if normed[i][j] > 0:
CEnt += normed[i][j]*np.log2(Px/(normed[i][j]))
return CEnt