def test_mttkrp(self): t = T.array([[[0, 1, 3, 4], [4, 0, 2, 1], [4, 2, 3, 4]], [[2, 4, 2, 3], [3, 3, 2, 4], [2, 3, 0, 2]]]) dtensor = sktensor.dtensor(t) factors = [None] * 3 for i in range(3): factors[i] = T.random.rand(t.shape[i], 3) # print(factors) # print(dtensor.uttkrp(factors, 0)) # print(mttkrp(t, factors, 0)) # T.testing.assert_array_almost_equal(dtensor.uttkrp(factors, 0), # mttkrp(t, factors, 0)) # 对展开的细节理解不一样,导致结果不一样,但是两种算法都没有问题 # T.testing.assert_array_almost_equal(dtensor.unfold(0), unfold(t, 0)) from sktensor.core import khatrirao from .. import seq_kr order = list(range(0)) + list(range(0 + 1, 3)) T.testing.assert_array_almost_equal( seq_kr(factors, exclude=0, reverse=True), khatrirao(tuple(factors[i] for i in order), reverse=True)) order = list(range(1)) + list(range(1 + 1, 3)) T.testing.assert_array_almost_equal( seq_kr(factors, exclude=1, reverse=True), khatrirao(tuple(factors[i] for i in order), reverse=True))
def test_khatrirao(): A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) B = np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9]]) C = np.array([[1, 8, 21], [2, 10, 24], [3, 12, 27], [4, 20, 42], [8, 25, 48], [12, 30, 54], [7, 32, 63], [14, 40, 72], [21, 48, 81]]) D = khatrirao((A, B)) assert C.shape == D.shape assert (C == D).all()
def toarray(self): """ Converts a ktensor into a dense multidimensional ndarray Returns ------- arr : np.ndarray Fully computed multidimensional array whose shape matches the original ktensor. """ A = dot(self.lmbda, khatrirao(tuple(self.U)).T) return A.reshape(self.shape)
def uttkrp(self, U, n): order = range(n) + range(n + 1, self.ndim) Z = khatrirao(tuple(U[i] for i in order), reverse=True) return self.unfold(n).dot(Z)