def test_validate_cp_tensor(): rng = tl.check_random_state(12345) true_shape = (3, 4, 5) true_rank = 3 cp_tensor = random_cp(true_shape, true_rank) (weights, factors) = cp_normalize(cp_tensor) # Check correct rank and shapes are returned shape, rank = _validate_cp_tensor((weights, factors)) assert_equal( shape, true_shape, err_msg='Returned incorrect shape (got {}, expected {})'.format( shape, true_shape)) assert_equal( rank, true_rank, err_msg='Returned incorrect rank (got {}, expected {})'.format( rank, true_rank)) # One of the factors has the wrong rank factors[0], copy = tl.tensor(rng.random_sample((4, 4))), factors[0] with assert_raises(ValueError): _validate_cp_tensor((weights, factors)) # Not the correct amount of weights factors[0] = copy wrong_weights = weights[1:] with assert_raises(ValueError): _validate_cp_tensor((wrong_weights, factors)) # Not enough factors with assert_raises(ValueError): _validate_cp_tensor((weights[:1], factors[:1]))
def test_cp_flip_sign(): shape = (3, 4, 5) rank = 4 cp_tensor = random_cp(shape, rank) weights, factors = cp_flip_sign(cp_tensor) assert_(tl.all(tl.mean(factors[1], axis=0) > 0)) assert_(tl.all(tl.mean(factors[2], axis=0) > 0)) assert_equal(cp_tensor.rank, cp_tensor.rank) assert_array_equal(cp_tensor.weights, weights) assert_array_almost_equal(cp_to_tensor((weights, factors)), cp_to_tensor(cp_tensor))
def test_cp_mode_dot(): """Test for cp_mode_dot We will compare cp_mode_dot (which operates directly on decomposed tensors) with mode_dot (which operates on full tensors) and check that the results are the same. """ rng = tl.check_random_state(12345) shape = (5, 4, 6) rank = 3 cp_ten = random_cp(shape, rank=rank, orthogonal=True, full=False) full_tensor = tl.cp_to_tensor(cp_ten) # matrix for mode 1 matrix = tl.tensor(rng.random_sample((7, shape[1]))) # vec for mode 2 vec = tl.tensor(rng.random_sample(shape[2])) # Test cp_mode_dot with matrix res = cp_mode_dot(cp_ten, matrix, mode=1, copy=True) # Note that if copy=True is not respected, factors will be changes # And the next test will fail res = tl.cp_to_tensor(res) true_res = mode_dot(full_tensor, matrix, mode=1) assert_array_almost_equal(true_res, res) # Check that the data was indeed copied rec = tl.cp_to_tensor(cp_ten) assert_array_almost_equal(full_tensor, rec) # Test cp_mode_dot with vec res = cp_mode_dot(cp_ten, vec, mode=2, copy=True) res = tl.cp_to_tensor(res) true_res = mode_dot(full_tensor, vec, mode=2) assert_equal(res.shape, true_res.shape) assert_array_almost_equal(true_res, res)