【问题标题】:Convert my model predicted array to categorical using a condition使用条件将我的模型预测数组转换为分类
【发布时间】:2025-12-26 08:55:12
【问题描述】:

我已经构建了一个 MLP 神经网络 -> 训练 -> 保存 -> 加载 -> 现在我正在测试我加载的模型。

我使用 y_pred=loaded_model(Variable(featuresTest)) 使用 pytorch 进行预测,然后将我的张量转换为数组 y_pred_arr,这是我的结果:

array([[-1.1663326 ,  0.369073  ],
       [-1.4255922 ,  0.23584184],
       [-2.045612  ,  1.4165274 ],
       ...,
       [ 4.327711  , -4.1331964 ],
       [-1.255816  ,  0.65834284],
       [ 6.642277  , -7.4430957 ]], dtype=float32)

我试图比较的真实标签数组 y_test 是分类的

array([[0., 1.],
       [0., 1.],
       [0., 1.],
       ...,
       [1., 0.],
       [0., 1.],
       [1., 0.]], dtype=float32)

现在我正在尝试使用sklearn.metrics ->分类报告,但是由于我的预测数组显然是连续的,我正在尝试将其转换为分类,该分类使用条件将每个数组中的最高正数转换为1 例如:

我在预测数组中的第一组是[-1.4255922 , 0.23584184], [ 0 , 1],因为0.2358 是预测中最高的正类。

我试过用:

from keras.utils.np_utils import to_categorical
labels123 = to_categorical(y_pred_arr, dtype = "int64")

但是,得到了这个错误:

IndexError: index -75 is out of bounds for axis 1 with size 74

我能在这方面获得一些帮助吗?任何帮助将不胜感激

【问题讨论】:

    标签: python arrays numpy keras pytorch


    【解决方案1】:

    试试这个。

    from keras.utils.np_utils import to_categorical
    labels123 = to_categorical(np.argmax(y_pred_arr, 1), dtype = "int64")
    

    【讨论】:

    • 请点击我的答案旁边的复选标记接受它作为答案。如果觉得有用,也可以点赞。