python - 创建自定义估算器 : State Mean Estimator

标签 python pandas machine-learning scikit-learn

我试图开发一个非常简单的初始模型来预测疗养院根据其位置可能需要支付的罚款金额。

这是我的类定义

#initial model to predict the amount of fines a nursing home might expect to pay based on its location
from sklearn.base import BaseEstimator, RegressorMixin, TransformerMixin

class GroupMeanEstimator(BaseEstimator, RegressorMixin):
    #defines what a group is by using grouper
    #initialises an empty dictionary for group averages
    def __init__(self, grouper):
        self.grouper = grouper
        self.group_averages = {}

    #Any calculation I require for my predict method goes here
    #Specifically, I want to groupby the group grouper is set by
    #I want to then find out what is the mean penalty by each group
    #X is the data containing the groups
    #Y is fine_totals
    #map each state to its mean fine_tot
    def fit(self, X, y):
        #Use self.group_averages to store the average penalty by group
        Xy = X.join(y) #Joining X&y together
        state_mean_series = Xy.groupby(self.grouper)[y.name].mean() #Creating a series of state:mean penalties
        #populating a dictionary with state:mean key:value pairs
        for row in state_mean_series.iteritems():
            self.group_averages[row[0]] = row[1]
        return self

    #The amount of fine an observation is likely to receive is based on his group mean
    #Want to first populate the list with the number of observations
    #For each observation in the list, what is his group and then set the likely fine to his group mean.
    #Return the list
    def predict(self, X):
        dictionary = self.group_averages
        group = self.grouper
        list_of_predictions = [] #initialising a list to store our return values
        for row in X.itertuples(): #iterating through each row in X
            prediction = dictionary[row.STATE] #Getting the value from group_averages dict using key row.group
            list_of_predictions.append(prediction)
        return list_of_predictions

它适用于此 state_model.predict(data.sample(5))

但是当我尝试这样做时崩溃了: state_model.predict(pd.DataFrame([{'STATE': 'AS'}]))

我的模型无法处理这种可能性,我想寻求帮助来纠正它。

最佳答案

我看到的问题出在您的 fit 方法中,iteritems基本上是遍历列而不是行。您应该使用 itertuples 它将为您提供行数据。只需将 fit 方法中的循环更改为

for row in pd.DataFrame(state_mean_series).itertuples(): #row format is [STATE, mean_value]
    self.group_averages[row[0]] = row[1]

然后在您的预测方法中,只需执行以下操作即可进行故障安全检查

prediction = dictionary.get(row.STATE, None) # None is the default value here in case the 'AS' doesn't exist. you may replace it with what ever you want

关于python - 创建自定义估算器 : State Mean Estimator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264671/

相关文章:

python - 更改线图中线段的颜色

python - Pandas:将增量数字添加到一列的重复值的后缀,这些重复值按另一列的值分组并按索引排序

python - 从 pip 安装后没有 python 的 CLI 应用程序

python - 创建具有相同尺寸的交集 DataFrame

python - 使用 sklearn 或 numpy 的基于内容的推荐系统

algorithm - Adaboost 和前向阶段相加建模

python - 给定多个预测向量,如何有效地获得得票最多的标签(在 numpy/pytorch 中)?

Python - 打开文件 - readline - 列表 - 转换为字符串

python - 自动 PostgreSQL CREATE TABLE 和从 CSV 或 Pandas DataFrame 插入

python - 根据具有不同索引的引用数据帧连接数据帧中的特定列对