Skip to main content
 首页 » 编程设计

python之如何修复 'Float' 对象没有属性 'exp'

2025年05月04日11mfrbuaa

我在 Python 中有以下高斯方程:

numpy.exp((-(x-m)**2)/(2*sigma)) 

前提是x是一个矩阵。

但是,方程不会运行,我得到以下错误:

AttributeError: 'Float' object has no attribute 'exp' 

我该如何解决这个问题?

EDIT-1

进行以下编辑:

map(float(),np.exp((-(x-m)**2)/(2*sigma))) 

引发错误:

TypeError: 'float' object is not callable 

EDIT-2

这是值 x 的示例:

[[-0.20646505  0.07763347 -0.16161097  0.370439  ] 
 [-0.91295327 -0.73768934 -0.78909055  0.06156045] 
 [-0.37242104  0.51828245 -1.16138222 -0.02489585] 
 [-1.07890926 -0.29704036 -1.7888618  -0.3337744 ]] 
 
m = 5 
sigma = 1 

谢谢。

请您参考如下方法:

这可能是因为您将数组的 dtype 作为对象,所以将其转换为 float ,即

x = np.array([[-0.20646505,  0.07763347, -0.16161097,  0.370439  ], 
              [-0.91295327,-0.73768934, -0.78909055,  0.06156045], 
              [-0.37242104,  0.51828245, -1.16138222, -0.02489585], 
              [-1.07890926, -0.29704036, -1.7888618,  -0.3337744 ]],dtype=object) 
 
m = 5 
sigma = 1 
np.exp((-(x-m)**2)/(2*sigma))  

这将导致:

 AttributeError: 'float' object has no attribute 'exp' 

将其转换为 float 即:

np.exp((-(x.astype(float)-m)**2)/(2*sigma)) 
 
array([[  1.29935943e-06,   5.47758566e-06,   1.63950875e-06, 
      2.21778276e-05], 
   [  2.55786406e-08,   7.10033001e-08,   5.27984133e-08, 
      5.06026050e-06], 
   [  5.40131118e-07,   4.34936286e-05,   5.70846640e-09, 
      3.28945338e-06], 
   [  9.45644899e-09,   8.07503629e-07,   9.81698210e-11, 
      6.64271640e-07]]) 

这也取决于您使用的 numpy 版本。您还应该尝试更新 numpy,修复了很多错误。