mirror of
https://github.com/microsoft/qlib.git
synced 2026-07-12 07:16:54 +08:00
Add TFT benchmark
This commit is contained in:
15
examples/benchmarks/TFT/data_formatters/__init__.py
Normal file
15
examples/benchmarks/TFT/data_formatters/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2020 The Google Research Authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
235
examples/benchmarks/TFT/data_formatters/base.py
Normal file
235
examples/benchmarks/TFT/data_formatters/base.py
Normal file
@@ -0,0 +1,235 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2020 The Google Research Authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Lint as: python3
|
||||
"""Default data formatting functions for experiments.
|
||||
|
||||
For new datasets, inherit form GenericDataFormatter and implement
|
||||
all abstract functions.
|
||||
|
||||
These dataset-specific methods:
|
||||
1) Define the column and input types for tabular dataframes used by model
|
||||
2) Perform the necessary input feature engineering & normalisation steps
|
||||
3) Reverts the normalisation for predictions
|
||||
4) Are responsible for train, validation and test splits
|
||||
|
||||
|
||||
"""
|
||||
|
||||
import abc
|
||||
import enum
|
||||
|
||||
|
||||
# Type defintions
|
||||
class DataTypes(enum.IntEnum):
|
||||
"""Defines numerical types of each column."""
|
||||
REAL_VALUED = 0
|
||||
CATEGORICAL = 1
|
||||
DATE = 2
|
||||
|
||||
|
||||
class InputTypes(enum.IntEnum):
|
||||
"""Defines input types of each column."""
|
||||
TARGET = 0
|
||||
OBSERVED_INPUT = 1
|
||||
KNOWN_INPUT = 2
|
||||
STATIC_INPUT = 3
|
||||
ID = 4 # Single column used as an entity identifier
|
||||
TIME = 5 # Single column exclusively used as a time index
|
||||
|
||||
|
||||
class GenericDataFormatter(abc.ABC):
|
||||
"""Abstract base class for all data formatters.
|
||||
|
||||
User can implement the abstract methods below to perform dataset-specific
|
||||
manipulations.
|
||||
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def set_scalers(self, df):
|
||||
"""Calibrates scalers using the data supplied."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@abc.abstractmethod
|
||||
def transform_inputs(self, df):
|
||||
"""Performs feature transformation."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@abc.abstractmethod
|
||||
def format_predictions(self, df):
|
||||
"""Reverts any normalisation to give predictions in original scale."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@abc.abstractmethod
|
||||
def split_data(self, df):
|
||||
"""Performs the default train, validation and test splits."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def _column_definition(self):
|
||||
"""Defines order, input type and data type of each column."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@abc.abstractmethod
|
||||
def get_fixed_params(self):
|
||||
"""Defines the fixed parameters used by the model for training.
|
||||
|
||||
Requires the following keys:
|
||||
'total_time_steps': Defines the total number of time steps used by TFT
|
||||
'num_encoder_steps': Determines length of LSTM encoder (i.e. history)
|
||||
'num_epochs': Maximum number of epochs for training
|
||||
'early_stopping_patience': Early stopping param for keras
|
||||
'multiprocessing_workers': # of cpus for data processing
|
||||
|
||||
|
||||
Returns:
|
||||
A dictionary of fixed parameters, e.g.:
|
||||
|
||||
fixed_params = {
|
||||
'total_time_steps': 252 + 5,
|
||||
'num_encoder_steps': 252,
|
||||
'num_epochs': 100,
|
||||
'early_stopping_patience': 5,
|
||||
'multiprocessing_workers': 5,
|
||||
}
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# Shared functions across data-formatters
|
||||
@property
|
||||
def num_classes_per_cat_input(self):
|
||||
"""Returns number of categories per relevant input.
|
||||
|
||||
This is seqeuently required for keras embedding layers.
|
||||
"""
|
||||
return self._num_classes_per_cat_input
|
||||
|
||||
def get_num_samples_for_calibration(self):
|
||||
"""Gets the default number of training and validation samples.
|
||||
|
||||
Use to sub-sample the data for network calibration and a value of -1 uses
|
||||
all available samples.
|
||||
|
||||
Returns:
|
||||
Tuple of (training samples, validation samples)
|
||||
"""
|
||||
return -1, -1
|
||||
|
||||
def get_column_definition(self):
|
||||
""""Returns formatted column definition in order expected by the TFT."""
|
||||
|
||||
column_definition = self._column_definition
|
||||
|
||||
# Sanity checks first.
|
||||
# Ensure only one ID and time column exist
|
||||
def _check_single_column(input_type):
|
||||
|
||||
length = len([tup for tup in column_definition if tup[2] == input_type])
|
||||
|
||||
if length != 1:
|
||||
raise ValueError('Illegal number of inputs ({}) of type {}'.format(
|
||||
length, input_type))
|
||||
|
||||
_check_single_column(InputTypes.ID)
|
||||
_check_single_column(InputTypes.TIME)
|
||||
|
||||
identifier = [tup for tup in column_definition if tup[2] == InputTypes.ID]
|
||||
time = [tup for tup in column_definition if tup[2] == InputTypes.TIME]
|
||||
real_inputs = [
|
||||
tup for tup in column_definition if tup[1] == DataTypes.REAL_VALUED and
|
||||
tup[2] not in {InputTypes.ID, InputTypes.TIME}
|
||||
]
|
||||
categorical_inputs = [
|
||||
tup for tup in column_definition if tup[1] == DataTypes.CATEGORICAL and
|
||||
tup[2] not in {InputTypes.ID, InputTypes.TIME}
|
||||
]
|
||||
|
||||
return identifier + time + real_inputs + categorical_inputs
|
||||
|
||||
def _get_input_columns(self):
|
||||
"""Returns names of all input columns."""
|
||||
return [
|
||||
tup[0]
|
||||
for tup in self.get_column_definition()
|
||||
if tup[2] not in {InputTypes.ID, InputTypes.TIME}
|
||||
]
|
||||
|
||||
def _get_tft_input_indices(self):
|
||||
"""Returns the relevant indexes and input sizes required by TFT."""
|
||||
|
||||
# Functions
|
||||
def _extract_tuples_from_data_type(data_type, defn):
|
||||
return [
|
||||
tup for tup in defn if tup[1] == data_type and
|
||||
tup[2] not in {InputTypes.ID, InputTypes.TIME}
|
||||
]
|
||||
|
||||
def _get_locations(input_types, defn):
|
||||
return [i for i, tup in enumerate(defn) if tup[2] in input_types]
|
||||
|
||||
# Start extraction
|
||||
column_definition = [
|
||||
tup for tup in self.get_column_definition()
|
||||
if tup[2] not in {InputTypes.ID, InputTypes.TIME}
|
||||
]
|
||||
|
||||
categorical_inputs = _extract_tuples_from_data_type(DataTypes.CATEGORICAL,
|
||||
column_definition)
|
||||
real_inputs = _extract_tuples_from_data_type(DataTypes.REAL_VALUED,
|
||||
column_definition)
|
||||
|
||||
locations = {
|
||||
'input_size':
|
||||
len(self._get_input_columns()),
|
||||
'output_size':
|
||||
len(_get_locations({InputTypes.TARGET}, column_definition)),
|
||||
'category_counts':
|
||||
self.num_classes_per_cat_input,
|
||||
'input_obs_loc':
|
||||
_get_locations({InputTypes.TARGET}, column_definition),
|
||||
'static_input_loc':
|
||||
_get_locations({InputTypes.STATIC_INPUT}, column_definition),
|
||||
'known_regular_inputs':
|
||||
_get_locations({InputTypes.STATIC_INPUT, InputTypes.KNOWN_INPUT},
|
||||
real_inputs),
|
||||
'known_categorical_inputs':
|
||||
_get_locations({InputTypes.STATIC_INPUT, InputTypes.KNOWN_INPUT},
|
||||
categorical_inputs),
|
||||
}
|
||||
|
||||
return locations
|
||||
|
||||
def get_experiment_params(self):
|
||||
"""Returns fixed model parameters for experiments."""
|
||||
|
||||
required_keys = [
|
||||
'total_time_steps', 'num_encoder_steps', 'num_epochs',
|
||||
'early_stopping_patience', 'multiprocessing_workers'
|
||||
]
|
||||
|
||||
fixed_params = self.get_fixed_params()
|
||||
|
||||
for k in required_keys:
|
||||
if k not in fixed_params:
|
||||
raise ValueError('Field {}'.format(k) +
|
||||
' missing from fixed parameter definitions!')
|
||||
|
||||
fixed_params['column_definition'] = self.get_column_definition()
|
||||
|
||||
fixed_params.update(self._get_tft_input_indices())
|
||||
|
||||
return fixed_params
|
||||
261
examples/benchmarks/TFT/data_formatters/electricity.py
Normal file
261
examples/benchmarks/TFT/data_formatters/electricity.py
Normal file
@@ -0,0 +1,261 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2020 The Google Research Authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Lint as: python3
|
||||
"""Custom formatting functions for Electricity dataset.
|
||||
|
||||
Defines dataset specific column definitions and data transformations. Uses
|
||||
entity specific z-score normalization.
|
||||
"""
|
||||
|
||||
import data_formatters.base
|
||||
import libs.utils as utils
|
||||
import pandas as pd
|
||||
import sklearn.preprocessing
|
||||
|
||||
GenericDataFormatter = data_formatters.base.GenericDataFormatter
|
||||
DataTypes = data_formatters.base.DataTypes
|
||||
InputTypes = data_formatters.base.InputTypes
|
||||
|
||||
|
||||
class ElectricityFormatter(GenericDataFormatter):
|
||||
"""Defines and formats data for the electricity dataset.
|
||||
|
||||
Note that per-entity z-score normalization is used here, and is implemented
|
||||
across functions.
|
||||
|
||||
Attributes:
|
||||
column_definition: Defines input and data type of column used in the
|
||||
experiment.
|
||||
identifiers: Entity identifiers used in experiments.
|
||||
"""
|
||||
|
||||
_column_definition = [
|
||||
('id', DataTypes.REAL_VALUED, InputTypes.ID),
|
||||
('hours_from_start', DataTypes.REAL_VALUED, InputTypes.TIME),
|
||||
('power_usage', DataTypes.REAL_VALUED, InputTypes.TARGET),
|
||||
('hour', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('day_of_week', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('hours_from_start', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('categorical_id', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
"""Initialises formatter."""
|
||||
|
||||
self.identifiers = None
|
||||
self._real_scalers = None
|
||||
self._cat_scalers = None
|
||||
self._target_scaler = None
|
||||
self._num_classes_per_cat_input = None
|
||||
self._time_steps = self.get_fixed_params()['total_time_steps']
|
||||
|
||||
def split_data(self, df, valid_boundary=1315, test_boundary=1339):
|
||||
"""Splits data frame into training-validation-test data frames.
|
||||
|
||||
This also calibrates scaling object, and transforms data for each split.
|
||||
|
||||
Args:
|
||||
df: Source data frame to split.
|
||||
valid_boundary: Starting year for validation data
|
||||
test_boundary: Starting year for test data
|
||||
|
||||
Returns:
|
||||
Tuple of transformed (train, valid, test) data.
|
||||
"""
|
||||
|
||||
print('Formatting train-valid-test splits.')
|
||||
|
||||
index = df['days_from_start']
|
||||
train = df.loc[index < valid_boundary]
|
||||
valid = df.loc[(index >= valid_boundary - 7) & (index < test_boundary)]
|
||||
test = df.loc[index >= test_boundary - 7]
|
||||
|
||||
self.set_scalers(train)
|
||||
|
||||
return (self.transform_inputs(data) for data in [train, valid, test])
|
||||
|
||||
def set_scalers(self, df):
|
||||
"""Calibrates scalers using the data supplied.
|
||||
|
||||
Args:
|
||||
df: Data to use to calibrate scalers.
|
||||
"""
|
||||
print('Setting scalers with training data...')
|
||||
|
||||
column_definitions = self.get_column_definition()
|
||||
id_column = utils.get_single_col_by_input_type(InputTypes.ID,
|
||||
column_definitions)
|
||||
target_column = utils.get_single_col_by_input_type(InputTypes.TARGET,
|
||||
column_definitions)
|
||||
|
||||
# Format real scalers
|
||||
real_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.REAL_VALUED, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
# Initialise scaler caches
|
||||
self._real_scalers = {}
|
||||
self._target_scaler = {}
|
||||
identifiers = []
|
||||
for identifier, sliced in df.groupby(id_column):
|
||||
|
||||
if len(sliced) >= self._time_steps:
|
||||
|
||||
data = sliced[real_inputs].values
|
||||
targets = sliced[[target_column]].values
|
||||
self._real_scalers[identifier] \
|
||||
= sklearn.preprocessing.StandardScaler().fit(data)
|
||||
|
||||
self._target_scaler[identifier] \
|
||||
= sklearn.preprocessing.StandardScaler().fit(targets)
|
||||
identifiers.append(identifier)
|
||||
|
||||
# Format categorical scalers
|
||||
categorical_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.CATEGORICAL, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
categorical_scalers = {}
|
||||
num_classes = []
|
||||
for col in categorical_inputs:
|
||||
# Set all to str so that we don't have mixed integer/string columns
|
||||
srs = df[col].apply(str)
|
||||
categorical_scalers[col] = sklearn.preprocessing.LabelEncoder().fit(
|
||||
srs.values)
|
||||
num_classes.append(srs.nunique())
|
||||
|
||||
# Set categorical scaler outputs
|
||||
self._cat_scalers = categorical_scalers
|
||||
self._num_classes_per_cat_input = num_classes
|
||||
|
||||
# Extract identifiers in case required
|
||||
self.identifiers = identifiers
|
||||
|
||||
def transform_inputs(self, df):
|
||||
"""Performs feature transformations.
|
||||
|
||||
This includes both feature engineering, preprocessing and normalisation.
|
||||
|
||||
Args:
|
||||
df: Data frame to transform.
|
||||
|
||||
Returns:
|
||||
Transformed data frame.
|
||||
|
||||
"""
|
||||
|
||||
if self._real_scalers is None and self._cat_scalers is None:
|
||||
raise ValueError('Scalers have not been set!')
|
||||
|
||||
# Extract relevant columns
|
||||
column_definitions = self.get_column_definition()
|
||||
id_col = utils.get_single_col_by_input_type(InputTypes.ID,
|
||||
column_definitions)
|
||||
real_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.REAL_VALUED, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
categorical_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.CATEGORICAL, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
# Transform real inputs per entity
|
||||
df_list = []
|
||||
for identifier, sliced in df.groupby(id_col):
|
||||
|
||||
# Filter out any trajectories that are too short
|
||||
if len(sliced) >= self._time_steps:
|
||||
sliced_copy = sliced.copy()
|
||||
sliced_copy[real_inputs] = self._real_scalers[identifier].transform(
|
||||
sliced_copy[real_inputs].values)
|
||||
df_list.append(sliced_copy)
|
||||
|
||||
output = pd.concat(df_list, axis=0)
|
||||
|
||||
# Format categorical inputs
|
||||
for col in categorical_inputs:
|
||||
string_df = df[col].apply(str)
|
||||
output[col] = self._cat_scalers[col].transform(string_df)
|
||||
|
||||
return output
|
||||
|
||||
def format_predictions(self, predictions):
|
||||
"""Reverts any normalisation to give predictions in original scale.
|
||||
|
||||
Args:
|
||||
predictions: Dataframe of model predictions.
|
||||
|
||||
Returns:
|
||||
Data frame of unnormalised predictions.
|
||||
"""
|
||||
|
||||
if self._target_scaler is None:
|
||||
raise ValueError('Scalers have not been set!')
|
||||
|
||||
column_names = predictions.columns
|
||||
|
||||
df_list = []
|
||||
for identifier, sliced in predictions.groupby('identifier'):
|
||||
sliced_copy = sliced.copy()
|
||||
target_scaler = self._target_scaler[identifier]
|
||||
|
||||
for col in column_names:
|
||||
if col not in {'forecast_time', 'identifier'}:
|
||||
sliced_copy[col] = target_scaler.inverse_transform(sliced_copy[col])
|
||||
df_list.append(sliced_copy)
|
||||
|
||||
output = pd.concat(df_list, axis=0)
|
||||
|
||||
return output
|
||||
|
||||
# Default params
|
||||
def get_fixed_params(self):
|
||||
"""Returns fixed model parameters for experiments."""
|
||||
|
||||
fixed_params = {
|
||||
'total_time_steps': 8 * 24,
|
||||
'num_encoder_steps': 7 * 24,
|
||||
'num_epochs': 100,
|
||||
'early_stopping_patience': 5,
|
||||
'multiprocessing_workers': 5
|
||||
}
|
||||
|
||||
return fixed_params
|
||||
|
||||
def get_default_model_params(self):
|
||||
"""Returns default optimised model parameters."""
|
||||
|
||||
model_params = {
|
||||
'dropout_rate': 0.1,
|
||||
'hidden_layer_size': 160,
|
||||
'learning_rate': 0.001,
|
||||
'minibatch_size': 64,
|
||||
'max_gradient_norm': 0.01,
|
||||
'num_heads': 4,
|
||||
'stack_size': 1
|
||||
}
|
||||
|
||||
return model_params
|
||||
|
||||
def get_num_samples_for_calibration(self):
|
||||
"""Gets the default number of training and validation samples.
|
||||
|
||||
Use to sub-sample the data for network calibration and a value of -1 uses
|
||||
all available samples.
|
||||
|
||||
Returns:
|
||||
Tuple of (training samples, validation samples)
|
||||
"""
|
||||
return 450000, 50000
|
||||
327
examples/benchmarks/TFT/data_formatters/favorita.py
Normal file
327
examples/benchmarks/TFT/data_formatters/favorita.py
Normal file
@@ -0,0 +1,327 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2020 The Google Research Authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Lint as: python3
|
||||
"""Custom formatting functions for Favorita dataset.
|
||||
|
||||
Defines dataset specific column definitions and data transformations.
|
||||
"""
|
||||
|
||||
import data_formatters.base
|
||||
import libs.utils as utils
|
||||
import pandas as pd
|
||||
import sklearn.preprocessing
|
||||
|
||||
DataTypes = data_formatters.base.DataTypes
|
||||
InputTypes = data_formatters.base.InputTypes
|
||||
|
||||
|
||||
class FavoritaFormatter(data_formatters.base.GenericDataFormatter):
|
||||
"""Defines and formats data for the Favorita dataset.
|
||||
|
||||
Attributes:
|
||||
column_definition: Defines input and data type of column used in the
|
||||
experiment.
|
||||
identifiers: Entity identifiers used in experiments.
|
||||
"""
|
||||
|
||||
_column_definition = [
|
||||
('traj_id', DataTypes.REAL_VALUED, InputTypes.ID),
|
||||
('date', DataTypes.DATE, InputTypes.TIME),
|
||||
('log_sales', DataTypes.REAL_VALUED, InputTypes.TARGET),
|
||||
('onpromotion', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('transactions', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('oil', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('day_of_week', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('day_of_month', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('month', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('national_hol', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('regional_hol', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('local_hol', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('open', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('item_nbr', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
('store_nbr', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
('city', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
('state', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
('type', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
('cluster', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
('family', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
('class', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
('perishable', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT)
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
"""Initialises formatter."""
|
||||
|
||||
self.identifiers = None
|
||||
self._real_scalers = None
|
||||
self._cat_scalers = None
|
||||
self._target_scaler = None
|
||||
self._num_classes_per_cat_input = None
|
||||
|
||||
def split_data(self, df, valid_boundary=None, test_boundary=None):
|
||||
"""Splits data frame into training-validation-test data frames.
|
||||
|
||||
This also calibrates scaling object, and transforms data for each split.
|
||||
|
||||
Args:
|
||||
df: Source data frame to split.
|
||||
valid_boundary: Starting year for validation data
|
||||
test_boundary: Starting year for test data
|
||||
|
||||
Returns:
|
||||
Tuple of transformed (train, valid, test) data.
|
||||
"""
|
||||
|
||||
print('Formatting train-valid-test splits.')
|
||||
|
||||
if valid_boundary is None:
|
||||
valid_boundary = pd.datetime(2015, 12, 1)
|
||||
|
||||
fixed_params = self.get_fixed_params()
|
||||
time_steps = fixed_params['total_time_steps']
|
||||
lookback = fixed_params['num_encoder_steps']
|
||||
forecast_horizon = time_steps - lookback
|
||||
|
||||
df['date'] = pd.to_datetime(df['date'])
|
||||
df_lists = {'train': [], 'valid': [], 'test': []}
|
||||
for _, sliced in df.groupby('traj_id'):
|
||||
index = sliced['date']
|
||||
train = sliced.loc[index < valid_boundary]
|
||||
train_len = len(train)
|
||||
valid_len = train_len + forecast_horizon
|
||||
valid = sliced.iloc[train_len - lookback:valid_len, :]
|
||||
test = sliced.iloc[valid_len - lookback:valid_len + forecast_horizon, :]
|
||||
|
||||
sliced_map = {'train': train, 'valid': valid, 'test': test}
|
||||
|
||||
for k in sliced_map:
|
||||
item = sliced_map[k]
|
||||
|
||||
if len(item) >= time_steps:
|
||||
df_lists[k].append(item)
|
||||
|
||||
dfs = {k: pd.concat(df_lists[k], axis=0) for k in df_lists}
|
||||
|
||||
train = dfs['train']
|
||||
self.set_scalers(train, set_real=True)
|
||||
|
||||
# Use all data for label encoding to handle labels not present in training.
|
||||
self.set_scalers(df, set_real=False)
|
||||
|
||||
# Filter out identifiers not present in training (i.e. cold-started items).
|
||||
def filter_ids(frame):
|
||||
identifiers = set(self.identifiers)
|
||||
index = frame['traj_id']
|
||||
return frame.loc[index.apply(lambda x: x in identifiers)]
|
||||
|
||||
valid = filter_ids(dfs['valid'])
|
||||
test = filter_ids(dfs['test'])
|
||||
|
||||
return (self.transform_inputs(data) for data in [train, valid, test])
|
||||
|
||||
def set_scalers(self, df, set_real=True):
|
||||
"""Calibrates scalers using the data supplied.
|
||||
|
||||
Label encoding is applied to the entire dataset (i.e. including test),
|
||||
so that unseen labels can be handled at run-time.
|
||||
|
||||
Args:
|
||||
df: Data to use to calibrate scalers.
|
||||
set_real: Whether to fit set real-valued or categorical scalers
|
||||
"""
|
||||
print('Setting scalers with training data...')
|
||||
|
||||
column_definitions = self.get_column_definition()
|
||||
id_column = utils.get_single_col_by_input_type(InputTypes.ID,
|
||||
column_definitions)
|
||||
target_column = utils.get_single_col_by_input_type(InputTypes.TARGET,
|
||||
column_definitions)
|
||||
|
||||
if set_real:
|
||||
|
||||
# Extract identifiers in case required
|
||||
self.identifiers = list(df[id_column].unique())
|
||||
|
||||
# Format real scalers
|
||||
self._real_scalers = {}
|
||||
for col in ['oil', 'transactions', 'log_sales']:
|
||||
self._real_scalers[col] = (df[col].mean(), df[col].std())
|
||||
|
||||
self._target_scaler = (df[target_column].mean(), df[target_column].std())
|
||||
|
||||
else:
|
||||
# Format categorical scalers
|
||||
categorical_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.CATEGORICAL, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
categorical_scalers = {}
|
||||
num_classes = []
|
||||
if self.identifiers is None:
|
||||
raise ValueError('Scale real-valued inputs first!')
|
||||
id_set = set(self.identifiers)
|
||||
valid_idx = df['traj_id'].apply(lambda x: x in id_set)
|
||||
for col in categorical_inputs:
|
||||
# Set all to str so that we don't have mixed integer/string columns
|
||||
srs = df[col].apply(str).loc[valid_idx]
|
||||
categorical_scalers[col] = sklearn.preprocessing.LabelEncoder().fit(
|
||||
srs.values)
|
||||
|
||||
num_classes.append(srs.nunique())
|
||||
|
||||
# Set categorical scaler outputs
|
||||
self._cat_scalers = categorical_scalers
|
||||
self._num_classes_per_cat_input = num_classes
|
||||
|
||||
def transform_inputs(self, df):
|
||||
"""Performs feature transformations.
|
||||
|
||||
This includes both feature engineering, preprocessing and normalisation.
|
||||
|
||||
Args:
|
||||
df: Data frame to transform.
|
||||
|
||||
Returns:
|
||||
Transformed data frame.
|
||||
|
||||
"""
|
||||
output = df.copy()
|
||||
|
||||
if self._real_scalers is None and self._cat_scalers is None:
|
||||
raise ValueError('Scalers have not been set!')
|
||||
|
||||
column_definitions = self.get_column_definition()
|
||||
|
||||
categorical_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.CATEGORICAL, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
# Format real inputs
|
||||
for col in ['log_sales', 'oil', 'transactions']:
|
||||
mean, std = self._real_scalers[col]
|
||||
output[col] = (df[col] - mean) / std
|
||||
|
||||
if col == 'log_sales':
|
||||
output[col] = output[col].fillna(0.) # mean imputation
|
||||
|
||||
# Format categorical inputs
|
||||
for col in categorical_inputs:
|
||||
string_df = df[col].apply(str)
|
||||
output[col] = self._cat_scalers[col].transform(string_df)
|
||||
|
||||
return output
|
||||
|
||||
def format_predictions(self, predictions):
|
||||
"""Reverts any normalisation to give predictions in original scale.
|
||||
|
||||
Args:
|
||||
predictions: Dataframe of model predictions.
|
||||
|
||||
Returns:
|
||||
Data frame of unnormalised predictions.
|
||||
"""
|
||||
output = predictions.copy()
|
||||
|
||||
column_names = predictions.columns
|
||||
mean, std = self._target_scaler
|
||||
for col in column_names:
|
||||
if col not in {'forecast_time', 'identifier'}:
|
||||
output[col] = (predictions[col] * std) + mean
|
||||
|
||||
return output
|
||||
|
||||
# Default params
|
||||
def get_fixed_params(self):
|
||||
"""Returns fixed model parameters for experiments."""
|
||||
|
||||
fixed_params = {
|
||||
'total_time_steps': 120,
|
||||
'num_encoder_steps': 90,
|
||||
'num_epochs': 100,
|
||||
'early_stopping_patience': 5,
|
||||
'multiprocessing_workers': 5
|
||||
}
|
||||
|
||||
return fixed_params
|
||||
|
||||
def get_default_model_params(self):
|
||||
"""Returns default optimised model parameters."""
|
||||
|
||||
model_params = {
|
||||
'dropout_rate': 0.1,
|
||||
'hidden_layer_size': 240,
|
||||
'learning_rate': 0.001,
|
||||
'minibatch_size': 128,
|
||||
'max_gradient_norm': 100.,
|
||||
'num_heads': 4,
|
||||
'stack_size': 1
|
||||
}
|
||||
|
||||
return model_params
|
||||
|
||||
def get_num_samples_for_calibration(self):
|
||||
"""Gets the default number of training and validation samples.
|
||||
|
||||
Use to sub-sample the data for network calibration and a value of -1 uses
|
||||
all available samples.
|
||||
|
||||
Returns:
|
||||
Tuple of (training samples, validation samples)
|
||||
"""
|
||||
return 450000, 50000
|
||||
|
||||
def get_column_definition(self):
|
||||
""""Formats column definition in order expected by the TFT.
|
||||
|
||||
Modified for Favorita to match column order of original experiment.
|
||||
|
||||
Returns:
|
||||
Favorita-specific column definition
|
||||
"""
|
||||
|
||||
column_definition = self._column_definition
|
||||
|
||||
# Sanity checks first.
|
||||
# Ensure only one ID and time column exist
|
||||
def _check_single_column(input_type):
|
||||
|
||||
length = len([tup for tup in column_definition if tup[2] == input_type])
|
||||
|
||||
if length != 1:
|
||||
raise ValueError('Illegal number of inputs ({}) of type {}'.format(
|
||||
length, input_type))
|
||||
|
||||
_check_single_column(InputTypes.ID)
|
||||
_check_single_column(InputTypes.TIME)
|
||||
|
||||
identifier = [tup for tup in column_definition if tup[2] == InputTypes.ID]
|
||||
time = [tup for tup in column_definition if tup[2] == InputTypes.TIME]
|
||||
real_inputs = [
|
||||
tup for tup in column_definition if tup[1] == DataTypes.REAL_VALUED and
|
||||
tup[2] not in {InputTypes.ID, InputTypes.TIME}
|
||||
]
|
||||
|
||||
col_definition_map = {tup[0]: tup for tup in column_definition}
|
||||
col_order = [
|
||||
'item_nbr', 'store_nbr', 'city', 'state', 'type', 'cluster', 'family',
|
||||
'class', 'perishable', 'onpromotion', 'day_of_week', 'national_hol',
|
||||
'regional_hol', 'local_hol'
|
||||
]
|
||||
categorical_inputs = [
|
||||
col_definition_map[k] for k in col_order if k in col_definition_map
|
||||
]
|
||||
|
||||
return identifier + time + real_inputs + categorical_inputs
|
||||
220
examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
Normal file
220
examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
Normal file
@@ -0,0 +1,220 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2020 The Google Research Authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Lint as: python3
|
||||
"""Custom formatting functions for Alpha158 dataset.
|
||||
|
||||
Defines dataset specific column definitions and data transformations.
|
||||
"""
|
||||
|
||||
import data_formatters.base
|
||||
import libs.utils as utils
|
||||
import sklearn.preprocessing
|
||||
|
||||
GenericDataFormatter = data_formatters.base.GenericDataFormatter
|
||||
DataTypes = data_formatters.base.DataTypes
|
||||
InputTypes = data_formatters.base.InputTypes
|
||||
|
||||
class Alpha158Formatter(GenericDataFormatter):
|
||||
"""Defines and formats data for the Alpha158 dataset.
|
||||
|
||||
Attributes:
|
||||
column_definition: Defines input and data type of column used in the
|
||||
experiment.
|
||||
identifiers: Entity identifiers used in experiments.
|
||||
"""
|
||||
|
||||
_column_definition = [
|
||||
('instrument', DataTypes.CATEGORICAL, InputTypes.ID),
|
||||
('LABEL0', DataTypes.REAL_VALUED, InputTypes.TARGET),
|
||||
('date', DataTypes.DATE, InputTypes.TIME),
|
||||
('month', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('day_of_week', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
# Selected 10 features
|
||||
('RESI5', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('WVMA5', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('RSQR5', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('KLEN', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('RSQR10', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('CORR5', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('CORD5', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('CORR10', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('ROC60', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('RESI10', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('const', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
"""Initialises formatter."""
|
||||
|
||||
self.identifiers = None
|
||||
self._real_scalers = None
|
||||
self._cat_scalers = None
|
||||
self._target_scaler = None
|
||||
self._num_classes_per_cat_input = None
|
||||
|
||||
def split_data(self, df, valid_boundary=2016, test_boundary=2018):
|
||||
"""Splits data frame into training-validation-test data frames.
|
||||
|
||||
This also calibrates scaling object, and transforms data for each split.
|
||||
|
||||
Args:
|
||||
df: Source data frame to split.
|
||||
valid_boundary: Starting year for validation data
|
||||
test_boundary: Starting year for test data
|
||||
|
||||
Returns:
|
||||
Tuple of transformed (train, valid, test) data.
|
||||
"""
|
||||
|
||||
print('Formatting train-valid-test splits.')
|
||||
|
||||
index = df['year']
|
||||
train = df.loc[index < valid_boundary]
|
||||
valid = df.loc[(index >= valid_boundary) & (index < test_boundary)]
|
||||
test = df.loc[index >= test_boundary]
|
||||
|
||||
self.set_scalers(train)
|
||||
|
||||
return (self.transform_inputs(data) for data in [train, valid, test])
|
||||
|
||||
def set_scalers(self, df):
|
||||
"""Calibrates scalers using the data supplied.
|
||||
|
||||
Args:
|
||||
df: Data to use to calibrate scalers.
|
||||
"""
|
||||
print('Setting scalers with training data...')
|
||||
|
||||
column_definitions = self.get_column_definition()
|
||||
id_column = utils.get_single_col_by_input_type(InputTypes.ID,
|
||||
column_definitions)
|
||||
target_column = utils.get_single_col_by_input_type(InputTypes.TARGET,
|
||||
column_definitions)
|
||||
|
||||
# Extract identifiers in case required
|
||||
self.identifiers = list(df[id_column].unique())
|
||||
|
||||
# Format real scalers
|
||||
real_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.REAL_VALUED, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
data = df[real_inputs].values
|
||||
self._real_scalers = sklearn.preprocessing.StandardScaler().fit(data)
|
||||
self._target_scaler = sklearn.preprocessing.StandardScaler().fit(
|
||||
df[[target_column]].values) # used for predictions
|
||||
|
||||
# Format categorical scalers
|
||||
categorical_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.CATEGORICAL, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
categorical_scalers = {}
|
||||
num_classes = []
|
||||
for col in categorical_inputs:
|
||||
# Set all to str so that we don't have mixed integer/string columns
|
||||
srs = df[col].apply(str)
|
||||
categorical_scalers[col] = sklearn.preprocessing.LabelEncoder().fit(
|
||||
srs.values)
|
||||
num_classes.append(srs.nunique())
|
||||
|
||||
# Set categorical scaler outputs
|
||||
self._cat_scalers = categorical_scalers
|
||||
self._num_classes_per_cat_input = num_classes
|
||||
|
||||
def transform_inputs(self, df):
|
||||
"""Performs feature transformations.
|
||||
|
||||
This includes both feature engineering, preprocessing and normalisation.
|
||||
|
||||
Args:
|
||||
df: Data frame to transform.
|
||||
|
||||
Returns:
|
||||
Transformed data frame.
|
||||
|
||||
"""
|
||||
output = df.copy()
|
||||
|
||||
if self._real_scalers is None and self._cat_scalers is None:
|
||||
raise ValueError('Scalers have not been set!')
|
||||
|
||||
column_definitions = self.get_column_definition()
|
||||
|
||||
real_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.REAL_VALUED, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
categorical_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.CATEGORICAL, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
# Format real inputs
|
||||
output[real_inputs] = self._real_scalers.transform(df[real_inputs].values)
|
||||
|
||||
# Format categorical inputs
|
||||
for col in categorical_inputs:
|
||||
string_df = df[col].apply(str)
|
||||
output[col] = self._cat_scalers[col].transform(string_df)
|
||||
|
||||
return output
|
||||
|
||||
def format_predictions(self, predictions):
|
||||
"""Reverts any normalisation to give predictions in original scale.
|
||||
|
||||
Args:
|
||||
predictions: Dataframe of model predictions.
|
||||
|
||||
Returns:
|
||||
Data frame of unnormalised predictions.
|
||||
"""
|
||||
output = predictions.copy()
|
||||
|
||||
column_names = predictions.columns
|
||||
|
||||
for col in column_names:
|
||||
if col not in {'forecast_time', 'identifier'}:
|
||||
output[col] = self._target_scaler.inverse_transform(predictions[col])
|
||||
|
||||
return output
|
||||
|
||||
# Default params
|
||||
def get_fixed_params(self):
|
||||
"""Returns fixed model parameters for experiments."""
|
||||
|
||||
fixed_params = {
|
||||
'total_time_steps': 16 + 6,
|
||||
'num_encoder_steps': 16,
|
||||
'num_epochs': 100,
|
||||
'early_stopping_patience': 5,
|
||||
'multiprocessing_workers': 5,
|
||||
}
|
||||
|
||||
return fixed_params
|
||||
|
||||
def get_default_model_params(self):
|
||||
"""Returns default optimised model parameters."""
|
||||
|
||||
model_params = {
|
||||
'dropout_rate': 0.3,
|
||||
'hidden_layer_size': 160,
|
||||
'learning_rate': 0.01,
|
||||
'minibatch_size': 64,
|
||||
'max_gradient_norm': 0.01,
|
||||
'num_heads': 1,
|
||||
'stack_size': 1
|
||||
}
|
||||
|
||||
return model_params
|
||||
117
examples/benchmarks/TFT/data_formatters/traffic.py
Normal file
117
examples/benchmarks/TFT/data_formatters/traffic.py
Normal file
@@ -0,0 +1,117 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2020 The Google Research Authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Lint as: python3
|
||||
"""Custom formatting functions for Traffic dataset.
|
||||
|
||||
Defines dataset specific column definitions and data transformations. This also
|
||||
performs z-score normalization across the entire dataset, hence re-uses most of
|
||||
the same functions as volatility.
|
||||
"""
|
||||
|
||||
import data_formatters.base
|
||||
import data_formatters.volatility
|
||||
|
||||
VolatilityFormatter = data_formatters.volatility.VolatilityFormatter
|
||||
DataTypes = data_formatters.base.DataTypes
|
||||
InputTypes = data_formatters.base.InputTypes
|
||||
|
||||
|
||||
class TrafficFormatter(VolatilityFormatter):
|
||||
"""Defines and formats data for the traffic dataset.
|
||||
|
||||
This also performs z-score normalization across the entire dataset, hence
|
||||
re-uses most of the same functions as volatility.
|
||||
|
||||
Attributes:
|
||||
column_definition: Defines input and data type of column used in the
|
||||
experiment.
|
||||
identifiers: Entity identifiers used in experiments.
|
||||
"""
|
||||
|
||||
_column_definition = [
|
||||
('id', DataTypes.REAL_VALUED, InputTypes.ID),
|
||||
('hours_from_start', DataTypes.REAL_VALUED, InputTypes.TIME),
|
||||
('values', DataTypes.REAL_VALUED, InputTypes.TARGET),
|
||||
('time_on_day', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('day_of_week', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('hours_from_start', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('categorical_id', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
]
|
||||
|
||||
def split_data(self, df, valid_boundary=151, test_boundary=166):
|
||||
"""Splits data frame into training-validation-test data frames.
|
||||
|
||||
This also calibrates scaling object, and transforms data for each split.
|
||||
|
||||
Args:
|
||||
df: Source data frame to split.
|
||||
valid_boundary: Starting year for validation data
|
||||
test_boundary: Starting year for test data
|
||||
|
||||
Returns:
|
||||
Tuple of transformed (train, valid, test) data.
|
||||
"""
|
||||
|
||||
print('Formatting train-valid-test splits.')
|
||||
|
||||
index = df['sensor_day']
|
||||
train = df.loc[index < valid_boundary]
|
||||
valid = df.loc[(index >= valid_boundary - 7) & (index < test_boundary)]
|
||||
test = df.loc[index >= test_boundary - 7]
|
||||
|
||||
self.set_scalers(train)
|
||||
|
||||
return (self.transform_inputs(data) for data in [train, valid, test])
|
||||
|
||||
# Default params
|
||||
def get_fixed_params(self):
|
||||
"""Returns fixed model parameters for experiments."""
|
||||
|
||||
fixed_params = {
|
||||
'total_time_steps': 8 * 24,
|
||||
'num_encoder_steps': 7 * 24,
|
||||
'num_epochs': 100,
|
||||
'early_stopping_patience': 5,
|
||||
'multiprocessing_workers': 5
|
||||
}
|
||||
|
||||
return fixed_params
|
||||
|
||||
def get_default_model_params(self):
|
||||
"""Returns default optimised model parameters."""
|
||||
|
||||
model_params = {
|
||||
'dropout_rate': 0.3,
|
||||
'hidden_layer_size': 320,
|
||||
'learning_rate': 0.001,
|
||||
'minibatch_size': 128,
|
||||
'max_gradient_norm': 100.,
|
||||
'num_heads': 4,
|
||||
'stack_size': 1
|
||||
}
|
||||
|
||||
return model_params
|
||||
|
||||
def get_num_samples_for_calibration(self):
|
||||
"""Gets the default number of training and validation samples.
|
||||
|
||||
Use to sub-sample the data for network calibration and a value of -1 uses
|
||||
all available samples.
|
||||
|
||||
Returns:
|
||||
Tuple of (training samples, validation samples)
|
||||
"""
|
||||
return 450000, 50000
|
||||
214
examples/benchmarks/TFT/data_formatters/volatility.py
Normal file
214
examples/benchmarks/TFT/data_formatters/volatility.py
Normal file
@@ -0,0 +1,214 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2020 The Google Research Authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Lint as: python3
|
||||
"""Custom formatting functions for Volatility dataset.
|
||||
|
||||
Defines dataset specific column definitions and data transformations.
|
||||
"""
|
||||
|
||||
import data_formatters.base
|
||||
import libs.utils as utils
|
||||
import sklearn.preprocessing
|
||||
|
||||
GenericDataFormatter = data_formatters.base.GenericDataFormatter
|
||||
DataTypes = data_formatters.base.DataTypes
|
||||
InputTypes = data_formatters.base.InputTypes
|
||||
|
||||
|
||||
class VolatilityFormatter(GenericDataFormatter):
|
||||
"""Defines and formats data for the volatility dataset.
|
||||
|
||||
Attributes:
|
||||
column_definition: Defines input and data type of column used in the
|
||||
experiment.
|
||||
identifiers: Entity identifiers used in experiments.
|
||||
"""
|
||||
|
||||
_column_definition = [
|
||||
('Symbol', DataTypes.CATEGORICAL, InputTypes.ID),
|
||||
('date', DataTypes.DATE, InputTypes.TIME),
|
||||
('log_vol', DataTypes.REAL_VALUED, InputTypes.TARGET),
|
||||
('open_to_close', DataTypes.REAL_VALUED, InputTypes.OBSERVED_INPUT),
|
||||
('days_from_start', DataTypes.REAL_VALUED, InputTypes.KNOWN_INPUT),
|
||||
('day_of_week', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('day_of_month', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('week_of_year', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('month', DataTypes.CATEGORICAL, InputTypes.KNOWN_INPUT),
|
||||
('Region', DataTypes.CATEGORICAL, InputTypes.STATIC_INPUT),
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
"""Initialises formatter."""
|
||||
|
||||
self.identifiers = None
|
||||
self._real_scalers = None
|
||||
self._cat_scalers = None
|
||||
self._target_scaler = None
|
||||
self._num_classes_per_cat_input = None
|
||||
|
||||
def split_data(self, df, valid_boundary=2016, test_boundary=2018):
|
||||
"""Splits data frame into training-validation-test data frames.
|
||||
|
||||
This also calibrates scaling object, and transforms data for each split.
|
||||
|
||||
Args:
|
||||
df: Source data frame to split.
|
||||
valid_boundary: Starting year for validation data
|
||||
test_boundary: Starting year for test data
|
||||
|
||||
Returns:
|
||||
Tuple of transformed (train, valid, test) data.
|
||||
"""
|
||||
|
||||
print('Formatting train-valid-test splits.')
|
||||
|
||||
index = df['year']
|
||||
train = df.loc[index < valid_boundary]
|
||||
valid = df.loc[(index >= valid_boundary) & (index < test_boundary)]
|
||||
test = df.loc[index >= test_boundary]
|
||||
|
||||
self.set_scalers(train)
|
||||
|
||||
return (self.transform_inputs(data) for data in [train, valid, test])
|
||||
|
||||
def set_scalers(self, df):
|
||||
"""Calibrates scalers using the data supplied.
|
||||
|
||||
Args:
|
||||
df: Data to use to calibrate scalers.
|
||||
"""
|
||||
print('Setting scalers with training data...')
|
||||
|
||||
column_definitions = self.get_column_definition()
|
||||
id_column = utils.get_single_col_by_input_type(InputTypes.ID,
|
||||
column_definitions)
|
||||
target_column = utils.get_single_col_by_input_type(InputTypes.TARGET,
|
||||
column_definitions)
|
||||
|
||||
# Extract identifiers in case required
|
||||
self.identifiers = list(df[id_column].unique())
|
||||
|
||||
# Format real scalers
|
||||
real_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.REAL_VALUED, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
data = df[real_inputs].values
|
||||
self._real_scalers = sklearn.preprocessing.StandardScaler().fit(data)
|
||||
self._target_scaler = sklearn.preprocessing.StandardScaler().fit(
|
||||
df[[target_column]].values) # used for predictions
|
||||
|
||||
# Format categorical scalers
|
||||
categorical_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.CATEGORICAL, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
categorical_scalers = {}
|
||||
num_classes = []
|
||||
for col in categorical_inputs:
|
||||
# Set all to str so that we don't have mixed integer/string columns
|
||||
srs = df[col].apply(str)
|
||||
categorical_scalers[col] = sklearn.preprocessing.LabelEncoder().fit(
|
||||
srs.values)
|
||||
num_classes.append(srs.nunique())
|
||||
|
||||
# Set categorical scaler outputs
|
||||
self._cat_scalers = categorical_scalers
|
||||
self._num_classes_per_cat_input = num_classes
|
||||
|
||||
def transform_inputs(self, df):
|
||||
"""Performs feature transformations.
|
||||
|
||||
This includes both feature engineering, preprocessing and normalisation.
|
||||
|
||||
Args:
|
||||
df: Data frame to transform.
|
||||
|
||||
Returns:
|
||||
Transformed data frame.
|
||||
|
||||
"""
|
||||
output = df.copy()
|
||||
|
||||
if self._real_scalers is None and self._cat_scalers is None:
|
||||
raise ValueError('Scalers have not been set!')
|
||||
|
||||
column_definitions = self.get_column_definition()
|
||||
|
||||
real_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.REAL_VALUED, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
categorical_inputs = utils.extract_cols_from_data_type(
|
||||
DataTypes.CATEGORICAL, column_definitions,
|
||||
{InputTypes.ID, InputTypes.TIME})
|
||||
|
||||
# Format real inputs
|
||||
output[real_inputs] = self._real_scalers.transform(df[real_inputs].values)
|
||||
|
||||
# Format categorical inputs
|
||||
for col in categorical_inputs:
|
||||
string_df = df[col].apply(str)
|
||||
output[col] = self._cat_scalers[col].transform(string_df)
|
||||
|
||||
return output
|
||||
|
||||
def format_predictions(self, predictions):
|
||||
"""Reverts any normalisation to give predictions in original scale.
|
||||
|
||||
Args:
|
||||
predictions: Dataframe of model predictions.
|
||||
|
||||
Returns:
|
||||
Data frame of unnormalised predictions.
|
||||
"""
|
||||
output = predictions.copy()
|
||||
|
||||
column_names = predictions.columns
|
||||
|
||||
for col in column_names:
|
||||
if col not in {'forecast_time', 'identifier'}:
|
||||
output[col] = self._target_scaler.inverse_transform(predictions[col])
|
||||
|
||||
return output
|
||||
|
||||
# Default params
|
||||
def get_fixed_params(self):
|
||||
"""Returns fixed model parameters for experiments."""
|
||||
|
||||
fixed_params = {
|
||||
'total_time_steps': 252 + 5,
|
||||
'num_encoder_steps': 252,
|
||||
'num_epochs': 100,
|
||||
'early_stopping_patience': 5,
|
||||
'multiprocessing_workers': 5,
|
||||
}
|
||||
|
||||
return fixed_params
|
||||
|
||||
def get_default_model_params(self):
|
||||
"""Returns default optimised model parameters."""
|
||||
|
||||
model_params = {
|
||||
'dropout_rate': 0.3,
|
||||
'hidden_layer_size': 160,
|
||||
'learning_rate': 0.01,
|
||||
'minibatch_size': 64,
|
||||
'max_gradient_norm': 0.01,
|
||||
'num_heads': 1,
|
||||
'stack_size': 1
|
||||
}
|
||||
|
||||
return model_params
|
||||
Reference in New Issue
Block a user