簡體   English   中英

缺少類別的單熱編碼

[英]One-hot-encoding with missing categories

我有一個帶有類別列的數據集。 為了使用線性回歸,我對這一列進行了 1-hot 編碼。

我的集合有 10 列,包括類別列。 刪除該列並附加 1-hot 編碼矩陣后,我最終得到 14 列 (10 - 1 + 5)。

所以我用形狀矩陣 (n, 14) 訓練(擬合)我的 LinearRegression 模型。

訓練之后,我想在訓練集的一個子集上測試它,所以我只先取了 5 個,然后將它們放入相同的管道中。 但是這 5 個第一個只包含其中的 3 個類別。 因此,在通過管道后,我只剩下一個形狀為 (n, 13) 的矩陣,因為它缺少 2 個類別。

如何強制 1-hot 編碼器使用 5 個類別?

我正在使用 sklearn 的 LabelBinarizer。

錯誤是“將測試數據通過同一管道”。 基本上我在做:

data_prepared = full_pipeline.fit_transform(train_set)

lin_reg = LinearRegression()
lin_reg.fit(data_prepared, labels)

some_data = train_set.iloc[:5]
some_data_prepared = full_pipeline.fit_transform(some_data)

lin_reg.predict(some_data_prepared)
# => error because mismatching shapes

有問題的線路是:

some_data_prepared = full_pipeline.fit_transform(some_data)

通過執行fit_transform ,我將 LabelBinarizer 適合僅包含 3 個標簽的集合。 相反,我應該這樣做:

some_data_prepared = full_pipeline.transform(some_data)

通過這種方式,我使用由全套 ( train_set ) 擬合的管道並以相同的方式對其進行轉換。

謝謝@Vivek Kumar

我遇到了這個問題,我無法通過scikit-learn找到解決方案。

我正在使用 pandas .get_dummies()來做類似於OneHotEncoder

下面是我為處理這個確切問題而制作的一個函數,請隨意使用它並改進它(如果您發現任何錯誤,請告訴我,我實際上只是從我的代碼庫中的一個更具體的函數中制作的)

import numpy as np
import pandas as pd

def one_hot_encoding_fixed_columns(pandas_series, fixed_columns):

    # Creates complete fixed columns list (with nan and 'other')
    fixed_columns = list(fixed_columns)
    fixed_columns.extend([np.nan, 'other'])

    # Get dummies dataset
    ohe_df = pd.get_dummies(pandas_series, dummy_na=True)

    # Create blank 'other' column
    ohe_df['other'] = 0

    # Check if columns created by get_dummies() are in 'fixed_columns' list.
    for column in ohe_df.columns:

        if column not in fixed_columns:
            # If not in 'fixed_columns', transforms exceeding column into 'other'.
            ohe_df['other'] = ohe_df['other'] + ohe_df[column]
            ohe_df.drop(columns=[column])

    # Check if elements in 'fixed_columns' are in the df generated by get_dummies()
    for column in fixed_columns:

        if column not in ohe_df.columns:
            # If the element is not present, create a new column with all values set to 0.
            ohe_df['column'] = 0

    # Reorders columns according to fixed columns
    ohe_df = ohe_df[fixed_columns]

    return ohe_df

基本上,您創建一個包含將始終使用的列的列表。 如果test樣本沒有給定類別的任何元素,則會創建values = 0的相應列。 如果test具有不在train樣本中的新值,則將其歸類為other

我已經注釋掉了代碼,我希望它是可以理解的,如果你有任何問題,請告訴我,我會澄清它。

此函數的輸入是pandas_series = df['column_name'] ,您可以在訓練集上執行類似fixed_columns = df[selected_column].str[0].value_counts().index.values之類的操作來生成值用於測試集。

基本上,首先我們需要對基礎數據應用 fit_transform,然后對樣本數據應用變換,因此樣本數據也將獲得與基礎數據相同的列數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM