循环创建 类
Create classes in a loop
我想定义一个 class,然后为该 class 生成一个动态副本数。
现在,我有这个:
class xyz(object):
def __init__(self):
self.model_type = ensemble.RandomForestClassifier()
self.model_types = {}
self.model = {}
for x in range(0,5):
self.model_types[x] = self.model_type
def fit_model():
for x in range(0,5):
self.model[x] = self.model_types[x].fit(data[x])
def score_model():
for x in range(0,5):
self.pred[x] = self.model[x].predict(data[x])
我想拟合 5 个不同的模型,但我认为 Python 指向同一个 class 5 次,而不是在模型字典中创建 5 个不同的 class。
这意味着当我使用 "score_model" 方法时,它只是对最后一个拟合的模型进行评分,而不是对 5 个独特的模型进行评分。
我认为我只需要使用继承来用 5 个不同的 class 填充模型 [] 字典,但我不确定该怎么做?
在您的原始代码中,您创建了一个实例并使用了五次。相反,您只想在将 class 添加到 model_types 数组时初始化它,如以下代码所示。
class xyz(object):
def __init__(self):
self.model_type = ensemble.RandomForestClassifier
self.model_types = {}
self.model = {}
for x in range(0,5):
self.model_types[x] = self.model_type()
def fit_model():
for x in range(0,5):
self.model[x] = self.model_types[x].fit(data[x])
def score_model():
for x in range(0,5):
self.pred[x] = self.model[x].predict(data[x])
在python中一切都是对象,所以你的变量也可以指向一个class,然后你的变量可以被当作一个class。
我想定义一个 class,然后为该 class 生成一个动态副本数。
现在,我有这个:
class xyz(object):
def __init__(self):
self.model_type = ensemble.RandomForestClassifier()
self.model_types = {}
self.model = {}
for x in range(0,5):
self.model_types[x] = self.model_type
def fit_model():
for x in range(0,5):
self.model[x] = self.model_types[x].fit(data[x])
def score_model():
for x in range(0,5):
self.pred[x] = self.model[x].predict(data[x])
我想拟合 5 个不同的模型,但我认为 Python 指向同一个 class 5 次,而不是在模型字典中创建 5 个不同的 class。
这意味着当我使用 "score_model" 方法时,它只是对最后一个拟合的模型进行评分,而不是对 5 个独特的模型进行评分。
我认为我只需要使用继承来用 5 个不同的 class 填充模型 [] 字典,但我不确定该怎么做?
在您的原始代码中,您创建了一个实例并使用了五次。相反,您只想在将 class 添加到 model_types 数组时初始化它,如以下代码所示。
class xyz(object):
def __init__(self):
self.model_type = ensemble.RandomForestClassifier
self.model_types = {}
self.model = {}
for x in range(0,5):
self.model_types[x] = self.model_type()
def fit_model():
for x in range(0,5):
self.model[x] = self.model_types[x].fit(data[x])
def score_model():
for x in range(0,5):
self.pred[x] = self.model[x].predict(data[x])
在python中一切都是对象,所以你的变量也可以指向一个class,然后你的变量可以被当作一个class。