【问题标题】:Only length-1 arrays can be converted to Python scalars with log只有长度为 1 的数组可以用 log 转换为 Python 标量
【发布时间】:2016-03-10 15:59:31
【问题描述】:
from numpy import * 
from pylab import * 
from scipy import * 
from scipy.signal import * 
from scipy.stats import * 


testimg = imread('path')  

hist = hist(testimg.flatten(), 256, range=[0.0,1.0])[0]
hist = hist + 0.000001
prob = hist/sum(hist)


entropia = -1.0*sum(prob*log(prob))#here is error
print 'Entropia: ', entropia

我有这个代码,但我不知道可能是什么问题,感谢您的帮助

【问题讨论】:

  • 它在这里运行。错误是什么?可以添加错误输出吗?

标签: python python-2.7 numpy scipy


【解决方案1】:

这就是为什么你永远不应该使用from module import * 的一个例子。你忽略了函数的来源。当您使用多个from module import * 调用时,一个模块的命名空间可能会破坏另一个模块的命名空间。事实上,根据错误消息,这似乎就是这里发生的事情。

请注意,当log 引用numpy.log 时,-1.0*sum(prob*np.log(prob)) 可以正确计算:

In [43]: -1.0*sum(prob*np.log(prob))
Out[43]: 4.4058820963782122

但是当log 引用math.log 时,会引发 TypeError:

In [44]: -1.0*sum(prob*math.log(prob))
TypeError: only length-1 arrays can be converted to Python scalars

解决方法是使用显式模块导入和显式引用模块命名空间中的函数:

import numpy as np
import matplotlib.pyplot as plt

testimg = np.random.random((10,10))

hist = plt.hist(testimg.flatten(), 256, range=[0.0,1.0])[0]
hist = hist + 0.000001
prob = hist/sum(hist)

# entropia = -1.0*sum(prob*np.log(prob))
entropia = -1.0*(prob*np.log(prob)).sum()
print 'Entropia: ', entropia
# prints something like:  Entropia:  4.33996609845

您发布的代码不会产生错误,但实际代码中的某处log 必须绑定到math.log 而不是numpy.log。使用import module 并使用module.function 引用函数将帮助您避免将来出现此类错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-27
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    相关资源
    最近更新 更多