代码之家  ›  专栏  ›  技术社区  ›  Jivan

GPU上的Keras模型:在自定义损耗函数中使用Pandas

  •  0
  • Jivan  · 技术社区  · 5 年前

    我试图在Keras中定义以下(玩具)自定义损失函数:

    def flexed_distance_loss(y_true, y_pred):
        y_true_df = pd.DataFrame(y_true, columns=my_columns)
    
        # do something with y_true_df
    
        return categorical_crossentropy(y_true_df.values, y_pred)
    

    我在GPU上运行这个模型 tf.distribute.MirroredStrategy() .

    编译模型不会产生错误,但在运行时 model.fit() ,发生以下错误:

    >>> y_true_df = pd.DataFrame(y_true, columns=my_columns)
    
    OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed:
    AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
    

    熊猫似乎在尝试迭代张量 y_true ,这在图形模式下是禁止的(在GPU上训练时首选的模式)。

    我必须明白,在GPU上训练时,在丢失功能内使用熊猫是不可能的吗?

    除了直接在TensorFlow中进行所有操作之外,还有什么其他可行的选择呢?我正在做大量的重新索引和合并工作,我无法想象在原生TensorFlow代码中做这些工作的痛苦。

    注:

    作为参考,这就是我试图进行的操纵:

    def flexed_distance_loss(y_true, y_pred):
        y_true_df = pd.DataFrame(y_true, columns=my_columns)
        y_true_custom = y_true_df.idxmax(axis=1).to_frame(name='my_name')
    
        y_true_df = pd.concat([y_true_custom, y_true_df], axis=1)
    
        y_true_df = y_true_df.where(y_true_df != 0, np.NaN)
        y_true_df = y_true_df.reset_index().set_index('my_name')
    
        nearby = y_true_df.fillna(pivoted_df.reindex(y_true_df.index)) \
                                .fillna(0) \
                                .set_index('index').sort_index()
    
        nearby = np.expm1(nearby).div(np.sum(np.expm1(nearby), axis=1), axis=0)
    
        y_true_flexed = nearby.values
    
        return categorical_crossentropy(y_true_flexed, y_pred)
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   Jivan    5 年前

    实际上,我意识到我在自定义损失函数中所做的一切都是转换 y_true .在实际情况中,我是基于一些随机数来转换它的( if random.random() > 0.1 然后应用转换)。

    class BatchGenerator(tf.keras.utils.Sequence):
    
        def __init__(self, indices, batch_size, mode):
            self.indices = indices
            self.batch_size = batch_size
            self.mode = mode
    
        def __len__(self):
            return math.ceil(len(self.indices) / self.batch_size)
    
        def __getitem__(self, idx):
            batch = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]
            X_batch = X[batch, :]
            y_batch = y[batch, :]
    
            if self.mode == 'train' and random.random() > 0.3:
                # pick y from regular batch
                return X_batch, y_batch
            else:
                # apply flex-distancing to y
                return X_batch, flex_distance_batch(y_batch)
    
    batch_size = 512*4
    
    train_generator = BatchGenerator(range(0, test_cutoff), batch_size, 'train')
    test_generator = BatchGenerator(range(test_cutoff, len(y_df)), batch_size, 'test')
    

    通过这种方式,可以直接从批处理生成器应用转换,这里完全允许使用Pandas,因为我们只处理CPU上的NumPy阵列。