File size: 7,459 Bytes
276b412 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
import tempfile
from pathlib import Path
import datasets
import pandas as pd
_VERSION = "1.0.0"
_DESCRIPTION = "Chronos datasets"
_CITATION = """
@article{ansari2024chronos,
author = {Ansari, Abdul Fatir and Stella, Lorenzo and Turkmen, Caner and Zhang, Xiyuan, and Mercado, Pedro and Shen, Huibin and Shchur, Oleksandr and Rangapuram, Syama Syndar and Pineda Arango, Sebastian and Kapoor, Shubham and Zschiegner, Jasper and Maddix, Danielle C. and Wang, Hao and Mahoney, Michael W. and Torkkola, Kari and Gordon Wilson, Andrew and Bohlke-Schneider, Michael and Wang, Yuyang},
title = {Chronos: Learning the Language of Time Series},
journal = {arXiv preprint arXiv:2403.07815},
year = {2024}
}
"""
_ETTH = "ETTh"
_ETTM = "ETTm"
_SPANISH_ENERGY_AND_WEATHER = "spanish_energy_and_weather"
_BRAZILIAN_TEMPERATURE = "brazilian_cities_temperature"
class ChronosExtraConfig(datasets.BuilderConfig):
def __init__(
self,
name: str,
license: str = None,
homepage: str = None,
**kwargs,
):
super().__init__(name=name, **kwargs)
self.license = license
self.homepage = homepage
class ChronosExtraBuilder(datasets.GeneratorBasedBuilder):
BUILDER_CONFIG_CLASS = ChronosExtraConfig
BUILDER_CONFIGS = [
ChronosExtraConfig(
name=_ETTH,
license="CC BY-ND 4.0",
homepage="https://github.com/zhouhaoyi/ETDataset",
version=_VERSION,
),
ChronosExtraConfig(
name=_ETTM,
license="CC BY-ND 4.0",
homepage="https://github.com/zhouhaoyi/ETDataset",
version=_VERSION,
),
ChronosExtraConfig(
name=_BRAZILIAN_TEMPERATURE,
license="Database Contents License (DbCL) v1.0",
homepage="https://www.kaggle.com/datasets/volpatto/temperature-timeseries-for-some-brazilian-cities",
version=_VERSION,
),
ChronosExtraConfig(
name=_SPANISH_ENERGY_AND_WEATHER,
homepage="https://www.kaggle.com/datasets/nicholasjhana/energy-consumption-generation-prices-and-weather",
version=_VERSION,
),
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
citation=_CITATION,
version=self.config.version,
license=self.config.license,
homepage=self.config.homepage,
)
def _split_generators(self, dl_manager):
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN),
]
def _generate_examples(self):
if self.config.name in [_ETTH, _ETTM]:
yield from _ett_generator(self.config.name)
elif self.config.name == _SPANISH_ENERGY_AND_WEATHER:
yield from _spanish_energy_generator()
elif self.config.name == _BRAZILIAN_TEMPERATURE:
yield from _brazilian_temperature_generator()
def _ett_generator(name: str):
for region in [1, 2]:
url = f"https://raw.githubusercontent.com/zhouhaoyi/ETDataset/main/ETT-small/{name}{region}.csv?download=1"
df = pd.read_csv(url, parse_dates=["date"])
df = df.rename(columns={"date": "timestamp"})
entry = {"id": f"{name}{region}"}
for col in df.columns:
entry[col] = df[col].to_numpy()
yield region, entry
def _download_from_kaggle(dataset_name, download_path) -> None:
from kaggle.api.kaggle_api_extended import KaggleApi
api = KaggleApi()
api.authenticate()
api.dataset_download_files(dataset_name, path=download_path, unzip=True)
def _spanish_energy_generator():
with tempfile.TemporaryDirectory() as download_path:
_download_from_kaggle(
"nicholasjhana/energy-consumption-generation-prices-and-weather",
download_path,
)
download_path = Path(download_path)
df_energy = pd.read_csv(download_path / "energy_dataset.csv")
df_energy["time"] = pd.to_datetime(df_energy["time"], utc=True)
df_energy.set_index("time", inplace=True)
# Drop non-informative columns / columns containing forecasts
constant_columns = df_energy.columns[df_energy.nunique() <= 1].to_list()
forecast_columns = [
col for col in df_energy.columns if "forecast" in col or "day ahead" in col
]
columns_to_drop = constant_columns + forecast_columns
df_energy = df_energy.drop(columns_to_drop, axis=1)
entry = {"id": "0", "timestamp": df_energy.index.to_numpy(dtype="datetime64[ms]")}
for col in df_energy.columns:
saved_name = col.replace(" ", "_")
entry[saved_name] = df_energy[col].to_numpy(dtype="float64")
# Weather data
df_weather = pd.read_csv(download_path / "weather_features.csv")
df_weather["dt_iso"] = pd.to_datetime(df_weather["dt_iso"], utc=True)
df_weather = (
df_weather.rename(columns={"dt_iso": "time"})
.drop_duplicates(subset=["time", "city_name"], keep="first")
.set_index("time")
)
weather_features = [
"temp",
"temp_min",
"temp_max",
"pressure",
"humidity",
"wind_speed",
"wind_deg",
"rain_1h",
"snow_3h",
"clouds_all",
]
for feature in weather_features:
for city, df_for_city in df_weather.groupby("city_name"):
saved_name = f"{city.lstrip()}_{feature}"
entry[saved_name] = df_for_city[feature].to_numpy(dtype="float64")
assert df_for_city.index.equals(df_energy.index)
yield 0, entry
def _brazilian_temperature_generator():
months = [
"JAN",
"FEB",
"MAR",
"APR",
"MAY",
"JUN",
"JUL",
"AUG",
"SEP",
"OCT",
"NOV",
"DEC",
]
with tempfile.TemporaryDirectory() as download_path:
_download_from_kaggle(
"volpatto/temperature-timeseries-for-some-brazilian-cities", download_path
)
for filename in sorted(Path(download_path).iterdir()):
city = filename.name.split("_", maxsplit=1)[1].split(".")[0]
df = pd.read_csv(filename)
df = df.set_index("YEAR")[months]
first_timestamp = f"{df.index[0]}-01-01"
df = df.stack()
df[df == 999.9] = float("nan")
entry = {
"id": city,
"timestamp": pd.date_range(
first_timestamp, freq="MS", periods=len(df), unit="ms"
).to_numpy(),
"temperature": df.to_numpy("float32"),
}
yield city, entry
|