机器学习 - 测试集的特征比训练集少

Pau*_*los 3 python machine-learning

伙计们。我正在开发一个机器学习模型,但我有一个疑问。让我们假设我的火车数据有以下数据:

身份证 | 动物 | 年龄 | 栖息地

0 | 鱼 | 2 | 海

1 | 鹰| 1 | 山

2 | 鱼 | 3 | 海

3 | 蛇 | 4 | 森林

如果我应用 One-hot Encoding,它将生成以下矩阵:

身份证 | 动物_鱼 | Animal_Hawk | 动物_蛇| 年龄 | ...

0 | 1 | 0 | 0 | 2 | ...

1 | 0 | 1 | 0 | 1 | ...

2 | 1 | 0 | 0 | 3 | ...

3 | 0 | 0 | 1 | 4 | ...

这很漂亮,而且在大多数情况下都有效。但是,如果我的测试集包含比训练集更少(或更多)的特征呢?如果我的测试集不包含“鱼”怎么办?它将少生成一个类别。

你们能帮我解决这种问题吗?

谢谢

bla*_*ite 6

听起来您的训练集和测试集是完全分开的。这是一个关于如何自动将“缺失”特征添加到给定数据集的最小示例:

import pandas as pd

# Made-up training dataset
train = pd.DataFrame({'animal': ['cat', 'cat', 'dog', 'dog', 'fish', 'fish', 'bear'],
                      'age': [12, 13, 31, 12, 12, 32, 90]})

# Made-up test dataset (notice how two classes are from train are missing entirely)
test = pd.DataFrame({'animal': ['fish', 'fish', 'dog'],
                      'age': [15, 62, 1]})

# Discrete column to be one-hot-encoded
col = 'animal'

# Create dummy variables for each level of `col`
train_animal_dummies = pd.get_dummies(train[col], prefix=col)
train = train.join(train_animal_dummies)

test_animal_dummies = pd.get_dummies(test[col], prefix=col)
test = test.join(test_animal_dummies)

# Find the difference in columns between the two datasets
# This will work in trivial case, but if you want to limit to just one feature
# use this: f = lambda c: col in c; feature_difference = set(filter(f, train)) - set(filter(f, test))
feature_difference = set(train) - set(test)

# create zero-filled matrix where the rows are equal to the number
# of row in `test` and columns equal the number of categories missing (i.e. set difference 
# between relevant `train` and `test` columns
feature_difference_df = pd.DataFrame(data=np.zeros((test.shape[0], len(feature_difference))),
                                     columns=list(feature_difference))

# add "missing" features back to `test
test = test.join(feature_difference_df)
Run Code Online (Sandbox Code Playgroud)

test 从这里开始:

   age animal  animal_dog  animal_fish
0   15   fish         0.0          1.0
1   62   fish         0.0          1.0
2    1    dog         1.0          0.0
Run Code Online (Sandbox Code Playgroud)

对此:

   age animal  animal_dog  animal_fish  animal_cat  animal_bear
0   15   fish         0.0          1.0         0.0          0.0
1   62   fish         0.0          1.0         0.0          0.0
2    1    dog         1.0          0.0         0.0          0.0
Run Code Online (Sandbox Code Playgroud)

假设每行(每个动物)只能是一个动物,它的罚款,我们增加一个animal_bear功能(一个排序的“是一个熊”测试/功能),因为假设的是,如果出现任何的熊test,即信息将在animal列中说明。

根据经验,animal在构建/训练模型时尝试考虑所有可能的特征(例如 的所有可能值)是一个好主意。正如评论中所提到的,有些方法在处理缺失数据方面比其他方法更好,但是如果您可以从一开始就做到这一切,那可能是个好主意。现在,如果您接受自由文本输入(因为可能的输入数量永无止境),那将很难做到。