' NoneType'对象不支持__init__中的项目赋值

时间:2017-09-29 06:33:44

标签: python numpy scikit-learn

我在Kaggle学习机器学习this tutorial

我尝试修改项目结构,因此我创建了一个新的.py文件来创建一个新类。这是班级:

class ModelHelper(object):
    def __init__(self, model, seed=0, params=None):
        params['random_state'] = seed # TypeError: 'NoneType' object does not support item assignment
        self.model = model(**params)

    def train(self, x_train, y_train):
        self.model.fit(x_train, y_train)

    def predict(self, x):
        return self.model.predict(x)

    def fit(self, x, y):
        return self.model.fit(x, y)

    def feature_importances(self, x, y):
        print(self.model.fit(x, y).feature_importances_)

这就是我用它的方式:

from helper import ModelHelper

log_reg = ModelHelper(model=LogisticRegression);

这是我收到的完整错误:

Traceback (most recent call last):
  File "F:/backup/PycharmProjects/KaggleTitanic/DataAnalysis.py", line 191, in <module>
    log_reg = ModelHelper(model=LogisticRegression);
  File "F:\backup\PycharmProjects\KaggleTitanic\ModelHelper.py", line 3, in __init__
    params['random_state'] = seed # TypeError: 'NoneType' object does not support item assignment
TypeError: 'NoneType' object does not support item assignment

可能是我params=None参数中__init__引起的错误。我想要的是使这个params字段可选(如果我不想,我不必传递它)

1 个答案:

答案 0 :(得分:1)

修改ModelHelper,以便在未传递值的情况下正确初始化params的默认值。

class ModelHelper(object):
    def __init__(self, model, seed=0, params=None):
        if params is None:
            params = {}
        params['random_state'] = seed # TypeError: 'NoneType' object does not support item assignment
        self.model = model(**params)

    def train(self, x_train, y_train):
        self.model.fit(x_train, y_train)

    def predict(self, x):
        return self.model.predict(x)

    def fit(self, x, y):
        return self.model.fit(x, y)

    def feature_importances(self, x, y):
        print(self.model.fit(x, y).feature_importances_)

有必要在呼叫签名中使用params=None而不是params={},以便ModelHelper的每个实例都使用自己独立的params字典。也可以通过更改呼叫签名来使用**params来完成此操作,但我建议上面的答案是为了不破坏您使用此签名调用的任何代码。