keras后端proba到分类

keras backend proba to categorical

我正在使用 keras 后端构建自定义指标。第一步是将概率张量(softmax 的输出)转换为分类数据 例如:

from keras import backend as K
y_pred = K.variable([[0.7, 0.2, 0.1],[0.2, 0.8, 0],[0.2,0.2,0.6],[0.9,0.05,0.05]])
K.eval(y_pred)

给予

array([[ 0.69999999,  0.2       ,  0.1       ],
       [ 0.2       ,  0.80000001,  0.        ],
       [ 0.2       ,  0.2       ,  0.60000002],
       [ 0.89999998,  0.05      ,  0.05      ]], dtype=float32)

我想得到:

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

我找到了 K.argmax 函数,但不知道如何使用它来替换张量中的值。

max_index = K.cast(K.argmax(y_pred, 1), "int32")
lol_index = K.arange(y_pred.shape[0], dtype="int32")
y_pred[index, max_index]

给出:

ValueError: Shape must be rank 1 but is rank 2 for 'strided_slice_32' (op: 'StridedSlice') with input shapes: [4,3], [2,4], [2,4], [2].

好的,经过一番研究,我找到了解决方案:

K.one_hot(K.argmax(y_pred), 3)