首页 > 解决方案 > 如何为我的 y_pred 分配正确的 ID?

问题描述

我有一个pd.Dataframe包含列的数据集:

index, text, label, ID

ID 以特定方式给出,以便文本可以按 ID 分组。我对文本进行了预处理,制作了一个Pipeline,做了一个sklearn.model_selection.train_test_split并使用 gridsearch( gs.fit(x_train,y_train)) 进行了预测。现在我有了我的原始数据集 x_train、x_test、y_train、y_testy_pred。y_pred 在哪里y_pred = gs_fit.best_estimator_.predict(x_test)

这就是我想要的:

我现在想找出我的 y_pred 的相应 ID,以查看 ID 中的某些组是否比其他组预测得更好。

我的问题是,我不再有索引,预处理后的文本不同,因此我不确定如何找出哪个 y_pred 连接到哪个 ID。任何想法如何做到这一点?

标签: pythonpandasdataframescikit-learn

解决方案


我相信它index被保留了。X_test.index == y_test.index

# ... assumes you split your DataFrame and no resetting of index

X, y = df[['feature_1','feature_2']], df[['target']]

# train_size or test_size
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=.8, random_state=42)

# index is kept. So the 
print(all(X_test.index == y_test.index)) # True

所以只需使用索引来定位ID。y_pred将以与 X_test.index 相同的外观排序。

# return only test IDs and their predictions
results = df[df.index == X_test.index][['ID']]
results['y_pred'] = y_pred
print(results)

如果index由于使用 Pandas 以外的其他数据结构而丢失,则另一个技巧是预先附加ID到 text 上AC123 | text input here。您的文本函数必须排除|. 对后者进行任何文本预处理。然后您可以使用第一部分来查找 ID


推荐阅读