gpt4 book ai didi

python - 如何反转标签的 One-Hot Encoding 以评估 ML/DL 模型?

转载 作者:行者123 更新时间:2023-12-05 03:59:12 25 4
gpt4 key购买 nike

此问题已在 Stackoverflow 上多次提及,但没有一个为我目前面临的问题/错误提供解决方案。

目前,我用作标签的数据集的 y 必须使用 One-Hot Encoding 进行转换,以便我的深度学习网络/模型可以将其作为 categorical_crossentropy.

但现在问题出现了,为了评估我的数据,它需要再次使用原始标签来预测 y。

import pandas as pd
import numpy as np

keypoints = pd.read_csv('keypoints.csv')

X = keypoints.iloc[:,1:76]
y = keypoints.iloc[:,-1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)

这里 y 是 3 个不同标签的列表,假设 A、B 和 C 的形状为 (63564, 1)

所以使用 One-Hot 编码我能够将它拆分:

le = LabelEncoder()
y = le.fit_transform(y)
ohe = OneHotEncoder(categorical_features = [0])
y = ohe.fit_transform(y[:,None]).toarray()

这里新的 y 的形状是 (63564, 3),看起来像:

[[0. 0. 1.]
[0. 0. 1.]
[0. 0. 1.]
...
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]]

运行我的深度学习网络后,我想使用以下方法对其进行评估:

......
#Evaluation and such
y_pred = model.predict(X_test, verbose=0)
y_classes = model.predict_classes(X_test, verbose=0)

#Reduce to 1D
y_pred = y_pred[:, 0]
y_classes = y_classes[:, 0]

#Confution Matrix
print(confusion_matrix(y_test, y_classes))

#Accuracy: (tp + tn) / (p + n)
accuracy = accuracy_score(y_test, y_classes)
print('Accuracy: %f' % accuracy)
#Precision tp / (tp + fp)
precision = precision_score(y_test, y_classes)
print('Precision: %f' % precision)
#Recall: tp / (tp + fn)
recall = recall_score(y_test, y_classes)
print('Recall: %f' % recall)
#F1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_classes)
print('F1 score: %f' % f1)

但是当然这不会接受 0 和 1 作为标签:

ValueError: Classification metrics can't handle a mix of unknown and continuous-multioutput targets

所以我的问题是

How do i reverese the One-Hot Encoded labels so that I can run the evaluation of my DL model?

最佳答案

您可能需要 inverse_transform,如 examples section of sklearn.preprocessing.OneHotEncoder 中所述

>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder(handle_unknown='ignore')
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.transform([['Female', 1], ['Male', 4]]).toarray()
array([[1., 0., 1., 0., 0.],
[0., 1., 0., 0., 0.]])
>>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]])
array([['Male', 1],
[None, 2]], dtype=object)

关于python - 如何反转标签的 One-Hot Encoding 以评估 ML/DL 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57444974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com