我在运行Scikit Learn页面上的“手写数字识别”代码示例时,遇到了问题 (点击此处查看具体代码)。
当我运行以下代码行时:
classifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2])
我的终端显示以下错误:
Traceback (most recent call last): File "plot_digits_classification.py", line 35, in <module> classifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2])TypeError: slice indices must be integers or None or have an __index__ method
为什么会发生这种情况?我怎样才能让这个代码示例正常工作?
回答:
在Python 2中,使用/
运算符对int
类型的参数进行除法运算时,会返回一个int
。而在Python 3中,/
运算符无论参数是否为int
,都会返回一个float
。在Python 3中,如果想要得到int
类型的结果,可以使用//
运算符,例如6//3
。
因此,您的代码应改为:
classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2])
依此类推。