python - 自定义损失函数实现

标签 python keras theano

我正在尝试实现自己的新损失函数。 当我尝试调试它(或在其中打印)时,我注意到它仅在代码的模型创建部分被调用一次。

如果在拟合模型时无法将代码运行到此函数中,我如何知道 y_pred 和 y_true 包含什么(形状、数据等)?

我写了这个损失函数:

def my_loss(y_true, y_pred):
    # run over the sequence, jump by 3
    # calc the label
    # if the label incorrect punish

    y_pred = K.reshape(y_pred, (1, 88, 3))

    y_pred = K.argmax(y_pred, axis=1)

    zero_count = K.sum(K.clip(y_pred, 0, 0))
    one_count = K.sum(K.clip(y_pred, 1, 1))
    two_count = K.sum(K.clip(y_pred, 2, 2))

    zero_punish = 1 - zero_count / K.count_params(y_true)
    one_punish = 1- one_count/ K.count_params(y_true)
    two_punish = 1- two_count/ K.count_params(y_true)

    false_arr = K.not_equal(y_true, y_pred)

    mask0 = K.equal(y_true, K.zeros_like(y_pred))
    mask0_miss = K.dot(false_arr, mask0) * zero_punish

    mask1 = K.equal(y_true, K.ones_like(y_pred))
    mask1_miss = K.dot(false_arr, mask1) * one_punish

    mask2 = K.equal(y_true, K.zeros_like(y_pred)+2)
    mask2_miss = K.dot(false_arr, mask2) * two_punish

    return K.sum(mask0_miss) + K.sum(mask1_miss) + K.sum(mask2_miss)

它失败了:

theano.gof.fg.MissingInputError: A variable that is an input to the graph was 
neither provided as an input to the function nor given a value. A chain of 
variables leading from this input to an output is [/dense_1_target, Shape.0]. 
This chain may not be unique
Backtrace when the variable is created:

如何修复它?

最佳答案

你必须明白 Theano 是一种符号语言。例如,当我们在Keras中定义以下损失函数时:

def myLossFn(y_true, y_pred):
    return K.mean(K.abs(y_pred - y_true), axis=-1)

Theano 只是在计算图中制定一个符号规则,该规则将在获取值时执行,即当您使用一些小批量训练模型时。

就如何调试模型的问题而言,您可以使用 theano.function 来解决。现在,您想知道您的损失计算是否正确。您执行以下操作。

您可以实现损失函数的 python/numpy 版本。将两个随机向量传递给 numpy-loss-function 并获取一个数字。要验证 theano 是否给出几乎相同的结果,请定义如下内容。

import theano
from theano import tensor as T
from keras import backend as K

Y_true = T.frow('Y_true')
Y_pred = T.fcol('Y_pred')
out = K.mean(K.abs(Y_pred - Y_true), axis=-1)

f = theano.function([Y_true, Y_pred], out)

# creating some values
y_true = np.random.random((10,))
y_pred = np.random.random((10,))

numpy_loss_result = np.mean(np.abs(y_true-y_pred))
theano_loss_result = f(y_true, y_pred)

# check if both are close enough
print numpy_loss_result-theano_loss_result # should be less than 1e-5

基本上,theano.function 是一种放置值并评估这些符号表达式的方法。我希望这会有所帮助。

关于python - 自定义损失函数实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42774856/

相关文章:

python - 通过索引不同表中的行/列来创建新列。代码错误

neural-network - 如何检查 theano 仅使用 FP32?

numpy - 为 pymc3 声明 theano 变量

python - theano.tensor.nnet.conv.conv2d 的输出大小

python - 导入 keras 时出现 ValueError «您正在尝试使用旧的 GPU 后端»

python - 如何使用 Flask 连接到远程 cassandra db?

python - 初学者 python 翻译器 : I am unable to convert a list from shelve module into a string

python - 在Python中生成STIX时的警告消息

python - 使用keras生成器时什么是纪元?

python - 尽管网络很大、样本量很小并且数据经过预处理,但 Tensorflow LSTM 仍无法学习