On this tutorial, we construct a complicated agentic AI system that autonomously handles time sequence forecasting utilizing the Darts library mixed with a light-weight HuggingFace mannequin for reasoning. We design the agent to function in a notion–reasoning–motion cycle, the place it first analyzes patterns within the knowledge, then selects an applicable forecasting mannequin, generates predictions, and eventually explains and visualizes the outcomes. By strolling by way of this pipeline, we expertise how agentic AI can convey collectively statistical modeling and pure language reasoning to make forecasting each correct and interpretable. Take a look at the FULL CODES right here.
!pip set up darts transformers pandas matplotlib numpy -q
import pandas as pd
import numpy as np
from darts import TimeSeries
from darts.fashions import ExponentialSmoothing, NaiveSeasonal, LinearRegressionModel
from darts.metrics import mape, rmse
from transformers import pipeline
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
We start by putting in and importing the important libraries, together with Darts for time sequence forecasting, Transformers for reasoning, and supporting packages like pandas, NumPy, and matplotlib. With these instruments in place, we arrange the muse to construct and run our autonomous forecasting agent. Take a look at the FULL CODES right here.
class TimeSeriesAgent:
"""Autonomous agent for time sequence evaluation and forecasting"""
def __init__(self):
print("🤖 Initializing Agent Mind...")
self.llm = pipeline("text-generation", mannequin="distilgpt2", max_length=150,
do_sample=True, temperature=0.7)
self.fashions = {
'exponential_smoothing': ExponentialSmoothing(),
'naive_seasonal': NaiveSeasonal(Ok=12),
'linear_regression': LinearRegressionModel(lags=12)
}
self.selected_model = None
self.forecast = None
def understand(self, knowledge):
"""Agent perceives and analyzes the time sequence knowledge"""
print("n👁️ PERCEPTION PHASE")
self.ts = TimeSeries.from_dataframe(knowledge, 'date', 'worth', freq='M')
development = "growing" if knowledge['value'].iloc[-1] > knowledge['value'].iloc[0] else "lowering"
volatility = knowledge['value'].std() / knowledge['value'].imply()
seasonality = self._detect_seasonality(knowledge['value'])
evaluation = {
'size': len(knowledge),
'development': development,
'volatility': f"{volatility:.2f}",
'has_seasonality': seasonality,
'imply': f"{knowledge['value'].imply():.2f}",
'vary': f"{knowledge['value'].min():.2f} to {knowledge['value'].max():.2f}"
}
print(f"📊 Knowledge Factors: {evaluation['length']}")
print(f"📈 Development: {evaluation['trend'].higher()}")
print(f"🎲 Volatility: {evaluation['volatility']}")
print(f"🔄 Seasonality: {'Detected' if seasonality else 'Not detected'}")
return evaluation
def _detect_seasonality(self, sequence, threshold=0.3):
"""Easy seasonality detection"""
if len(sequence) < 24:
return False
acf = np.correlate(sequence - sequence.imply(), sequence - sequence.imply(), mode="full")
acf = acf[len(acf)//2:]
acf /= acf[0]
return np.max(acf[12:24]) > threshold if len(acf) > 24 else False
def motive(self, evaluation):
"""Agent causes about which mannequin to make use of"""
print("n🧠 REASONING PHASE")
immediate = f"Time sequence evaluation: {evaluation['length']} knowledge factors, {evaluation['trend']} development, "
f"volatility {evaluation['volatility']}, seasonality: {evaluation['has_seasonality']}. "
thought = self.llm(immediate, max_length=100, num_return_sequences=1)[0]['generated_text']
print(f"💭 Agent Considering: {thought[:150]}...")
if evaluation['has_seasonality']:
self.selected_model="naive_seasonal"
motive = "Seasonality detected - utilizing Naive Seasonal mannequin"
elif float(evaluation['volatility']) > 0.3:
self.selected_model="exponential_smoothing"
motive = "Excessive volatility - utilizing Exponential Smoothing"
else:
self.selected_model="linear_regression"
motive = "Steady development - utilizing Linear Regression"
print(f"✅ Resolution: {motive}")
return self.selected_model
def act(self, horizon=12):
"""Agent takes motion: trains mannequin and generates forecast"""
print("n⚡ ACTION PHASE")
practice, val = self.ts[:-12], self.ts[-12:]
mannequin = self.fashions[self.selected_model]
print(f"🎯 Coaching {self.selected_model}...")
mannequin.match(practice)
self.forecast = mannequin.predict(horizon)
if len(val) > 0:
val_pred = mannequin.predict(len(val))
accuracy = 100 - mape(val, val_pred)
print(f"📊 Validation Accuracy: {accuracy:.2f}%")
print(f"🔮 Generated {horizon}-step forecast")
return self.forecast
def clarify(self):
"""Agent explains its predictions"""
print("n💬 EXPLANATION PHASE")
forecast_values = self.forecast.values().flatten()
hist_values = self.ts.values().flatten()
change = ((forecast_values[-1] - hist_values[-1]) / hist_values[-1]) * 100
route = "improve" if change > 0 else "lower"
clarification = f"Primarily based on my evaluation utilizing {self.selected_model}, "
f"I predict a {abs(change):.1f}% {route} within the subsequent interval. "
f"Forecast vary: {forecast_values.min():.2f} to {forecast_values.max():.2f}. "
f"Historic imply was {hist_values.imply():.2f}."
print(f"📝 {clarification}")
immediate = f"Forecast abstract: {clarification} Clarify implications:"
abstract = self.llm(immediate, max_length=120)[0]['generated_text']
print(f"n🤖 Agent Abstract: {abstract[:200]}...")
return clarification
def visualize(self):
"""Agent creates visualization of its work"""
print("n📊 Producing visualization...")
plt.determine(figsize=(14, 6))
self.ts.plot(label="Historic Knowledge", lw=2)
self.forecast.plot(label=f'Forecast ({self.selected_model})',
lw=2, linestyle="--")
plt.title('🤖 Agentic AI Time Collection Forecast', fontsize=16, fontweight="daring")
plt.xlabel('Date', fontsize=12)
plt.ylabel('Worth', fontsize=12)
plt.legend(loc="greatest", fontsize=11)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.present()
We outline a TimeSeriesAgent that thinks with a light-weight HuggingFace mannequin and acts with a small portfolio of Darts fashions. We understand patterns (development, volatility, seasonality), motive to decide on the perfect mannequin, then practice, forecast, and validate. Lastly, we clarify the prediction in plain language and visualize historical past versus forecast. Take a look at the FULL CODES right here.
def create_sample_data():
"""Generate pattern time sequence knowledge"""
dates = pd.date_range(begin="2020-01-01", durations=48, freq='M')
development = np.linspace(100, 150, 48)
seasonality = 10 * np.sin(np.linspace(0, 4*np.pi, 48))
noise = np.random.regular(0, 3, 48)
values = development + seasonality + noise
return pd.DataFrame({'date': dates, 'worth': values})
We create a helper operate create_sample_data() that generates artificial time sequence knowledge with a transparent development, sinusoidal seasonality, and random noise. This permits us to simulate sensible month-to-month knowledge from 2020 to 2023 for testing and demonstrating the agent’s forecasting workflow. Take a look at the FULL CODES right here.
def primary():
"""Fundamental execution: Agent autonomously handles forecasting activity"""
print("="*70)
print("🚀 AGENTIC AI TIME SERIES FORECASTING SYSTEM")
print("="*70)
print("n📥 Loading knowledge...")
knowledge = create_sample_data()
print(f"Loaded {len(knowledge)} knowledge factors from 2020-01 to 2023-12")
agent = TimeSeriesAgent()
evaluation = agent.understand(knowledge)
agent.motive(evaluation)
agent.act(horizon=12)
agent.clarify()
agent.visualize()
print("n" + "="*70)
print("✅ AGENT COMPLETED FORECASTING TASK SUCCESSFULLY")
print("="*70)
if __name__ == "__main__":
primary()
We outline the primary operate that runs the total agentic AI pipeline. We load artificial time sequence knowledge, let the TimeSeriesAgent understand patterns, motive to pick out the perfect mannequin, act by coaching and forecasting, clarify the outcomes, and eventually visualize them. This completes the end-to-end autonomous notion, reasoning, and motion cycle.
In conclusion, we see how an autonomous agent can analyze time sequence knowledge, motive about mannequin choice, generate forecasts, and clarify its predictions in pure language. By combining Darts with HuggingFace, we create a compact but highly effective framework that not solely produces correct forecasts but in addition clearly communicates insights. We full the cycle with visualization, reinforcing how agentic AI makes forecasting extra intuitive and interactive.
Take a look at the FULL CODES right here. Be at liberty to take a look at our GitHub Web page for Tutorials, Codes and Notebooks. Additionally, be at liberty to comply with us on Twitter and don’t neglect to hitch our 100k+ ML SubReddit and Subscribe to our E-newsletter. Wait! are you on telegram? now you may be part of us on telegram as effectively.
Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is dedicated to harnessing the potential of Synthetic Intelligence for social good. His most up-to-date endeavor is the launch of an Synthetic Intelligence Media Platform, Marktechpost, which stands out for its in-depth protection of machine studying and deep studying information that’s each technically sound and simply comprehensible by a large viewers. The platform boasts of over 2 million month-to-month views, illustrating its reputation amongst audiences.