Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

How to implement cross entropy for binary segmentation using symbol only? #18333

Answered by wkcn
John1231983 asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @John1231983 , using mx.nd.pick will simplify the code.

import mxnet as mx

B, C, H, W = 2, 2, 3, 4

x = mx.random.uniform(-1, 1, shape=(B, C, H, W)) 
target = mx.random.randint(0, C, shape=(B, 1, H, W)) 

f = mx.nd.softmax(x)
# target size of Bx1xHxW
target_squeeze = mx.nd.squeeze(target, axis=1) #size of BxHxW
target_squeeze = mx.nd.one_hot(target_squeeze, depth = 2, on_value = -1.0, off_value = 0.0) 
# Transpose from BxHxWx2 to Bx2xHxW
target_squeeze = mx.nd.transpose(target_squeeze, axes=(0,3,1,2))
# Get log of feature f
f_log  = mx.nd.log(f)
batch_size =32
f_sum = mx.nd.sum(target_squeeze * f_log)/batch_size
print(f_sum)

lscore = -mx.nd.log_softmax(x)
target_squeeze = mx.nd.squeeze(

Replies: 4 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by szha
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #18333 on September 05, 2020 19:33.