Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

Only length-1 arrays can be converted to Python scalars with log

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

I have this code and I do not know what could be the problem, thanks for any help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...