ARIMA预测报错:无法将float64转为int64(same_kind规则)
Hey, let's work through this error you're facing! That Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind' message boils down to a data type mismatch between your input data and the ARIMA model's internal calculations.
What's causing this?
Your specific dataset is stored as int64 (integer) values, while other datasets you're using are likely floating-point. When you save the ARIMA model and reload it to run forecasts, the model tries to perform subtraction operations that produce float64 results—but it's attempting to store those results in a structure expecting integers. Python's same_kind casting rule blocks this implicit conversion (to avoid accidental data loss), hence the error.
The fix is simple
All you need to do is convert your input data to floating-point before fitting the model. Here's your revised code with the key fix plus a minor syntax correction:
import pandas as pd from statsmodels.tsa.arima.model import ARIMA from statsmodels.tsa.arima.model import ARIMAResults def forecast_fit(df): series = df # Critical fix: Convert integer data to float64 to match model's internal math X = series.values.astype('float64') train = X model = ARIMA(X, order=(1,0,1)) model_fit = model.fit(disp=0) model_fit.save('model.pkl') # Fit the model with your target dataframe forecast_fit(df) # Out-of-sample forecast (fixed the missing closing quote here too!) loaded = ARIMAResults.load('model.pkl') forecast = loaded.forecast(steps=17)[0] df_forecast = pd.DataFrame(forecast, columns=[f"{col}_hat" for col in df.columns])
Quick additional notes
- I fixed a tiny syntax error in your original code:
loaded = ARIMAResults.load('model.pkl)was missing a closing single quote—easy typo to overlook! - If you're using an older version of
statsmodels(pre-0.12), adjust the imports tofrom statsmodels.tsa.arima_model import ARIMA, ARIMAResultsinstead. - Converting integers to
float64doesn't lose any data, and it ensures the model's floating-point operations don't hit type conflicts during forecasting.
内容的提问来源于stack exchange,提问作者Ankit Tripathi

