使用R语言Auto Arima预测非平稳时间序列遇问题,求代码审核
Hey there! I noticed you're running into issues using Auto ARIMA for forecasting non-stationary time series. Let's walk through your code and spot potential problems, plus suggest actionable fixes:
1. Your Current Code (Formatted & Fixed for Clarity)
Here's your code cleaned up with proper syntax and safer variable naming:
# 读取数据 r <- read.csv('../Amazon/Amazon1.csv', header = TRUE, stringsAsFactors = FALSE) # 时间序列构建 ts_data <- ts(t(r[,1:25]), frequency = 12, start = c(2016, 1) ) # 绘制时间序列 ts.plot(ts_data[,1:2], type = 'b', xlab = 'Monthly Cycle', ylab = 'Number of Sales', main = "(TIME SERIES) Amazon Sales Cycle ...")
(Quick note: I renamed your ts variable to ts_data because ts() is a built-in base R function—using it as a variable name can cause unexpected bugs later! Also fixed the unclosed quote in the main argument that would have thrown a syntax error.)
2. Key Issues & Optimization Tips
- Variable Naming Conflict: As mentioned above, avoid using
tsas an object name—it overwrites the corets()function. Stick to descriptive names likesales_tsorts_datainstead. - Data Transposition Validation: You’re transposing
r[,1:25]witht()—double-check that your original CSV is structured correctly. If your CSV has rows as variables (e.g., different product lines) and columns as monthly time points, the transposition makes sense. If rows are months and columns are variables, you might be mixing up the time order. Usehead(ts_data)to confirm the sequence matches your 2016-01 start date. - Non-Stationarity Handling: Even though Auto ARIMA can automatically select differencing orders, it’s smart to verify stationarity first with a formal test like the Augmented Dickey-Fuller (ADF) test:
If the p-value is > 0.05, your series is non-stationary. Auto ARIMA should pick up the need for differencing, but you can explicitly setlibrary(tseries) # Test stationarity for the first sales series adf_result <- adf.test(ts_data[,1]) print(adf_result)D=1(seasonal differencing) if you spot strong seasonal trends in your plot. - Add Auto ARIMA Implementation: You haven’t included the actual Auto ARIMA forecasting code yet! Here’s a robust template to add once your time series is properly structured:
Usinglibrary(forecast) # Build Auto ARIMA model for the first sales series arima_model <- auto.arima(ts_data[,1], seasonal = TRUE, stepwise = FALSE, approximation = FALSE) # Forecast next 12 months forecast_result <- forecast(arima_model, h = 12) # Plot the forecast plot(forecast_result)stepwise = FALSEandapproximation = FALSEensures the model searches the full range of possible ARIMA parameters, which leads to more reliable forecasts for non-stationary data.
内容的提问来源于stack exchange,提问作者Enormic doubtist
相关产品推荐
相关产品推荐

