只能将长度为1的数组转换为带日志的Python标量 [英] Only length-1 arrays can be converted to Python scalars with log

查看:103
本文介绍了只能将长度为1的数组转换为带日志的Python标量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

这是为什么您永远不要使用from module import *的一个示例.您看不到功能从何而来.当您使用多个from module import *调用时,一个模块的名称空间可能会破坏另一个模块的名称空间.确实,基于错误消息,这似乎是这里发生的事情.

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.

请注意,当log引用numpy.log时,可以计算出-1.0*sum(prob*np.log(prob))而不会出现错误:

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

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

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


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


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.

这篇关于只能将长度为1的数组转换为带日志的Python标量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆