如何将预测输出与原始观察联系起来?

数据挖掘 机器学习 深度学习 神经网络 分类 数据挖掘
2022-02-20 01:10:17

正在使用逻辑回归数据进行二元分类

我有 1000 行和 28 个特征。三到四个变量是 Id 变量,例如 product_id、subject_id 等

在 train_test 拆分期间,我将它们删除,如下所示

X = df.drop(['status','Product_ID','subject_ID'], axis=1)
y = df.status
X_train, X_test, y_train, y_test = train_test_split(X, y, 
                                                    test_size=0.25,
                                                    random_state=0)

一旦我这样做了,我会做一些预处理和建模任务,如下所示

a)encoding分别用于训练和测试的分类变量 b) model.fit() c) model.predict() d) 最后,我得到y_pred并将其与y_test.

我的问题如下

a) 当 中没有标识符时y_pred,我如何链接回来以获取该实例的完整行?意思是,我想要该观察的完整数据行以及新列predicted_status(在已经存在的实际status列旁边)。无论如何ID在模型构建过程中包含变量但使其效果为0(或者只是作为无用的列留在那里)

b) 在训练测试拆分、编码、交叉验证、测试等过程中是否会保留相同的顺序

c)如果我们根据某些标准(例如 2015-2020 年(成为火车)和 2020 年成为测试之后的任何时间)拆分训练和测试,会发生什么?

1个回答

保留subject_ID并在 train_test_split 传递给没有 ID 列的模型数据帧之后,如下所示:

df.loc[ : , df.columns != 'subject_ID']

除非您在预测期间明确改组数据点,否则我相信通常返回的预测会保持初始顺序。绝对值得检查您正在使用的特定型号。

编辑:

请参阅下面的整个过程的示例:

import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split


iris = sns.load_dataset('iris')
# you don't need this, you have subject IDs.
iris['Subject_ID'] = numpy.random.randint(1, 10000, iris.shape[0])
# use subject IDs as index.
iris.set_index('Subject_ID', inplace=True)

# Split your data, index will be persisted.
Xtrain, Xtest, ytrain, ytest = train_test_split(
               iris.loc[ : , iris.columns != 'species'], 
               iris['species'],
               random_state=1
               )

# Model and predict.
from sklearn.naive_bayes import GaussianNB  # 1. choose model class
model = GaussianNB()                        # 2. instantiate model
model.fit(Xtrain, ytrain)                   # 3. fit model to data
y_hat = model.predict(Xtest, )              # 4. predict on new data

# Append predictions, original datapoint IDs will be encoded in the index.
Xtest["predictions"] = y_hat

# Test by joining original labels, using a dummy dataset for prediction.
Xtest = Xtest.join(iris['species'], how='inner')
Xtest.head()
>>>
主题_ID 萼片长度 萼片宽度 花瓣长度 花瓣宽度 预测 物种
2265 5.8 4.0 1.2 0.2 濑户 濑户
1961年 5.1 2.5 3.0 1.1 杂色 杂色
4177 6.6 3.0 4.4 1.4 杂色 杂色
6041 5.4 3.9 1.3 0.4 濑户 濑户
8500 7.9 3.8 6.4 2.0 弗吉尼亚 弗吉尼亚