Act as a spelling corrector, content editor, and text improver. ONLY return the rewritten text and nothing else.

Strictly follow these rules:
- Correct spelling, grammar, and punctuation errors in the given text
- Enhance clarity and conciseness without altering the original meaning
- Use the same language as the original text
- Divide lengthy sentences into shorter, more readable ones
- Eliminate unnecessary repetition while preserving important points
- Prioritize active voice over passive voice for a more engaging tone
- Opt for simpler, more accessible vocabulary when possible
- ALWAYS ensure the original meaning and intention of the given text
- ALWAYS maintain the original language of the text
- ALWAYS maintain the existing tone of voice and style, e.g. formal, casual, polite, etc.
- NEVER surround the improved text with quotes or any additional formatting
- If the text is already well-written and requires no improvement, do not change the given text

Text to improve:



from darts import TimeSeries
from darts.models import KalmanForecaster
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import matplotlib.pyplot as plt

# Define the train-test split ratio
train_ratio = 0.95

# Sample data for demonstration purposes
filtered_refgps = filtered_refgps  # assume this is already defined

# Determine the number of training samples
num_samples = len(filtered_refgps)
train_size = int(num_samples * train_ratio)

# Create a date range for the entire dataset
date_range = pd.date_range(start='2023-01-01', periods=num_samples, freq='D')

# Create a DataFrame with the date range and the filtered_refgps data
df = pd.DataFrame({'value': filtered_refgps}, index=date_range)

# Split the data into train and test sets
train_df = df.iloc[:train_size]
test_df = df.iloc[train_size:]

# Convert to TimeSeries with explicit frequency handling
train_series = TimeSeries.from_dataframe(train_df, freq='D', fill_missing_dates=True)

# Initialize KalmanForecaster
model = KalmanForecaster()

# Initial training
model.fit(train_series)

preds = []

# Process test data in a rolling window fashion
window_size = len(train_series)
for i in range(len(test_df)):
    # Get the current window of data
    current_window = df.iloc[i:i+window_size]
    current_series = TimeSeries.from_dataframe(current_window, freq='D', fill_missing_dates=True)
    
    # Fit the model on the current window
    model.fit(current_series)
    
    # Make one-step ahead prediction
    pred = model.predict(1)
    preds.append(pred)

    if (i + 1) % 10 == 0:
        print(f"Processed {i + 1}/{len(test_df)} observations")

# Extract predicted values
flattened_preds = np.array([pred.values()[0][0] for pred in preds])

# Calculate performance metrics
mse = mean_squared_error(test_df['value'], flattened_preds)
rmse = np.sqrt(mse)
mae = mean_absolute_error(test_df['value'], flattened_preds)
r2 = r2_score(test_df['value'], flattened_preds)

print(f'MSE: {mse:.4f}, RMSE: {rmse:.4f}, MAE: {mae:.4f}, R2: {r2:.4f}')

# Plot results
plt.figure(figsize=(12, 6))
plt.plot(test_df.index, test_df['value'].values, label='Actual')
plt.plot(test_df.index, flattened_preds, label='Predicted')
plt.legend()
plt.title('Kalman Filter Forecaster: Actual vs Predicted')
plt.xlabel('Date')
plt.ylabel('Value')
plt.show()