import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import animation
# torch
import torch
import torch.nn.functional as F
from torch_geometric_temporal.nn.recurrent import GConvGRU
# scipy
from scipy.interpolate import interp1d
# utils
import time
import pickle
from tqdm import tqdm
# rpy2
import rpy2
import rpy2.robjects as ro
from rpy2.robjects.vectors import FloatVector
from rpy2.robjects.packages import importr
Class of Method(GNAR) lag 1
ST-GCN
GNAR fiveNet,fivenodes
import
class RecurrentGCN(torch.nn.Module):
def __init__(self, node_features, filters):
super(RecurrentGCN, self).__init__()
self.recurrent = GConvGRU(node_features, filters, 2)
self.linear = torch.nn.Linear(filters, 1)
def forward(self, x, edge_index, edge_weight):
= self.recurrent(x, edge_index, edge_weight)
h = F.relu(h)
h = self.linear(h)
h return h
my functions
def load_data(fname):
with open(fname, 'rb') as outfile:
= pickle.load(outfile)
data_dict return data_dict
def save_data(data_dict,fname):
with open(fname,'wb') as outfile:
pickle.dump(data_dict,outfile)
def plot(f,*args,t=None,h=2.5,**kwargs):
= f.shape
T,N if t == None: t = range(T)
= plt.figure()
fig = fig.subplots(N,1)
ax for n in range(N):
*args,**kwargs)
ax[n].plot(t,f[:,n],'node='+str(n))
ax[n].set_title(*h)
fig.set_figheight(N
fig.tight_layout()
plt.close()return fig
def plot_add(fig,f,*args,t=None,**kwargs):
= f.shape[0]
T = f.shape[1]
N if t == None: t = range(T)
= fig.get_axes()
ax for n in range(N):
*args,**kwargs)
ax[n].plot(t,f[:,n],return fig
def make_Psi(T):
= np.zeros((T,T))
W for i in range(T):
for j in range(T):
if i==j :
= 0
W[i,j] elif np.abs(i-j) <= 1 :
= 1
W[i,j] = np.array(W.sum(axis=1))
d = np.diag(d)
D = np.array(np.diag(1/np.sqrt(d)) @ (D-W) @ np.diag(1/np.sqrt(d)))
L = np.linalg.eigh(L)
lamb, Psi return Psi
= importr('EbayesThresh').ebayesthresh ebayesthresh
def trim(f):
= np.array(f)
f if len(f.shape)==1: f = f.reshape(-1,1)
= f.shape
T,N = make_Psi(T)
Psi = Psi.T @ f # apply dft
fbar = np.stack([ebayesthresh(FloatVector(fbar[:,i])) for i in range(N)],axis=1)
fbar_threshed = Psi @ fbar_threshed # inverse dft
fhat return fhat
def update_from_freq_domain(signal, missing_index):
= np.array(signal)
signal = signal.shape
T,N = trim(signal)
signal_trimed for i in range(N):
= signal_trimed[missing_index[i],i]
signal[missing_index[i],i] return signal
test myfunctions
-
read data
= load_data('./data/fivenodes.pkl') data
-
save data
#save_data(data, './data/fivenodes.pkl')
-
plot
=plot(data['f'],'--',color='C0')
fig fig
-
plot_add
=plot_add(fig,data['f'],'o',color='C1')
fig fig
-
trim
= np.linspace(0,10,1000)
t = np.stack([np.sin(2*t) + np.random.randn(1000), np.cos(4*t) + np.random.randn(1000)],axis=1)
f = plot(f, alpha=0.5)
fig = plot_add(fig, trim(f))
fig 'blue: observed, orange: trimed',size=14)
fig.suptitle(
fig.tight_layout() fig
data 정리
-
데이터정리
= torch.tensor(data['edges'])
edges_tensor = np.array(data['f'])
fiveVTS = edges_tensor.nonzero()
nonzero_indices = np.array(nonzero_indices).T
fiveNet_edge = 200
T = 5 # number of Nodes
N = fiveNet_edge
E = np.array([1,2,3,4,5])
V = np.arange(0,T)
t = 1
node_features = torch.tensor(E)
edge_index = torch.tensor(np.array([1,1,1,1,1,1,1,1,1,1]),dtype=torch.float32) edge_attr
-
train / test
= fiveVTS[:int(len(fiveVTS)*0.8)]
fiveVTS_train = fiveVTS[int(len(fiveVTS)*0.8):] fiveVTS_test
= plot(fiveVTS,'--.',color='gray')
fig = plot_add(fig,fiveVTS_train,'--o',label='train',color='C0')
fig = plot_add(fig,fiveVTS_test,'--o',label='test',color='C1',t=range(160,200))
fig = fig.get_axes()
ax for a in ax:
a.legend()10)
fig.set_figwidth( fig
Random Missing Values
class Missing:
def __init__(self,df):
self.df = df
self.N = N
self.number = []
def miss(self,percent=0.5):
self.missing = self.df.copy()
self.percent = percent
for i in range(self.N):
#self.seed = np.random.choice(1000,1,replace=False)
#np.random.seed(self.seed)
self.number.append(np.random.choice(int(len(self.df))-1,int(len(self.df)*self.percent),replace=False))
self.missing[self.number[i],i] = float('nan')
def first_mean(self):
self.train_mean = self.missing.copy()
for i in range(self.N):
self.train_mean[self.number[i],i] = np.nanmean(self.missing[:,i])
def second_linear(self):
self.train_linear = pd.DataFrame(self.missing)
self.train_linear.interpolate(method='linear', inplace=True)
self.train_linear = self.train_linear.fillna(0)
self.train_linear = np.array(self.train_linear).reshape(int(len(self.df)),N)
-
30% 결측치 발생
= Missing(fiveVTS_train)
_zero = 0.3) _zero.miss(percent
= plot(fiveVTS,'--o',color='gray',label='complete data',alpha=0.2)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'o',color='C0',label='observed')
a.plot(_zero.missing[:,i],'x',color='C1',label='missing')
a.plot(_zero.number[i],fiveVTS_train[:,i][_zero.number[i]],
a.legend()10)
fig.set_figwidth( fig
-
결측치를 평균으로 보간
_zero.first_mean()= plot(fiveVTS,'--o',color='gray',label='complete data',alpha=0.2)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'o',color='C0',label='observed')
a.plot(_zero.missing[:,i],'x',color='C1',label='missing')
a.plot(_zero.number[i],fiveVTS_train[:,i][_zero.number[i]],'-',color='red',label='padding mean')
a.plot(_zero.train_mean[:,i],
a.legend()15)
fig.set_figwidth( fig
-
결측치를 linear interpolation
_zero.second_linear()
= plot(fiveVTS,'--o',color='gray',label='complete data',alpha=0.2)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'o',color='C0',label='observed')
a.plot(_zero.missing[:,i],'x',color='C1',label='missing')
a.plot(_zero.number[i],fiveVTS_train[:,i][_zero.number[i]],'-',color='red',label='linear interpolation')
a.plot(_zero.train_linear[:,i],
a.legend()15)
fig.set_figwidth( fig
Enhencement of STGCN
시나리오1 (Baseline)
시나리오1
- missing rate: 0%
- 보간방법: None
STGCN 으로 적합 + 예측
= torch.tensor(fiveVTS_train).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(fiveVTS_train).reshape(int(T*0.8),N,1).float()[1:,:,:] y
= torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[:-1,:,:]).float()
XX = torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[1:,:,:]).float() yy
= RecurrentGCN(node_features=1, filters=4)
net = torch.optim.Adam(net.parameters(), lr=0.01)
optimizer
net.train()for epoch in tqdm(range(50)):
for time, (xt,yt) in enumerate(zip(X,y)):
= net(xt, edge_index, edge_attr)
yt_hat = torch.mean((yt_hat-yt)**2)
cost
cost.backward()
optimizer.step() optimizer.zero_grad()
100%|██████████| 50/50 [00:34<00:00, 1.43it/s]
= torch.stack([net(xt, edge_index, edge_attr) for xt in X]).detach().numpy()
yhat = torch.stack([net(xt, edge_index, edge_attr) for xt in XX]).detach().numpy() yyhat
= yhat.squeeze() # stgcn은 stgcn에 의한 적합결과를 의미함
stgcn_train = yyhat.squeeze() stgcn_test
= (((y-yhat).squeeze())**2).mean(axis=0)
train_mse_eachnode_stgcn = (((y-yhat).squeeze())**2).mean()
train_mse_total_stgcn = (((yy-yyhat).squeeze())**2).mean(axis=0)
test_mse_eachnode_stgcn = (((yy-yyhat).squeeze())**2).mean() test_mse_total_stgcn
GNAR 으로 적합 + 예측
-
%load_ext rpy2.ipython
The rpy2.ipython extension is already loaded. To reload it, use:
%reload_ext rpy2.ipython
%%R
library(GNAR)
library(igraph) library(tidyverse)
%R -i fiveVTS_train
%%R
<- GNARfit(vts = fiveVTS_train, net = fiveNet, alphaOrder = 1, betaOrder = c(1))
answer <- predict(answer,n.ahead=40) prediction
%%R
<- residuals(answer)
gnar_train <- prediction gnar_test
%R -o gnar_train
%R -o gnar_test
= (gnar_train**2).mean(axis=0)
train_mse_eachnode_gnar = (gnar_train**2).mean()
train_mse_total_gnar = ((fiveVTS_test - gnar_test.reshape(-1,5))**2).mean(axis=0)
test_mse_eachnode_gnar = ((fiveVTS_test - gnar_test.reshape(-1,5))**2).mean() test_mse_total_gnar
결과시각화
train_mse_total_gnar,test_mse_total_gnar
(0.9994323113693153, 1.2692101967317866)
= plot(fiveVTS,'--.',h=4,color='gray',label='complete data',alpha=0.5)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'node{0} \n mse(train) = {1:.2f}, mse(test) = {2:.2f} \n mse(train) = {3:.2f}, mse(test) = {4:.2f}'.format(i,train_mse_eachnode_stgcn[i],test_mse_eachnode_stgcn[i],train_mse_eachnode_gnar[i],test_mse_eachnode_gnar[i]))
a.set_title(range(1,160),stgcn_train[:,i],label='STCGCN (train)',color='C0')
a.plot(range(160,199),stgcn_test[:,i],label='STCGCN (test)',color='C0')
a.plot(range(1,160),gnar_train.reshape(-1,5)[:,i],label='GNAR (train)',color='C1')
a.plot(range(161,201),gnar_test.reshape(-1,5)[:,i],label='GNAR (test)',color='C1')
a.plot(
a.legend()14)
fig.set_figwidth("Scenario1: STGCN \n missing=0% \n interpolation=None \n\n STGCN: mse(train) = {0:.2f}, mse(test) = {1:.2f} \n GNAR: mse(train) = {2:.2f}, mse(test) = {3:.2f} \n".format(train_mse_total_stgcn,test_mse_total_stgcn,train_mse_total_gnar,test_mse_total_gnar),size=15)
fig.suptitle(
fig.tight_layout() fig
시나리오2
시나리오2
- missing rate: 50%
- 보간방법: linear
-
결측치생성 + 보간
= Missing(fiveVTS_train)
_zero = 0.5)
_zero.miss(percent _zero.second_linear()
= _zero.number
missing_index = _zero.train_linear interpolated_signal
= plot(fiveVTS,'--o',h=4,color='gray',label='complete data',alpha=0.2)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'xk',label='missing')
a.plot(missing_index[i],fiveVTS_train[:,i][missing_index[i]],'-',color='gray',label='linear interpolation')
a.plot(interpolated_signal[:,i],
a.legend()15)
fig.set_figwidth( fig
STGCN 으로 적합 + 예측
= torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[1:,:,:] y
= torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[:-1,:,:]).float()
XX = torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[1:,:,:]).float() yy
= RecurrentGCN(node_features=1, filters=4)
net = torch.optim.Adam(net.parameters(), lr=0.01)
optimizer
net.train()for epoch in tqdm(range(50)):
for time, (xt,yt) in enumerate(zip(X,y)):
= net(xt, edge_index, edge_attr)
yt_hat = torch.mean((yt_hat-yt)**2)
cost
cost.backward()
optimizer.step() optimizer.zero_grad()
100%|██████████| 50/50 [00:35<00:00, 1.41it/s]
= torch.stack([net(xt, edge_index, edge_attr) for xt in X]).detach().numpy()
yhat = torch.stack([net(xt, edge_index, edge_attr) for xt in XX]).detach().numpy() yyhat
= torch.tensor(fiveVTS_train).reshape(int(T*0.8),N,1).float()[1:,:,:]
real_y
= (((real_y-yhat).squeeze())**2).mean(axis=0)
train_mse_eachnode_stgcn = (((real_y-yhat).squeeze())**2).mean()
train_mse_total_stgcn = (((yy-yyhat).squeeze())**2).mean(axis=0)
test_mse_eachnode_stgcn = (((yy-yyhat).squeeze())**2).mean() test_mse_total_stgcn
= yhat.squeeze() # stgcn은 stgcn에 의한 적합결과를 의미함
stgcn_train = yyhat.squeeze() stgcn_test
ESTGCN 으로 적합 + 예측
= torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[1:,:,:] y
= torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[:-1,:,:]).float()
XX = torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[1:,:,:]).float() yy
-
ESTGCN
= RecurrentGCN(node_features=1, filters=4)
net = torch.optim.Adam(net.parameters(), lr=0.01)
optimizer
net.train()= interpolated_signal.copy()
signal for epoch in tqdm(range(50)):
= update_from_freq_domain(signal,missing_index)
signal = torch.tensor(signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(signal).reshape(int(T*0.8),N,1).float()[1:,:,:]
y for time, (xt,yt) in enumerate(zip(X,y)):
= net(xt, edge_index, edge_attr)
yt_hat = torch.mean((yt_hat-yt)**2)
cost
cost.backward()
optimizer.step()
optimizer.zero_grad()= torch.concat([X.squeeze(),yt_hat.detach().squeeze().reshape(1,-1)]) signal
100%|██████████| 50/50 [00:37<00:00, 1.33it/s]
= torch.stack([net(xt, edge_index, edge_attr) for xt in X]).detach().numpy()
yhat = torch.stack([net(xt, edge_index, edge_attr) for xt in XX]).detach().numpy() yyhat
= torch.tensor(fiveVTS_train).reshape(int(T*0.8),N,1).float()[1:,:,:]
real_y
= (((real_y-yhat).squeeze())**2).mean(axis=0)
train_mse_eachnode_estgcn = (((real_y-yhat).squeeze())**2).mean()
train_mse_total_estgcn = (((yy-yyhat).squeeze())**2).mean(axis=0)
test_mse_eachnode_estgcn = (((yy-yyhat).squeeze())**2).mean() test_mse_total_estgcn
= yhat.squeeze() # stgcn은 stgcn에 의한 적합결과를 의미함
estgcn_train = yyhat.squeeze() estgcn_test
GNAR 으로 적합 + 예측
-
= np.array(X).squeeze()
X_train1 = np.array(XX).squeeze() X_test1
%R -i X_train1
%%R
<- GNARfit(vts = X_train1, net = fiveNet, alphaOrder = 1, betaOrder = c(1))
answer <- predict(answer,n.ahead=40) prediction
%%R
<- residuals(answer)
gnar_train <- prediction gnar_test
%R -o gnar_train
%R -o gnar_test
= (gnar_train**2).mean(axis=0)
train_mse_eachnode_gnar = (gnar_train**2).mean()
train_mse_total_gnar = ((X_test1 - gnar_test[1:,:])**2).mean(axis=0)
test_mse_eachnode_gnar = ((X_test1 - gnar_test[1:,:])**2).mean() test_mse_total_gnar
결과시각화
train_mse_total_gnar,test_mse_total_gnar
(0.7473098322871093, 1.3231643342748722)
= plot(fiveVTS,'--.',h=4,color='gray',label='complete data',alpha=0.5)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'node{0} \n STGCN: mse(train) = {1:.2f}, mse(test) = {2:.2f} \n ESTGCN: mse(train) = {3:.2f}, mse(test) = {4:.2f}\n GNAR: mse(train) = {5:.2f}, mse(test) = {6:.2f}'.format(i,train_mse_eachnode_stgcn[i],test_mse_eachnode_stgcn[i],train_mse_eachnode_estgcn[i],test_mse_eachnode_estgcn[i],train_mse_eachnode_gnar[i],test_mse_eachnode_gnar[i]))
a.set_title('xk',label='missing')
a.plot(missing_index[i],fiveVTS_train[:,i][missing_index[i]],'-',color='gray',label='linear interpolation')
a.plot(interpolated_signal[:,i],range(1,160),stgcn_train.squeeze()[:,i],'--.',label='STCGCN (train)',color='C0')
a.plot(range(160,199),stgcn_test.squeeze()[:,i],'--.',label='STCGCN (test)',color='C0')
a.plot(range(1,160),estgcn_train.squeeze()[:,i],label='ESTCGCN (train)',color='C1')
a.plot(range(161,200),estgcn_test.squeeze()[:,i],label='ESTCGCN (test)',color='C1')
a.plot(range(1,159),gnar_train[:,i],label='GNAR (train)',color='C2')
a.plot(range(161,201),gnar_test[:,i],label='GNAR (test)',color='C2')
a.plot(
a.legend()14)
fig.set_figwidth("Scenario2: \n missing=50% \n interpolation=linear \n\n STGCN: mse(train) = {0:.2f}, mse(test) = {1:.2f} \n ESTGCN: mse(train) = {2:.2f}, mse(test) = {3:.2f} \n GNAR: mse(train) = {4:.2f}, mse(test) = {5:.2f} \n".format(train_mse_total_stgcn,test_mse_total_stgcn,train_mse_total_estgcn,test_mse_total_estgcn,train_mse_total_gnar,test_mse_total_gnar),size=15)
fig.suptitle(
fig.tight_layout() fig
시나리오3
시나리오3
- missing rate: 80%
- 보간방법: linear
-
결측치생성 + 보간
= Missing(fiveVTS_train)
_zero = 0.8)
_zero.miss(percent _zero.second_linear()
= _zero.number
missing_index = _zero.train_linear interpolated_signal
= plot(fiveVTS,'--o',h=4,color='gray',label='complete data',alpha=0.2)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'xk',label='missing')
a.plot(missing_index[i],fiveVTS_train[:,i][missing_index[i]],'-',color='gray',label='linear interpolation')
a.plot(interpolated_signal[:,i],
a.legend()15)
fig.set_figwidth( fig
STGCN 으로 적합 + 예측
= torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[1:,:,:] y
= torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[:-1,:,:]).float()
XX = torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[1:,:,:]).float() yy
= RecurrentGCN(node_features=1, filters=4)
net = torch.optim.Adam(net.parameters(), lr=0.01)
optimizer
net.train()for epoch in tqdm(range(50)):
for time, (xt,yt) in enumerate(zip(X,y)):
= net(xt, edge_index, edge_attr)
yt_hat = torch.mean((yt_hat-yt)**2)
cost
cost.backward()
optimizer.step() optimizer.zero_grad()
100%|██████████| 50/50 [00:35<00:00, 1.39it/s]
= torch.stack([net(xt, edge_index, edge_attr) for xt in X]).detach().numpy()
yhat = torch.stack([net(xt, edge_index, edge_attr) for xt in XX]).detach().numpy() yyhat
= torch.tensor(fiveVTS_train).reshape(int(T*0.8),N,1).float()[1:,:,:]
real_y
= (((real_y-yhat).squeeze())**2).mean(axis=0)
train_mse_eachnode_stgcn = (((real_y-yhat).squeeze())**2).mean()
train_mse_total_stgcn = (((yy-yyhat).squeeze())**2).mean(axis=0)
test_mse_eachnode_stgcn = (((yy-yyhat).squeeze())**2).mean() test_mse_total_stgcn
= yhat.squeeze() # stgcn은 stgcn에 의한 적합결과를 의미함
stgcn_train = yyhat.squeeze() stgcn_test
ESTGCN 으로 적합 + 예측
= torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[1:,:,:] y
= torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[:-1,:,:]).float()
XX = torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[1:,:,:]).float() yy
-
ESTGCN
= RecurrentGCN(node_features=1, filters=4)
net = torch.optim.Adam(net.parameters(), lr=0.01)
optimizer
net.train()= interpolated_signal.copy()
signal for epoch in tqdm(range(50)):
= update_from_freq_domain(signal,missing_index)
signal = torch.tensor(signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(signal).reshape(int(T*0.8),N,1).float()[1:,:,:]
y for time, (xt,yt) in enumerate(zip(X,y)):
= net(xt, edge_index, edge_attr)
yt_hat = torch.mean((yt_hat-yt)**2)
cost
cost.backward()
optimizer.step()
optimizer.zero_grad()= torch.concat([X.squeeze(),yt_hat.detach().squeeze().reshape(1,-1)]) signal
100%|██████████| 50/50 [00:37<00:00, 1.33it/s]
= torch.stack([net(xt, edge_index, edge_attr) for xt in X]).detach().numpy()
yhat = torch.stack([net(xt, edge_index, edge_attr) for xt in XX]).detach().numpy() yyhat
= torch.tensor(fiveVTS_train).reshape(int(T*0.8),N,1).float()[1:,:,:]
real_y
= (((real_y-yhat).squeeze())**2).mean(axis=0)
train_mse_eachnode_estgcn = (((real_y-yhat).squeeze())**2).mean()
train_mse_total_estgcn = (((yy-yyhat).squeeze())**2).mean(axis=0)
test_mse_eachnode_estgcn = (((yy-yyhat).squeeze())**2).mean() test_mse_total_estgcn
= yhat.squeeze() # stgcn은 stgcn에 의한 적합결과를 의미함
estgcn_train = yyhat.squeeze() estgcn_test
GNAR 으로 적합 + 예측
-
= np.array(X).squeeze()
X_train1 = np.array(XX).squeeze() X_test1
%R -i X_train1
%%R
<- GNARfit(vts = X_train1, net = fiveNet, alphaOrder = 1, betaOrder = c(1))
answer <- predict(answer,n.ahead=40) prediction
%%R
<- residuals(answer)
gnar_train <- prediction gnar_test
%R -o gnar_train
%R -o gnar_test
= (gnar_train**2).mean(axis=0)
train_mse_eachnode_gnar = (gnar_train**2).mean()
train_mse_total_gnar = ((X_test1 - gnar_test[1:,:])**2).mean(axis=0)
test_mse_eachnode_gnar = ((X_test1 - gnar_test[1:,:])**2).mean() test_mse_total_gnar
결과시각화
train_mse_total_gnar,test_mse_total_gnar
(0.38358787816283946, 1.3239931193379793)
= plot(fiveVTS,'--.',h=4,color='gray',label='complete data',alpha=0.5)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'node{0} \n STGCN: mse(train) = {1:.2f}, mse(test) = {2:.2f} \n ESTGCN: mse(train) = {3:.2f}, mse(test) = {4:.2f}\n GNAR: mse(train) = {5:.2f}, mse(test) = {6:.2f}'.format(i,train_mse_eachnode_stgcn[i],test_mse_eachnode_stgcn[i],train_mse_eachnode_estgcn[i],test_mse_eachnode_estgcn[i],train_mse_eachnode_gnar[i],test_mse_eachnode_gnar[i]))
a.set_title('xk',label='missing')
a.plot(missing_index[i],fiveVTS_train[:,i][missing_index[i]],'-',color='gray',label='linear interpolation')
a.plot(interpolated_signal[:,i],range(1,160),stgcn_train.squeeze()[:,i],'--.',label='STCGCN (train)',color='C0')
a.plot(range(160,199),stgcn_test.squeeze()[:,i],'--.',label='STCGCN (test)',color='C0')
a.plot(range(1,160),estgcn_train.squeeze()[:,i],label='ESTCGCN (train)',color='C1')
a.plot(range(161,200),estgcn_test.squeeze()[:,i],label='ESTCGCN (test)',color='C1')
a.plot(range(1,159),gnar_train[:,i],label='GNAR (train)',color='C2')
a.plot(range(161,201),gnar_test[:,i],label='GNAR (test)',color='C2')
a.plot(
a.legend()14)
fig.set_figwidth("Scenario3: \n missing=80% \n interpolation=linear \n\n STGCN: mse(train) = {0:.2f}, mse(test) = {1:.2f} \n ESTGCN: mse(train) = {2:.2f}, mse(test) = {3:.2f} \n GNAR: mse(train) = {4:.2f}, mse(test) = {5:.2f} \n".format(train_mse_total_stgcn,test_mse_total_stgcn,train_mse_total_estgcn,test_mse_total_estgcn,train_mse_total_gnar,test_mse_total_gnar),size=15)
fig.suptitle(
fig.tight_layout() fig
시나리오4
시나리오4
- missing rate: 30%
- 보간방법: linear
-
결측치생성 + 보간
= Missing(fiveVTS_train)
_zero = 0.3)
_zero.miss(percent _zero.second_linear()
= _zero.number
missing_index = _zero.train_linear interpolated_signal
= plot(fiveVTS,'--o',h=4,color='gray',label='complete data',alpha=0.2)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'xk',label='missing')
a.plot(missing_index[i],fiveVTS_train[:,i][missing_index[i]],'-',color='gray',label='linear interpolation')
a.plot(interpolated_signal[:,i],
a.legend()15)
fig.set_figwidth( fig
STGCN 으로 적합 + 예측
= torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[1:,:,:] y
= torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[:-1,:,:]).float()
XX = torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[1:,:,:]).float() yy
= RecurrentGCN(node_features=1, filters=4)
net = torch.optim.Adam(net.parameters(), lr=0.01)
optimizer
net.train()for epoch in tqdm(range(50)):
for time, (xt,yt) in enumerate(zip(X,y)):
= net(xt, edge_index, edge_attr)
yt_hat = torch.mean((yt_hat-yt)**2)
cost
cost.backward()
optimizer.step() optimizer.zero_grad()
100%|██████████| 50/50 [00:27<00:00, 1.85it/s]
= torch.stack([net(xt, edge_index, edge_attr) for xt in X]).detach().numpy()
yhat = torch.stack([net(xt, edge_index, edge_attr) for xt in XX]).detach().numpy() yyhat
= torch.tensor(fiveVTS_train).reshape(int(T*0.8),N,1).float()[1:,:,:]
real_y
= (((real_y-yhat).squeeze())**2).mean(axis=0)
train_mse_eachnode_stgcn = (((real_y-yhat).squeeze())**2).mean()
train_mse_total_stgcn = (((yy-yyhat).squeeze())**2).mean(axis=0)
test_mse_eachnode_stgcn = (((yy-yyhat).squeeze())**2).mean() test_mse_total_stgcn
= yhat.squeeze() # stgcn은 stgcn에 의한 적합결과를 의미함
stgcn_train = yyhat.squeeze() stgcn_test
ESTGCN 으로 적합 + 예측
= torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(interpolated_signal).reshape(int(T*0.8),N,1).float()[1:,:,:] y
= torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[:-1,:,:]).float()
XX = torch.tensor(fiveVTS_test.reshape(int(T*0.2),N,1)[1:,:,:]).float() yy
-
ESTGCN
= RecurrentGCN(node_features=1, filters=4)
net = torch.optim.Adam(net.parameters(), lr=0.01)
optimizer
net.train()= interpolated_signal.copy()
signal for epoch in tqdm(range(50)):
= update_from_freq_domain(signal,missing_index)
signal = torch.tensor(signal).reshape(int(T*0.8),N,1).float()[:int(T*0.8-1),:,:]
X = torch.tensor(signal).reshape(int(T*0.8),N,1).float()[1:,:,:]
y for time, (xt,yt) in enumerate(zip(X,y)):
= net(xt, edge_index, edge_attr)
yt_hat = torch.mean((yt_hat-yt)**2)
cost
cost.backward()
optimizer.step()
optimizer.zero_grad()= torch.concat([X.squeeze(),yt_hat.detach().squeeze().reshape(1,-1)]) signal
100%|██████████| 50/50 [00:27<00:00, 1.79it/s]
= torch.stack([net(xt, edge_index, edge_attr) for xt in X]).detach().numpy()
yhat = torch.stack([net(xt, edge_index, edge_attr) for xt in XX]).detach().numpy() yyhat
= torch.tensor(fiveVTS_train).reshape(int(T*0.8),N,1).float()[1:,:,:]
real_y
= (((real_y-yhat).squeeze())**2).mean(axis=0)
train_mse_eachnode_estgcn = (((real_y-yhat).squeeze())**2).mean()
train_mse_total_estgcn = (((yy-yyhat).squeeze())**2).mean(axis=0)
test_mse_eachnode_estgcn = (((yy-yyhat).squeeze())**2).mean() test_mse_total_estgcn
= yhat.squeeze() # stgcn은 stgcn에 의한 적합결과를 의미함
estgcn_train = yyhat.squeeze() estgcn_test
GNAR 으로 적합 + 예측
-
= np.array(X).squeeze()
X_train1 = np.array(XX).squeeze() X_test1
%R -i X_train1
%%R
<- GNARfit(vts = X_train1, net = fiveNet, alphaOrder = 1, betaOrder = c(1))
answer <- predict(answer,n.ahead=40) prediction
%%R
<- residuals(answer)
gnar_train <- prediction gnar_test
%R -o gnar_train
%R -o gnar_test
= (gnar_train**2).mean(axis=0)
train_mse_eachnode_gnar = (gnar_train**2).mean()
train_mse_total_gnar = ((X_test1 - gnar_test[1:,:])**2).mean(axis=0)
test_mse_eachnode_gnar = ((X_test1 - gnar_test[1:,:])**2).mean() test_mse_total_gnar
결과시각화
train_mse_total_gnar,test_mse_total_gnar
(0.7978462123549198, 1.3146463350699074)
= plot(fiveVTS,'--.',h=4,color='gray',label='complete data',alpha=0.5)
fig = fig.get_axes()
ax for i,a in enumerate(ax):
'node{0} \n STGCN: mse(train) = {1:.2f}, mse(test) = {2:.2f} \n ESTGCN: mse(train) = {3:.2f}, mse(test) = {4:.2f}\n GNAR: mse(train) = {5:.2f}, mse(test) = {6:.2f}'.format(i,train_mse_eachnode_stgcn[i],test_mse_eachnode_stgcn[i],train_mse_eachnode_estgcn[i],test_mse_eachnode_estgcn[i],train_mse_eachnode_gnar[i],test_mse_eachnode_gnar[i]))
a.set_title('xk',label='missing')
a.plot(missing_index[i],fiveVTS_train[:,i][missing_index[i]],'-',color='gray',label='linear interpolation')
a.plot(interpolated_signal[:,i],range(1,160),stgcn_train.squeeze()[:,i],'--.',label='STCGCN (train)',color='C0')
a.plot(range(160,199),stgcn_test.squeeze()[:,i],'--.',label='STCGCN (test)',color='C0')
a.plot(range(1,160),estgcn_train.squeeze()[:,i],label='ESTCGCN (train)',color='C1')
a.plot(range(161,200),estgcn_test.squeeze()[:,i],label='ESTCGCN (test)',color='C1')
a.plot(range(1,159),gnar_train[:,i],label='GNAR (train)',color='C2')
a.plot(range(160,200),gnar_test[:,i],label='GNAR (test)',color='C2')
a.plot(
a.legend()14)
fig.set_figwidth("Scenario3: \n missing=80% \n interpolation=linear \n\n STGCN: mse(train) = {0:.2f}, mse(test) = {1:.2f} \n ESTGCN: mse(train) = {2:.2f}, mse(test) = {3:.2f} \n GNAR: mse(train) = {4:.2f}, mse(test) = {5:.2f} \n".format(train_mse_total_stgcn,test_mse_total_stgcn,train_mse_total_estgcn,test_mse_total_estgcn,train_mse_total_gnar,test_mse_total_gnar),size=15)
fig.suptitle(
fig.tight_layout() fig