本文介绍了如何使用 scikit-learn 数字数据集解决“NoneType"对象没有属性“写入"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 scikit 上进行第一次练习-学习,但即使我运行他们的解决方案代码(如下所示)我得到紧随其后的代码块中的错误.有谁知道为什么会这样?我该如何解决?

在尝试使用此数据集时,预测方法也失败,出于某种原因,使用问题最底部的代码对 iris 数据集似乎工作正常.对不起,如果我遗漏了一些非常明显的东西,我不是一个真正的程序员.

回溯(最近一次调用最后一次):文件C:\Users\user2491873\Desktop\scikit_exercise.py",第 30 行,在 <module> 中打印(knn.fit(X_train, y_train).score(X_test, y_test))文件C:\Python33\lib\site-packages\sklearn\base.py",第 279 行,得分返回accuracy_score(y, self.predict(X))文件C:\Python33\lib\site-packages\sklearn\neighbors\classification.py",第 131 行,在预测中neigh_dist, neigh_ind = self.kneighbors(X)文件C:\Python33\lib\site-packages\sklearn\neighbors\base.py",第 254 行,在 kneighbors 中警告等距()文件C:\Python33\lib\site-packages\sklearn\neighbors\base.py",第33行,在warn_equidistant警告.警告(味精,邻居警告,堆栈级别= 3)文件C:\Python33\lib\idlelib\PyShell.py",第 59 行,在 idle_showwarningfile.write(warnings.formatwarning(message, category, filename,AttributeError: 'NoneType' 对象没有属性 'write'

代码如下:

"""================================数字分类练习================================这个练习用于:ref:`clf_tut` 部分:ref:` supervisord_learning_tut` 部分:ref:`stat_learn_tut_index`."""从 sklearn 导入数据集、邻居、linear_model数字 = datasets.load_digits()X_digits = 数字.数据y_digits = 数字.目标n_samples = len(X_digits)X_train = X_digits[:.9 * n_samples]y_train = y_digits[:.9 * n_samples]X_test = X_digits[.9 * n_samples:]y_test = y_digits[.9 * n_samples:]knn = neighbor.KNeighborsClassifier()逻辑 = linear_model.LogisticRegression()打印('KNN 分数:%f' % knn.fit(X_train, y_train).score(X_test, y_test))\print('LogisticRegression 得分:%f'% 逻辑拟合 (X_train, y_train).score(X_test, y_test))

这是 Iris 数据集的代码,它似乎工作正常...

将 numpy 导入为 np>>>从 sklearn 导入数据集>>>虹膜 = datasets.load_iris()>>>iris_X = iris.data>>>iris_y = iris.target>>>np.unique(iris_y)数组([0, 1, 2])>>># 拆分训练和测试数据中的虹膜数据>>># 随机排列,随机分割数据>>>np.random.seed(0)>>>指数 = np.random.permutation(len(iris_X))>>>iris_X_train = iris_X[索引[:-10]]>>>iris_y_train = iris_y[指数[:-10]]>>>iris_X_test = iris_X[指数[-10:]]>>>iris_y_test = iris_y[指数[-10:]]>>># 创建并拟合最近邻分类器>>>从 sklearn.neighbors 导入 KNeighborsClassifier>>>knn = KNeighborsClassifier()>>>knn.fit(iris_X_train,iris_y_train)KNeighborsClassifier(algorithm='auto', Leaf_size=30, n_neighbors=5, p=2,warn_on_equidistant=True, weights='uniform')>>>knn.predict(iris_X_test)数组([1, 2, 1, 0, 0, 0, 2, 1, 2, 0])>>>iris_y_test数组([1, 1, 1, 0, 0, 0, 2, 1, 2, 0])
解决方案

如果您阅读回溯消息,则意味着表达式 file.write(warnings.formatwarning(消息、类别、文件名、...) 设置为 None 而不是预期的通道(例如程序的标准输出或用户界面中的缓冲区).>

这意味着这可能是 IDLE 中的一个错误.如果你用谷歌搜索错误信息,你会得到:

http://bugs.python.org/issue18030

反过来又指向:

http://bugs.python.org/issue13582

所以这个bug确实和scikit-learn无关.我建议你:

  • 或者通过输入 python -m idlelib.idle

  • cmd 控制台启动 IDLE
  • 或使用不同的 Python IDE/环境.

I'm trying to do the first exercise on scikit-learn, but even when I run their solution code (shown below) I get the error in the code block immediately following. Does anyone know why this is happening? How can I resolve this?

The predict method also fails when trying to use this dataset, for some reason it seems to work fine for the iris dataset using the code at the very bottom of the question. sorry if I am missing something very obvious, I am not an actual programmer.

Traceback (most recent call last):
  File "C:\Users\user2491873\Desktop\scikit_exercise.py", line 30, in <module>
    print(knn.fit(X_train, y_train).score(X_test, y_test))
  File "C:\Python33\lib\site-packages\sklearn\base.py", line 279, in score
    return accuracy_score(y, self.predict(X))
  File "C:\Python33\lib\site-packages\sklearn\neighbors\classification.py", line 131,     in predict
    neigh_dist, neigh_ind = self.kneighbors(X)
  File "C:\Python33\lib\site-packages\sklearn\neighbors\base.py", line 254, in kneighbors
warn_equidistant()
  File "C:\Python33\lib\site-packages\sklearn\neighbors\base.py", line 33, in warn_equidistant
    warnings.warn(msg, NeighborsWarning, stacklevel=3)
  File "C:\Python33\lib\idlelib\PyShell.py", line 59, in idle_showwarning
file.write(warnings.formatwarning(message, category, filename,
AttributeError: 'NoneType' object has no attribute 'write'

here is the code:

"""
================================
Digits Classification Exercise
================================

This exercise is used in the :ref:`clf_tut` part of the
:ref:`supervised_learning_tut` section of the
:ref:`stat_learn_tut_index`.
"""

from sklearn import datasets, neighbors, linear_model

digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target

n_samples = len(X_digits)

X_train = X_digits[:.9 * n_samples]
y_train = y_digits[:.9 * n_samples]
X_test = X_digits[.9 * n_samples:]
y_test = y_digits[.9 * n_samples:]

knn = neighbors.KNeighborsClassifier()
logistic = linear_model.LogisticRegression()

print('KNN score: %f' % knn.fit(X_train, y_train).score(X_test, y_test))\
print('LogisticRegression score: %f'
      % logistic.fit(X_train, y_train).score(X_test, y_test))

This is the code for the Iris dataset which seems to work fine...

import numpy as np
>>> from sklearn import datasets
>>> iris = datasets.load_iris()
>>> iris_X = iris.data
>>> iris_y = iris.target
>>> np.unique(iris_y)
array([0, 1, 2])

>>> # Split iris data in train and test data
>>> # A random permutation, to split the data randomly
>>> np.random.seed(0)
>>> indices = np.random.permutation(len(iris_X))
>>> iris_X_train = iris_X[indices[:-10]]
>>> iris_y_train = iris_y[indices[:-10]]
>>> iris_X_test  = iris_X[indices[-10:]]
>>> iris_y_test  = iris_y[indices[-10:]]
>>> # Create and fit a nearest-neighbor classifier
>>> from sklearn.neighbors import KNeighborsClassifier
>>> knn = KNeighborsClassifier()
>>> knn.fit(iris_X_train, iris_y_train)
KNeighborsClassifier(algorithm='auto', leaf_size=30, n_neighbors=5, p=2,
           warn_on_equidistant=True, weights='uniform')
>>> knn.predict(iris_X_test)
array([1, 2, 1, 0, 0, 0, 2, 1, 2, 0])
>>> iris_y_test
array([1, 1, 1, 0, 0, 0, 2, 1, 2, 0])    
解决方案

If you read the traceback message it means that the variable file in the expression file.write(warnings.formatwarning(message, category, filename, ...) is set to None instead of the expected channel (for instance the standard output of the program or a buffer in the user interface).

This means that this is probably a bug in IDLE. If you google the error message you will get:

http://bugs.python.org/issue18030

which in turn points to:

http://bugs.python.org/issue13582

So this bug is indeed not related to scikit-learn. I would suggest you to:

  • either launch IDLE from the cmd console by typing python -m idlelib.idle

  • or use a different Python IDE / environment.

这篇关于如何使用 scikit-learn 数字数据集解决“NoneType"对象没有属性“写入"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 08:42