亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從keras dropout層中提取dropout mask?

從keras dropout層中提取dropout mask?

喵喵時光機 2022-06-02 11:07:45
我想在訓練時從每個批次的順序 Keras 模型中的丟失層中提取和存儲丟失掩碼 [1/0 數組]。我想知道在 Keras 中是否有直接的方法可以做到這一點,或者我是否需要切換到 tensorflow(如何在 Tensorflow 中獲取 dropout 掩碼)。將不勝感激任何幫助!我對 TensorFlow 和 Keras 很陌生。None我嘗試使用但在調用前一層后 得到的 dropout 層有幾個函數(dropout_layer.get_output_mask()、dropout_layer.get_input_mask()) 。model = tf.keras.Sequential()model.add(tf.keras.layers.Flatten(name="flat", input_shape=(28, 28, 1)))model.add(tf.keras.layers.Dense(    512,    activation='relu',    name = 'dense_1',    kernel_initializer=tf.keras.initializers.GlorotUniform(seed=123),    bias_initializer='zeros'))dropout = tf.keras.layers.Dropout(0.2, name = 'dropout') #want this layer's maskmodel.add(dropout)x = dropout.output_masky = dropout.input_maskmodel.add(tf.keras.layers.Dense(    10,    activation='softmax',    name='dense_2',    kernel_initializer=tf.keras.initializers.GlorotUniform(seed=123),    bias_initializer='zeros'))model.compile(...)model.fit(...)
查看完整描述

2 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

它在 Keras 中并不容易暴露。它深入到它調用 TensorFlow 輟學。


所以,雖然你使用的是 Keras,但它也將是圖中的一個張量,可以通過名稱獲?。ㄕ业剿拿Q:在 Tensorflow 中,獲取圖中所有張量的名稱)。


這個選項當然會缺少一些 keras 信息,您可能必須在 Lambda 層內執行此操作,以便 Keras 將某些信息添加到張量。而且您必須格外小心,因為即使不訓練(跳過掩碼),張量也會存在


現在,您還可以使用不那么 hacky 的方式,這可能會消耗一些處理:


def getMask(x):

    boolMask = tf.not_equal(x, 0)

    floatMask = tf.cast(boolMask, tf.float32) #or tf.float64

    return floatMask

用一個Lambda(getMasc)(output_of_dropout_layer)


Sequential但是,您將需要一個功能性 API,而不是使用模型Model。


inputs = tf.keras.layers.Input((28, 28, 1))

outputs = tf.keras.layers.Flatten(name="flat")(inputs)

outputs = tf.keras.layers.Dense(

    512,

    #    activation='relu', #relu will be a problem here

    name = 'dense_1',

    kernel_initializer=tf.keras.initializers.GlorotUniform(seed=123),

    bias_initializer='zeros')(outputs)


outputs = tf.keras.layers.Dropout(0.2, name = 'dropout')(outputs)

mask = Lambda(getMask)(outputs)

#there isn't "input_mask"



#add the missing relu: 

outputs = tf.keras.layers.Activation('relu')(outputs)

outputs = tf.keras.layers.Dense(

    10,

    activation='softmax',

    name='dense_2',

    kernel_initializer=tf.keras.initializers.GlorotUniform(seed=123),

    bias_initializer='zeros')(outputs)


model = Model(inputs, outputs)

model.compile(...)

model.fit(...)

訓練和預測

由于您無法訓練掩碼(這沒有任何意義),因此不應將其作為訓練模型的輸出。


現在,我們可以試試這個:


trainingModel = Model(inputs, outputs)    

predictingModel = Model(inputs, [output, mask])    

但是預測中不存在掩碼,因為 dropout 僅應用于訓練。所以這最終不會給我們帶來任何好處。


訓練的唯一方法是使用虛擬損失和虛擬目標:


def dummyLoss(y_true, y_pred):

    return y_true #but this might evoke a "None" gradient problem since it's not trainable, there is no connection to any weights, etc.    


model.compile(loss=[loss_for_main_output, dummyLoss], ....)


model.fit(x_train, [y_train, np.zeros((len(y_Train),) + mask_shape), ...)

不能保證這些會起作用。


查看完整回答
反對 回復 2022-06-02
?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

通過簡單地擴展提供的 dropout 層,我找到了一種非常 hacky 的方法。(幾乎所有來自TF的代碼。)


class MyDR(tf.keras.layers.Layer):

def __init__(self,rate,**kwargs):

    super(MyDR, self).__init__(**kwargs)


    self.noise_shape = None

    self.rate = rate



def _get_noise_shape(self,x, noise_shape=None):

    # If noise_shape is none return immediately.

    if noise_shape is None:

        return array_ops.shape(x)

    try:

        # Best effort to figure out the intended shape.

        # If not possible, let the op to handle it.

        # In eager mode exception will show up.

        noise_shape_ = tensor_shape.as_shape(noise_shape)

    except (TypeError, ValueError):

        return noise_shape


    if x.shape.dims is not None and len(x.shape.dims) == len(noise_shape_.dims):

        new_dims = []

        for i, dim in enumerate(x.shape.dims):

            if noise_shape_.dims[i].value is None and dim.value is not None:

                new_dims.append(dim.value)

            else:

                new_dims.append(noise_shape_.dims[i].value)

        return tensor_shape.TensorShape(new_dims)


    return noise_shape


def build(self, input_shape):

    self.noise_shape = input_shape

    print(self.noise_shape)

    super(MyDR,self).build(input_shape)


@tf.function

def call(self,input):

    self.noise_shape = self._get_noise_shape(input)

    random_tensor = tf.random.uniform(self.noise_shape, seed=1235, dtype=input.dtype)

    keep_prob = 1 - self.rate

    scale = 1 / keep_prob

    # NOTE: if (1.0 + rate) - 1 is equal to rate, then we want to consider that

    # float to be selected, hence we use a >= comparison.

    self.keep_mask = random_tensor >= self.rate

    #NOTE: here is where I save the binary masks. 

    #the file grows quite big!

    tf.print(self.keep_mask,output_stream="file://temp/droput_mask.txt")


    ret = input * scale * math_ops.cast(self.keep_mask, input.dtype)

    return ret


查看完整回答
反對 回復 2022-06-02
  • 2 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號