params = { "kernel": "poly", "degree": 3, "C": 0.9702637495163653 } Создание модели…
- User
params = { "kernel": "poly", "degree": 3, "C": 0.9702637495163653 }
Создание модели
model = MLForecast( models=[SVR(**params)], freq='h', lags=list(range(1, 24, 1)), )
Обучение моедли
model.fit(train_df, prediction_intervals=PredictionIntervals(n_windows=5, h=48))
forecasts = model.predict(48, level=[99, 95, 90, 75, 50])
/usr/local/lib/python3.11/site-packages/mlforecast/core.py:594: UserWarning: Found null values in lag1. warnings.warn(f'Found null values in {", ".join(cols_with_nulls)}.')
ValueError Traceback (most recent call last) Cell In[27], line 1 ----> 1 forecasts = model.predict(48, level=[99, 95, 90, 75, 50]) 2 forecasts["unique_id"] = 1
File /usr/local/lib/python3.11/site-packages/mlforecast/forecast.py:710, in MLForecast.predict(self, h, before_predict_callback, after_predict_callback, new_df, level, X_df, ids) 707 else: 708 ts = self.ts --> 710 forecasts = ts.predict( 711 models=self.models_, 712 horizon=h, 713 before_predict_callback=before_predict_callback, 714 after_predict_callback=after_predict_callback, 715 X_df=X_df, 716 ids=ids, 717 ) 718 if level is not None: 719 if self._cs_df is None:
File /usr/local/lib/python3.11/site-packages/mlforecast/core.py:787, in TimeSeries.predict(self, models, horizon, before_predict_callback, after_predict_callback, X_df, ids) 785 X_df = ufp.drop_columns(X_df, drop_cols) 786 if getattr(self, "max_horizon", None) is None: --> 787 preds = self._predict_recursive( 788 models=models, 789 horizon=horizon, 790 before_predict_callback=before_predict_callback, 791 after_predict_callback=after_predict_callback, 792 X_df=X_df, 793 ) 794 else: 795 preds = self._predict_multi( 796 models=models, 797 horizon=horizon, 798 before_predict_callback=before_predict_callback, 799 X_df=X_df, 800 )
File /usr/local/lib/python3.11/site-packages/mlforecast/core.py:639, in TimeSeries._predict_recursive(self, models, horizon, before_predict_callback, after_predict_callback, X_df) 637 if before_predict_callback is not None: 638 new_x = before_predict_callback(new_x) --> 639 predictions = model.predict(new_x) 640 if after_predict_callback is not None: 641 predictions = after_predict_callback(predictions)
File /usr/local/lib/python3.11/site-packages/sklearn/svm/_base.py:428, in BaseLibSVM.predict(self, X) 412 def predict(self, X): 413 """Perform regression on samples in X. 414 415 For an one-class model, +1 (inlier) or -1 (outlier) is returned. (...) 426 The predicted values. 427 """ --> 428 X = self._validate_for_predict(X) 429 predict = self._sparse_predict if self._sparse else self._dense_predict 430 return predict(X)
File /usr/local/lib/python3.11/site-packages/sklearn/svm/_base.py:606, in BaseLibSVM._validate_for_predict(self, X) 603 check_is_fitted(self) 605 if not callable(self.kernel): --> 606 X = self._validate_data( 607 X, 608 accept_sparse="csr", 609 dtype=np.float64, 610 order="C", 611 accept_large_sparse=False, 612 reset=False, 613 ) 615 if self._sparse and not sp.issparse(X): 616 X = sp.csr_matrix(X)
File /usr/local/lib/python3.11/site-packages/sklearn/base.py:633, in BaseEstimator._validate_data(self, X, y, reset, validate_separately, cast_to_ndarray, **check_params) 631 out = X, y 632 elif not no_val_X and no_val_y: --> 633 out = check_array(X, input_name="X", **check_params) 634 elif no_val_X and not no_val_y: 635 out = _check_y(y, **check_params)
File /usr/local/lib/python3.11/site-packages/sklearn/utils/validation.py:1064, in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name) 1058 raise ValueError( 1059 "Found array with dim %d. %s expected <= 2." 1060 % (array.ndim, estimator_name) 1061 ) 1063 if force_all_finite: -> 1064 _assert_all_finite( 1065 array, 1066 input_name=input_name, 1067 estimator_name=estimator_name, 1068 allow_nan=force_all_finite == "allow-nan", 1069 ) 1071 if copy: 1072 if _is_numpy_namespace(xp): 1073 # only make a copy if
arrayandarray_origmay share memory`File /usr/local/lib/python3.11/site-packages/sklearn/utils/validation.py:123, in _assert_all_finite(X, allow_nan, msg_dtype, estimator_name, input_name) 120 if first_pass_isfinite: 121 return --> 123 _assert_all_finite_element_wise( 124 X, 125 xp=xp, 126 allow_nan=allow_nan, 127 msg_dtype=msg_dtype, 128 estimator_name=estimator_name, 129 input_name=input_name, 130 )
File /usr/local/lib/python3.11/site-packages/sklearn/utils/validation.py:172, in _assert_all_finite_element_wise(X, xp, allow_nan, msg_dtype, estimator_name, input_name) 155 if estimator_name and input_name == "X" and has_nan_error: 156 # Improve the error message on how to handle missing values in 157 # scikit-learn. 158 msg_err += ( 159 f"\n{estimator_name} does not accept missing values" 160 " encoded as NaN natively. For supervised learning, you might want" (...) 170 "#estimators-that-handle-nan-values" 171 ) --> 172 raise ValueError(msg_err)
ValueError: Input X contains NaN. SVR does not accept missing values encoded as NaN natively. For supervised learning, you might want to consider sklearn.ensemble.HistGradientBoostingClassifier and Regressor which accept missing values encoded as NaNs natively. Alternatively, it is possible to preprocess the data, for instance by using an imputer transformer in a pipeline or drop samples with missing values. See https://scikit-learn.org/stable/modules/impute.html You can find a list of all estimators that handle NaN values at the following page: https://scikit-learn.org/stable/modules/impute.html#estimators-that-handle-nan-values
- Assistant
The error message you are encountering indicates that there are null (NaN) values in your dataset, specifically in the lag features you've created. The
SVRmodel fromscikit-learndoes not support missing values encoded as NaNs. To resolve this issue, you need to handle the missing values in your dataset before fitting the model.Here are a few strategies you can use to deal with NaN values:
1. Drop Rows with NaN Values
If the amount of data lost is acceptable, you can simply drop rows that contain NaNs. You would do something like this:
# Drop rows with NaN values train_df_cleaned = train_df.dropna()2. Impute Missing Values
You can replace NaN values with a specific value, like the mean or median of the series, or use more advanced techniques like interpolation:
Using mean to fill NaNs:
train_df['column_name'].fillna(train_df['column_name'].mean(), inplace=True)Using linear interpolation:
train_df['column_name'].interpolate(method='linear', inplace=True)3. Check Lag Features
Ensure that your lag features are correctly defined. Lags will create NaN values for the initial rows of your dataset. For example, if you define lag 1, the first row will have a NaN value for that lag.
You can handle these NaNs specifically after calculating lags:
# After creating lags train_df.fillna(method='bfill', inplace=True) # Backward fill4. Verify Your Lag Definition
Make sure your lag features are set correctly. In your case, you are using
list(range(1, 24, 1)), which creates lags from 1 to 23. Depending on your dataset and how far back you look for lags, the earlier rows will inevitably have NaN values.Implementing the Changes
After you have decided on a strategy for handling NaN values, incorporate the cleaning step before fitting the model:
# Clean your dataset train_df_cleaned = train_df.dropna() # or use one of the imputation methods # Ensure that lag features are correctly defined without NaN model.fit(train_df_cleaned, prediction_intervals=PredictionIntervals(n_windows=5, h=48)) forecasts = model.predict(48, level=[99, 95, 90, 75, 50])Additional Note
If you remove rows or impute data, always be mindful of how it may affect your model's performance and validity. It may be beneficial to analyze the data further to determine why NaN values are present and how they may impact your forecasts.