如何预测功能数量与测试集中可用的功能数量不匹配?

时间:2018-08-29 08:24:58

标签: python pandas machine-learning categorical-data supervised-learning

我正在使用熊猫get_dummies将类别变量转换为虚拟变量/指标变量,它在数据集中引入了新功能。然后,我们将此数据集拟合/训练到模型中。

由于X_trainX_test的维度保持不变,因此当我们对测试数据进行预测时,它可以很好地与测试数据X_test配合使用。

现在可以说我们在另一个csv文件中有测试数据(输出未知)。当我们使用get_dummies转换这组测试数据时,结果数据集可能不具有我们训练模型所用的相同数量的特征。稍后,当我们将模型与该数据集一起使用时,其失败,因为测试集中的特征数量与模型不匹配。

任何想法我们如何处理?

代码:

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split

# Load the dataset
in_file = 'train.csv'
full_data = pd.read_csv(in_file)
outcomes = full_data['Survived']
features_raw = full_data.drop('Survived', axis = 1)
features = pd.get_dummies(features_raw)
features = features.fillna(0.0)
X_train, X_test, y_train, y_test = train_test_split(features, outcomes, 
test_size=0.2, random_state=42)
model = 
DecisionTreeClassifier(max_depth=50,min_samples_leaf=6,min_samples_split=2)
model.fit(X_train,y_train)

y_train_pred = model.predict(X_train)
#print (X_train.shape)
y_test_pred = model.predict(X_test)


from sklearn.metrics import accuracy_score
train_accuracy = accuracy_score(y_train, y_train_pred)
test_accuracy = accuracy_score(y_test, y_test_pred)
print('The training accuracy is', train_accuracy)
print('The test accuracy is', test_accuracy)

# DOing again to test another set of data
test_data = 'test.csv'
test_data1 = pd.read_csv(test_data)

test_data2 = pd.get_dummies(test_data1)
test_data3 = test_data2.fillna(0.0)
print(test_data2.shape)
print (model.predict(test_data3))

1 个答案:

答案 0 :(得分:0)

似乎之前曾问过类似的问题,但最有效/最简单的方法是遵循Thibault Clement描述的here

# Get missing columns in the training test
missing_cols = set( X_train.columns ) - set( X_test.columns )
# Add a missing column in test set with default value equal to 0
for c in missing_cols:
    X_test[c] = 0
# Ensure the order of column in the test set is in the same order than in train set
X_test = X_test[X_train.columns]

还值得注意的是,您的模型只能使用经过训练的功能,因此,如果X_test和X_train中有其他列而不是更少,则在预测之前必须将其删除。