簡體   English   中英

在 tf keras 中屏蔽用於分段分割的損失函數

[英]Mask the Loss function for segmantic segmentation in tf keras

我有大小(256,256)圖像,它們被分為 10 個類( 09 )。 我想在這個數據集上訓練一個語義分割網絡,但只想把它當作一個 9 類問題(即忽略2類)。

我的問題是,是否有像掩碼這樣的東西,我可以在不評估損失的地方進行解析。

我目前的做法是:我是在one hot encoding之前修改圖片的對應區域,即:


# change any pixel with value 2 to 255
target = tf.where(target==2,tf.constant(255,shape=(256, 256), dtype=tf.uint8),target) 

# change 3 -> 2, 4 -> 3, ..., 9 -> 8    
for i in range(3,10):
    target = tf.where(target==i,tf.constant(i-1,shape=(256, 256), dtype=tf.uint8),target)

# do one hot
out = tf.one_hot(target,9)

並訓練一個具有 9 類輸出的網絡。 過去值為2所有像素都[0,0,0,0,0,0,0,0,0]熱編碼為[0,0,0,0,0,0,0,0,0]並且不應計入損失函數(categorical_crossentropy)。 無論如何,我不確定這是否會在我們除以像素數(常數 256^2)時產生問題,並且如果圖像的大部分被零向量標記,這將減少其他標簽的影響。

我在Tensorflow 2.0使用tf.keras

我認為您可以使用權重向量來實現您在這里需要的東西。

# Creating a random vector of targets of size (128)
target = tf.constant(np.random.randint(0,10, size=128).astype(np.int32))
# Create weights of size (128) and reshape to (128,1)
weights = tf.cast(tf.not_equal(target, 2), tf.float32)[:,tf.newaxis]

# do one hot and multiply by weights
out = tf.one_hot(target,9) * weights

話雖如此,這是為了得到一個零向量。 但是忽略這些像素的標准方法是將實際交叉熵損失乘以權重而不是 onehot 向量。

out = tf.one_hot(target,9)
# pred is the predictions made
loss = tf.keras.losses.CategoricalCrossentropy()(out, pred) * weights

這將使損失忽略值為 2 的像素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM