0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

watsonx.ai/Granite TimeSeriesModelの備忘録

Last updated at Posted at 2025-06-05

データ準備

# %% 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

モデル構築&予測

# %%
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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?