未验证 提交 27f49254 编写于 作者: Y yuehuayingxueluo 提交者: GitHub

clear fluid apis in loss.py v_1 (#48132)

* clear fluid apis: center_loss, bpr_loss, edit_distance, hsigmoid, sampled_softmax_with_cross_entropy, rank_loss, margin_rank_loss,  sigmoid_cross_entropy_with_logits, huber_loss

* fix python/paddle/fluid/layers/loss.py

* fix test_layers.py

* fix CI bug

* fix nn.py
上级 cbdc86b5
......@@ -23,7 +23,6 @@ from .initializer import Constant
from .layers import detection
__all__ = [
'EditDistance',
'DetectionMAP',
]
......@@ -126,95 +125,6 @@ class Evaluator:
return state
class EditDistance(Evaluator):
"""
Warning: This would be deprecated in the future. Please use fluid.metrics.EditDistance
instead.
Accumulate edit distance sum and sequence number from mini-batches and
compute the average edit_distance and instance error of all batches.
Args:
input: the sequences predicted by network.
label: the target sequences which must have same sequence count
with input.
ignored_tokens(list of int): Tokens that should be removed before
calculating edit distance.
Examples:
.. code-block:: python
exe = fluid.executor(place)
distance_evaluator = fluid.Evaluator.EditDistance(input, label)
for epoch in PASS_NUM:
distance_evaluator.reset(exe)
for data in batches:
loss = exe.run(fetch_list=[cost])
distance, instance_error = distance_evaluator.eval(exe)
In the above example:
'distance' is the average of the edit distance in a pass.
'instance_error' is the instance error rate in a pass.
"""
def __init__(self, input, label, ignored_tokens=None, **kwargs):
super().__init__("edit_distance", **kwargs)
main_program = self.helper.main_program
if main_program.current_block().idx != 0:
raise ValueError("You can only invoke Evaluator in root block")
self.total_distance = self._create_state(
dtype='float32', shape=[1], suffix='total_distance'
)
self.seq_num = self._create_state(
dtype='int64', shape=[1], suffix='seq_num'
)
self.instance_error = self._create_state(
dtype='int64', shape=[1], suffix='instance_error'
)
distances, seq_num = layers.edit_distance(
input=input, label=label, ignored_tokens=ignored_tokens
)
zero = layers.fill_constant(shape=[1], value=0.0, dtype='float32')
compare_result = layers.equal(distances, zero)
compare_result_int = layers.cast(x=compare_result, dtype='int64')
seq_right_count = layers.reduce_sum(compare_result_int)
instance_error_count = layers.elementwise_sub(
x=seq_num, y=seq_right_count
)
total_distance = layers.reduce_sum(distances)
layers.sums(
input=[self.total_distance, total_distance], out=self.total_distance
)
layers.sums(input=[self.seq_num, seq_num], out=self.seq_num)
layers.sums(
input=[self.instance_error, instance_error_count],
out=self.instance_error,
)
self.metrics.append(total_distance)
self.metrics.append(instance_error_count)
def eval(self, executor, eval_program=None):
if eval_program is None:
eval_program = Program()
block = eval_program.current_block()
with program_guard(main_program=eval_program):
total_distance = _clone_var_(block, self.total_distance)
seq_num = _clone_var_(block, self.seq_num)
instance_error = _clone_var_(block, self.instance_error)
seq_num = layers.cast(x=seq_num, dtype='float32')
instance_error = layers.cast(x=instance_error, dtype='float32')
avg_distance = layers.elementwise_div(x=total_distance, y=seq_num)
avg_instance_error = layers.elementwise_div(
x=instance_error, y=seq_num
)
result = executor.run(
eval_program, fetch_list=[avg_distance, avg_instance_error]
)
return np.array(result[0]), np.array(result[1])
class DetectionMAP(Evaluator):
"""
Warning: This would be deprecated in the future. Please use fluid.metrics.DetectionMAP
......
此差异已折叠。
......@@ -702,7 +702,7 @@ class EditDistance(MetricBase):
"""
if self.seq_num == 0:
raise ValueError(
"There is no data in EditDistance Metric. Please check layers.edit_distance output has been added to EditDistance."
"There is no data in EditDistance Metric. Please check paddle.nn.functional.loss.edit_distance output has been added to EditDistance."
)
avg_distance = self.total_distance / self.seq_num
avg_instance_error = self.instance_error / float(self.seq_num)
......
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import numpy as np
import paddle
import paddle.static
from paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest
class TestBase(IPUOpTest):
def setUp(self):
self.set_atol()
self.set_training()
self.set_data_feed()
self.set_feed_attr()
self.set_op_attrs()
def set_data_feed(self):
x = np.random.uniform(size=[3, 4, 2, 2])
target = np.random.uniform(size=[3, 4, 2, 2])
self.feed_fp32 = {
"x": x.astype(np.float32),
"target": target.astype(np.float32),
}
self.feed_fp16 = {
"x": x.astype(np.float16),
"target": target.astype(np.float16),
}
def set_feed_attr(self):
self.feed_shape = [x.shape for x in self.feed_fp32.values()]
self.feed_list = list(self.feed_fp32.keys())
def set_op_attrs(self):
self.attrs = {
'delta': 1.0,
}
@IPUOpTest.static_graph
def build_model(self, on_ipu):
x = paddle.static.data(
name=self.feed_list[0], shape=self.feed_shape[0], dtype="float32"
)
target = paddle.static.data(
name=self.feed_list[1], shape=self.feed_shape[1], dtype='float32'
)
out = paddle.fluid.layers.huber_loss(x, target, **self.attrs)
self.fetch_list = [out.name]
def run_model(self, exec_mode):
self.run_op_test(exec_mode)
def test(self):
for m in IPUOpTest.ExecutionMode:
if not self.skip_mode(m):
self.build_model(self.is_ipu_mode(m))
self.run_model(m)
self.check()
class TestCase1(TestBase):
def set_op_attrs(self):
self.attrs = {
'delta': 0.5,
}
class TestCase2(TestBase):
def set_op_attrs(self):
self.attrs = {
'delta': 0.0,
}
if __name__ == "__main__":
unittest.main()
......@@ -63,7 +63,7 @@ class TestBase(IPUOpTest):
right = paddle.static.data(
name=self.feed_list[2], shape=self.feed_shape[2], dtype='float32'
)
out = paddle.fluid.layers.margin_rank_loss(label, left, right)
out = paddle.nn.functional.margin_ranking_loss(left, right, label)
self.fetch_list = [out.name]
def run_model(self, exec_mode):
......
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import numpy as np
import paddle
import paddle.static
from paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest
class TestBase(IPUOpTest):
def setUp(self):
self.set_atol()
self.set_training()
self.set_data_feed()
self.set_feed_attr()
def set_data_feed(self):
label = np.random.uniform(size=[3, 1])
left = np.random.uniform(size=[3, 1])
right = np.random.uniform(size=[3, 1])
self.feed_fp32 = {
"label": label.astype(np.float32),
"left": left.astype(np.float32),
"right": right.astype(np.float32),
}
self.feed_fp16 = {
"label": label.astype(np.float16),
"left": left.astype(np.float16),
"right": right.astype(np.float16),
}
def set_feed_attr(self):
self.feed_shape = [x.shape for x in self.feed_fp32.values()]
self.feed_list = list(self.feed_fp32.keys())
@IPUOpTest.static_graph
def build_model(self, on_ipu):
label = paddle.static.data(
name=self.feed_list[0], shape=self.feed_shape[0], dtype="float32"
)
left = paddle.static.data(
name=self.feed_list[1], shape=self.feed_shape[1], dtype='float32'
)
right = paddle.static.data(
name=self.feed_list[2], shape=self.feed_shape[2], dtype='float32'
)
out = paddle.fluid.layers.rank_loss(label, left, right)
self.fetch_list = [out.name]
def run_model(self, exec_mode):
self.run_op_test(exec_mode)
def test(self):
for m in IPUOpTest.ExecutionMode:
if not self.skip_mode(m):
self.build_model(self.is_ipu_mode(m))
self.run_model(m)
self.check()
if __name__ == "__main__":
unittest.main()
......@@ -37,7 +37,6 @@ class TestHuberLossOp(OpTest):
def setUp(self):
self.op_type = 'huber_loss'
self.set_mlu()
self.python_api = paddle.fluid.layers.huber_loss
self.python_out_sig = ["Out"]
self.delta = 1.0
self.init_input()
......@@ -103,28 +102,5 @@ def TestHuberLossOp3(TestHuberLossOp):
return (6, 6, 1)
class TestHuberLossOpError(unittest.TestCase):
def test_errors(self):
with program_guard(Program(), Program()):
# the input and label must be Variable
xw = np.random.random((6, 6)).astype("float32")
xr = fluid.data(name='xr', shape=[None, 6], dtype="float32")
lw = np.random.random((6, 6)).astype("float32")
lr = fluid.data(name='lr', shape=[None, 6], dtype="float32")
delta = 1.0
self.assertRaises(TypeError, fluid.layers.huber_loss, xr, lw, delta)
self.assertRaises(TypeError, fluid.layers.huber_loss, xw, lr, delta)
# the dtype of input and label must be float32 or float64
xw2 = fluid.data(name='xw2', shape=[None, 6], dtype="int32")
lw2 = fluid.data(name='lw2', shape=[None, 6], dtype="int32")
self.assertRaises(
TypeError, fluid.layers.huber_loss, xw2, lr, delta
)
self.assertRaises(
TypeError, fluid.layers.huber_loss, xr, lw2, delta
)
if __name__ == '__main__':
unittest.main()
......@@ -126,27 +126,6 @@ def TestHuberLossOpFP16(TestHuberLossOp):
@unittest.skipIf(
not paddle.is_compiled_with_npu(), "core is not compiled with NPU"
)
class TestHuberLossOpError(unittest.TestCase):
def test_errors(self):
with program_guard(Program(), Program()):
# the input and label must be Variable
xw = np.random.random((6, 6)).astype("float32")
xr = fluid.data(name='xr', shape=[None, 6], dtype="float32")
lw = np.random.random((6, 6)).astype("float32")
lr = fluid.data(name='lr', shape=[None, 6], dtype="float32")
delta = 1.0
self.assertRaises(TypeError, fluid.layers.huber_loss, xr, lw, delta)
self.assertRaises(TypeError, fluid.layers.huber_loss, xw, lr, delta)
# the dtype of input and label must be float32 or float64
xw2 = fluid.data(name='xw2', shape=[None, 6], dtype="int32")
lw2 = fluid.data(name='lw2', shape=[None, 6], dtype="int32")
self.assertRaises(
TypeError, fluid.layers.huber_loss, xw2, lr, delta
)
self.assertRaises(
TypeError, fluid.layers.huber_loss, xr, lw2, delta
)
if __name__ == '__main__':
......
......@@ -15,7 +15,7 @@
import unittest
import numpy as np
from op_test import OpTest
import paddle.fluid as fluid
import paddle
class TestCenterLossOp(OpTest):
......@@ -89,72 +89,6 @@ class TestCenterLossOpNoUpdate(TestCenterLossOp):
self.need_update = False
class BadInputTestCenterLoss(unittest.TestCase):
def test_error(self):
with fluid.program_guard(fluid.Program()):
def test_bad_x():
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
label = fluid.layers.data(
name='label', shape=[2, 1], dtype='int32'
)
res = fluid.layers.center_loss(
data,
label,
num_classes=1000,
alpha=0.2,
param_attr=fluid.initializer.Xavier(uniform=False),
update_center=True,
)
self.assertRaises(TypeError, test_bad_x)
def test_bad_y():
data = fluid.layers.data(
name='data', shape=[2, 32], dtype='float32'
)
label = [[2], [3]]
res = fluid.layers.center_loss(
data,
label,
num_classes=1000,
alpha=0.2,
param_attr=fluid.initializer.Xavier(uniform=False),
update_center=True,
)
self.assertRaises(TypeError, test_bad_y)
def test_bad_alpha():
data = fluid.layers.data(
name='data2',
shape=[2, 32],
dtype='float32',
append_batch_size=False,
)
label = fluid.layers.data(
name='label2',
shape=[2, 1],
dtype='int32',
append_batch_size=False,
)
alpha = fluid.layers.data(
name='alpha',
shape=[1],
dtype='int64',
append_batch_size=False,
)
res = fluid.layers.center_loss(
data,
label,
num_classes=1000,
alpha=alpha,
param_attr=fluid.initializer.Xavier(uniform=False),
update_center=True,
)
self.assertRaises(TypeError, test_bad_alpha)
if __name__ == "__main__":
paddle.enable_static()
unittest.main()
......@@ -1440,14 +1440,18 @@ class TestRemoteHsigmoid(TestDistLookupTableBase):
),
)
cost = fluid.layers.hsigmoid(
loss = paddle.nn.HSigmoidLoss(
feature_size=emb.shape[1],
num_classes=num_total_classes,
is_custom=True,
is_sparse=is_sparse,
)
cost = loss(
input=emb,
label=label,
num_classes=num_total_classes,
path_table=path_table,
path_code=path_code,
is_custom=True,
is_sparse=is_sparse,
)
avg_cost = paddle.mean(cost)
# optimizer
......
......@@ -17,7 +17,6 @@ import numpy as np
import paddle
import paddle.fluid as fluid
import paddle.nn.functional as F
from paddle.fluid import Program, program_guard
import paddle.fluid.initializer as I
import math
from op_test import OpTest, skip_check_grad_ci
......@@ -305,15 +304,19 @@ class TestHSigmoidOpWithSparseGrad(unittest.TestCase):
),
)
cost = fluid.layers.hsigmoid(
loss = paddle.nn.HSigmoidLoss(
feature_size=emb.shape[1],
num_classes=3,
bias_attr=True,
is_custom=True,
is_sparse=is_sparse,
)
cost = loss(
input=emb,
label=label,
bias_attr=True,
num_classes=3,
path_table=path_table,
path_code=path_code,
is_custom=True,
is_sparse=is_sparse,
)
avg_cost = fluid.layers.reduce_mean(cost)
......@@ -633,16 +636,19 @@ class TestHSigmoidLossAPI(unittest.TestCase):
path_code = fluid.data('path_code', [-1, -1], 'int64')
weight_attr = I.NumpyArrayInitializer(self.weight_np)
bias_attr = I.NumpyArrayInitializer(self.bias_np)
out = fluid.layers.hsigmoid(
x,
labels,
self.num_classes,
weight_attr,
bias_attr,
'out',
path_table,
path_code,
self.is_custom,
loss = paddle.nn.HSigmoidLoss(
feature_size=x.shape[1],
num_classes=self.num_classes,
weight_attr=weight_attr,
bias_attr=bias_attr,
is_custom=self.is_custom,
name='out',
)
out = loss(
input=x,
label=labels,
path_table=path_table,
path_code=path_code,
)
exe = fluid.Executor(self.place)
......@@ -730,28 +736,6 @@ class TestHSigmoidLossAPI(unittest.TestCase):
self.assertRaises(ValueError, F.hsigmoid_loss, x, label, 0, weight)
paddle.enable_static()
# test paddle.fluid.layers.hsigmoid
with program_guard(Program()):
label = fluid.data('label', [4, 1], 'int64')
# The input type must be Variable.
self.assertRaises(TypeError, fluid.layers.hsigmoid, 1, label, 2)
# The input dtype must be float16, float32, float64.
x_int32 = fluid.data(name='x_int32', shape=[4, 3], dtype='int32')
self.assertRaises(
TypeError, fluid.layers.hsigmoid, x_int32, label, 2
)
# support the input dtype is float32
x_fp32 = fluid.data(name='x_fp32', shape=[4, 3], dtype='float32')
fluid.layers.hsigmoid(x_fp32, label, 2)
# The label type must be Variable.
self.assertRaises(TypeError, fluid.layers.hsigmoid, x_fp32, 1, 2)
# The label dtype must be int64.
label_int32 = fluid.data('label_int32', [4, 1], 'int32')
self.assertRaises(
TypeError, fluid.layers.hsigmoid, x_fp32, label_int32, 2
)
class TestHSigmoidLossAPICustom(TestHSigmoidLossAPI):
def set_attrs(self):
......
......@@ -15,9 +15,7 @@
import unittest
import numpy as np
from op_test import OpTest
import paddle.fluid as fluid
import paddle
from paddle.fluid import Program, program_guard
def huber_loss_forward(val, delta):
......@@ -31,7 +29,6 @@ def huber_loss_forward(val, delta):
class TestHuberLossOp(OpTest):
def setUp(self):
self.op_type = 'huber_loss'
self.python_api = paddle.fluid.layers.huber_loss
self.python_out_sig = ["Out"]
self.delta = 1.0
self.init_input()
......@@ -54,10 +51,10 @@ class TestHuberLossOp(OpTest):
return (100, 1)
def test_check_output(self):
self.check_output(check_eager=True)
self.check_output(check_eager=False)
def test_check_grad_normal(self):
self.check_grad(['X', 'Y'], 'Out', check_eager=True)
self.check_grad(['X', 'Y'], 'Out', check_eager=False)
def test_check_grad_ingore_x(self):
self.check_grad(
......@@ -85,29 +82,6 @@ def TestHuberLossOp3(TestHuberLossOp):
return (6, 6, 1)
class TestHuberLossOpError(unittest.TestCase):
def test_errors(self):
with program_guard(Program(), Program()):
# the input and label must be Variable
xw = np.random.random((6, 6)).astype("float32")
xr = fluid.data(name='xr', shape=[None, 6], dtype="float32")
lw = np.random.random((6, 6)).astype("float32")
lr = fluid.data(name='lr', shape=[None, 6], dtype="float32")
delta = 1.0
self.assertRaises(TypeError, fluid.layers.huber_loss, xr, lw, delta)
self.assertRaises(TypeError, fluid.layers.huber_loss, xw, lr, delta)
# the dtype of input and label must be float32 or float64
xw2 = fluid.data(name='xw2', shape=[None, 6], dtype="int32")
lw2 = fluid.data(name='lw2', shape=[None, 6], dtype="int32")
self.assertRaises(
TypeError, fluid.layers.huber_loss, xw2, lr, delta
)
self.assertRaises(
TypeError, fluid.layers.huber_loss, xr, lw2, delta
)
if __name__ == '__main__':
paddle.enable_static()
unittest.main()
......@@ -2984,7 +2984,6 @@ class TestBook(LayerTest):
"make_gaussian_random_batch_size_like",
"make_kldiv_loss",
"make_prelu",
"make_sampled_softmax_with_cross_entropy",
"make_sampling_id",
"make_uniform_random_batch_size_like",
}
......@@ -3091,18 +3090,6 @@ class TestBook(LayerTest):
append_batch_size=append_batch_size,
)
def make_sampled_softmax_with_cross_entropy(self):
with program_guard(
fluid.default_main_program(), fluid.default_startup_program()
):
logits = self._get_data(name='Logits', shape=[256], dtype='float32')
label = self._get_data(name='Label', shape=[1], dtype='int64')
num_samples = 25
output = layers.sampled_softmax_with_cross_entropy(
logits, label, num_samples
)
return output
def make_fit_a_line(self):
with program_guard(
fluid.default_main_program(),
......@@ -3237,33 +3224,6 @@ class TestBook(LayerTest):
x=dat, label=lbl, ignore_index=ignore_index
)
def make_hsigmoid(self):
self._force_to_use_cpu = True
with fluid.framework._dygraph_place_guard(place=fluid.CPUPlace()):
x = self._get_data(name='x', shape=[2], dtype='float32')
y = self._get_data(name='y', shape=[2], dtype='int64')
return layers.hsigmoid(input=x, label=y, num_classes=2)
# test hsigmod with custom tree structure
program2 = Program()
with program_guard(program2):
x2 = self._get_data(name='x2', shape=[4, 8], dtype='float32')
y2 = self._get_data(name='y2', shape=[4], dtype='int64')
path_table = self._get_data(
name='path_table', shape=[4, 6], dtype='int64'
)
path_code = self._get_data(
name='path_code', shape=[4, 6], dtype='int64'
)
return layers.hsigmoid(
input=x2,
label=y2,
num_classes=6,
path_table=path_table,
path_code=path_code,
is_custom=True,
)
def make_pool2d(self):
with program_guard(
fluid.default_main_program(), fluid.default_startup_program()
......@@ -3597,31 +3557,6 @@ class TestBook(LayerTest):
return out
return ids
def make_rank_loss(self):
with program_guard(
fluid.default_main_program(), fluid.default_startup_program()
):
label = self._get_data(
name='label',
append_batch_size=False,
shape=[16, 1],
dtype="float32",
)
left = self._get_data(
name='left',
append_batch_size=False,
shape=[16, 1],
dtype="float32",
)
right = self._get_data(
name='right',
append_batch_size=False,
shape=[16, 1],
dtype="float32",
)
out = layers.rank_loss(label, left, right, name="rank_loss")
return out
def make_shape(self):
with program_guard(
fluid.default_main_program(), fluid.default_startup_program()
......@@ -3691,14 +3626,6 @@ class TestBook(LayerTest):
out = layers.cross_entropy(x, label, False, 4)
return out
def make_bpr_loss(self):
self._force_to_use_cpu = True
with fluid.framework._dygraph_place_guard(place=fluid.CPUPlace()):
x = self._get_data(name="x", shape=[30, 10], dtype="float32")
label = self._get_data(name="label", shape=[30, 1], dtype="int64")
out = layers.bpr_loss(x, label)
return out
def make_expand(self):
with program_guard(
fluid.default_main_program(), fluid.default_startup_program()
......@@ -4585,17 +4512,6 @@ class TestBook(LayerTest):
)
return output
def test_edit_distance(self):
with self.static_graph():
predict = layers.data(
name='predict', shape=[-1, 1], dtype='int64', lod_level=1
)
label = layers.data(
name='label', shape=[-1, 1], dtype='int64', lod_level=1
)
evaluator = fluid.evaluator.EditDistance(predict, label)
return evaluator.metrics
def test_basic_gru(self):
input_size = 128
hidden_size = 256
......
......@@ -16,6 +16,7 @@ import unittest
import numpy as np
from op_test import OpTest
from paddle import fluid
import paddle
class TestMarginRankLossOp(OpTest):
......@@ -87,7 +88,9 @@ class TestMarginRankLossLayer(unittest.TestCase):
label = fluid.data("label", (self.batch_size, 1), "float32")
x1 = fluid.data("x1", (self.batch_size, 1), "float32")
x2 = fluid.data("x2", (self.batch_size, 1), "float32")
out = fluid.layers.margin_rank_loss(label, x1, x2, self.margin)
out = paddle.nn.functional.margin_ranking_loss(
x1, x2, label, self.margin, 'none'
)
exe = fluid.Executor(place)
exe.run(start)
......
......@@ -15,8 +15,6 @@
import unittest
import numpy as np
from op_test import OpTest
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
class TestRankLossOp(OpTest):
......@@ -84,31 +82,5 @@ class TestRankLossOp5(TestRankLossOp):
return (batch_size), (batch_size), (batch_size)
class TestRankLossOpError(unittest.TestCase):
def test_errors(self):
with program_guard(Program(), Program()):
label = fluid.data(name="label", shape=[16, 1], dtype="float32")
left = fluid.data(name="left", shape=[16, 1], dtype="float32")
right = fluid.data(name="right", shape=[16, 1], dtype="float32")
def test_label_Variable():
label_data = np.random.rand(16, 1).astype("float32")
out = fluid.layers.rank_loss(label_data, left, right)
self.assertRaises(TypeError, test_label_Variable)
def test_left_Variable():
left_data = np.random.rand(16, 1).astype("float32")
out = fluid.layers.rank_loss(label, left_data, right)
self.assertRaises(TypeError, test_left_Variable)
def test_right_Variable():
right_data = np.random.rand(16, 1).astype("float32")
out = fluid.layers.rank_loss(label, left, right_data)
self.assertRaises(TypeError, test_right_Variable)
if __name__ == '__main__':
unittest.main()
......@@ -17,8 +17,6 @@ from math import log
from math import exp
from op_test import OpTest
from scipy.special import logit
import unittest
import paddle.fluid as fluid
class TestTeacherStudentSigmoidLossOp(OpTest):
......@@ -71,20 +69,3 @@ class TestTeacherStudentSigmoidLossOp(OpTest):
def test_check_grad(self):
self.check_grad(["X"], "Y", numeric_grad_delta=0.005)
class TestTeacherStudentSigmoidLossInvalidInput(unittest.TestCase):
def test_error(self):
def test_invalid_input():
input = [512, 1]
label = fluid.data(name='label', shape=[None, 1], dtype='float32')
loss = fluid.layers.teacher_student_sigmoid_loss(input, label)
self.assertRaises(TypeError, test_invalid_input)
def test_invalid_label():
input = fluid.data(name='input1', shape=[None, 1], dtype='float32')
label = [512, 1]
loss = fluid.layers.teacher_student_sigmoid_loss(input, label)
self.assertRaises(TypeError, test_invalid_label)
......@@ -506,7 +506,6 @@ def edit_distance(
input_length(Tensor): The length for each sequence in `input` if it's of Tensor type, it should have shape `(batch_size, )` and its data type should be int64.
label_length(Tensor): The length for each sequence in `label` if it's of Tensor type, it should have shape `(batch_size, )` and its data type should be int64.
NOTE: To be avoid unexpected result, the value of every elements in input_length and label_length should be equal to the value of the second dimension of input and label. For example, The input: [[1,2,3,4],[5,6,7,8],[9,10,11,12]], the shape of input is [3,4] and the input_length should be [4,4,4]
NOTE: This Api is different from fluid.metrics.EditDistance
Returns:
Tuple:
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册