伙计们。
我正在开发一个机器学习模型,但我有一个疑问。让我们假设我的火车数据有以下数据:
身份证 |动物 |年龄 |栖息地
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 | ...
这很漂亮,而且在大多数情况下都有效。但是,如果我的测试集包含比训练集更少(或更多)的特征呢?如果我的测试集不包含“鱼”怎么办?它将少生成一个类别。
你们能帮我解决这种问题吗?
谢谢
最佳答案
听起来您的训练集和测试集是完全分开的。这是一个关于如何自动将“缺失”特征添加到给定数据集的最小示例:
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)
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
对此:
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
假设每一行(每只动物)只能是 一个 动物,我们可以添加
animal_bear
特征(一种“is-a-bear”测试/特征),因为假设有任何熊在 test
中,该信息将在 animal
列中说明。根据经验,在构建/训练模型时尝试考虑所有可能的特征(即
animal
的所有可能值)是一个好主意。正如评论中提到的,有些方法比其他方法更擅长处理丢失的数据,但如果你能从一开始就做到这一切,那可能是个好主意。现在,如果您接受自由文本输入(因为可能的输入数量永无止境),那将很难做到。关于python - 机器学习 - 测试集的特征比训练集少,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44266677/