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

在学习《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 "", 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()

我们就得到了我们想要的输出。
提示错误“'>=' not supported between instances of 'range' and 'int'”_第1张图片

你可能感兴趣的:(机器学习系统实现)