2016-06-01 76 views
0

如果我使用虚拟变量为分类值训练了sklearn中的模型,将单行特征提供给此模型以获取预测结果的最佳做法是什么?对于所有输入数据集,我试图获得分数。如果我的列数少于我用来训练/拟合模型的数据集,它会抛出一个错误。?使用sklearn的“预测”函数

只是为了阐明:在构建我的模型之前,我使用了一个具有5列并创建了118个虚拟列的数据集。现在我有一列有5列的数据,我想在predict函数中使用。我怎样才能做到这一点?

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

+0

你应该使用相同的函数来创建虚拟行到每列5行预测()'。 –

+0

非常感谢您的回复。但是如果我应用相同的虚拟函数,它只会创建5个虚拟列,因为它还没有看到其他功能。因此,在模型的培训数据中,可能会有'密苏里州','堪萨斯州','格鲁吉亚'的专栏,因为这三个州出现在原来的“州”栏中。当我去虚拟出我的特征来应用预测功能并且'State'是密苏里州时,它将只有1列('Missouri')而不是3('Missouri','Kansas','Georgia')。 – Johnny

回答

0

根据表状态扩展功能是错误的,因为您无法用其他数据重复该功能。如果你想以这种方式创建特征,你应该使用一个会记住特征结构的构造函数。既然你没有给出任何数据的例子,下面是你如何构造一个构造函数的主要思想:

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 
+0

像冠军一样工作。我非常感激!我不提供样本数据的道歉。 – Johnny