-
Notifications
You must be signed in to change notification settings - Fork 37
/
functions.py
87 lines (72 loc) · 2.21 KB
/
functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
import numpy as np
import pandas as pd
import tensorly.backend as T
import tensorly as tl
from tensorly.decomposition import tucker
from tensorly.base import unfold, fold
from tensorly.tenalg import multi_mode_dot, mode_dot
from tensorly.random import check_random_state
from scipy import linalg
from .svd import svd_fun
def svd_init(tensor, modes, ranks):
factors = []
for index, mode in enumerate(modes):
eigenvecs, _, _ = svd_fun(unfold(tensor, mode), n_eigenvecs=ranks[index])
factors.append(eigenvecs)
#print("factor mode: ", index)
return factors
def init(dims, ranks):
factors = []
for index, rank in enumerate(ranks):
U_i = np.zeros((rank, dims[index]))
mindim = min(dims[index], rank)
for i in range(mindim):
U_i[i][i] = 1
factors.append(U_i)
return factors
def autocorr(Y, lag=10):
"""
计算<Y(t), Y(t-0)>, ..., <Y(t), Y(t-lag)>
:param Y: list [tensor1, tensor2, ..., tensorT]
:param lag: int
:return: array(k+1)
"""
T = len(Y)
r = []
# print("Y")
# print(Y)
for l in range(lag+1):
product = 0
for t in range(T):
tl = l - t if t < l else t - l
product += np.sum(Y[t] * Y[tl])
r.append(product)
return r
def fit_ar(Y, p=10):
r = autocorr(Y, p)
#print("auto-corr:",r)
R = linalg.toeplitz(r[:p])
r = r[1:]
A = linalg.pinv(R).dot(r)
return A
def fit_ar_ma(Y,p=10,q=1):
#print("fit_ar_ma")
N = len(Y)
A = fit_ar(Y, p)
B = [0.]
if q>0:
Res = []
for i in range(p,N):
res = Y[i] - np.sum([ a * Y[i-j] for a, j in zip(A, range(1, p+1))], axis=0)
Res.append(res)
#Res = np.array(Res)
B = fit_ar(Res, q)
return A, B