官方文档:https://www.paddlepaddle.org.cn/documentation/docs/zh/api_cn/layers_cn/cross_entropy_cn.html
示例:
import paddle.fluid as fluid
import numpy as npclass_num = 7
x = fluid.data(name='x', shape=[-1, 1, 10], dtype='float32')
label = fluid.data(name='label', shape=[-1, 1], dtype='int64')
predict = fluid.layers.fc(input=x, size=class_num, act='softmax')
cost = fluid.layers.cross_entropy(input=predict, label=label)place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())samples = 6
np_x = np.random.random(size=(samples, 1, 10)).astype('float32')
np_y = np.random.randint(low=0, high=class_num, size=(samples, 1)).astype('int64')
print(np_x)
print(np_y)
output = exe.run(feed={"x": np_x, "label": np_y}, fetch_list = [cost])
print(output)
结果:
[[[0.4527526 0.79921854 0.4485681 0.34811467 0.7507561 0.8078209 0.72739184 0.5410976 0.4951061 0.08417795]][[0.69459516 0.5052644 0.09735702 0.17990156 0.04351452 0.4255496 0.34425682 0.5052834 0.9365378 0.06064539]][[0.09274481 0.9413779 0.3883635 0.65820855 0.60970956 0.13670038 0.64331406 0.08975768 0.7772037 0.8579608 ]][[0.68027896 0.90740174 0.02467881 0.94697666 0.84760493 0.90569997 0.4304838 0.43157798 0.44898176 0.77926594]][[0.94457364 0.27906907 0.913569 0.5994569 0.1048044 0.28563756 0.3188055 0.68807054 0.6438866 0.01220882]][[0.24974725 0.2163003 0.16348869 0.8209394 0.671093 0.30101737 0.3471077 0.79650295 0.02727815 0.40069225]]][[4][0][6][0][4][2]][array([[1.5678651],[1.8718125],[2.6164384],[1.7536728],[1.7999921],[1.4771321]], dtype=float32)]