watsonx.ai/Granite TimeSeriesModelの備忘録

# データ準備

```python
# %% https://raw.githubusercontent.com/IBM/watsonx-ai-samples/refs/heads/master/cloud/data/energy/energy_dataset.csv
import pandas as pd

df = pd.read_csv(filepath_or_buffer="energy_dataset.csv")
print(df.tail().to_markdown(index=True))

# %%
print(df.describe().to_markdown())

# %%
timestamp_column = "time"           # 時刻の列名
target_column = "total load actual" # 予測対象の列名

# %%
context_length = 608                # 学習データは後ろから609行から
future_context = 96                 # 実績値は後ろから96行から

# %% 実績値（後ろから96行から）
future_data = df.iloc[-future_context:,]
print(future_data.shape)

# %%
print(future_data.head().to_markdown(index=True))

# %% 学習データ（後ろから609行から96-1行まで）
data = df.iloc[-context_length:-future_context,]
print(data.shape)

# %%
print(data.head().to_markdown(index=True))

# %%
import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(10,2))
plt.plot(np.asarray(data[timestamp_column], dtype='datetime64[s]'), data[target_column], label="Historical data")
plt.plot(np.asarray(future_data[timestamp_column], dtype='datetime64[s]'), future_data[target_column], label="True", linestyle='dashed')
plt.title("Actual Total Load")
plt.show()
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3756172/f164e93d-6d8e-4818-81b3-5fc370c20eb0.png)

# モデル構築＆予測

```python
# %%
from dotenv import load_dotenv

load_dotenv(override=True)

# %%
import os

api_key = os.environ.get("CLOUD_API_KEY")
print(api_key)
project_id = os.environ.get("PROJECT_ID")
print(project_id)

# %%
from ibm_watsonx_ai import Credentials

credentials = Credentials(
    url="https://us-south.ml.cloud.ibm.com",
    api_key=api_key,
)

# %%
from ibm_watsonx_ai import APIClient

client = APIClient(credentials)

# %%
client.set.default_project(project_id)

# %%
for model in client.foundation_models.get_time_series_model_specs()["resources"]:
    print('--------------------------------------------------')
    print(f'model_id: {model["model_id"]}')
    print(f'functions: {model["functions"]}')
    print(f'long_description: {model["long_description"]}')
    print(f'label: {model["label"]}')

# %%
ts_model_id = client.foundation_models.TimeSeriesModels.GRANITE_TTM_512_96_R2

# %%
from ibm_watsonx_ai.foundation_models import TSModelInference

ts_model = TSModelInference(
    model_id=ts_model_id,
    api_client=client
)

# %%
from ibm_watsonx_ai.foundation_models.schema import TSForecastParameters

forecasting_params = TSForecastParameters(
    timestamp_column=timestamp_column,
    freq="1h",
    target_columns=[target_column],
)

# %%
results = ts_model.forecast(data=data, params=forecasting_params)['results'][0]
print(results)

# %%
plt.figure(figsize=(10,2))
plt.plot(np.asarray(data[timestamp_column], dtype='datetime64[s]'), data[target_column], label="Historical data")
plt.plot(np.asarray(results[timestamp_column], dtype='datetime64[s]'), results[target_column], label="Predicted")
plt.plot(np.asarray(future_data[timestamp_column], dtype='datetime64[s]'), future_data[target_column], label="True", linestyle='dashed')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3756172/71761a2e-6abb-4cb5-a536-5ef2b70708da.png)