提示错误“'>=' 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 "<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()

我们就得到了我们想要的输出。
泊松分布图

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值