标签: loss-function

在自定义损失函数中获取权重

我正在尝试实现一个自定义损失函数,该函数给出加权像素交叉熵值。

我已经用“sample_weight_mode='temporal'”编译了模型,并为每个单独的图像传递了不同的权重。为此,我有以下几点:

model.fit_generator(train_generator,...)
Run Code Online (Sandbox Code Playgroud)

其中,train_generator 生成具有以下维度的 (input_image, target_label, weight) 元组:

input_image  ->  (48, 64, 64, 1)
target_label ->  (196608, 1)
weight       ->  (196608,)
Run Code Online (Sandbox Code Playgroud)

是否有可能实现一个损失函数,获得这个相应的权重作为参数?任何人都可以让我知道是否可以实现如下所示的功能?

def pixelwise_cross_entropy(target, output, weight):
    #~ target = tf.convert_to_tensor(target, dtype=tf.float32)
    #~ output = tf.convert_to_tensor(output, dtype=tf.float32)
    _EPSILON = 10e-8

    output /= tf.reduce_sum(output, axis=len(output.get_shape()) - 1, keep_dims=True)

    epsilon = tf.cast(tf.convert_to_tensor(_EPSILON), output.dtype.base_dtype)
    output = tf.clip_by_value(output, epsilon, 1. - epsilon)

    return - tf.reduce_sum(target * tf.log(output) * weight, axis=len(output.get_shape()) - 1)
Run Code Online (Sandbox Code Playgroud)

权重图是目标的形态学侵蚀版本。我尝试在自定义损失函数本身中创建权重图。由于我的数据是 3D,我不能使用 tensorflow 的“tf.nn.erosion2d”。

而且我无法将张量对象转换为 numpy 数组来执行此操作,因为它会产生以下负维度错误。

tensorflow.python.framework.errors_impl.InvalidArgumentError: Shape [-1,-1,-1] has negative …
Run Code Online (Sandbox Code Playgroud)

python deep-learning keras tensorflow loss-function

5
推荐指数
0
解决办法
461
查看次数

变分自动编码器损失函数(keras)

我正在使用 Keras 构建一个变分自动编码器。我很大程度上受到@Fchollet 示例的启发:https : //github.com/fchollet/keras/blob/master/examples/variational_autoencoder.py

但我正在处理连续数据。我的输出是一个持续时间,而不是像 MNIST 那样对数字进行排名。在这方面,我将损失函数从 binary_crossentropy 更改为 mean_squared_error。我主要想知道第二项,即 KL 散度。它应该适用于连续数据吗?我无法绕过它。对我来说,它应该将相似的数据紧密地放在潜在空间中。例如,在 MNIST 数据的 cas 中,将每个“1”放在潜在空间中,将每个“2”放在一起等等......因为我正在处理连续数据,它是如何工作的?在我的情况下有更好的丢失功能吗?

这是丢失的功能:

def vae_loss(x, x_decoded_mean):
    xent_loss = original_dim *metrics.mean_squared_error(x, x_decoded_mean)
    kl_loss = - 0.5 * K.mean(1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma), axis=-1)
    return K.mean(xent_loss + kl_loss)
vae.compile(optimizer='Adam', loss=vae_loss)
Run Code Online (Sandbox Code Playgroud)

这是 3D 潜在空间中的表示。 在此处输入图片说明

如您所见,一些类似的数据会根据需要放在一起。当我将 kl_loss 函数的系数增加到 "-100000" 而不是 "-0.5" 时会发生以下情况: 在此处输入图片说明

我以为我会以几乎线性的方式从蓝色变为红色。相反,我以混乱的方式获得了所有数据的集群。

你们能帮帮我吗?谢谢 !

python python-3.x autoencoder keras loss-function

5
推荐指数
1
解决办法
2426
查看次数

Keras中的自定义损失函数,如何处理占位符

我正在尝试在 TF/Keras 中生成自定义损失函数,如果它在会话中运行并传递常量,则损失函数会起作用,但是,它在编译成 Keras 时停止工作。

成本函数(感谢 Lior 将其转换为 TF)

def ginicTF(actual,pred):

    n = int(actual.get_shape()[-1])

    inds =  K.reverse(tf.nn.top_k(pred,n)[1],axes=[0]) 
    a_s = K.gather(actual,inds) 
    a_c = K.cumsum(a_s)
    giniSum = K.sum(a_c)/K.sum(a_s) - (n+1)/2.0

    return giniSum / n

def gini_normalizedTF(a,p):
    return -ginicTF(a, p) / ginicTF(a, a)

#Test the cost function

sess = tf.InteractiveSession()

p = [0.9, 0.3, 0.8, 0.75, 0.65, 0.6, 0.78, 0.7, 0.05, 0.4, 0.4, 0.05, 0.5, 0.1, 0.1]
a = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, …
Run Code Online (Sandbox Code Playgroud)

python-3.x keras gini tensorflow loss-function

5
推荐指数
0
解决办法
1086
查看次数

如何对自定义 Keras / Tensorflow 损失函数中的值进行排序?

介绍

我想为 Keras 实现一个自定义损失函数。我想这样做,因为我对数据集的当前结果不满意。我认为这是因为目前内置的损失函数专注于整个数据集。我只想关注数据集中的最高值。这就是为什么我提出了以下自定义损失函数的想法:

自定义损失函数的想法

自定义损失函数应取最高值的前 4 个预测,并用相应的真实值减去它。然后取该减法的绝对值,乘以一些权重,并将其添加到总损失总和中。

为了更好地理解这个自定义损失函数,我使用列表输入对其进行了编程。希望通过这个例子可以更好地理解:

以下示例计算 i=0 时的损失 = 4*abs(0.7-0.5)+3*abs(0.5-0.7)+2*abs(0.4-0.45) +1*abs(0.4-0.3) = 1.6

然后将其除以 div_top,在本例中为 10(对于 i=0,则为 0.16),对所有其他 i 重复所有操作,最后取所有样本的平均值。

top = 4
div_top = 0.5*top*(top+1)


def own_loss(y_true, y_pred):
    loss_per_sample = [0]*len(y_pred)
    for i in range(len(y_pred)):
        sorted_pred, sorted_true = (list(t) for t in zip(*sorted(zip(y_pred[i], y_true[i]))))
        for k in range(top):
            loss_per_sample[i] += (top-k)*abs(sorted_pred[-1-k]-sorted_true[-1-k])
    loss_per_sample = [t/div_top for t in loss_per_sample]
    return sum(loss_per_sample)/len(loss_per_sample)


y_pred = [[0.1, 0.4, 0.7, 0.4, 0.4, 0.5, 0.3, 0.2],
          [0.3, 0.8, 0.5, 0.3, 0.1, …
Run Code Online (Sandbox Code Playgroud)

python backend keras tensorflow loss-function

5
推荐指数
1
解决办法
3858
查看次数

如何有条件地为张量赋值[掩蔽损失函数]?

我想创建一个 L2 损失函数,它忽略标签值为 0 的值(=> 像素)。张量batch[1]包含标签,output而是净输出的张量,两者的形状均为(None,300,300,1).

labels_mask = tf.identity(batch[1])
labels_mask[labels_mask > 0] = 1
loss = tf.reduce_sum(tf.square((output-batch[1])*labels_mask))/tf.reduce_sum(labels_mask)
Run Code Online (Sandbox Code Playgroud)

我当前的代码屈服于TypeError: 'Tensor' object does not support item assignment(在第二行)。什么是张量流方式来做到这一点?我还尝试将损失归一化为tf.reduce_sum(labels_mask),我希望它像这样工作。

python machine-learning loss tensorflow loss-function

5
推荐指数
2
解决办法
3611
查看次数

使用张量流检查评估中**每个样本**的损失函数,keras

在 Keras/Tensorflow 中,我试图实现一种主动学习机制,为此我需要获得每个样本的损失。我目前evaluate对每个样本执行一次,需要很长时间(每 100 毫秒一个样本)。有没有好的方法来实现这一点?

我看到了类似的线程,Keras-批次内每个样本的损失,但我不了解那里的物流,因为它只是打印。

有人用 Keras/Tensorflow 解决了这个问题吗?

提前致谢。

编辑:看起来我可以做到fitCallback制作批量大小 1,但我想为evaluateor执行此操作predict

python keras tensorflow loss-function

5
推荐指数
0
解决办法
731
查看次数

在训练期间逐渐更新 Keras 中自定义损失的权重

我在 Keras(张量流后端)中定义了一个自定义损失函数,该函数由重建 MSE 以及学习的概率分布和标准正态分布之间的 kullback leibler 散度组成。(它用于变分自动编码器。)

我希望能够在训练期间慢慢增加 KL 散度项对成本的影响,权重称为“reg”,从 reg=0.0 开始,逐渐增加,直到达到 1.0。我希望将增长率调整为超参数。(到目前为止,我只是将“reg”参数设置为常量 0.5。)

Keras 中有执行此操作的功能吗?

def vae_loss(y_true,y_pred):
    reg = 0.5
    # Average cosine distance for all words in a sequence 
    reconstruction_loss = tf.reduce_mean(mean_squared_error(y_true, y_pred),1)    
    # Second part of the loss ensures the z probability distribution doesn't stray too far from normal
    KL_divergence_loss = tf.reduce_mean(tf.log(z_sigma) + tf.div((1 + tf.square(z_mu)),2*tf.square(z_sigma)) - 0.5,1)
    loss = reconstruction_loss + tf.multiply(reg,KL_divergence_loss)
    return loss
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow loss-function keras-2

5
推荐指数
0
解决办法
1112
查看次数

keras loss 是否必须每批次输出一个标量或整批输出一个标量?

我在一个相关的问题中读到keras 自定义损失函数必须为每个批次项目返回一个标量。

我写了一个损失函数,为整个批次输出一个标量,网络似乎收敛了。但是,我无法找到任何关于此的文档或代码中究竟发生了什么。某处有广播吗?如果我添加样本权重会发生什么?有人能指出魔法发生的地方吗?

谢谢!

python neural-network keras tensorflow loss-function

5
推荐指数
1
解决办法
408
查看次数

无法在损失函数中使用 VGG 特征的 MSE

tf.kerastensorflow 2.0.0 我有一个网络中使用 keras ( ) ,它的输入是一个图像,输出也是一个图像。我想在 VGG 特征空间中使用 MSE、MSE 和其他一些损失的组合,这取决于中间层输出。我正在定义一个自定义损失函数。我能够构建模型,使用自定义损失进行编译。但是当我训练使用fit_generator,我得到了一个SymbolicException说法Inputs to eager execution function cannot be Keras symbolic tensors

完整代码
训练文件:

def __init__(self, gray_images: bool, verbose: bool = True):
    super().__init__(gray_images, verbose)
    self.model = None
    self.vgg_feature_extractor = VggFeaturesExtractor(model_name='vgg16', layers=[3, 6, 10])

def build_model():
    image_input = Input(shape=(None, None, num_input_channels))
    out1 = self.build_out1_model(image_input, num_filters, depth_t)
    out2 = self.build_out2_model(image_input, num_filters, depth_n, use_bnorm)
    enhanced_image = ... # Some function of image_input, out1 and out2

    self.model …
Run Code Online (Sandbox Code Playgroud)

python customization keras loss-function tensorflow2.0

5
推荐指数
1
解决办法
700
查看次数

损失函数的爆炸式增长,LSTM 自动编码器

我正在训练一个 LSTM 自动编码器,但损失函数随机上升,如下图所示: 损失函数爆炸截图 我尝试了多种方法来防止这种情况发生,调整批量大小,调整图层中的神经元数量,但似乎没有任何帮助。我检查了我的输入数据以查看它是否包含空值/无穷大值,但它没有,它也被标准化了。这是我的代码供参考:

model = Sequential()
model.add(Masking(mask_value=0, input_shape=(430, 3)))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2, activation='relu'))
model.add(RepeatVector(430))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2, activation='relu', return_sequences=True))
model.add(TimeDistributed(Dense(3)))
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])

context_paths = loadFile()
X_train, X_test = train_test_split(context_paths, test_size=0.20)

history = model.fit(X_train, X_train, epochs=1, batch_size=4, verbose=1, validation_data=(X_test, X_test))
Run Code Online (Sandbox Code Playgroud)

损失函数在随机时间点爆炸,有时早些,有时晚些。我读到这个线程可能出现的问题,但在尝试多次后的事情这一点我不知道怎样做才能防止损失函数从随机暴涨。任何建议表示赞赏。除此之外,我可以看到我的准确度并没有增加多少,所以问题可能是相互关联的。

python autoencoder lstm keras loss-function

5
推荐指数
2
解决办法
1063
查看次数