用于二进制编码(非单热编码)分类数据的Keras自定义丢失函数

问题描述 投票:3回答:2

我需要帮助为Keras编写自定义丢失/度量函数。我的类别是二进制编码(不是一热的)。我想在真实类和预测类之间进行逐位比较。

例如,Real-label:0x1111111111 Predicted-label:0x1011101111

预测标签有10位中的8位正确,因此该匹配的准确度应为0.8而不是0.0。我不知道我是如何支持使用Keras命令执行此操作的。

编辑1:目前我正在使用这样的东西,但它还没有工作:

def custom_binary_error(y_true, y_pred, n=11):
    diff_dec = K.tf.bitwise.bitwise_xor(K.tf.cast(y_true, K.tf.int32), K.tf.cast(y_pred, K.tf.int32))
    diff_bin = K.tf.mod(K.tf.bitwise.right_shift(K.tf.expand_dims(diff_dec,1), K.tf.range(n)), 2)
    diff_sum = K.tf.math.reduce_sum(diff_bin, 1)
    diff_percent = K.tf.math.divide(diff_sum, 11)
    return K.tf.math.reduce_mean(diff_percent, 0)

我收到此错误:

ValueError: Dimensions must be equal, but are 2048 and 11 for 'loss/activation_1_loss/RightShift' (op: 'RightShift') with input shapes: [?,1,2048], [11].
keras deep-learning categorical-data loss-function multiclass-classification
2个回答
0
投票

我正在尝试一些假设y_true, y_pred是正整数。

def custom_binary_error(y_true, y_pred):
    width = y_true.bit_length() if y_true.bit_length() > y_pred.bit_length() else y_pred.bit_length()       # finds the greater width of bit sequence, not sure if needed
    diff = np.bitwise_xor(y_true, y_pred)       # 1 when different, 0 when same
    error = np.binary_repr(diff, width=width).count('1')/width       # calculate % of '1's
    return K.variable(error)

使用1-error来提高准确性。我没有测试过;这只是为了提出一个想法。


0
投票

这是您定义错误的方法:

import tensorflow as tf

def custom_binary_error(y_true, y_pred):
    y_true = tf.cast(y_true, tf.bool)
    y_pred = tf.cast(y_pred, tf.bool)
    xored = tf.logical_xor(y_true, y_pred)
    notxored = tf.logical_not(xored)
    sum_xored = tf.reduce_sum(tf.cast(xored, tf.float32))
    sum_notxored = tf.reduce_sum(tf.cast(notxored, tf.float32))
    return sum_xored / (sum_xored + sum_notxored)

用2个6号标签测试它:

import tensorflow as tf

y_train_size = 6

y_train = [[1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]
y_pred = tf.convert_to_tensor([[1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 0]])
y = tf.placeholder(tf.int32, shape=(None, y_train_size))
error = custom_binary_error(y, y_pred)
with tf.Session() as sess:
    res = sess.run(error, feed_dict={y:y_train})
    print(res) # 0.25

Keras中使用它:

import tensorflow as tf
import numpy as np

y_train_size = 6

def custom_binary_error(y_true, y_pred):
    y_true = tf.cast(y_true, tf.bool)
    y_pred = tf.cast(y_pred, tf.bool)
    xored = tf.logical_xor(y_true, y_pred)
    notxored = tf.logical_not(xored)
    sum_xored = tf.reduce_sum(tf.cast(xored, tf.float32))
    sum_notxored = tf.reduce_sum(tf.cast(notxored, tf.float32))
    return sum_xored / (sum_xored + sum_notxored)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(y_train_size))

model.compile(optimizer=tf.keras.optimizers.SGD(0.01),
              loss=[tf.keras.losses.MeanAbsoluteError()],
              metrics=[custom_binary_error])

y_train = np.array([[1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]])
x_train = np.random.normal(size=(2, 2))

model.fit(x_train, y_train, epochs=2)

将导致:

Epoch 1/2
2/2 [==============================] - 0s 23ms/sample - loss: 1.4097 - custom_binary_error: 0.5000
Epoch 2/2
2/2 [==============================] - 0s 328us/sample - loss: 1.4017 - custom_binary_error: 0.5000

注意

如果你想要准确而不是错误,那么custom_binary_error()函数应该返回

sum_notxored / (sum_xored + sum_notxored)
© www.soinside.com 2019 - 2024. All rights reserved.