Created by: still-wait
test=develop
Add a new public nn API,paddle.nn.loss.CrossEntropyLoss(reduction='sum'|'mean'|'none')
.
Usage example:
# declarative mode
import paddle
import paddle.fluid as fluid
import numpy as np
input = fluid.layers.data(name='input', shape=[3,5], dtype='float32')
label = fluid.layers.data(name='label', shape=[3,1], dtype='int64')
weight = fluid.layers.data(name='weight', shape=[5], dtype='float32')
ce_loss = paddle.nn.loss.CrossEntropyLoss(weight=weight, reduction='mean')
output = ce_loss(input,label)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
input_data = np.random.random([3,5]).astype("float32")
label_data = np.array([[1], [3], [4]]).astype("int64")
weight_data = np.random.random([5]).astype("float32")
output = exe.run(fluid.default_main_program(),
feed={"input":input_data, "label":label_data,"weight":weight_data},
fetch_list=[output],
return_numpy=True)
print(output)
# imperative mode
import paddle.fluid.dygraph as dg
with dg.guard(place) as g:
input = dg.to_variable(input_data)
label = dg.to_variable(label_data)
weight = dg.to_variable(weight_data)
ce_loss = paddle.nn.loss.CrossEntropyLoss(weight=weight, reduction='mean')
output = ce_loss(input,label)
print(output.numpy())