id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
13,415
import sys import bpy from os.path import join import math import numpy as np from mathutils import Matrix, Vector, Quaternion, Euler import os import json def init_location(cam, theta, r): # Originally, theta is negtivate # the center of circle coord is (-1, 0), r is np.random.normal(8, 1) x, z = (math.co...
null
13,416
import sys import bpy from os.path import join import math import numpy as np from mathutils import Matrix, Vector, Quaternion, Euler def deg2rad(angle): return -np.pi * (angle + 90) / 180. import os import json The provided code snippet includes necessary dependencies for implementing the `init_scene` function. W...
cam_ob.matrix_world = Matrix(((0., 0., 1, params['camera_distance']+dis), (0., -1, 0., -1.0), (-1., 0., 0., 0.), (0.0, 0.0, 0.0, 1.0)))
13,417
import sys import bpy from os.path import join import math import numpy as np from mathutils import Matrix, Vector, Quaternion, Euler import os import json def setState0(): for ob in bpy.data.objects.values(): ob.select = False bpy.context.scene.objects.active = None
null
13,418
import sys import bpy from os.path import join import math import numpy as np from mathutils import Matrix, Vector, Quaternion, Euler part_match = {'root': 'root', 'bone_00': 'Pelvis', 'bone_01': 'L_Hip', 'bone_02': 'R_Hip', 'bone_03': 'Spine1', 'bone_04': 'L_Knee', 'bone_05': 'R_Knee', 'bone_06': 'Spine2...
null
13,419
import sys import bpy from os.path import join import math import numpy as np from mathutils import Matrix, Vector, Quaternion, Euler import os import json def load_motions(path): from glob import glob filenames = sorted(glob(join(path, '*.json'))) print(filenames) motions = {} # for filename in fil...
null
13,420
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner, transfer_weights from src.callback.tracking import * from src.callback.patch_mask import * from src.callback.transforms import * from src.metrics import * from src...
null
13,421
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner, transfer_weights from src.callback.tracking import * from src.callback.patch_mask import * from src.callback.transforms import * from src.metrics import * from src...
null
13,422
import torch from torch import nn from .core import Callback The provided code snippet includes necessary dependencies for implementing the `create_patch` function. Write a Python function `def create_patch(xb, patch_len, stride)` to solve the following problem: xb: [bs x seq_len x n_vars] Here is the function: def ...
xb: [bs x seq_len x n_vars]
13,423
import torch from torch import nn from .core import Callback def random_masking(xb, mask_ratio): # xb: [bs x num_patch x n_vars x patch_len] bs, L, nvars, D = xb.shape x = xb.clone() len_keep = int(L * (1 - mask_ratio)) noise = torch.rand(bs, L, nvars,device=xb.device) # noise in [0,...
null
13,424
import torch from torch import nn from .core import Callback def random_masking_3D(xb, mask_ratio): # xb: [bs x num_patch x dim] bs, L, D = xb.shape x = xb.clone() len_keep = int(L * (1 - mask_ratio)) noise = torch.rand(bs, L, device=xb.device) # noise in [0, 1], bs x L ...
null
13,425
from cmath import inf from ..basics import * from .core import Callback from torch.optim import lr_scheduler from torch.optim.lr_scheduler import _LRScheduler The provided code snippet includes necessary dependencies for implementing the `valley` function. Write a Python function `def valley(lrs:list, losses:list)` t...
Suggests a learning rate from the longest valley and returns its index
13,426
from torch import nn import collections from collections import OrderedDict import torch import os from datetime import timedelta def init_ddp(): local_rank = int(os.environ.get('LOCAL_RANK')) world_size = int(os.environ.get('WORLD_SIZE')) rank = int(os.environ.get('RANK')) torch.cuda.set_device(local...
null
13,427
import os import numpy as np import pandas as pd import os import torch from torch.utils.data import Dataset, DataLoader from sklearn.preprocessing import StandardScaler from src.data.timefeatures import time_features import warnings def _torch(*dfs): return tuple(torch.from_numpy(x).float() for x in dfs)
null
13,428
from typing import List import numpy as np import pandas as pd from pandas.tseries import offsets from pandas.tseries.frequencies import to_offset def time_features_from_frequency_str(freq_str: str) -> List[TimeFeature]: """ Returns a list of time features that will be appropriate for the given frequency string...
null
13,429
from typing import List import torch from torch.optim import Adam from torch import nn from torch.nn.parallel import DistributedDataParallel from .basics import * from .callback.core import * from .callback.tracking import * from .callback.scheduler import * from .callback.distributed import * from .utils import * fr...
Save `model` to `file` along with `opt` (if available, and if `with_opt`)
13,430
from typing import List import torch from torch.optim import Adam from torch import nn from torch.nn.parallel import DistributedDataParallel from .basics import * from .callback.core import * from .callback.tracking import * from .callback.scheduler import * from .callback.distributed import * from .utils import * fr...
load the saved model
13,431
from typing import List import torch from torch.optim import Adam from torch import nn from torch.nn.parallel import DistributedDataParallel from .basics import * from .callback.core import * from .callback.tracking import * from .callback.scheduler import * from .callback.distributed import * from .utils import * fr...
Return `path/file` if file is a string or a `Path`, file otherwise
13,432
from typing import List import torch from torch.optim import Adam from torch import nn from torch.nn.parallel import DistributedDataParallel from .basics import * from .callback.core import * from .callback.tracking import * from .callback.scheduler import * from .callback.distributed import * from .utils import * fr...
null
13,433
from typing import List import torch from torch.optim import Adam from torch import nn from torch.nn.parallel import DistributedDataParallel from .basics import * from .callback.core import * from .callback.tracking import * from .callback.scheduler import * from .callback.distributed import * from .utils import * fr...
null
13,434
from typing import List import torch from torch.optim import Adam from torch import nn from torch.nn.parallel import DistributedDataParallel from .basics import * from .callback.core import * from .callback.tracking import * from .callback.scheduler import * from .callback.distributed import * from .utils import * fr...
layers is a list of module names
13,435
import torch import collections from collections import OrderedDict def set_device(usage=5): "set the device that has usage < default usage " device_ids = get_available_cuda(usage=usage) torch.cuda.set_device(device_ids[0]) # get the first available device def get_available_cuda(usage=10): if not...
Return or set default device; `use_cuda`: None - CUDA if available; True - error if not available; False - CPU
13,436
import torch import collections from collections import OrderedDict def default_device(use_cuda=True): "Return or set default device; `use_cuda`: None - CUDA if available; True - error if not available; False - CPU" if not torch.cuda.is_available(): use_cuda = False return torch.device(torch.cuda.cu...
Recursively put `b` on `device` components of b are torch tensors
13,437
import torch import collections from collections import OrderedDict The provided code snippet includes necessary dependencies for implementing the `to_numpy` function. Write a Python function `def to_numpy(b)` to solve the following problem: Components of b are torch tensors Here is the function: def to_numpy(b): ...
Components of b are torch tensors
13,438
import torch from torch import nn import math def PositionalEncoding(q_len, d_model, normalize=True): pe = torch.zeros(q_len, d_model) position = torch.arange(0, q_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_...
null
13,439
import torch from torch import nn The provided code snippet includes necessary dependencies for implementing the `sigmoid_range` function. Write a Python function `def sigmoid_range(x, low, high)` to solve the following problem: Sigmoid function with range `(low, high)` Here is the function: def sigmoid_range(x, low...
Sigmoid function with range `(low, high)`
13,440
import torch from torch import nn def get_activation_fn(activation): if callable(activation): return activation() elif activation.lower() == "relu": return nn.ReLU() elif activation.lower() == "gelu": return nn.GELU() raise ValueError(f'{activation} is not available. You can use "relu", "gelu", or a ca...
null
13,441
import torch from torch import Tensor import torch.nn.functional as F def mse(y_true, y_pred): return F.mse_loss(y_true, y_pred, reduction='mean')
null
13,442
import torch from torch import Tensor import torch.nn.functional as F def rmse(y_true, y_pred): return torch.sqrt(F.mse_loss(y_true, y_pred, reduction='mean'))
null
13,443
import torch from torch import Tensor import torch.nn.functional as F def mae(y_true, y_pred): return F.l1_loss(y_true, y_pred, reduction='mean')
null
13,444
import torch from torch import Tensor import torch.nn.functional as F def r2_score(y_true, y_pred): from sklearn.metrics import r2_score return r2_score(y_true, y_pred)
null
13,445
import torch from torch import Tensor import torch.nn.functional as F def mape(y_true, y_pred): from sklearn.metrics import mean_absolute_percentage_error return mean_absolute_percentage_error(y_true, y_pred)
null
13,446
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner, transfer_weights from src.callback.core import * from src.callback.tracking import * from src.callback.patch_mask import * from src.callback.transforms import * fr...
null
13,447
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner, transfer_weights from src.callback.core import * from src.callback.tracking import * from src.callback.patch_mask import * from src.callback.transforms import * fr...
null
13,448
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner, transfer_weights from src.callback.core import * from src.callback.tracking import * from src.callback.patch_mask import * from src.callback.transforms import * fr...
null
13,449
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner, transfer_weights from src.callback.core import * from src.callback.tracking import * from src.callback.patch_mask import * from src.callback.transforms import * fr...
null
13,450
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner from src.callback.core import * from src.callback.tracking import * from src.callback.scheduler import * from src.callback.patch_mask import * from src.callback.tra...
null
13,451
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner from src.callback.core import * from src.callback.tracking import * from src.callback.scheduler import * from src.callback.patch_mask import * from src.callback.tra...
null
13,452
import numpy as np import pandas as pd import os import torch from torch import nn from src.models.patchTST import PatchTST from src.learner import Learner from src.callback.core import * from src.callback.tracking import * from src.callback.scheduler import * from src.callback.patch_mask import * from src.callback.tra...
null
13,453
import torch from torch import nn import math def get_activation_fn(activation): if callable(activation): return activation() elif activation.lower() == "relu": return nn.ReLU() elif activation.lower() == "gelu": return nn.GELU() raise ValueError(f'{activation} is not available. You can use "relu", "ge...
null
13,454
import torch from torch import nn import math def PositionalEncoding(q_len, d_model, normalize=True): pe = torch.zeros(q_len, d_model) position = torch.arange(0, q_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_...
null
13,455
import argparse import numpy as np import time import torch import torch.optim as optim import pyraformer.Pyraformer_LR as Pyraformer from tqdm import tqdm from data_loader import * from utils.tools import TopkMSELoss, metric The provided code snippet includes necessary dependencies for implementing the `dataset_param...
Prepare specific parameters for different datasets
13,456
import argparse import numpy as np import time import torch import torch.optim as optim import pyraformer.Pyraformer_LR as Pyraformer from tqdm import tqdm from data_loader import * from utils.tools import TopkMSELoss, metric def prepare_dataloader(args): """ Load data and prepare dataloader. """ data_dict = { ...
Evaluate preptrained models
13,457
import argparse import numpy as np import time import torch import torch.optim as optim import pyraformer.Pyraformer_LR as Pyraformer from tqdm import tqdm from data_loader import * from utils.tools import TopkMSELoss, metric def parse_args(): parser = argparse.ArgumentParser() # running mode parser.add_a...
null
13,458
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datetime import datetime, timedelta import pandas as pd import math import numpy as np import random from tqdm import trange from io import BytesIO from urllib.request import urlopen from zipfile ...
Divide the training sequence into windows
13,459
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datetime import datetime, timedelta import pandas as pd import math import numpy as np import random from tqdm import trange from io import BytesIO from urllib.request import urlopen from zipfile ...
Get covariates
13,460
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datetime import datetime, timedelta import pandas as pd import math import numpy as np import random from tqdm import trange from io import BytesIO from urllib.request import urlopen from zipfile ...
null
13,461
from numpy.lib.npyio import save import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from tqdm import trange import zipfile def load_data(filedir): data_frame = pd.read_csv(filedir, header=0, parse_dates=True) #names=['app_name', 'zone', 'time', 'value'] data_frame = data_frame.dr...
null
13,462
from numpy.lib.npyio import save import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from tqdm import trange import zipfile def visualize(data, index, save_dir): os.makedirs(save_dir, exist_ok=True) for i in range(index): x = np.arange(len(data[i])) f = plt.figure()...
null
13,463
from numpy.lib.npyio import save import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from tqdm import trange import zipfile def normalize(inputs, seq_length): base_seq = inputs[:, :(seq_length-1), 0] nonzeros = (base_seq > 0).sum(1) v = base_seq.sum(1) / nonzeros v[v == 0] =...
Divide the training sequence into windows
13,464
from numpy.lib.npyio import save import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from tqdm import trange import zipfile def dezip(filedir): zip_file = zipfile.ZipFile(filedir) zip_list = zip_file.namelist() parent_dir = filedir.split('/')[0] for f in zip_list: ...
null
13,465
import numpy as np import matplotlib.pyplot as plt from fbm import FBM The provided code snippet includes necessary dependencies for implementing the `fractional_brownian_noise` function. Write a Python function `def fractional_brownian_noise(length, hurst, step)` to solve the following problem: Genereate fractional b...
Genereate fractional brownian noise
13,466
import numpy as np import matplotlib.pyplot as plt from fbm import FBM def generate_sin(x, T, A): """Generate a mixed sinusoidal sequence""" y = np.zeros(len(x)) for i in range(len(T)): y += A[i] * np.sin(2 * np.pi / T[i] * x) return y def gen_covariates(x, index): """Generate covariates""" ...
synthesis a mixed sinusoidal dataset
13,467
import numpy as np import matplotlib.pyplot as plt from fbm import FBM def covariance(data): """compute the covariance of the data""" data_mean = data.mean(0) data = data - data_mean length = data.shape[1] data_covariance = np.zeros((length, length)) for i in range(length): for j in rang...
Plot the covariance of the generated fractional brownian noise
13,468
import os import pandas as pd from torch.utils.data import Dataset, DataLoader from utils.tools import StandardScaler from utils.timefeatures import time_features import numpy as np import torch import warnings The provided code snippet includes necessary dependencies for implementing the `get_all_v` function. Write a...
Get the normalization parameters of each sequence
13,469
import os import pandas as pd from torch.utils.data import Dataset, DataLoader from utils.tools import StandardScaler from utils.timefeatures import time_features import numpy as np import torch import warnings def gen_covariates(times, num_covariates): """Get covariates""" covariates = np.zeros((times.shape[0]...
preprocess the elect dataset for long range forecasting
13,470
import os import pandas as pd from torch.utils.data import Dataset, DataLoader from utils.tools import StandardScaler from utils.timefeatures import time_features import numpy as np import torch import warnings The provided code snippet includes necessary dependencies for implementing the `preprocess_flow` function. W...
preprocess the app flow dataset for long range forecasting
13,471
import os import pandas as pd from torch.utils.data import Dataset, DataLoader from utils.tools import StandardScaler from utils.timefeatures import time_features import numpy as np import torch import warnings def split(split_start, label, cov, pred_length): all_data = [] for batch_idx in range(len(label)): ...
null
13,472
import numpy as np from numpy.core.defchararray import split import pandas as pd from datetime import datetime from scipy import stats import os def load_data(datadir): df = pd.read_csv(datadir) data = (df.values).transpose(1, 0) return data
null
13,473
import numpy as np from numpy.core.defchararray import split import pandas as pd from datetime import datetime from scipy import stats import os The provided code snippet includes necessary dependencies for implementing the `get_covariates` function. Write a Python function `def get_covariates(data_len, start_day)` to...
Get covariates
13,474
import numpy as np from numpy.core.defchararray import split import pandas as pd from datetime import datetime from scipy import stats import os def normalize(inputs, seq_length): base_seq = inputs[:, :seq_length, 0] nonzeros = (base_seq > 0).sum(1) inputs = inputs[nonzeros > 0] base_seq = inputs[:, :se...
Divide the training sequence into windows
13,475
from typing import List import math import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from hierarchical_mm_tvm import graph_mm as graph_mm_tvm import argparse import time import numpy as np from math import sqrt torch.cuda.set_device(0) import pynvml The provided code snippe...
Get the query-key index for PAM-TVM
13,476
from typing import List import math import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from hierarchical_mm_tvm import graph_mm as graph_mm_tvm import argparse import time import numpy as np from math import sqrt torch.cuda.set_device(0) import pynvml The provided code snippe...
Get the key-query index from query-key index for PAM-TVM
13,477
from typing import List import math import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from hierarchical_mm_tvm import graph_mm as graph_mm_tvm import argparse import time import numpy as np from math import sqrt torch.cuda.set_device(0) import pynvml The provided code snippe...
Get the attention mask of PAM-Naive
13,478
from typing import List import math import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from hierarchical_mm_tvm import graph_mm as graph_mm_tvm import argparse import time import numpy as np from math import sqrt import pynvml def parsing(): parser = argparse.ArgumentPars...
null
13,479
from typing import List import math import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from hierarchical_mm_tvm import graph_mm as graph_mm_tvm import argparse import time import numpy as np from math import sqrt torch.cuda.set_device(0) print('Using device: {}'.format(torch.c...
Test the time and CUDA memory consumption of normal self attention.
13,480
from typing import List import math import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from hierarchical_mm_tvm import graph_mm as graph_mm_tvm import argparse import time import numpy as np from math import sqrt torch.cuda.set_device(0) print('Using device: {}'.format(torch.c...
Test the time and CUDA memory consumption of PAM.
13,481
from typing import List import math import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from hierarchical_mm_tvm import graph_mm as graph_mm_tvm import argparse import time import numpy as np from math import sqrt torch.cuda.set_device(0) print('Using device: {}'.format(torch.c...
Test the time and CUDA memory consumption of Prob-sparse self attention.
13,482
from torch.functional import align_tensors import torch.nn as nn from torch.nn.modules.linear import Linear from .SubLayers import MultiHeadAttention, PositionwiseFeedForward import torch from .embed import DataEmbedding, CustomEmbedding import math The provided code snippet includes necessary dependencies for impleme...
Get the attention mask of PAM-Naive
13,483
from torch.functional import align_tensors import torch.nn as nn from torch.nn.modules.linear import Linear from .SubLayers import MultiHeadAttention, PositionwiseFeedForward import torch from .embed import DataEmbedding, CustomEmbedding import math The provided code snippet includes necessary dependencies for impleme...
Gather features from PAM's pyramid sequences
13,484
from torch.functional import align_tensors import torch.nn as nn from torch.nn.modules.linear import Linear from .SubLayers import MultiHeadAttention, PositionwiseFeedForward import torch from .embed import DataEmbedding, CustomEmbedding import math The provided code snippet includes necessary dependencies for impleme...
Get causal attention mask for decoder.
13,485
from torch.functional import align_tensors import torch.nn as nn from torch.nn.modules.linear import Linear from .SubLayers import MultiHeadAttention, PositionwiseFeedForward import torch from .embed import DataEmbedding, CustomEmbedding import math The provided code snippet includes necessary dependencies for impleme...
Get the index of the key that a given query needs to attend to.
13,486
from torch.functional import align_tensors import torch.nn as nn from torch.nn.modules.linear import Linear from .SubLayers import MultiHeadAttention, PositionwiseFeedForward import torch from .embed import DataEmbedding, CustomEmbedding import math The provided code snippet includes necessary dependencies for impleme...
Get the index of the query that can attend to the given key.
13,487
import argparse import time import torch import torch.optim as optim from torch.utils.data.sampler import RandomSampler from tqdm import tqdm import os import pyraformer.Pyraformer_SS as Pyraformer from data_loader import * import os from utils.tools import SingleStepLoss as LossFactory from utils.tools import AE_loss ...
Prepare specific parameters for different datasets
13,488
import argparse import time import torch import torch.optim as optim from torch.utils.data.sampler import RandomSampler from tqdm import tqdm import os import pyraformer.Pyraformer_SS as Pyraformer from data_loader import * import os from utils.tools import SingleStepLoss as LossFactory from utils.tools import AE_loss ...
Evaluate preptrained models
13,489
import argparse import time import torch import torch.optim as optim from torch.utils.data.sampler import RandomSampler from tqdm import tqdm import os import pyraformer.Pyraformer_SS as Pyraformer from data_loader import * import os from utils.tools import SingleStepLoss as LossFactory from utils.tools import AE_loss ...
null
13,490
from typing import List import numpy as np import pandas as pd from pandas.tseries import offsets from pandas.tseries.frequencies import to_offset def time_features_from_frequency_str(freq_str: str) -> List[TimeFeature]: """ Returns a list of time features that will be appropriate for the given frequency string...
null
13,491
import numpy as np import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `get_frequency_modes` function. Write a Python function `def get_frequency_modes(seq_len, modes=64, mode_select_method='random')` to solve the following problem: get modes on frequency d...
get modes on frequency domain: 'random' means sampling randomly; 'else' means sampling the lowest modes;
13,492
import torch import torch.nn as nn import numpy as np from functools import partial from scipy.special import eval_legendre from sympy import Poly, legendre, Symbol, chebyshevt def legendreDer(k, x): def _legendre(k, x): return (2*k+1) * eval_legendre(k, x) out = 0 for i in np.arange(k-1,-1,-2): ...
null
13,493
import torch import torch.nn as nn import numpy as np from functools import partial from scipy.special import eval_legendre from sympy import Poly, legendre, Symbol, chebyshevt def train(model, train_loader, optimizer, epoch, device, verbose = 0, lossFn = None, lr_schedule=None, post_proc = lambda args: args)...
null
13,494
import time import torch import torch.nn as nn import numpy as np import math from torch.nn.functional import interpolate def decor_time(func): def func2(*args, **kw): now = time.time() y = func(*args, **kw) t = time.time() - now print('call <{}>, time={}'.format(func.__name__, t)) ...
null
13,495
from data_provider.data_loader import Dataset_ETT_hour, Dataset_ETT_minute, Dataset_Custom,Dataset_sin from torch.utils.data import DataLoader data_dict = { 'ETTh1': Dataset_ETT_hour, 'ETTh2': Dataset_ETT_hour, 'ETTm1': Dataset_ETT_minute, 'ETTm2': Dataset_ETT_minute, 'custom': Dataset_Custom, '...
null
13,496
from typing import List import numpy as np import pandas as pd from pandas.tseries import offsets from pandas.tseries.frequencies import to_offset def time_features_from_frequency_str(freq_str: str) -> List[TimeFeature]: def time_features(dates, freq='h'): return np.vstack([feat(dates) for feat in time_features_fr...
null
13,497
import numpy as np import torch import matplotlib.pyplot as plt def adjust_learning_rate(optimizer, epoch, args): # lr = args.learning_rate * (0.2 ** (epoch // 2)) if args.lradj == 'type1': lr_adjust = {epoch: args.learning_rate * (0.5 ** ((epoch - 1) // 1))} elif args.lradj == 'type2': lr_...
null
13,498
import numpy as np import torch import matplotlib.pyplot as plt plt.switch_backend('agg') The provided code snippet includes necessary dependencies for implementing the `visual` function. Write a Python function `def visual(true, preds=None, name='./pic/test.pdf')` to solve the following problem: Results visualization...
Results visualization
13,499
import numpy as np def MAE(pred, true): return np.mean(np.abs(pred - true)) def MSE(pred, true): return np.mean((pred - true) ** 2) def RMSE(pred, true): return np.sqrt(MSE(pred, true)) def MAPE(pred, true): return np.mean(np.abs((pred - true) / true)) def MSPE(pred, true): return np.mean(np.square(...
null
13,500
import numpy as np def RSE(pred, true): return np.sqrt(np.sum((true - pred) ** 2)) / np.sqrt(np.sum((true - true.mean()) ** 2)) def CORR(pred, true): u = ((true - true.mean(0)) * (pred - pred.mean(0))).sum(0) d = np.sqrt(((true - true.mean(0)) ** 2 * (pred - pred.mean(0)) ** 2).sum(0)) return (u / d).me...
null
13,501
from data_provider.data_loader import Dataset_ETT_hour, Dataset_ETT_minute, Dataset_Custom, Dataset_Pred from torch.utils.data import DataLoader data_dict = { 'ETTh1': Dataset_ETT_hour, 'ETTh2': Dataset_ETT_hour, 'ETTm1': Dataset_ETT_minute, 'ETTm2': Dataset_ETT_minute, 'custom': Dataset_Custom, } ...
null
13,502
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from tqdm import tqdm import pmdarima as pm import threading from sklearn.ensemble import GradientBoostingRegressor def _arima(seq,pred_len,bt,i): model = pm.auto_arima(seq) forecasts = model.predict(pred_len) return for...
null
13,503
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from tqdm import tqdm import pmdarima as pm import threading from sklearn.ensemble import GradientBoostingRegressor def _sarima(season,seq,pred_len,bt,i): model = pm.auto_arima(seq, seasonal=True, m=season) forecasts = model....
null
13,504
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from tqdm import tqdm import pmdarima as pm import threading from sklearn.ensemble import GradientBoostingRegressor def _gbrt(seq,seq_len,pred_len,bt,i): model = GradientBoostingRegressor() model.fit(np.arange(seq_len).reshap...
null
13,506
import numpy as np import torch import matplotlib.pyplot as plt import time def adjust_learning_rate(optimizer, scheduler, epoch, args, printout=True): # lr = args.learning_rate * (0.2 ** (epoch // 2)) if args.lradj == 'type1': lr_adjust = {epoch: args.learning_rate * (0.5 ** ((epoch - 1) // 1))} e...
null
13,507
import numpy as np import torch import matplotlib.pyplot as plt import time plt.switch_backend('agg') The provided code snippet includes necessary dependencies for implementing the `visual` function. Write a Python function `def visual(true, preds=None, name='./pic/test.pdf')` to solve the following problem: Results v...
Results visualization
13,508
import numpy as np import torch import matplotlib.pyplot as plt import time The provided code snippet includes necessary dependencies for implementing the `test_params_flop` function. Write a Python function `def test_params_flop(model,x_shape)` to solve the following problem: If you want to thest former's flop, you n...
If you want to thest former's flop, you need to give default value to inputs in model.forward(), the following code can only pass one argument to forward()
13,509
import numpy as np def RSE(pred, true): def CORR(pred, true): def MAE(pred, true): def MSE(pred, true): def RMSE(pred, true): def MAPE(pred, true): def MSPE(pred, true): def metric(pred, true): mae = MAE(pred, true) mse = MSE(pred, true) rmse = RMSE(pred, true) mape = MAPE(pred, true) mspe = MSPE(p...
null
13,510
import os from config import ANTHROPIC_API_KEY from llm import stream_claude_response, stream_openai_response from prompts import assemble_prompt from prompts.types import Stack ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", None) async def stream_openai_response( messages: List[ChatCompletionMessagePara...
null
13,511
from fastapi import APIRouter from fastapi.responses import HTMLResponse async def get_status(): return HTMLResponse( content="<h3>Your backend is running correctly. Please open the front-end URL (default is http://localhost:5173) to use screenshot-to-code.</h3>" )
null
13,512
import os import traceback from fastapi import APIRouter, WebSocket import openai from config import ANTHROPIC_API_KEY, IS_PROD, SHOULD_MOCK_AI_RESPONSE from custom_types import InputMode from llm import ( CODE_GENERATION_MODELS, Llm, stream_claude_response, stream_claude_response_native, stream_ope...
null
13,513
import os from fastapi import APIRouter from pydantic import BaseModel from evals.utils import image_to_data_url from evals.config import EVALS_DIR class Eval(BaseModel): input: str output: str async def image_to_data_url(filepath: str): with open(filepath, "rb") as image_file: encoded_string = bas...
null
13,514
import base64 from fastapi import APIRouter from pydantic import BaseModel import httpx def bytes_to_data_url(image_bytes: bytes, mime_type: str) -> str: async def capture_screenshot( target_url: str, api_key: str, device: str = "desktop" ) -> bytes: class ScreenshotRequest(BaseModel): class ScreenshotResponse(Base...
null
13,515
from dataclasses import dataclass, replace from typing import List, Tuple from minichain import OpenAI, prompt, show, transform, Mock def chat_response(model, state: State) -> State: return model.stream(state) def update(state, chat_output): result = chat_output.split("Assistant:")[-1] return state.push(res...
null