我编写了一个自定义类来对数据集的元素进行分组,拟合每个组,然后根据拟合模型对每个组运行预测。我希望能够返回每个拟合的系数(大概在字典中),以便我可以引用它们并绘制每个拟合的最佳拟合线。
调用标准 .coef_
或 .get_params
方法不起作用,因为这些方法尝试检索的项目是 groupby 对象。或者,我尝试介绍以下内容:
def get_coefs():
coefs_dict = {}
for name, values in dataframe.groupby(self.groupby_column):
coefs_dict[name] = self.drugs_dict[name].coefs_
return coefs_dict
但得到以下内容:
<bound method GroupbyEstimator.get_coefs of GroupbyEstimator(groupby_column='ndc',
pipeline_factory=<function pipeline_factory at 0x0000018DAD207268>)>
这是我编写的类(class):
from sklearn import base
import numpy as np
import pandas as pd
class GroupbyEstimator(base.BaseEstimator, base.RegressorMixin):
def __init__(self, groupby_column, pipeline_factory):
self.groupby_column = groupby_column
self.pipeline_factory = pipeline_factory
def fit(self, dataframe, label):
self.drugs_dict = {}
self.label = label
dataframe = pd.get_dummies(dataframe)
for name, values in dataframe.groupby(self.groupby_column):
y = values[label]
X = values.drop(columns = [label, self.groupby_column], axis = 1)
self.drugs_dict[name] = self.pipeline_factory().fit(X, y)
return self
def get_coefs():
self.coefs_dict = {}
self.coefs_dict[name] = self.drugs_dict[name].named_steps["lin_reg"].coef_
return self.coefs_dict
def predict(self, test_data):
price_pred_list = []
for idx, row in test_data.iterrows():
name = row[self.groupby_column]
regression_coefs = self.drugs_dict[name]
row = pd.DataFrame(row).T
X = row.drop(columns = [self.label, self.groupby_column], axis = 1).values.reshape(1, -1)
drug_price_pred = regression_coefs.predict(X)
price_pred_list.append([name, drug_price_pred])
return price_pred_list
预期结果是格式为的字典:
{drug_a: [coefficient_1, coefficient_2,...coefficient_n],
drug_b: [coefficient_1, coefficient_2,...coefficient_n],
drug_c: [coefficient_1, coefficient_2,...coefficient_n]}
管道工厂是这样的。稍后我将使用替代回归器、pca、gridsearchcv 等来构建它(只要我可以从单独回归的 groupby 对象中获取参数。
def pipeline_factory():
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
return Pipeline([
('lin_reg', LinearRegression())
])
编辑:按照建议添加了 get_coefs 方法。不幸的是,如上所示,它仍然返回相同的错误。
最佳答案
问题出在 self.drugs_dict
上,它是 Pipeline
对象的字典,因此您不能直接在它们上使用 coef_
。 coef_ 是与估计器对象关联的属性,在您的情况下,估计器对象是 LinearRegression 对象。因此,访问系数的正确方法将是 self.drugs_dict[name].named_steps["lin_reg"].coef_
而不是 self.drugs_dict[name].coefs_
您的 get_coefs()
方法。
关于python-3.x - 如何获得每个组/模型的系数/截距,以便为每个组绘制拟合线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58740553/