For gluon, how to define NET (MODEL) and LOSS for multi_labels?
This maybe a complex question about applicaiton of mxnet. And I really got stuck for a loooog time. I hope someone could help me out, thanks very much~
target: I want to transfer the multi_label net to gluon version. The similar example with R is here.The core idea is to learn to predict 4 labels in a net. l And I have 2 problems with mxnet 0.12 on win10.
First, accordingly, to define net with gluon, I wrote with hybridBlock like:
class Net(gluon.HybridBlock):
def __init__(self, **kwargs):
super(Net, self).__init__(**kwargs)
with self.name_scope():
self.cov1 = gluon.nn.Conv2D(channels=32, kernel_size=(5, 5))
self.cov2 = gluon.nn.Conv2D(channels=32, kernel_size=(5, 5))
self.cov3 = gluon.nn.Conv2D(channels=32, kernel_size=(3, 3))
self.max_pool = gluon.nn.MaxPool2D(pool_size=(2, 2), strides=(1, 1))
self.avg_pool = gluon.nn.AvgPool2D(pool_size=(2, 2), strides=(1, 1))
self.flatten = gluon.nn.Flatten()
self.dense_256 = gluon.nn.Dense(256)
self.dense_10 = gluon.nn.Dense(10)
def hybrid_forward(self, F, x):
x = F.relu(self.max_pool(self.cov1(x)))
x = F.relu(self.max_pool(self.cov2(x)))
for _ in range(2):
x = F.relu(self.avg_pool(self.cov3(x)))
x = self.flatten(x)
x = F.relu(self.dense_256(x))
x1 = self.dense_10(x) # for 10 nums
x2 = self.dense_10(x)
x3 = self.dense_10(x)
x4 = self.dense_10(x)
out1 = F.concat(*[x1, x2, x3, x4], dim=0)
return out1
# return x1
# maybe no need to use the following 3 statements in gluon
# label = mx.symbol.transpose(data = label)
# label = mx.symbol.Reshape(data = label, target_shape = (0,))
# return mx.symbol.SoftmaxOutput(data=fc2, label=label, name="softmax")
About the net:
Q1; As I didn't find any example to modify label when defining net in hybrid class, I guess it is correct to just end with out1 = F.concat(*[x1, x2, x3, x4], dim=0)?
Then, when defining the 'trainer' (gluon version), the core code is like:
for i, batch in enumerate(train_iter): # data shape = BYXC, label shape = (batchsize,)
# get batch info and store data label on GPU
data, label, batch_size = get_batch(batch, ctx)
with autograd.record():
output = net(data) # data shape must be BCYX, output shape = (batchsize*Label_NUM,SOFTMAX_NUM)
label = label.T.reshape((-1,)) # before: label shape = (batchsize*Label_NUM,)
L = losser(output, label)
L.backward()
trainer.step(batch_size)
def get_batch(batch, ctx):
"""return data and label on ctx"""
'''the batch shape should be BCYX'''
if isinstance(batch, list): # for gluon.data.DataLoader
data, label = batch
else: # for (subclass) of mx.io.DataBatch
data, label = batch.data[0], batch.label[0]
return (data.as_in_context(ctx), label.as_in_context(ctx), data.shape[0]) # data.shape[0] = batch_size
# if no use try_all_gpu(),TypeError: object of type 'Context' has no len()
# return (gluon.utils.split_and_load(data, ctx),
# gluon.utils.split_and_load(label, ctx),
# data.shape[0])
And here with the losser(loss function), it is defined as gluon.loss.SoftmaxCrossEntropyLoss():
Q2: As it would not be treated as correct unless all 4 labels in 1 example are matched,then is label = label.T.reshape((-1,)) essential and correct here to calculate loss? by the way, even for the referred old version, I still didn't understand why the label need to transpose and flat to a long vector.
you can use SoftmaxCrossEntropyLoss(axis=-1) for data=(batch, label_num, num_class) and label=(batch, label_num)
@piiswrong, Thanks for your answer. But still confused. Do you mean the output shape of net(data) should be (batch, label_num, num_class) and the true label shape should be (batch, label_num) ,then use these 2 to calculate loss? And what does -1 mean for SoftmaxCrossEntropyLoss? Accordingly, I know axis (int, default -1) – The axis to sum over when computing softmax and entropy.
Proposed Label: "Python", "Question", "Example", "Gluon", "Modelling"
@dbsxdbsx
I modified slightly your code, adding the expand_dims and changing the concat dim so that your output is indeed
(batch, label_num, num_class)
class Net(gluon.HybridBlock):
def __init__(self, **kwargs):
super(Net, self).__init__(**kwargs)
with self.name_scope():
self.cov1 = gluon.nn.Conv2D(channels=32, kernel_size=(5, 5))
self.cov2 = gluon.nn.Conv2D(channels=32, kernel_size=(5, 5))
self.cov3 = gluon.nn.Conv2D(channels=32, kernel_size=(3, 3))
self.max_pool = gluon.nn.MaxPool2D(pool_size=(2, 2), strides=(1, 1))
self.avg_pool = gluon.nn.AvgPool2D(pool_size=(2, 2), strides=(1, 1))
self.flatten = gluon.nn.Flatten()
self.dense_256 = gluon.nn.Dense(256)
self.dense_10 = gluon.nn.Dense(10)
def hybrid_forward(self, F, x):
x = F.relu(self.max_pool(self.cov1(x)))
x = F.relu(self.max_pool(self.cov2(x)))
for _ in range(2):
x = F.relu(self.avg_pool(self.cov3(x)))
x = self.flatten(x)
x = F.relu(self.dense_256(x))
x1 = self.dense_10(x).expand_dims(axis=1) # for 10 nums
x2 = self.dense_10(x).expand_dims(axis=1)
x3 = self.dense_10(x).expand_dims(axis=1)
x4 = self.dense_10(x).expand_dims(axis=1)
out1 = F.concat(*[x1, x2, x3, x4], dim=1)
return out1
For example, for batch=8, num_label=4, num_classes=10 we indeed get the shape we expect:
net = Net()
net.initialize()
output = net(mx.nd.ones((8,3,224,224)))
output.shape
(8, 4, 10)
For the loss, as indicated by @piiswrong it works indeed. For example let's consider the following code:
loss = gluon.loss.SoftmaxCrossEntropyLoss()
# We create a hypothetical output of shape (batch, num_label, num_class)
batch = 2
num_label = 4
num_class = 10
output = mx.nd.zeros(((batch, num_label, num_class)))
# We create a corresponding label of shape (batch, num_label)
label = [1,2,3,4]
labels = mx.nd.array([label]*batch)
labels
[[ 1. 2. 3. 4.]
[ 1. 2. 3. 4.]]
<NDArray 2x4 @cpu(0)>
# We assign a high value for the output in the right label
for i in range(batch):
for j in range(num_label):
output[i][j][labels[i][j]] = 100
output
[[[ 0. 100. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 100. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 100. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 100. 0. 0. 0. 0. 0.]]
[[ 0. 100. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 100. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 100. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 100. 0. 0. 0. 0. 0.]]]
<NDArray 2x4x10 @cpu(0)>
loss(output, labels)
Indeed the loss is 0 because the output matches the labels!
[ 0. 0.]
<NDArray 2 @cpu(0)>
If we modify one value to be as high as the one corresponding to the correct label, we should see the loss increase in the first sample of our batch
output[0][0][0] = 100
loss(output, labels)
[ 0.1732868 0. ]
<NDArray 2 @cpu(0)>
@yzhliu can you please close? @dbsxdbsx if you want to follow up, please create a post on https://discuss.mxnet.io, thanks!
@dbsxdbsx If you still face problem with Thomas's solution, feel free to reopen or create a post on discuss as Thomas suggested. Close for now. Thanks
@ThomasDelteil ,thanks for your so concrete description. I would check it by following your suggestion.