我正在学习机器从Kaggle上的本教程学习。
我尝试修改项目结构,因此我创建一个新的.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:backupPycharmProjectsKaggleTitanicModelHelper.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
可能是我的__init__
参数中params=None
引起的错误。我想要的是使此params
字段可选(如果我不想,我不必通过它)
修改 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
来执行此操作,但是我建议以上答案是为了不破坏您可能已经使用此签名的任何代码。