为了账号安全,请及时绑定邮箱和手机立即绑定

在 Keras 中实现批量依赖损失

在 Keras 中实现批量依赖损失

手掌心 2021-08-05 10:12:59
我在 Keras 中设置了一个自动编码器。我希望能够根据预定的“精度”向量对输入向量的特征进行加权。这个连续值向量与输入的长度相同,每个元素都在范围内[0, 1],对应于对应输入元素的置信度,其中1为完全置信度,0为不置信度。对于每个示例,我都有一个精度向量。我已经定义了一个考虑到这个精度向量的损失。在这里,低置信度特征的重建被降低权重。def MAEpw_wrapper(y_prec):    def MAEpw(y_true, y_pred):        return K.mean(K.square(y_prec * (y_pred - y_true)))    return MAEpw我的问题是精度张量y_prec取决于批次。我希望能够y_prec根据当前批次进行更新,以便每个精度向量与其观察正确关联。我做了以下工作:global y_precy_prec = K.variable(P[:32])这P是一个包含所有精度向量的 numpy 数组,其索引对应于示例。我初始化y_prec为批量大小为 32 的正确形状。然后我定义以下内容DataGenerator:class DataGenerator(Sequence):    def __init__(self, batch_size, y, shuffle=True):        self.batch_size = batch_size        self.y = y        self.shuffle = shuffle        self.on_epoch_end()    def on_epoch_end(self):        self.indexes = np.arange(len(self.y))        if self.shuffle == True:            np.random.shuffle(self.indexes)    def __len__(self):        return int(np.floor(len(self.y) / self.batch_size))    def __getitem__(self, index):        indexes = self.indexes[index * self.batch_size: (index+1) * self.batch_size]        # Set precision vector.        global y_prec        new_y_prec = K.variable(P[indexes])        y_prec = K.update(y_prec, new_y_prec)        # Get training examples.        y = self.y[indexes]        return y, y在这里,我的目标是y_prec在生成批处理的同一函数中进行更新。这似乎正在y_prec按预期更新。然后我定义我的模型架构:最后,我编译并运行:model2.compile(optimizer='adam', loss=MAEpw_wrapper(y_prec))model2.fit_generator(DataGenerator(32, digits.data), epochs=100)哪里digits.data是一个 numpy 观察数组。然而,这最终定义了单独的图形:StopIteration: Tensor("Variable:0", shape=(32, 64), dtype=float32_ref) must be from the same graph as Tensor("Variable_4:0", shape=(32, 64), dtype=float32_ref).我已经搜索了 SO 以解决我的问题,但我发现没有任何效果。任何有关如何正确执行此操作的帮助表示赞赏。
查看完整描述

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号