您的位置:首页 > 编程语言 > Python开发

提示错误“'>=' not supported between instances of 'range' and 'int'”

2018-03-29 11:20 946 查看
在学习《Designing Machine Learning Systems with Python》(中文名《机器学习系统设计——python语言实现》)一书中,第三章第二节第三小节部分的泊松分布的python代码在python3.6上运行时报错

TypeError: '>=' not supported between instances of 'range' and 'int'


错误信息很明显,’>=’符号不支持两个类型不同的字符之间的比较,从代码中我们可以很容易知道

from scipy.stats import poisson
import matplotlib.pyplot as plt
def pois(x = 1000):
xr = range(x)
ps = poisson(xr)
plt.plot(ps.pmf(x/2))
plt.show()

pois()


关键在于poisson()函数的输入,即xr这个变量,它的类型是range类型,而range类型不能与一个int类型直接判断。我们只需要对它的类型进行下修改就可以了。

我们知道我们的目的是让xr这个变量中的每一个值都与’>=’符号后的int类型数值进行下判断,并将所有结果一起返回。那么我们就可以先试下list类型

输入:

b = list(range(10))
b >= 0


输出:

Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: '>=' not supported between instances of 'list' and 'int'


看来不行,那么我们就想到了numpy库中也有一个类似的arange()函数,我们测试下。

输入:

import numpy as np
a = np.arange(10)
a >= 0


输出:

array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
True])


我们得到了一个array类型的数组。这就是我们想要的答案。返回书中的例子,我们的代码就应该修改为

import numpy as np
from scipy.stats import poisson
import matplotlib.pyplot as plt
def pois(x = 1000):
xr = np.arange(x)
ps = poisson(xr)
plt.plot(ps.pmf(x/2))
plt.show()

pois()


我们就得到了我们想要的输出。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 机器学习
相关文章推荐