机器学习实战-Py3.X错误合集

零. 常见

1
TypeError: 'range' object doesn't support item deletion
  • 注:3.x中range()要改为list(rang()),因为python3中range不返回数组对象,而是返回range对象
1
AttributeError: 'dict' object has no attribute 'iteritems'
  • iteritems()要改为items()

二. kNN

  • 报错:

    1
    NameError: name 'reload' is not defined

  • 在前面加入命令(个人推荐直接写在mian函数里面简单快捷)

    1
    from imp import reload

四. 朴素贝叶斯

  • 报错:

    1
    UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 199: illegal multibyte sequence

  • 那是因为书上的下面这两行代码有点问题:

    1
    2
    3
    4
    5
    6
    7
    wordList = textParse(open('email/spam/%d.txt' % i).read()
    wordList = textParse(open('email/ham/%d.txt' % i).read()
    需要将上面的代码更为下面这两行:
    wordList = textParse(open('email/spam/%d.txt' % i, "rb").read().decode('GBK','ignore') )
    wordList = textParse(open('email/ham/%d.txt' % i, "rb").read().decode('GBK','ignore') )

    因为有可能文件中存在类似“�”非法字符。

  • 报错:

    1
    TypeError: 'range' object doesn't support item deletion

1
AttributeError: 'dict' object has no attribute 'iteritems'
  • 参考常见错误

五. Logistic回归

  • 报错:
    1
    TypeError: 'numpy.float64' object cannot be interpreted as an integer

这里是因为numpy版本问题,更改版本解决

1
pip install -U numpy==1.11.0

  • 报错:

    1
    TypeError: 'range' object doesn't support item deletion

  • 参考常见错误

  • 报错:

    1
    AttributeError: 'numpy.ndarray' object has no attribute 'getA'

  • 注释掉plotBestFit()的矩阵转为数组,因为在输入时已经转换为数组了

    1
    2
    3
    4
    5
    plotBestFit(weights)
    '''
    # 矩阵变为数组,使用gradAscent时加入
    weights = wei.getA()
    '''

参考来自

机器学习实战Py3.x填坑记