This is an example of why you should never use from module import *
. You lose sight of where functions come from. When you use multiple from module import *
calls, one module's namespace may clobber another module's namespace. Indeed, based on the error message, that appears to be what is happening here.
Notice that when log
refers to numpy.log
, then -1.0*sum(prob*np.log(prob))
can be computed without error:
In [43]: -1.0*sum(prob*np.log(prob))
Out[43]: 4.4058820963782122
but when log
refers to math.log
, then a TypeError is raised:
In [44]: -1.0*sum(prob*math.log(prob))
TypeError: only length-1 arrays can be converted to Python scalars
The fix is to use explicit module imports and explicit references to functions from the module's namespace:
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
The code you posted does not produce the error, but somewhere in your actual code log
must be getting bound to math.log
instead of numpy.log
. Using import module
and referencing functions with module.function
will help you avoid this kind of error in the future.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…