It seems you are running into an error because one of the models you are using for forecasting, possibly the DynamicOptimizedTheta, requires at least 2 complete cycles of seasonal data to decompose the series, which corresponds to 104 observations for a season_length of 52. However, it appears that for some unique_ids in the dataset y_cl4_over_45, there are only 82 observations available, which is insufficient for this model to operate correctly.
User
this is strange, I'll give you another model using adifferent aggregation on y_cl4, please dont confuse the 2 models, # Display 200 rows in Polars output
pl.Config.set_tbl_rows(200)
Function to perform the grouping, counting, and sorting of lengths
Assistant
User
same library, same models except no CES on first model, dataset just different level of aggregation, the first one is more complex
Assistant
User
I mean it's not feasbiel to filter out more series for first model to 104 weeks
Assistant
User
how to I check the version of statsforecast
Assistant
To check the version of the statsforecast library (or any Python package) that you currently have installed, you can use the pip command or inspect it from within your Python code.
Using pip from the command line:
pip show statsforecast
This command will display various details about the package, including the version number.
Using Python code:
You can check the version by importing the statsforecast package and then checking its __version__ attribute:
This will print out the version of statsforecast that is currently installed in your Python environment.
If you are working with Jupyter notebooks, IPython shells, or any standard Python interpreter, you can execute the above line of code directly to get the version information. Remember to make sure that you're using the Python environment where the statsforecast library is installed when running the command or the code.
User
so I was doing some research online and it seeems this happens because some series might have some gap causing the seasoanl decompose tio not work correctly, can we check what series doing this and how many of them
Assistant
User
def has_sufficient_data(df, season_length=52, required_cycles=2):
# Define a function that checks if a series has enough data and no large gaps
def check_series_has_enough_data(series_group):
# Check if the number of observations meets the minimum requirement
if len(series_group) < (season_length * required_cycles):
return False
# You can add more conditions here to check for gaps if needed
# For example, if series_group[‘ds’] is not consecutive for time
return True
Assistant
It appears there's an issue with the Polars code snippet that I initially provided, specifically with the return type of the check_series_has_enough_data function. The function is returning a Boolean, but since we're using it inside a GroupBy operation with apply (which expects a DataFrame return type), we must return a DataFrame instead.
User
15 return result
~/anaconda3/lib/python3.10/site-packages/polars/utils/deprecation.py in ?(*args, **kwargs)
56 issue_deprecation_warning(
57 f"{function.__name__} is deprecated. {message}",
58 version=version,
59 )
---> 60 return function(*args, **kwargs)
~/anaconda3/lib/python3.10/site-packages/polars/dataframe/frame.py in ?(self, function, return_dtype, inference_size)
10788 inference_size
10789 Only used in the case when the custom function returns rows.
10790 This uses the first n rows to determine the output schema
10791 """
AttributeError: module 'polars' has no attribute 'count_distinct'
Assistant
User
is there an easier way? all your solutions got errrors
Assistant
User
how to I convert this into line plot # Filter the data
filtered_data = y_cl4.filter(y_cl4['unique_id'] == "12409676_US04_8_1131042")
Extract the 'y' values for the unique_id
y_values = filtered_data['y']
Plot the data
plt.figure(figsize=(10, 6))
plt.plot(filtered_data['ds'].to_pandas(), y_values.to_pandas(), marker='o', linestyle='', markersize=2)
plt.title('OrderQuantity by WeekDate for unique_id "12522129_US01_9_5338738"')
plt.xlabel('WeekDate')
plt.ylabel('OrderQuantity')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Assistant
To plot a line chart using Matplotlib in Python, you should ensure that your data is sorted by the date column ds. After filtering the data and extracting the values, you can plot them directly using Matplotlib.
However, it seems there is a typo in your plot title's unique_id, which should match the unique_id you've filtered by ("12409676_US04_8_1131042" instead of ). Here is the corrected and streamlined code for plotting:
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
Print the list
for forecast in forecasts_list:
print(forecast) RemoteTraceback Traceback (most recent call last)
RemoteTraceback:
"""
Traceback (most recent call last):
File "/Users/tungnguyen/anaconda3/lib/python3.10/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/core.py", line 322, in cross_validation
raise error
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/core.py", line 319, in cross_validation
res_i = model.forecast(**forecast_kwargs)
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/models.py", line 1292, in forecast
mod = auto_theta(
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/theta.py", line 633, in auto_theta
y_decompose = seasonal_decompose(y, model=decomposition_type, period=m).seasonal
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsmodels/tsa/seasonal.py", line 171, in seasonal_decompose
raise ValueError(
ValueError: x must have 2 complete cycles requires 104 observations. x only has 82 observation(s)
"""
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
Cell In[22], line 21
18 sf = StatsForecast(models=models, freq='1w', n_jobs=-1)
20 # Perform cross-validation with a step size of 1 to mimic an expanding window
---> 21 crossvalidation_df = sf.cross_validation(df=y_cl4_over_45, h=5, step_size=1, n_windows=10, sort_df=True)
23 # Calculate the ensemble mean
24 ensemble = crossvalidation_df[['AutoARIMA', 'AutoETS', 'DynamicOptimizedTheta']].mean(axis=1)
File ~/anaconda3/lib/python3.10/site-packages/statsforecast/core.py:1248, in _StatsForecast._cross_validation_parallel(self, h, test_size, step_size, input_size, fitted, level, refit, target_col)
1232 future = executor.apply_async(
1233 ga.cross_validation,
1234 (
(...)
1245 ),
1246 )
1247 futures.append(future)
-> 1248 out = [f.get() for f in futures]
1249 fcsts = [d["forecasts"] for d in out]
1250 fcsts = np.vstack(fcsts)
File ~/anaconda3/lib/python3.10/site-packages/statsforecast/core.py:1248, in (.0)
1232 future = executor.apply_async(
1233 ga.cross_validation,
1234 (
(...)
1245 ),
1246 )
1247 futures.append(future)
-> 1248 out = [f.get() for f in futures]
1249 fcsts = [d["forecasts"] for d in out]
1250 fcsts = np.vstack(fcsts)
ValueError: x must have 2 complete cycles requires 104 observations. x only has 82 observation(s)
To resolve this, you can either:
Filter the dataset y_cl4_over_45 to ensure that all series have at least 104 observations before passing them to the cross-validation function.
Modify your models list to exclude models that require at least 2 complete cycles, or adjust the season_length if appropriate.
Here's an updated version of your code snippet to filter the dataset y_cl4_over_45 before cross-validation:
# First, determine the minimum number of required observations
min_observations_required = 104
# Ensure that each series in y_cl4_over_45 has enough observations
valid_ids = (
y_cl4_over_45
.groupby('unique_id')
.agg(pl.count().alias('count'))
.filter(pl.col('count') >= min_observations_required)
.select('unique_id')
)
# Filter y_cl4_over_45 for valid unique_ids
y_cl4_over_45_valid = y_cl4_over_45.filter(pl.col('unique_id').is_in(valid_ids['unique_id']))
# Perform cross-validation with a step size of 1 to mimic an expanding window
# Now use y_cl4_over_45_valid for the cross-validation
crossvalidation_df = sf.cross_validation(df=y_cl4_over_45_valid, h=5, step_size=1, n_windows=10, sort_df=True)
Please incorporate this snippet before the cross-validation step to ensure that you are only using series with a sufficient number of observations.
If adjusting y_cl4_over_45 does not solve the problem, consider revising the set of models you are using in the forecasting ensemble. For example, you could remove the DynamicOptimizedTheta model if many of your series do not meet the minimum observation requirement, or you could use a different model that does not have such requirements.
ensemble = crossvalidation_df[['AutoARIMA', 'AutoETS', 'CES', 'DynamicOptimizedTheta']].mean(axis=1) so the shortest series 40 weeks and I used even higher h and n_windows but there was no problem doing cross validation and 104 weeks forecast, I even included Complex Exponential Smoothing (CES) which takes more time and a bit harder to fit, why would this be the case, the shortest week length for first model is 46
The reason your second model with AutoARIMA, AutoETS, AutoCES, and DynamicOptimizedTheta works successfully, despite having series with as few as 40 weeks of data, likely has to do with the internal handling of data within these models. It’s possible that some or all of these models are able to handle shorter series by padding data, using simpler non-seasonal versions, or using some other form of imputation to deal with the lack of two full seasonal cycles.
When you received the error in the first instance, it specifically pointed to the DynamicOptimizedTheta model, which was expecting at least two complete cycles, or 104 observations, for a season_length of 52.
There are a few possibilities that might explain why you didn't encounter an error with the second model:
AutoARIMA, AutoETS, and AutoCES may be better suited to handle shorter time series and do not necessarily require two full seasonal cycles to generate forecasts. They could be operating on non-seasonal versions or using model configurations that are less rigid.
The StatsForecast library might have been updated to handle exceptions internally, depending on your usage scenario.
You may be using a different subset of data for the second model, although it might seem that you are using the same dataset (y_cl4). Perhaps an internal filter or different step within your workflow is resulting in different unique series being fed to the models, causing an implicit filter on the length of the series.
A change in the hyperparameters (h and n_windows) might have influenced how the data was divided into training and test sets, possibly avoiding the problematic scenario where a short series was causing trouble.
It’s also worth noting that the error message indicated an issue at prediction time—not fitting time—which suggests that during the cross-validation process, the model might have encountered issues generating forecasts for the validation window due to insufficient data to accommodate the seasonal decompose step (for the DynamicOptimizedTheta model specifically).
If you are interested in understanding the discrepancy more deeply, you might want to:
Examine the cross-validation framework to ensure it does not accidentally omit data points or series.
Check the actual series being passed to both models to confirm their lengths.
Update/review any library code or documentation in case of changes in how models or cross-validation methods handle series with insufficient length.
Test each model independently to better understand their individual behavior and requirements for time series length.
Ultimately, the models are black box algorithms with details hidden within the implementation. However, addressing the minimum requirement for seasonal models based solely on the error message from your initial attempt seems to be the correct approach. If you can, observe how each model behaves with shorter series and consult the respective model's documentation for more details.
Given that the datasets have different levels of aggregation and the first one is more complex, there are a few factors to consider:
Aggregation level and series length: Even though the shortest series in the second dataset is 40 weeks, it might still work because the models are capable of handling shorter series lengths, or because the cross-validation framework within StatsForecast is executing successfully with enough historical data points to generate forecasts for the requested horizon. Depending on how StatsForecast handles cross-validation internally, it's possible that enough data points remain to forecast the required horizon for each window.
Model flexibility: Certain models can handle shorter series by internally adjusting their parameters or the model specification. For example, AutoARIMA can run in a non-seasonal mode if it detects insufficient data for a seasonal model, and similar behavior might be expected from other models such as AutoETS.
Data distribution or variation: A more complex dataset might exhibit more fluctuation or noise, potentially affecting the model's ability to capture the underlying pattern, especially when dealing with shorter series. This could lead to internal checks that prevent the model from running if it detects that the quality of the output might be compromised.
Internal changes in the library:StatsForecast could have been updated between your two attempts, resulting in different handling of series lengths within cross-validation or within the models themselves. This might explain why the more recent attempt with four models, including CES, didn't face any issues.
In the first instance, the error message specifically pointed out that DynamicOptimizedTheta expected at least two complete cycles, which corresponds to a minimum of 104 observations for a season_length of 52. If this requirement holds true for the first dataset but not for the second one, there might be additional logic in place that's handling the datasets differently based on their characteristics, or the error might arise from a different kind of limitation within the first dataset.
If you want to troubleshoot this further, here are some steps you can take:
Ensure consistency: Confirm that the y_cl4 variable used in the second attempt indeed represents the full set of series you intend to use for cross-validation and that no implicit data filters apply.
Debug individual series: Test the cross-validation function on individual series from the first dataset to isolate the issue. Identify if the error originates from a specific unique_id or a subset of unique_ids.
Contact library maintainers: If the behavior is not consistent or expected, consider reaching out to the maintainers of the StatsForecast library with a reproducible example to gain insight into the internal workings or whether there might be a bug or an undocumented feature affecting your results.
Review library updates: Check the library's changelog for any updates between your analysis sessions that might impact behavior.
Simplify the model suite: Try running the first, more complex dataset with a reduced set of models that might be more flexible regarding season length requirements.
By taking these steps, you should be able to determine more confidently why the two seemingly analogous situations are yielding different results and how to adapt your approach accordingly.
If filtering out series with less than 104 weeks of data is not feasible for the first model, there are some alternative strategies you can explore to accommodate the limited data:
Model Exclusion:
Exclude the DynamicOptimizedTheta model or any other models that require a minimum of 104 observations, and rely on the remaining models that can handle shorter series.
Model Adjustment:
Adjust DynamicOptimizedTheta or other models to work with a shorter seasonal period that matches the data you have. This would mean changing the season_length parameter to fit the length of the cycles present in your data—if such cycles exist and are known.
Imputation/Filling:
Temporarily impute or fill in missing values to extend the time series to the required length. This can allow models to run, but keep in mind that imputing data introduces assumptions about the missing values that may not hold true and can affect forecast accuracy.
Time Series Transformation:
Transform the time series to a representation that doesn't require full seasonal cycles. For example, you can use differencing to remove the seasonal component before modeling.
Custom Cross-Validation:
Implement a custom cross-validation scheme that only evaluates forecasts for windows where sufficient historical data is available for each series, skipping windows where data is insufficient.
Incremental Training:
For series with limited historical data, consider incrementally training the models as new data arrives until you have enough data to fully use the desired models.
Simpler Models:
Use simpler time series models that don't require two full seasonal cycles. These might not be as accurate as the more complex models but would provide a solution for producing forecasts with limited data.
Revisit Data Aggregation:
Consider whether the data aggregation process can be adjusted to produce time series with more observations. For example, if the data is aggregated monthly, weekly aggregation might provide more data points.
Combination Approach:
Use a combination of models, where shorter series are forecasted with models that can handle them, while longer series are forecasted with the full suite of models including DynamicOptimizedTheta.
Expert Judgment:
Consult domain experts to adjust the forecasts for the shorter series manually or to suggest plausible values that can be used to extend the series to the required length.
Implementing any of these strategies will depend on the specific context of your problem, the nature of the data, and the business requirements for the forecasts. Consider testing each approach to see which one provides the best balance between model performance and handling the limitations of your dataset.
To determine which specific series are causing the issue with the DynamicOptimizedTheta model due to gaps in the data, you can inspect each unique_id group individually and check for the number of observations and gaps. A gap means that there is a break in the time series data, leading to non-consecutive periods (e.g., missing weeks).
Here's a conceptual approach using Polars to identify such series:
import polars as pl
def has_sufficient_data(df, season_length=52, required_cycles=2):
# Define a function that checks if a series has enough data and no large gaps
def check_series_has_enough_data(series_group):
# Check if the number of observations meets the minimum requirement
if len(series_group) < (season_length * required_cycles):
return False
# You can add more conditions here to check for gaps if needed
# For example, if series_group['ds'] is not consecutive for time
return True
# Group the data by 'unique_id' and then apply the function
result = df.groupby('unique_id').apply(check_series_has_enough_data)
# The result is a DataFrame indicating if each group meets the condition
return result
# Let's assume y_cl4 is your DataFrame, which includes columns 'unique_id' and 'ds'
# Apply the function to your DataFrame
sufficient_data_by_series = has_sufficient_data(y_cl4)
# Filter out the series that do not have sufficient data
series_with_issues = sufficient_data_by_series.filter(pl.col("has_sufficient_data") == False)
# Now, series_with_issues contains the unique_ids that have issues
print(series_with_issues)
If you want to specifically check for gaps, you can modify the check_series_has_enough_data function to check the time intervals between consecutive observations.
Here's a more detailed example that checks for both gaps and sufficient length:
def check_series_has_sufficient_data_and_no_gaps(series_group, frequency='1w'):
# Check if the number of observations meets the minimum requirement
if len(series_group) < (season_length * required_cycles):
return False
# Check for gaps in the series based on the expected frequency
series_group = series_group.sort('ds') # Sort the series by the date column
expected_dates = pl.date_range(
start=series_group['ds'].min(),
end=series_group['ds'].max(),
interval=frequency
)
# If the number of expected dates doesn't match the actual dates, there's a gap
if len(expected_dates) != len(series_group):
return False
return True
# Group the data by 'unique_id' and then apply the function
sufficient_data_by_series = y_cl4.groupby('unique_id').apply(check_series_has_sufficient_data_and_no_gaps)
# Filter out the series that do not have sufficient data
series_with_issues = sufficient_data_by_series.filter(pl.col("has_sufficient_data") == False)
This code checks the date range between the minimum and maximum dates of each series and compares it against the actual number of dates in the series to detect gaps.
By applying these functions to your data, you should be able to identify which series are causing problems with the DynamicOptimizedTheta model. This will allow you to either address the data issues directly or exclude those series from your modeling process.
# Group the data by ‘unique_id’ and then apply the function
result = df.groupby('unique_id').apply(check_series_has_enough_data)
# The result is a DataFrame indicating if each group meets the condition
return result
Let’s assume y_cl4 is your DataFrame, which includes columns ‘unique_id’ and ‘ds’
File ~/anaconda3/lib/python3.10/site-packages/polars/dataframe/group_by.py:773, in GroupBy.apply(self, function)
760 @deprecate_renamed_function("map_groups", version="0.19.0")
761 def apply(self, function: Callable[[DataFrame], DataFrame]) -> DataFrame:
762 """
763 Apply a custom/user-defined function (UDF) over the groups as a sub-DataFrame.
764
(...)
771 Custom function.
772 """
--> 773 return self.map_groups(function)
File ~/anaconda3/lib/python3.10/site-packages/polars/dataframe/group_by.py:322, in GroupBy.map_groups(self, function)
318 msg = "cannot call map_groups when grouping by an expression"
319 raise TypeError(msg)
321 return self.df.class._from_pydf(
--> 322 self.df._df.group_by_map_groups(
323 list(self.by), function, self.maintain_order
324 )
325 )
PanicException: Could not get DataFrame attribute '_df'. Make sure that you return a DataFrame object.: PyErr { type: <class 'AttributeError'>, value: AttributeError("'bool' object has no attribute '_df'"), traceback: None }
Let's update the function to return a DataFrame with a new column that indicates whether the series has enough data and no gaps:
def has_sufficient_data(df, season_length=52, required_cycles=2):
# Define a function that checks if a series has enough data and looks for large gaps
def check_series_has_enough_data(series_group):
# Check if the number of observations meets the minimum requirement
sufficient_data = len(series_group) >= (season_length * required_cycles)
no_large_gaps = True # Place your gap-checking code here if required
# Return the results as a DataFrame
return pl.DataFrame({"has_sufficient_data": [sufficient_data and no_large_gaps]})
# Group the data by 'unique_id' and then apply the function
result = df.groupby('unique_id').agg(pl.col("*")).apply(check_series_has_enough_data)
# The result is a DataFrame indicating if each group meets the condition
return result
# Apply the function to your DataFrame
sufficient_data_by_series = has_sufficient_data(y_cl4)
# Filter out the series that do not have sufficient data
series_with_issues = sufficient_data_by_series.filter(pl.col("has_sufficient_data") == False)
# Now, series_with_issues contains the unique_ids that have issues
print(series_with_issues)
If you want to check for gaps within each series, you can add the appropriate logic in the placeholder # Place your gap-checking code here if required within the check_series_has_enough_data function. The gap-checking logic might involve comparing the expected dates considering the data frequency with the actual dates available in the series.
Additionally, ensure that the y_cl4 DataFrame is sorted by 'unique_id' and then by the date column 'ds' before you apply the function. It's critical that the time series data is in time order within each group to analyze gaps in the series correctly.
Sorry for the confusion. It seems there might have been some issues in my previous explanation on how to apply a function to a Polars DataFrame grouped by some key. Let's correct that.
Here is a revised approach using the Polars library to check each unique ID series within your DataFrame for the required amount of data.
This approach will:
Sort your DataFrame by 'unique_id' and 'ds' date column.
Check each group for the number of observations.
Optionally, check for gaps if your time series requires continuous data within each unique ID.
import polars as pl
# Assuming 'y_cl4' DataFrame contains a 'unique_id' and a 'ds' date column.
# Data should be sorted by 'unique_id' and 'ds' prior to applying the function.
# Define the threshold for the minimum number of observations.
season_length = 52
required_cycles = 2
min_observations_required = season_length * required_cycles
# Group by 'unique_id' and aggregate to get observation counts for each group.
obs_counts_by_group = (
y_cl4.lazy()
.with_column((pl.count().over('unique_id')).alias('num_observations'))
.collect()
)
# Another approach for gap detection is to find the minimum and maximum dates
# and check if the number of unique dates matches the span of the range minus gaps.
# This assumes y_cl4 is pre-sorted by 'unique_id' and 'ds'.
check_gaps_group = (
y_cl4.lazy()
.select([
'unique_id',
'ds'
])
.with_columns([
pl.min('ds').over('unique_id').alias('min_date'),
pl.max('ds').over('unique_id').alias('max_date'),
pl.count('ds').over('unique_id').alias('observation_count'),
pl.count_distinct('ds').over('unique_id').alias('distinct_dates_count')
])
.distinct()
.filter((pl.col('observation_count') != pl.col('distinct_dates_count')) |
(pl.col('observation_count') < min_observations_required))
.collect()
)
# Now, 'check_gaps_group' will contain 'unique_id's with data issues:
# either gaps in the series or insufficient amount of data.
print(check_gaps_group.filter(pl.col('distinct_dates_count') < min_observations_required))
# You could then take the unique_ids that fail the checks from 'check_gaps_group'
# and deal with them according to your requirements, e.g., imputation, exclusion, etc.
Please note that you might need to adjust the filter conditions according to the structure and requirements of your data and whether gaps in dates are acceptable.
In this snippet, check_gaps_group will contain the unique_ids for which either there are gaps in the data or the number of observations is below the threshold. You can then deal with those series accordingly.
I apologize for the error. It looks like there's a mistake as the correct Polars function to count distinct values is n_unique instead of count_distinct. Let's correct this and go through the revised Polars code to identify series with gaps or an insufficient number of data points:
import polars as pl
# Assuming 'y_cl4' DataFrame contains a 'unique_id' and a 'ds' date column.
# Data should be sorted by 'unique_id' and 'ds' prior to applying the function.
# Define the threshold for the minimum number of observations.
season_length = 52
required_cycles = 2
min_observations_required = season_length * required_cycles
# Group by 'unique_id' and aggregate to get observation counts for each group.
obs_counts_by_group = (
y_cl4.lazy()
.with_column(pl.count().over("unique_id").alias("num_observations"))
.collect()
)
# Another approach for gap detection is to find the minimum and maximum dates
# and check if the number of unique dates matches the span of the range minus gaps.
# This assumes y_cl4 is pre-sorted by 'unique_id' and 'ds'.
check_gaps_group = (
y_cl4.lazy()
.with_columns([
pl.col("ds").count().over("unique_id").alias("observation_count"),
pl.col("ds").n_unique().over("unique_id").alias("distinct_dates_count"),
pl.first("ds").over("unique_id").alias("first_date"),
pl.last("ds").over("unique_id").alias("last_date"),
])
.groupby("unique_id")
.agg([
pl.max("observation_count").alias("max_observation_count"),
pl.max("distinct_dates_count").alias("max_distinct_dates_count"),
pl.max("first_date").alias("actual_first_date"),
pl.max("last_date").alias("actual_last_date"),
])
.with_columns([
pl.date_range(pl.col("actual_first_date"), pl.col("actual_last_date"), "1w").count().alias("expected_weeks_count")
])
.filter(
(pl.col("max_observation_count") < min_observations_required) |
(pl.col("max_observation_count") != pl.col("expected_weeks_count"))
)
.collect()
)
# Now, 'check_gaps_group' will contain 'unique_id's with data issues:
# either gaps in the series or an insufficient amount of data.
print(check_gaps_group)
Here is the summary of what each part does:
It counts the number of observations and distinct dates for each 'unique_id.'
It finds the first and last date for each 'unique_id.'
It calculates the expected number of weeks between the first and last date.
It filters for 'unique_id's where the actual number of observations is less than the minimum required or does not match the expected number of weeks (indicating gaps).
Now, check_gaps_group will contain the unique_ids for which there are gaps or insufficient data. You can further analyze these cases or decide on how to handle them before proceeding with your forecasting models.
I apologize for the confusion and inconvenience. Let's simplify the process and try a direct approach using a more concise Polars code snippet to check for gaps and sufficient length within each unique_id series.
Firstly, make sure you've sorted your dataframe by ds within each unique_id group. Here's an approach that should work:
import polars as pl
# Assuming 'y_cl4' DataFrame contains 'unique_id' and 'ds' date column
season_length = 52
required_cycles = 2
min_observations_required = season_length * required_cycles
# Calculate the difference between each date and its predecessor within each 'unique_id'
y_cl4 = y_cl4.sort(["unique_id", "ds"])
date_diffs = y_cl4.select([
pl.col("unique_id"),
pl.col("ds").diff().over("unique_id").alias("date_diff")
])
# Find each 'unique_id' with gaps (where difference between dates > 1 week assuming weekly data)
unique_ids_with_gaps = (
date_diffs
.filter(pl.col("date_diff") > pl.duration(days=7)) # Filter for gaps larger than 1 week, assuming weekly data
.select("unique_id")
.unique()
)
# Extract a list of 'unique_id' with gaps
ids_with_gaps = unique_ids_with_gaps["unique_id"].to_list()
# Calculate series lengths for each 'unique_id', assuming no missing 'unique_id' groups in the data
series_lengths = (
y_cl4
.groupby("unique_id")
.agg(pl.count("ds").alias("series_length"))
)
# Find 'unique_id' with too few observations
unique_ids_with_insufficient_length = (
series_lengths
.filter(pl.col("series_length") < min_observations_required)
.select("unique_id")
)
# Extract a list of 'unique_id' with insufficient length
ids_with_insufficient_length = unique_ids_with_insufficient_length["unique_id"].to_list()
# Combine lists and find unique 'unique_id's that have either issue
ids_with_issues = list(set(ids_with_gaps + ids_with_insufficient_length))
# Output the 'unique_id' with gaps or insufficient lengths
print("IDs with issues:", ids_with_issues)
This code aims to:
Calculate the difference in days between consecutive observations within each unique_id series.
Find unique_ids that have gaps greater than 7 days (assuming weekly data).
Calculate the lengths of each series and find unique_ids with fewer observations than the minimum required.
Consolidate the unique_ids with either issue and output the list.
Please try running this code on your data, and it should identify the unique_ids that have insufficient lengths or gaps larger than a week. If data for any unique_id is entirely missing in 'y_cl4', the group by operation won't count zero-length series, so ensure that the data frame includes all unique_id groups, even those without records, if it's important to your analysis.
"12522129_US01_9_5338738"
import matplotlib.pyplot as plt
# Filter the data
filtered_data = y_cl4.filter(pl.col('unique_id') == "12409676_US04_8_1131042")
# Ensure the data is sorted by the 'ds' date column
filtered_data = filtered_data.sort('ds')
# Convert the 'ds' column to Pandas datetime series for better plotting
ds_values = filtered_data['ds'].to_pandas()
# Extract the 'y' values (OrderQuantity) for the unique_id
y_values = filtered_data['y'].to_pandas()
# Plot the data as a line plot
plt.figure(figsize=(10, 6))
plt.plot(ds_values, y_values, marker='o', linestyle='-', markersize=2)
plt.title('OrderQuantity by WeekDate for unique_id "12409676_US04_8_1131042"')
plt.xlabel('WeekDate')
plt.ylabel('OrderQuantity')
plt.xticks(rotation=45) # Rotate the x-axis labels for better readability
plt.tight_layout() # Adjust the plot to ensure everything fits without overlapping
plt.show()
In this code snippet:
We first make sure the data for plotting is sorted by ds to ensure the line plot is correct.
We extract the relevant columns (ds and y).
We convert the ds column to a Pandas datetime series because Matplotlib handles Pandas datetime objects well for the x-axis. This step also provides better formatting and control over date axis labels.
We plot ds_values as our x-axis and y_values as our y-axis using plt.plot(). We use markers to indicate each data point and draw a connecting line between points.
The title is updated to reflect the correct unique_id.
Finally, we call plt.show() to display the plot.
After running this code, you should see a line plot that visualizes the OrderQuantity (y column) by WeekDate (ds column) for the specified unique_id.