def test_in_top_k_pre_dim_runtime_error(test_case): with test_case.assertRaises(Exception) as context: target = flow.tensor([3, 1], dtype=flow.int32) prediction = flow.tensor( [[[0.0, 1.0, 2.0, 3.0]], [[3.0, 2.0, 1.0, 0.0]]], dtype=flow.float32) out = flow.in_top_k(target, prediction, k=1) test_case.assertTrue( "The dimension of predictions must be 2" in str(context.exception))
def test_in_top_k_num_equal_runtime_error(test_case): with test_case.assertRaises(Exception) as context: target = flow.tensor([[3, 1]], dtype=flow.int32) prediction = flow.tensor( [[0.0, 1.0, 2.0, 3.0], [3.0, 2.0, 1.0, 0.0]], dtype=flow.float32) out = flow.in_top_k(target, prediction, k=1) test_case.assertTrue( "The num of targets must equal the num of predictions" in str( context.exception))
def _test_in_top_k_impl(test_case, shape, k, device): np_targets = np.random.randint(0, shape[1], size=shape[0]) np_predictions = np.random.rand(*shape) of_targets = flow.tensor(np_targets, dtype=flow.int32, device=flow.device(device), requires_grad=False) of_predictions = flow.tensor( np_predictions, dtype=flow.float32, device=flow.device(device), requires_grad=True, ) of_out = flow.in_top_k(of_targets, of_predictions, k) np_out = _in_top_k_np(np_targets, np_predictions, k) test_case.assertTrue( np.allclose(of_out.numpy(), np_out, 0.0001, 0.0001, equal_nan=True))