我在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
字段可选(如果我不想,我不必传递它)
答案 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
来完成此操作,但我建议上面的答案是为了不破坏您使用此签名调用的任何代码。