在分配给熊猫数据帧之前和之后测量时,我无法获得匹配的准确性分数



我正在研究一个分类器,它将使用来自Target_Column的非nan值来预测应该是什么来代替所有nan值。但是在训练模型后,我会在将预测分配给原始数据帧中的新列之前和之后对其进行测试。这两个测试不匹配。对我来说,问题似乎是预测之后的转换之一以某种方式打乱了预测,使它们不再匹配。我已经删除了尽可能多的无关代码。

##############################################################
### Here is the initial data transformation for background ###
###       You can skip to next section for now...          ###
##############################################################
df = pd.read_excel('./Data/[Excel File That Holds Data].xlsx')
df['Target_Column'] = df['Target_Column'].astype('str').str.strip()
le = LabelEncoder()
y_full = le_sub_system.fit_transform(df['Target_Column'].astype('str').str.strip())
desc_vec = TfidfVectorizer(ngram_range=(1,3), max_features=1000)
tag_vec = TfidfVectorizer(ngram_range=(1,4), analyzer='char', max_features=1000)
desc = desc_vec.fit_transform(df.descriptor.astype('str').fillna(''))
tag = tag_vec.fit_transform(df.tag.astype('str').fillna(''))
X = scipy.sparse.hstack([desc, tag])
### The indexing here matches the indexing done in the line marked below ###
nan_encoding = le.transform(['nan'])[0]
X_train = X.todense()[y_full != nan_encoding]
y_train = y_full[y_full != nan_encoding]
X_train.shape, y_train.shape #---> ((94669, 2000), (94669,))
########################################
### Here is where the problem starts ###
########################################
clf = xgb.XGBClassifier(n_estimators=10, max_depth=11, tree_method='gpu_hist', n_jobs=94)
clf.fit(X_train, y_train)
out_full = clf.predict(X)
out_training_set = clf.predict(X_train)
df['Target_Predicted'] = le.inverse_transform(out_full)
>>> accuracy_score(out_training_set, y_train) 
0.9832152024421933
### The indexing here matches the indexing done in the lines marked above ###
>>> print(accuracy_score(df.Target_Column[y_full != nan_encoding], df.Target_Predicted[y_full != nan_encoding]))
0.0846422799438042
>>> print(accuracy_score(df.Target_Column[(df.Target_Column != 'nan')], df.Target_Predicted[(df.Target_Column!= 'nan')]))
0.0846422799438042
>>> (df.Target_Column[(df.Target_Column!= 'nan')].values == le.inverse_transform(y_train)).all()
True
>>> (df.Target_Column[y_full != nan_encoding] == le.inverse_transform(y_train)).all()
True
>>> (le.transform(df.Target_Predicted[y_full != nan_encoding]) == out[y_full != nan_encoding]).all()
True

如您所见,为数据帧中新创建的列编制索引的两种方法返回相同的结果,并且它们的索引方式与我最初创建训练集时完全相同,并且(对于实际目标值(返回完全相同的值。那么准确性是如何改变的呢?

我认为这可能与您在稀疏矩阵上使用预测的事实有关(或者可能像您建议的那样有一些洗牌(。Anyhoo,尝试只用nans(或您需要表示缺失值的任何值(填充预测列,然后用密集数据帧中的预测填充具有目标变量的索引:

tmp = pd.Series(y_full)
valid_indexes = tmp[tmp!=nan_encoding].index.values
df['Target_Predicted'] = le.inverse_transform(nan_encoding)
df.Target_Predicted.iloc[valid_indexes ,] = le.inverse_transform(out_training_set)

希望对您有所帮助!

问题在于在稀疏矩阵上进行预测,正如Davide DN在他的答案中所建议的那样。更改行

out_full = clf.predict(X)

out_full = clf.predict(X.todense())

立即解决了问题。希望如果其他人有同样的问题,那么他们的数据以密集格式放入内存中。

最新更新