【问题标题】:Using sklearn's 'predict' function使用 sklearn 的“预测”功能
【发布时间】:2016-06-01 01:42:32
【问题描述】:

如果我在sklearn 中使用虚拟变量作为分类值训练模型,那么将单行特征输入该模型以获得预测结果的最佳做法是什么?对于所有输入数据集,我正在尝试获取分数。如果我的列数少于用于训练/拟合模型的数据集,会引发错误吗?

澄清一下:在构建模型之前,我采用了一个包含 5 列的数据集并创建了超过 118 个虚拟列。现在我有一行数据,包含 5 列,我想在 predict 函数中使用。我该怎么做?

这里的任何帮助将不胜感激。

【问题讨论】:

  • 您应该将用于创建虚拟行的相同函数应用于每个 5 列行,然后再将其馈送到predict()
  • 非常感谢您的回复。但是如果我应用相同的虚拟函数,它只会创建 5 个虚拟列,因为它还没有看到其他功能。因此,在模型的训练数据中,可能有“密苏里州”、“堪萨斯州”、“乔治亚州”列,因为这 3 个州出现在原始“州”列中。当我去模拟我的特征以应用预测函数并且“州”是密苏里州时,它将只有 1 列(“密苏里州”)而不是 3 列(“密苏里州”、“堪萨斯州”、“乔治亚州”)。

标签: python scikit-learn svm random-forest predict


【解决方案1】:

根据表状态扩展功能是错误的,因为您不能用其他数据重复它。如果你想以这种方式创建特征,你应该使用一个能记住特征结构的构造函数。由于您没有提供数据示例,因此主要思想是如何制作构造函数:

import pandas as pd

data = pd.DataFrame([['Missouri', 'center', 'Jan', 55, 11],
                     ['Kansas', 'center', 'Mar', 54, 31],
                     ['Georgia', 'east', 'Jan', 37, 18]],
                     columns=('state', 'pos', 'month', 'High Temp', 'Low Temp'))


test =  pd.DataFrame([['Missouri', 'center', 'Feb', 44, 23], 
                      ['Missouri', 'center', 'Mar', 55, 33]],
                      columns=('state', 'pos', 'month', 'High Temp', 'Low Temp'))  


class DummyColumns():
    def __init__(self, data):
        # Columns constructor
        self.empty = pd.DataFrame(columns=(list(data.columns) +
                                           list(data.state.unique()) +
                                           list(data.pos.unique()) +
                                           ['Winter', 'Not winter']))
    def __call__(self, data):
        # Initializing with zeros
        self.df = pd.DataFrame(data=0, columns=self.empty.columns, index=data.index)        
        for row in data.itertuples():
            self.df.loc[row.Index, :5] = row[1:]
            self.df.loc[row.Index, row.state] = 1
            self.df.loc[row.Index, row.pos] = 1
            if row.month in ['Dec', 'Jan', 'Feb']:
                self.df.loc[row.Index, 'Winter'] = 1
            else:
                self.df.loc[row.Index, 'Not winter'] = 1
        return self.df       

add_dummy = DummyColumns(data)
dummy_test = add_dummy(test)
print dummy_test

      state     pos month  High Temp  Low Temp  Missouri  Kansas  Georgia  \
0  Missouri  center   Feb         44        23         1       0        0   
1  Missouri  center   Mar         55        33         1       0        0   

   center  east  Winter  Not winter  
0       1     0       1           0  
1       1     0       0           1  

【讨论】:

  • 像冠军一样工作。我非常感激!我很抱歉没有提供样本数据。
猜你喜欢
  • 2017-08-22
  • 2018-03-23
  • 2021-03-27
  • 1970-01-01
  • 2019-04-06
  • 2017-08-07
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多