使用sklearn的'预测'功能

时间:2016-06-01 01:42:33

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

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

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

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

1 个答案:

答案 0 :(得分: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