2016-06-01 51 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

相關問題