ForecastingGridSearchCV#
- class ForecastingGridSearchCV(forecaster, cv, param_grid, scoring=None, strategy='refit', refit=True, verbose=0, return_n_best_forecasters=1, backend='loky', update_behaviour='full_refit', error_score=nan, tune_by_instance=False, tune_by_variable=False, backend_params=None, n_jobs='deprecated')[source]#
执行网格搜索交叉验证以找到最优模型参数。
在初始窗口上拟合预测器,然后使用时间交叉验证来找到最优参数。
基于交叉验证迭代器执行网格搜索交叉验证,该迭代器编码交叉验证方案、要搜索的参数网格以及(可选)用于比较模型性能的评估指标。与 scikit-learn 中一样,调优通过通用的超参数接口进行,该接口允许使用不同的超参数重复拟合和评估同一个预测器。
- 参数:
- forecastersktime 预测器,BaseForecaster 实例或兼容接口
要调优的预测器,必须实现 sktime 预测器接口。可以使用 sklearn 回归器,但必须首先通过减少合成器之一(例如,通过
make_reduction
)将其转换为预测器- cv交叉验证生成器或可迭代对象
例如 SlidingWindowSplitter()
- strategy{"refit", "update", "no-update_params"} 中的一种,可选,默认值="refit"
cv 拟合中的数据摄取策略,内部传递给
evaluate
,定义了预测器在窗口扩展时看到新数据时的摄取模式:“refit” = 预测器的新副本被拟合到每个训练窗口;“update” = 预测器使用训练窗口数据按提供的顺序更新;“no-update_params” = 拟合到第一个训练窗口,不进行拟合或更新即可重用- update_behaviourstr, 可选,默认值 = "full_refit"
{"full_refit", "inner_only", "no_update"} 中的一种,表示调用 update 时预测器的行为:“full_refit” = 调优参数和内部估计器都在所有看到的数据上重新拟合;“inner_only” = 不重新调优参数,更新内部估计器;“no_update” = 不更新调优参数或内部估计器
- param_grid字典或字典列表
要评估的预测器的模型调优参数
- scoringsktime 指标 (BaseMetric),str,或可调用对象,可选 (默认值=None)
用于调优预测器的评分指标
可以搜索 sktime 指标对象 (BaseMetric) 的后代
使用
registry.all_estimators
搜索工具,例如通过all_estimators("metric", as_dataframe=True)
如果可调用,必须具有以下签名
(y_true: 1D np.ndarray, y_pred: 1D np.ndarray) -> float
,假设 np.ndarrays 具有相同的长度,并且值越低越好。sktime.performance_metrics.forecasting 中的指标都属于此形式。如果为 str,则使用 registry.resolve_alias 解析为上述之一。有效字符串是有效的 registry.craft 规范,其中包括任何 BaseMetric 对象的字符串表示形式,例如“MeanSquaredError()”;以及引用指标的 registry.ALIAS_DICT 的键。
如果为 None,则默认为 MeanAbsolutePercentageError()
- refitbool, 可选 (默认值=True)
True = 使用最佳参数在 fit 中对整个数据重新拟合预测器;False = 不进行重新拟合。该预测器不能用于预测。这用于调优超参数,然后将估计器用作参数估计器,例如通过 get_fitted_params 或 PluginParamsForecaster。
- verbose: int, 可选 (默认值=0)
- return_n_best_forecastersint, 默认值=1
如果需要返回 n 个最佳预测器,可以设置此值,并且 n 个最佳预测器将分配给 n_best_forecasters_。将 return_n_best_forecasters 设置为 -1 以返回所有预测器。
- error_score数值或字符串 ‘raise’,可选 (默认值=np.nan)
当预测器未能拟合时返回的测试分数。
- return_train_scorebool, 可选 (默认值=False)
- backend{"dask", "loky", "multiprocessing", "threading","ray"} 中的一种,默认值="loky"。
如果指定且
strategy
设置为“refit”,则并行运行评估。“None”:顺序执行循环,简单的列表推导
“loky”、“multiprocessing”和“threading”:使用
joblib.Parallel
循环“joblib”:自定义和第三方
joblib
后端,例如spark
“dask”:使用
dask
,需要环境中包含dask
包“ray”:使用
ray
,需要环境中包含ray
包
建议:使用“dask”或“loky”进行并行评估。“threading”由于 GIL 和用于“dask”和“loky”的序列化后端(
cloudpickle
)通常比“multiprocessing”中使用的标准pickle
库更健壮,因此不太可能看到速度提升。- error_score“raise”或数值,默认值=np.nan
如果在估计器拟合中发生异常,则分配给分数的数值。如果设置为“raise”,则会引发异常。如果给出数值,则会引发 FitFailedWarning。
- tune_by_instancebool, 可选 (默认值=False)
是否在传递给调优估计器的 Panel 或 Hierarchical 数据的情况下,按每个时间序列实例单独调优参数。仅当传递的时间序列是 Panel 或 Hierarchical 时才适用。如果为 True,预测器的克隆将分别拟合到每个实例,并在 forecasters_ 属性的字段中可用。其效果与将 ForecastByLevel 包装器应用于 self 相同。如果为 False,则为所有实例选择相同的最佳参数。
- tune_by_variablebool, 可选 (默认值=False)
是否在传递给调优估计器的多元数据的情况下,按每个时间序列变量单独调优参数。仅当传递的时间序列是严格多元时才适用。如果为 True,预测器的克隆将分别拟合到每个变量,并在 forecasters_ 属性的字段中可用。其效果与将 ColumnEnsembleForecaster 包装器应用于 self 相同。如果为 False,则为所有变量选择相同的最佳参数。
- backend_paramsdict, 可选
作为配置传递给后端的附加参数。直接传递给
utils.parallel.parallelize
。有效键取决于backend
的值“None”:无附加参数,忽略
backend_params
“loky”、“multiprocessing”和“threading”:默认
joblib
后端,可以在此处传递joblib.Parallel
的任何有效键,例如n_jobs
,但backend
除外,它直接由backend
控制。如果未传递n_jobs
,则默认为-1
,其他参数将默认为joblib
的默认值。“joblib”:自定义和第三方
joblib
后端,例如spark`. 可以在此处传递
joblib.Parallel
的任何有效键,例如n_jobs
,在这种情况下,必须将backend
作为backend_params
的一个键传递。如果未传递n_jobs
,则默认为-1
,其他参数将默认为joblib
的默认值。“dask”:可以传递
dask.compute
的任何有效键,例如scheduler
“ray”:可以传递以下键
“ray_remote_args”:
ray.init
的有效键字典- “shutdown_ray”:bool,默认值=True;False 防止
ray
在并行化后关闭。 并行化后关闭。
- “shutdown_ray”:bool,默认值=True;False 防止
“logger_name”:str,默认值=“ray”;要使用的日志记录器名称。
“mute_warnings”:bool,默认值=False;如果为 True,则禁止警告。
- 属性:
- best_index_int
- best_score_: float
最佳模型的得分
- best_params_dict
参数网格中的最佳参数值
- best_forecaster_estimator
使用最佳参数拟合的估计器
- cv_results_dict
网格搜索交叉验证的结果
- n_splits_: int
交叉验证数据中的分割数量
- refit_time_float
重新拟合最佳预测器所需时间(秒)
- scorer_function
用于对模型进行评分的函数
- n_best_forecasters_: 元组列表(“rank”,
) “rank”与 best_forecaster_ 相关
- n_best_scores_: float 列表
的得分,从最佳到最差排序n_best_forecasters_
- forecasters_pd.DataFramee
包含所有拟合预测器及其参数的 DataFrame。仅当 tune_by_instance=True 或 tune_by_variable=True 且其中至少一个适用时存在。在这种情况下,其他属性不在此对象中,仅在 forecasters_ 的字段中。
示例
>>> from sktime.datasets import load_shampoo_sales >>> from sktime.forecasting.model_selection import ForecastingGridSearchCV >>> from sktime.split import ExpandingWindowSplitter >>> from sktime.forecasting.naive import NaiveForecaster >>> y = load_shampoo_sales() >>> fh = [1,2,3] >>> cv = ExpandingWindowSplitter(fh=fh) >>> forecaster = NaiveForecaster() >>> param_grid = {"strategy" : ["last", "mean", "drift"]} >>> gscv = ForecastingGridSearchCV( ... forecaster=forecaster, ... param_grid=param_grid, ... cv=cv) >>> gscv.fit(y) ForecastingGridSearchCV(...) >>> y_pred = gscv.predict(fh)
使用 sklearn 符号同时进行高级模型元调优(模型选择)和多个预测器的超参数调优
>>> from sktime.datasets import load_shampoo_sales >>> from sktime.forecasting.exp_smoothing import ExponentialSmoothing >>> from sktime.forecasting.naive import NaiveForecaster >>> from sktime.split import ExpandingWindowSplitter >>> from sktime.forecasting.model_selection import ForecastingGridSearchCV >>> from sktime.forecasting.compose import TransformedTargetForecaster >>> from sktime.forecasting.theta import ThetaForecaster >>> from sktime.transformations.series.impute import Imputer >>> y = load_shampoo_sales() >>> pipe = TransformedTargetForecaster(steps=[ ... ("imputer", Imputer()), ... ("forecaster", NaiveForecaster())]) >>> cv = ExpandingWindowSplitter( ... initial_window=24, ... step_length=12, ... fh=[1,2,3]) >>> gscv = ForecastingGridSearchCV( ... forecaster=pipe, ... param_grid=[{ ... "forecaster": [NaiveForecaster(sp=12)], ... "forecaster__strategy": ["drift", "last", "mean"], ... }, ... { ... "imputer__method": ["mean", "drift"], ... "forecaster": [ThetaForecaster(sp=12)], ... }, ... { ... "imputer__method": ["mean", "median"], ... "forecaster": [ExponentialSmoothing(sp=12)], ... "forecaster__trend": ["add", "mul"], ... }, ... ], ... cv=cv, ... ) >>> gscv.fit(y) ForecastingGridSearchCV(...) >>> y_pred = gscv.predict(fh=[1,2,3])
方法
check_is_fitted
([方法名称])检查估计器是否已拟合。
clone
()获取具有相同超参数和配置的对象的克隆。
clone_tags
(估计器[, 标签名称])从另一个对象克隆标签作为动态覆盖。
create_test_instance
([参数集])使用第一个测试参数集构造类的实例。
创建所有测试实例列表及其名称列表。
fit
(y[, X, fh])将预测器拟合到训练数据。
fit_predict
(y[, X, fh, X_pred])拟合时间序列并在未来预测期进行预测。
get_class_tag
(标签名称[, 默认标签值])从类获取类标签值,包含来自父类的标签级继承。
从类获取类标签,包含来自父类的标签级继承。
获取 self 的配置标志。
get_fitted_params
([deep])获取拟合参数。
获取对象的参数默认值。
get_param_names
([sort])获取对象的参数名称。
get_params
([deep])获取此对象的参数值字典。
get_tag
(标签名称[, 默认标签值, ...])从实例获取标签值,包含标签级继承和覆盖。
get_tags
()从实例获取标签,包含标签级继承和覆盖。
get_test_params
([参数集])返回估计器的测试参数设置。
检查对象是否由其他 BaseObjects 组成。
load_from_path
(serial)从文件位置加载对象。
load_from_serial
(serial)从序列化内存容器加载对象。
predict
([fh, X])在未来预测期预测时间序列。
predict_interval
([fh, X, coverage])计算/返回预测区间预测。
predict_proba
([fh, X, marginal])计算/返回完全概率预测。
predict_quantiles
([fh, X, alpha])计算/返回分位数预测。
predict_residuals
([y, X])返回时间序列预测的残差。
predict_var
([fh, X, cov])计算/返回方差预测。
reset
()将对象重置为干净的初始化后状态。
save
([path, serialization_format])将序列化后的 self 保存到字节状对象或 (.zip) 文件。
score
(y[, X, fh])使用 MAPE(非对称)对预测与真实值进行评分。
set_config
(**config_dict)将配置标志设置为给定值。
set_params
(**params)设置此对象的参数。
set_random_state
([random_state, deep, ...])为 self 设置 random_state 伪随机种子参数。
set_tags
(**tag_dict)将实例级别标签覆盖设置为给定值。
update
(y[, X, update_params])更新截止值,以及(可选地)拟合参数。
update_predict
(y[, cv, X, update_params, ...])在测试集上迭代进行预测并更新模型。
update_predict_single
([y, fh, X, update_params])使用新数据更新模型并进行预测。
- classmethod get_test_params(parameter_set='default')[source]#
返回估计器的测试参数设置。
- 参数:
- parameter_setstr, 默认值="default"
要返回的测试参数集的名称,用于测试。如果未为某个值定义特殊参数,将返回
"default"
集。
- 返回值:
- paramsdict 或 dict 列表
- check_is_fitted(method_name=None)[source]#
检查估计器是否已拟合。
检查
_is_fitted
属性是否存在且为True
。在调用对象的fit
方法时,应将is_fitted
属性设置为True
。如果不存在,则引发
NotFittedError
。- 参数:
- method_namestr, 可选
调用此函数的方法的名称。如果提供,错误消息将包含此信息。
- 引发:
- NotFittedError
如果估计器尚未拟合。
- clone()[source]#
获取具有相同超参数和配置的对象的克隆。
克隆是一个没有共享引用的不同对象,处于初始化后状态。此函数等效于返回
self
的sklearn.clone
。等效于构造
type(self)
的新实例,并使用self
的参数,即type(self)(**self.get_params(deep=False))
。如果
self
上设置了配置,则克隆也将具有与原始相同的配置,等效于调用cloned_self.set_config(**self.get_config())
。在值上也等效于调用
self.reset
,不同之处在于clone
返回一个新对象,而不是像reset
那样改变self
。- 引发:
- 如果克隆不符合规范,则引发 RuntimeError,原因是
__init__
有误。
- 如果克隆不符合规范,则引发 RuntimeError,原因是
- clone_tags(estimator, tag_names=None)[source]#
从另一个对象克隆标签作为动态覆盖。
每个
scikit-base
兼容对象都有一个标签字典,用于存储关于对象的元数据。标签可用于存储关于对象的元数据,或控制对象的行为。标签是特定于实例
self
的键值对,它们是静态标志,在对象构造后不会更改。clone_tags
从另一个对象estimator
设置动态标签覆盖。clone_tags
方法应仅在对象的__init__
方法中调用,即在构造期间,或通过__init__
构造后直接调用。动态标签设置为
estimator
中标签的值,使用tag_names
中指定的名称。tag_names
的默认值将estimator
中的所有标签写入self
。可以通过
get_tags
或get_tag
查看当前标签值。- 参数:
- estimator一个 :class:BaseObject 或派生类的实例
- tag_namesstr 或 str 列表,默认值 = None
要克隆的标签名称。默认值(
None
)克隆estimator
中的所有标签。
- 返回值:
- self
self
的引用。
- classmethod create_test_instance(parameter_set='default')[source]#
使用第一个测试参数集构造类的实例。
- 参数:
- parameter_setstr, 默认值="default"
要返回的测试参数集的名称,用于测试。如果未为某个值定义特殊参数,将返回 “default” 集。
- 返回值:
- instance具有默认参数的类实例
- 具有默认参数的类实例
创建所有测试实例列表及其名称列表。
-
第 i 个元素是测试中对象的第 i 个实例的名称。如果实例多于一个,命名约定为
{cls.__name__}-{i}
,否则为{cls.__name__}
。 -
- 返回值:
- 截止点 = 预测器的“当前时间”状态。
cutoffpandas 兼容的索引元素,或 None
- 已传递的预测期。
将预测器拟合到训练数据。
将状态更改为“已拟合”。
写入 self
设置以“_”结尾的拟合模型属性,拟合属性可通过
get_fitted_params
查看。将
self.is_fitted
标志设置为True
。将
self.cutoff
设置为y
中看到的最后一个索引。
- 参数:
- 如果传递了
fh
,则将fh
存储到self.fh
。 ysktime 兼容数据容器格式的时间序列。
用于拟合预测器的时间序列。
sktime
中的各个数据格式是所谓的 mtype 规范,每个 mtype 都实现了抽象的 scitype。 scitypeSeries
= 单个时间序列,普通预测。pd.DataFrame
、pd.Series
或np.ndarray
(1D 或 2D)Panel
scitype = 时间序列集合,全局/面板预测。 带有 2 级行MultiIndex
(instance, time)
的pd.DataFrame
,3D np.ndarray
(instance, variable, time)
,Series
类型的pd.DataFrame
list
Hierarchical
scitype = 分层集合,用于分层预测。 带有 3 级或更多行MultiIndex
(hierarchy_1, ..., hierarchy_n, time)
的pd.DataFrame
有关数据格式的更多详细信息,请参阅关于 mtype 的术语表。 有关用法,请参阅预测教程
examples/01_forecasting.ipynb
fhint, 列表, pd.Index 可强制转换类型, 或
ForecastingHorizon
, 默认值=None- 编码要预测时间戳的预测期。 如果
self.get_tag("requires-fh-in-fit")
为True
,则必须在fit
中传递,不可选 Xsktime 兼容格式的时间序列, 可选 (默认值=None)。
- 用于拟合模型的外生时间序列。 应与
y
具有相同的 scitype(Series
、Panel
或Hierarchical
)。 如果self.get_tag("X-y-must-have-same-index")
为 True,则X.index
必须包含y.index
。 self对 self 的引用。
- 如果传递了
- 返回值:
- 对 self 的引用。
- fit_predict(y, X=None, fh=None, X_pred=None)[source]#
拟合时间序列并在未来预测期进行预测。
与
fit(y, X, fh).predict(X_pred)
相同。 如果未传递X_pred
,则与fit(y, fh, X).predict(X)
相同。将状态更改为“已拟合”。
写入 self
设置以“_”结尾的拟合模型属性,拟合属性可通过
get_fitted_params
查看。将
self.is_fitted
标志设置为True
。将
fh
存储到self.fh
。
- 参数:
- ysktime 兼容数据容器格式的时间序列
ysktime 兼容数据容器格式的时间序列。
用于拟合预测器的时间序列。
sktime
中的各个数据格式是所谓的 mtype 规范,每个 mtype 都实现了抽象的 scitype。 scitypeSeries
= 单个时间序列,普通预测。pd.DataFrame
、pd.Series
或np.ndarray
(1D 或 2D)Panel
scitype = 时间序列集合,全局/面板预测。 带有 2 级行MultiIndex
(instance, time)
的pd.DataFrame
,3D np.ndarray
(instance, variable, time)
,Series
类型的pd.DataFrame
list
Hierarchical
scitype = 分层集合,用于分层预测。 带有 3 级或更多行MultiIndex
(hierarchy_1, ..., hierarchy_n, time)
的pd.DataFrame
有关数据格式的更多详细信息,请参阅关于 mtype 的术语表。 有关用法,请参阅预测教程
examples/01_forecasting.ipynb
fhint, 列表, pd.Index 可强制转换类型, 或
ForecastingHorizon
, 默认值=None- fhint, 列表, pd.Index 可强制转换类型, 或
ForecastingHorizon
(不可选) 编码要预测时间戳的预测期。
如果 fh 不为 None 且不是 ForecastingHorizon 类型,则通过调用 _check_fh 强制转换为 ForecastingHorizon。特别是,如果 fh 是 pd.Index 类型,则通过 ForecastingHorizon(fh, is_relative=False) 强制转换。
- 用于拟合模型的外生时间序列。 应与
y
具有相同的 scitype(Series
、Panel
或Hierarchical
)。 如果self.get_tag("X-y-must-have-same-index")
为 True,则X.index
必须包含y.index
。 self对 self 的引用。
- X_predsktime 兼容格式的时间序列, 可选 (默认值=None)
预测中使用的外生时间序列。 如果传递,将在 predict 中代替 X 使用。 应与 fit 中的
y
具有相同的 scitype(Series
、Panel
或Hierarchical
)。 如果self.get_tag("X-y-must-have-same-index")
为 True,则X.index
必须包含fh
索引引用。
- 返回值:
- y_predsktime 兼容数据容器格式的时间序列
在
fh
处的点预测,具有与fh
相同的索引。y_pred
具有与最近传递的y
相同的类型:Series
、Panel
、Hierarchical
scitype,相同格式(见上文)
- classmethod get_class_tag(tag_name, tag_value_default=None)[source]#
从类获取类标签值,包含来自父类的标签级继承。
每个
scikit-base
兼容对象都有一个标签字典,用于存储关于对象的元数据。get_class_tag
方法是一个类方法,它仅考虑类级别标签值和覆盖来检索标签的值。它从对象返回名称为
tag_name
的标签值,考虑标签覆盖,按以下降序优先级排列:在类的
_tags
属性中设置的标签。在父类的
_tags
属性中设置的标签,
按继承顺序。
不考虑在实例上设置的动态标签覆盖,即通过
set_tags
或clone_tags
在实例上定义的覆盖。要检索具有潜在实例覆盖的标签值,请改用
get_tag
方法。- 参数:
- tag_namestr
标签值的名称。
- tag_value_default任何类型
如果未找到标签,则为默认/备用值。
- 返回值:
- tag_value
self
中tag_name
标签的值。 如果未找到,则返回tag_value_default
。
- classmethod get_class_tags()[source]#
从类获取类标签,包含来自父类的标签级继承。
每个
scikit-base
兼容对象都有一个标签字典,用于存储关于对象的元数据。标签可用于存储关于对象的元数据,或控制对象的行为。标签是特定于实例
self
的键值对,它们是静态标志,在对象构造后不会更改。The
get_class_tags
method is a class method, and retrieves the value of a tag taking into account only class-level tag values and overrides.It returns a dictionary with keys being keys of any attribute of
_tags
set in the class or any of its parent classes.Values are the corresponding tag values, with overrides in the following order of descending priority
在类的
_tags
属性中设置的标签。在父类的
_tags
属性中设置的标签,
按继承顺序。
Instances can override these tags depending on hyper-parameters.
To retrieve tags with potential instance overrides, use the
get_tags
method instead.不考虑在实例上设置的动态标签覆盖,即通过
set_tags
或clone_tags
在实例上定义的覆盖。For including overrides from dynamic tags, use
get_tags
.- collected_tagsdict
Dictionary of tag name : tag value pairs. Collected from
_tags
class attribute via nested inheritance. NOT overridden by dynamic tags set byset_tags
orclone_tags
.
- get_config()[source]#
获取 self 的配置标志。
Configs are key-value pairs of
self
, typically used as transient flags for controlling behaviour.get_config
returns dynamic configs, which override the default configs.Default configs are set in the class attribute
_config
of the class or its parent classes, and are overridden by dynamic configs set viaset_config
.Configs are retained under
clone
orreset
calls.- 返回值:
- config_dictdict
Dictionary of config name : config value pairs. Collected from _config class attribute via nested inheritance and then any overrides and new tags from _onfig_dynamic object attribute.
- get_fitted_params(deep=True)[source]#
获取拟合参数。
- State required
Requires state to be “fitted”.
- 参数:
- deepbool, default=True
Whether to return fitted parameters of components.
If True, will return a dict of parameter name : value for this object, including fitted parameters of fittable components (= BaseEstimator-valued parameters).
If False, will return a dict of parameter name : value for this object, but not include fitted parameters of components.
- 返回值:
- fitted_paramsdict with str-valued keys
Dictionary of fitted parameters, paramname : paramvalue keys-value pairs include
always: all fitted parameters of this object, as via
get_param_names
values are fitted parameter value for that key, of this objectif
deep=True
, also contains keys/value pairs of component parameters parameters of components are indexed as[componentname]__[paramname]
all parameters ofcomponentname
appear asparamname
with its valueif
deep=True
, also contains arbitrary levels of component recursion, e.g.,[componentname]__[componentcomponentname]__[paramname]
, etc
- classmethod get_param_defaults()[source]#
Get object’s parameter defaults.
- 返回值:
- default_dict: dict[str, Any]
Keys are all parameters of
cls
that have a default defined in__init__
. Values are the defaults, as defined in__init__
.
- classmethod get_param_names(sort=True)[source]#
Get object’s parameter names.
- 参数:
- sortbool, default=True
Whether to return the parameter names sorted in alphabetical order (True), or in the order they appear in the class
__init__
(False).
- 返回值:
- param_names: list[str]
List of parameter names of
cls
. Ifsort=False
, in same order as they appear in the class__init__
. Ifsort=True
, alphabetically ordered.
- get_params(deep=True)[source]#
获取此对象的参数值字典。
- 参数:
- deepbool, default=True
Whether to return parameters of components.
If
True
, will return adict
of parameter name : value for this object, including parameters of components (=BaseObject
-valued parameters).If
False
, will return adict
of parameter name : value for this object, but not include parameters of components.
- 返回值:
- paramsdict with str-valued keys
Dictionary of parameters, paramname : paramvalue keys-value pairs include
always: all parameters of this object, as via
get_param_names
values are parameter value for that key, of this object values are always identical to values passed at constructionif
deep=True
, also contains keys/value pairs of component parameters parameters of components are indexed as[componentname]__[paramname]
all parameters ofcomponentname
appear asparamname
with its valueif
deep=True
, also contains arbitrary levels of component recursion, e.g.,[componentname]__[componentcomponentname]__[paramname]
, etc
- get_tag(tag_name, tag_value_default=None, raise_error=True)[source]#
从实例获取标签值,包含标签级继承和覆盖。
每个
scikit-base
兼容对象都有一个标签字典,用于存储关于对象的元数据。标签可用于存储关于对象的元数据,或控制对象的行为。标签是特定于实例
self
的键值对,它们是静态标志,在对象构造后不会更改。The
get_tag
method retrieves the value of a single tag with nametag_name
from the instance, taking into account tag overrides, in the following order of descending priorityTags set via
set_tags
orclone_tags
on the instance,
at construction of the instance.
在类的
_tags
属性中设置的标签。在父类的
_tags
属性中设置的标签,
按继承顺序。
- 参数:
- tag_namestr
Name of tag to be retrieved
- tag_value_defaultany type, optional; default=None
Default/fallback value if tag is not found
- raise_errorbool
whether a
ValueError
is raised when the tag is not found
- 返回值:
- tag_valueAny
Value of the
tag_name
tag inself
. If not found, raises an error ifraise_error
is True, otherwise it returnstag_value_default
.
- 引发:
- ValueError, if
raise_error
isTrue
. The
ValueError
is then raised iftag_name
is not inself.get_tags().keys()
.
- ValueError, if
- get_tags()[source]#
从实例获取标签,包含标签级继承和覆盖。
每个
scikit-base
兼容对象都有一个标签字典,用于存储关于对象的元数据。标签可用于存储关于对象的元数据,或控制对象的行为。标签是特定于实例
self
的键值对,它们是静态标志,在对象构造后不会更改。The
get_tags
method returns a dictionary of tags, with keys being keys of any attribute of_tags
set in the class or any of its parent classes, or tags set viaset_tags
orclone_tags
.Values are the corresponding tag values, with overrides in the following order of descending priority
Tags set via
set_tags
orclone_tags
on the instance,
at construction of the instance.
在类的
_tags
属性中设置的标签。在父类的
_tags
属性中设置的标签,
按继承顺序。
- 返回值:
- collected_tagsdict
Dictionary of tag name : tag value pairs. Collected from
_tags
class attribute via nested inheritance and then any overrides and new tags from_tags_dynamic
object attribute.
- is_composite()[source]#
检查对象是否由其他 BaseObjects 组成。
A composite object is an object which contains objects, as parameters. Called on an instance, since this may differ by instance.
- 返回值:
- composite: bool
Whether an object has any parameters whose values are
BaseObject
descendant instances.
- property is_fitted[source]#
Whether
fit
has been called.Inspects object’s
_is_fitted` attribute that should initialize to ``False
during object construction, and be set to True in calls to an object’s fit method.- 返回值:
- bool
Whether the estimator has been fit.
- classmethod load_from_path(serial)[source]#
从文件位置加载对象。
- 参数:
- serialresult of ZipFile(path).open(“object)
- 返回值:
- deserialized self resulting in output at
path
, ofcls.save(path)
- deserialized self resulting in output at
- classmethod load_from_serial(serial)[source]#
从序列化内存容器加载对象。
- 参数:
- serial1st element of output of
cls.save(None)
- serial1st element of output of
- 返回值:
- deserialized self resulting in output
serial
, ofcls.save(None)
- deserialized self resulting in output
- predict(fh=None, X=None)[source]#
在未来预测期预测时间序列。
- State required
Requires state to be “fitted”, i.e.,
self.is_fitted=True
.
Accesses in self
Fitted model attributes ending in “_”.
self.cutoff
,self.is_fitted
- 将状态更改为“已拟合”。
Stores
fh
toself.fh
iffh
is passed and has not been passed previously.
- 参数:
- 编码要预测时间戳的预测期。 如果
self.get_tag("requires-fh-in-fit")
为True
,则必须在fit
中传递,不可选 The forecasting horizon encoding the time stamps to forecast at. Should not be passed if has already been passed in
fit
. If has not been passed in fit, must be passed, not optional如果 fh 不为 None 且不是 ForecastingHorizon 类型,则通过调用 _check_fh 强制转换为 ForecastingHorizon。特别是,如果 fh 是 pd.Index 类型,则通过 ForecastingHorizon(fh, is_relative=False) 强制转换。
- Xtime series in
sktime
compatible format, optional (default=None) Exogeneous time series to use in prediction. Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
infit
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must containfh
index reference.
- 编码要预测时间戳的预测期。 如果
- 返回值:
- y_predsktime 兼容数据容器格式的时间序列
在
fh
处的点预测,具有与fh
相同的索引。y_pred
具有与最近传递的y
相同的类型:Series
、Panel
、Hierarchical
scitype,相同格式(见上文)
- predict_interval(fh=None, X=None, coverage=0.9)[source]#
计算/返回预测区间预测。
If
coverage
is iterable, multiple intervals will be calculated.- State required
Requires state to be “fitted”, i.e.,
self.is_fitted=True
.
Accesses in self
Fitted model attributes ending in “_”.
self.cutoff
,self.is_fitted
- 将状态更改为“已拟合”。
Stores
fh
toself.fh
iffh
is passed and has not been passed previously.
- 参数:
- 编码要预测时间戳的预测期。 如果
self.get_tag("requires-fh-in-fit")
为True
,则必须在fit
中传递,不可选 The forecasting horizon encoding the time stamps to forecast at. Should not be passed if has already been passed in
fit
. If has not been passed in fit, must be passed, not optionalIf
fh
is not None and not of typeForecastingHorizon
, it is coerced toForecastingHorizon
internally (via_check_fh
).if
fh
isint
or array-like ofint
, it is interpreted as relative horizon, and coerced to a relativeForecastingHorizon(fh, is_relative=True)
.if
fh
is of typepd.Index
, it is interpreted as an absolute horizon, and coerced to an absoluteForecastingHorizon(fh, is_relative=False)
.
- Xtime series in
sktime
compatible format, optional (default=None) Exogeneous time series to use in prediction. Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
infit
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must containfh
index reference.- coveragefloat or list of float of unique values, optional (default=0.90)
nominal coverage(s) of predictive interval(s)
- 编码要预测时间戳的预测期。 如果
- 返回值:
- pred_intpd.DataFrame
- Column has multi-index: first level is variable name from y in fit,
- second level coverage fractions for which intervals were computed.
in the same order as in input
coverage
.
Third level is string “lower” or “upper”, for lower/upper interval end.
- Row index is fh, with additional (upper) levels equal to instance levels,
from y seen in fit, if y seen in fit was Panel or Hierarchical.
- Entries are forecasts of lower/upper interval end,
for var in col index, at nominal coverage in second col index, lower/upper depending on third col index, for the row index. Upper/lower interval end forecasts are equivalent to quantile forecasts at alpha = 0.5 - c/2, 0.5 + c/2 for c in coverage.
- predict_proba(fh=None, X=None, marginal=True)[source]#
计算/返回完全概率预测。
Note
currently only implemented for Series (non-panel, non-hierarchical) y.
requires
skpro
installed for the distribution objects returned.
- State required
Requires state to be “fitted”, i.e.,
self.is_fitted=True
.
Accesses in self
Fitted model attributes ending in “_”.
self.cutoff
,self.is_fitted
- 将状态更改为“已拟合”。
Stores
fh
toself.fh
iffh
is passed and has not been passed previously.
- 参数:
- 编码要预测时间戳的预测期。 如果
self.get_tag("requires-fh-in-fit")
为True
,则必须在fit
中传递,不可选 The forecasting horizon encoding the time stamps to forecast at. Should not be passed if has already been passed in
fit
. If has not been passed in fit, must be passed, not optionalIf
fh
is not None and not of typeForecastingHorizon
, it is coerced toForecastingHorizon
internally (via_check_fh
).if
fh
isint
or array-like ofint
, it is interpreted as relative horizon, and coerced to a relativeForecastingHorizon(fh, is_relative=True)
.if
fh
is of typepd.Index
, it is interpreted as an absolute horizon, and coerced to an absoluteForecastingHorizon(fh, is_relative=False)
.
- Xtime series in
sktime
compatible format, optional (default=None) Exogeneous time series to use in prediction. Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
infit
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must containfh
index reference.- marginalbool, optional (default=True)
whether returned distribution is marginal by time index
- 编码要预测时间戳的预测期。 如果
- 返回值:
- pred_distskpro BaseDistribution
predictive distribution if marginal=True, will be marginal distribution by time point if marginal=False and implemented by method, will be joint
- predict_quantiles(fh=None, X=None, alpha=None)[source]#
计算/返回分位数预测。
If
alpha
is iterable, multiple quantiles will be calculated.- State required
Requires state to be “fitted”, i.e.,
self.is_fitted=True
.
Accesses in self
Fitted model attributes ending in “_”.
self.cutoff
,self.is_fitted
- 将状态更改为“已拟合”。
Stores
fh
toself.fh
iffh
is passed and has not been passed previously.
- 参数:
- 编码要预测时间戳的预测期。 如果
self.get_tag("requires-fh-in-fit")
为True
,则必须在fit
中传递,不可选 The forecasting horizon encoding the time stamps to forecast at. Should not be passed if has already been passed in
fit
. If has not been passed in fit, must be passed, not optionalIf
fh
is not None and not of typeForecastingHorizon
, it is coerced toForecastingHorizon
internally (via_check_fh
).if
fh
isint
or array-like ofint
, it is interpreted as relative horizon, and coerced to a relativeForecastingHorizon(fh, is_relative=True)
.if
fh
is of typepd.Index
, it is interpreted as an absolute horizon, and coerced to an absoluteForecastingHorizon(fh, is_relative=False)
.
- Xtime series in
sktime
compatible format, optional (default=None) Exogeneous time series to use in prediction. Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
infit
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must containfh
index reference.- alphafloat or list of float of unique values, optional (default=[0.05, 0.95])
A probability or list of, at which quantile forecasts are computed.
- 编码要预测时间戳的预测期。 如果
- 返回值:
- quantilespd.DataFrame
- Column has multi-index: first level is variable name from y in fit,
second level being the values of alpha passed to the function.
- Row index is fh, with additional (upper) levels equal to instance levels,
from y seen in fit, if y seen in fit was Panel or Hierarchical.
- Entries are quantile forecasts, for var in col index,
at quantile probability in second col index, for the row index.
- predict_residuals(y=None, X=None)[source]#
返回时间序列预测的残差。
Residuals will be computed for forecasts at y.index.
If fh must be passed in fit, must agree with y.index. If y is an np.ndarray, and no fh has been passed in fit, the residuals will be computed at a fh of range(len(y.shape[0]))
- State required
Requires state to be “fitted”. If fh has been set, must correspond to index of y (pandas or integer)
- Accesses in self
Fitted model attributes ending in “_”. self.cutoff, self._is_fitted
- 将状态更改为“已拟合”。
Nothing.
- 参数:
- ysktime 兼容数据容器格式的时间序列
Time series with ground truth observations, to compute residuals to. Must have same type, dimension, and indices as expected return of predict.
If None, the y seen so far (self._y) are used, in particular
if preceded by a single fit call, then in-sample residuals are produced
if fit requires
fh
, it must have pointed to index of y in fit
- Xtime series in sktime compatible format, optional (default=None)
Exogeneous time series for updating and forecasting Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
infit
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must contain bothfh
index reference andy.index
.
- 返回值:
- y_restime series in
sktime
compatible data container format Forecast residuals at
fh`, with same index as ``fh
.y_res
has same type as they
that has been passed most recently:Series
,Panel
,Hierarchical
scitype, same format (see above)
- y_restime series in
- predict_var(fh=None, X=None, cov=False)[source]#
计算/返回方差预测。
- State required
Requires state to be “fitted”, i.e.,
self.is_fitted=True
.
Accesses in self
Fitted model attributes ending in “_”.
self.cutoff
,self.is_fitted
- 将状态更改为“已拟合”。
Stores
fh
toself.fh
iffh
is passed and has not been passed previously.
- 参数:
- 编码要预测时间戳的预测期。 如果
self.get_tag("requires-fh-in-fit")
为True
,则必须在fit
中传递,不可选 The forecasting horizon encoding the time stamps to forecast at. Should not be passed if has already been passed in
fit
. If has not been passed in fit, must be passed, not optionalIf
fh
is not None and not of typeForecastingHorizon
, it is coerced toForecastingHorizon
internally (via_check_fh
).if
fh
isint
or array-like ofint
, it is interpreted as relative horizon, and coerced to a relativeForecastingHorizon(fh, is_relative=True)
.if
fh
is of typepd.Index
, it is interpreted as an absolute horizon, and coerced to an absoluteForecastingHorizon(fh, is_relative=False)
.
- Xtime series in
sktime
compatible format, optional (default=None) Exogeneous time series to use in prediction. Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
infit
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must containfh
index reference.- covbool, optional (default=False)
if True, computes covariance matrix forecast. if False, computes marginal variance forecasts.
- 编码要预测时间戳的预测期。 如果
- 返回值:
- pred_varpd.DataFrame, format dependent on
cov
variable - If cov=False
- Column names are exactly those of
y
passed infit
/update
. For nameless formats, column index will be a RangeIndex.
- Row index is fh, with additional levels equal to instance levels,
from y seen in fit, if y seen in fit was Panel or Hierarchical.
Entries are variance forecasts, for var in col index. A variance forecast for given variable and fh index is a predicted
variance for that variable and index, given observed data.
- Column names are exactly those of
- If cov=True
- Column index is a multiindex: 1st level is variable names (as above)
2nd level is fh.
- Row index is fh, with additional levels equal to instance levels,
from y seen in fit, if y seen in fit was Panel or Hierarchical.
- Entries are (co-)variance forecasts, for var in col index, and
covariance between time index in row and col.
Note: no covariance forecasts are returned between different variables.
- pred_varpd.DataFrame, format dependent on
- reset()[source]#
将对象重置为干净的初始化后状态。
Results in setting
self
to the state it had directly after the constructor call, with the same hyper-parameters. Config values set byset_config
are also retained.A
reset
call deletes any object attributes, excepthyper-parameters = arguments of
__init__
written toself
, e.g.,self.paramname
whereparamname
is an argument of__init__
object attributes containing double-underscores, i.e., the string “__”. For instance, an attribute named “__myattr” is retained.
config attributes, configs are retained without change. That is, results of
get_config
before and afterreset
are equal.
Class and object methods, and class attributes are also unaffected.
Equivalent to
clone
, with the exception thatreset
mutatesself
instead of returning a new object.After a
self.reset()
call,self
is equal in value and state, to the object obtained after a constructor call``type(self)(**self.get_params(deep=False))``.- 返回值:
- self
Instance of class reset to a clean post-init state but retaining the current hyper-parameter values.
- save(path=None, serialization_format='pickle')[source]#
将序列化后的 self 保存到字节状对象或 (.zip) 文件。
Behaviour: if
path
is None, returns an in-memory serialized self ifpath
is a file location, stores self at that location as a zip filesaved files are zip files with following contents: _metadata - contains class of self, i.e., type(self) _obj - serialized self. This class uses the default serialization (pickle).
- 参数:
- pathNone or file location (str or Path)
if None, self is saved to an in-memory object if file location, self is saved to that file location. If
path=”estimator” then a zip file
estimator.zip
will be made at cwd.path=”/home/stored/estimator” then a zip file
estimator.zip
will be
stored in
/home/stored/
.- serialization_format: str, default = “pickle”
Module to use for serialization. The available options are “pickle” and “cloudpickle”. Note that non-default formats might require installation of other soft dependencies.
- 返回值:
- if
path
is None - in-memory serialized self - if
path
is file location - ZipFile with reference to the file
- if
- score(y, X=None, fh=None)[source]#
使用 MAPE(非对称)对预测与真实值进行评分。
- 参数:
- ypd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
Time series to score
- 编码要预测时间戳的预测期。 如果
self.get_tag("requires-fh-in-fit")
为True
,则必须在fit
中传递,不可选 编码要预测时间戳的预测期。
- Xpd.DataFrame, or 2D np.array, optional (default=None)
Exogeneous time series to score if self.get_tag(“X-y-must-have-same-index”), X.index must contain y.index
- 返回值:
- scorefloat
MAPE loss of self.predict(fh, X) with respect to y_test.
- set_config(**config_dict)[source]#
将配置标志设置为给定值。
- 参数:
- config_dictdict
Dictionary of config name : config value pairs. Valid configs, values, and their meaning is listed below
- displaystr, “diagram” (default), or “text”
how jupyter kernels display instances of self
“diagram” = html box diagram representation
“text” = string printout
- print_changed_onlybool, default=True
whether printing of self lists only self-parameters that differ from defaults (False), or all parameter names and values (False). Does not nest, i.e., only affects self and not component estimators.
- warningsstr, “on” (default), or “off”
whether to raise warnings, affects warnings from sktime only
“on” = will raise warnings from sktime
“off” = will not raise warnings from sktime
- backend:parallelstr, optional, default=”None”
backend to use for parallelization when broadcasting/vectorizing, one of
“None”:顺序执行循环,简单的列表推导
“loky”, “multiprocessing” and “threading”: uses
joblib.Parallel
“joblib”:自定义和第三方
joblib
后端,例如spark
“dask”:使用
dask
,需要环境中包含dask
包“ray”:使用
ray
,需要环境中包含ray
包
- backend:parallel:paramsdict, optional, default={} (no parameters passed)
additional parameters passed to the parallelization backend as config. Valid keys depend on the value of
backend:parallel
“None”:无附加参数,忽略
backend_params
“loky”、“multiprocessing”和“threading”:默认
joblib
后端,可以在此处传递joblib.Parallel
的任何有效键,例如n_jobs
,但backend
除外,它直接由backend
控制。如果未传递n_jobs
,则默认为-1
,其他参数将默认为joblib
的默认值。“joblib”: custom and 3rd party
joblib
backends, e.g.,spark
. Any valid keys forjoblib.Parallel
can be passed here, e.g.,n_jobs
,backend
must be passed as a key ofbackend_params
in this case. Ifn_jobs
is not passed, it will default to-1
, other parameters will default tojoblib
defaults.“dask”:可以传递
dask.compute
的任何有效键,例如scheduler
“ray”:可以传递以下键
“ray_remote_args”:
ray.init
的有效键字典- “shutdown_ray”: bool, default=True; False prevents
ray
from shutting down after parallelization.
- “shutdown_ray”: bool, default=True; False prevents
“logger_name”:str,默认值=“ray”;要使用的日志记录器名称。
“mute_warnings”:bool,默认值=False;如果为 True,则禁止警告。
- remember_databool, default=True
whether self._X and self._y are stored in fit, and updated in update. If True, self._X and self._y are stored and updated. If False, self._X and self._y are not stored and updated. This reduces serialization size when using save, but the update will default to “do nothing” rather than “refit to all data seen”.
- 返回值:
- selfreference to self.
Notes
Changes object state, copies configs in config_dict to self._config_dynamic.
- set_params(**params)[source]#
设置此对象的参数。
The method works on simple skbase objects as well as on composite objects. Parameter key strings
<component>__<parameter>
can be used for composites, i.e., objects that contain other objects, to access<parameter>
in the component<component>
. The string<parameter>
, without<component>__
, can also be used if this makes the reference unambiguous, e.g., there are no two parameters of components with the name<parameter>
.- 参数:
- **paramsdict
BaseObject parameters, keys must be
<component>__<parameter>
strings.__
suffixes can alias full strings, if unique among get_params keys.
- 返回值:
- selfreference to self (after parameters have been set)
- set_random_state(random_state=None, deep=True, self_policy='copy')[source]#
为 self 设置 random_state 伪随机种子参数。
Finds
random_state
named parameters viaself.get_params
, and sets them to integers derived fromrandom_state
viaset_params
. These integers are sampled from chain hashing viasample_dependent_seed
, and guarantee pseudo-random independence of seeded random generators.Applies to
random_state
parameters inself
, depending onself_policy
, and remaining component objects if and only ifdeep=True
.Note: calls
set_params
even ifself
does not have arandom_state
, or none of the components have arandom_state
parameter. Therefore,set_random_state
will reset anyscikit-base
object, even those without arandom_state
parameter.- 参数:
- random_stateint, RandomState instance or None, default=None
Pseudo-random number generator to control the generation of the random integers. Pass int for reproducible output across multiple function calls.
- deepbool, default=True
Whether to set the random state in skbase object valued parameters, i.e., component estimators.
If False, will set only
self
’srandom_state
parameter, if exists.If True, will set
random_state
parameters in component objects as well.
- self_policystr, one of {“copy”, “keep”, “new”}, default=”copy”
“copy” :
self.random_state
is set to inputrandom_state
“keep” :
self.random_state
is kept as is“new” :
self.random_state
is set to a new random state,
derived from input
random_state
, and in general different from it
- 返回值:
- selfreference to self
- set_tags(**tag_dict)[source]#
将实例级别标签覆盖设置为给定值。
每个
scikit-base
兼容对象都有一个标签字典,用于存储关于对象的元数据。Tags are key-value pairs specific to an instance
self
, they are static flags that are not changed after construction of the object. They may be used for metadata inspection, or for controlling behaviour of the object.set_tags
sets dynamic tag overrides to the values as specified intag_dict
, with keys being the tag name, and dict values being the value to set the tag to.The
set_tags
method should be called only in the__init__
method of an object, during construction, or directly after construction via__init__
.可以通过
get_tags
或get_tag
查看当前标签值。- 参数:
- **tag_dictdict
Dictionary of tag name: tag value pairs.
- 返回值:
- Self
Reference to self.
- update(y, X=None, update_params=True)[source]#
更新截止值,以及(可选地)拟合参数。
If no estimator-specific update method has been implemented, default fall-back is as follows
update_params=True
: fitting to all observed data so farupdate_params=False
: updates cutoff and remembers data only
- State required
Requires state to be “fitted”, i.e.,
self.is_fitted=True
.
Accesses in self
Fitted model attributes ending in “_”.
self.cutoff
,self.is_fitted
将状态更改为“已拟合”。
Updates
self.cutoff
to latest index seen iny
.If
update_params=True
, updates fitted model attributes ending in “_”.
- 参数:
- 如果传递了
fh
,则将fh
存储到self.fh
。 Time series with which to update the forecaster.
用于拟合预测器的时间序列。
sktime
中的各个数据格式是所谓的 mtype 规范,每个 mtype 都实现了抽象的 scitype。 scitypeSeries
= 单个时间序列,普通预测。pd.DataFrame
、pd.Series
或np.ndarray
(1D 或 2D)Panel
scitype = 时间序列集合,全局/面板预测。 带有 2 级行MultiIndex
(instance, time)
的pd.DataFrame
,3D np.ndarray
(instance, variable, time)
,Series
类型的pd.DataFrame
list
Hierarchical
scitype = 分层集合,用于分层预测。 带有 3 级或更多行MultiIndex
(hierarchy_1, ..., hierarchy_n, time)
的pd.DataFrame
有关数据格式的更多详细信息,请参阅关于 mtype 的术语表。 有关用法,请参阅预测教程
examples/01_forecasting.ipynb
fhint, 列表, pd.Index 可强制转换类型, 或
ForecastingHorizon
, 默认值=None- 用于拟合模型的外生时间序列。 应与
y
具有相同的 scitype(Series
、Panel
或Hierarchical
)。 如果self.get_tag("X-y-must-have-same-index")
为 True,则X.index
必须包含y.index
。 Exogeneous time series to update the model fit with Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must containy.index
.- update_paramsbool, optional (default=True)
whether model parameters should be updated. If
False
, only the cutoff is updated, model parameters (e.g., coefficients) are not updated.
- 如果传递了
- 返回值:
- selfreference to self
- update_predict(y, cv=None, X=None, update_params=True, reset_forecaster=True)[source]#
在测试集上迭代进行预测并更新模型。
Shorthand to carry out chain of multiple
update
/predict
executions, with data playback based on temporal splittercv
.Same as the following (if only
y
,cv
are non-default)self.update(y=cv.split_series(y)[0][0])
remember
self.predict()
(return later in single batch)self.update(y=cv.split_series(y)[1][0])
remember
self.predict()
(return later in single batch)etc
return all remembered predictions
If no estimator-specific update method has been implemented, default fall-back is as follows
update_params=True
: fitting to all observed data so farupdate_params=False
: updates cutoff and remembers data only
- State required
Requires state to be “fitted”, i.e.,
self.is_fitted=True
.
Accesses in self
Fitted model attributes ending in “_”.
self.cutoff
,self.is_fitted
- Writes to self (unless
reset_forecaster=True
) Updates
self.cutoff
to latest index seen iny
.If
update_params=True
, updates fitted model attributes ending in “_”.
Does not update state if
reset_forecaster=True
.- 参数:
- 如果传递了
fh
,则将fh
存储到self.fh
。 Time series with which to update the forecaster.
用于拟合预测器的时间序列。
sktime
中的各个数据格式是所谓的 mtype 规范,每个 mtype 都实现了抽象的 scitype。 scitypeSeries
= 单个时间序列,普通预测。pd.DataFrame
、pd.Series
或np.ndarray
(1D 或 2D)Panel
scitype = 时间序列集合,全局/面板预测。 带有 2 级行MultiIndex
(instance, time)
的pd.DataFrame
,3D np.ndarray
(instance, variable, time)
,Series
类型的pd.DataFrame
list
Hierarchical
scitype = 分层集合,用于分层预测。 带有 3 级或更多行MultiIndex
(hierarchy_1, ..., hierarchy_n, time)
的pd.DataFrame
有关数据格式的更多详细信息,请参阅关于 mtype 的术语表。 有关用法,请参阅预测教程
examples/01_forecasting.ipynb
fhint, 列表, pd.Index 可强制转换类型, 或
ForecastingHorizon
, 默认值=None- cvtemporal cross-validation generator inheriting from BaseSplitter, optional
for example,
SlidingWindowSplitter
orExpandingWindowSplitter
; default = ExpandingWindowSplitter withinitial_window=1
and defaults = individual data points in y/X are added and forecast one-by-one,initial_window = 1
,step_length = 1
andfh = 1
- Xtime series in sktime compatible format, optional (default=None)
Exogeneous time series for updating and forecasting Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
infit
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must containfh
index reference.- update_paramsbool, optional (default=True)
whether model parameters should be updated. If
False
, only the cutoff is updated, model parameters (e.g., coefficients) are not updated.- reset_forecasterbool, optional (default=True)
if True, will not change the state of the forecaster, i.e., update/predict sequence is run with a copy, and cutoff, model parameters, data memory of self do not change
if False, will update self when the update/predict sequence is run as if update/predict were called directly
- 如果传递了
- 返回值:
- y_predobject that tabulates point forecasts from multiple split batches
format depends on pairs (cutoff, absolute horizon) forecast overall
if collection of absolute horizon points is unique: type is time series in sktime compatible data container format cutoff is suppressed in output has same type as the y that has been passed most recently: Series, Panel, Hierarchical scitype, same format (see above)
if collection of absolute horizon points is not unique: type is a pandas DataFrame, with row and col index being time stamps row index corresponds to cutoffs that are predicted from column index corresponds to absolute horizons that are predicted entry is the point prediction of col index predicted from row index entry is nan if no prediction is made at that (cutoff, horizon) pair
- update_predict_single(y=None, fh=None, X=None, update_params=True)[source]#
使用新数据更新模型并进行预测。
This method is useful for updating and making forecasts in a single step.
If no estimator-specific update method has been implemented, default fall-back is first update, then predict.
- State required
Requires state to be “fitted”.
- Accesses in self
Fitted model attributes ending in “_”. Pointers to seen data, self._y and self.X self.cutoff, self._is_fitted If update_params=True, model attributes ending in “_”.
- 将状态更改为“已拟合”。
Update self._y and self._X with
y
andX
, by appending rows. Updates self.cutoff and self._cutoff to last index seen iny
. If update_params=True,updates fitted model attributes ending in “_”.
- 参数:
- 如果传递了
fh
,则将fh
存储到self.fh
。 Time series with which to update the forecaster.
用于拟合预测器的时间序列。
sktime
中的各个数据格式是所谓的 mtype 规范,每个 mtype 都实现了抽象的 scitype。 scitypeSeries
= 单个时间序列,普通预测。pd.DataFrame
、pd.Series
或np.ndarray
(1D 或 2D)Panel
scitype = 时间序列集合,全局/面板预测。 带有 2 级行MultiIndex
(instance, time)
的pd.DataFrame
,3D np.ndarray
(instance, variable, time)
,Series
类型的pd.DataFrame
list
Hierarchical
scitype = 分层集合,用于分层预测。 带有 3 级或更多行MultiIndex
(hierarchy_1, ..., hierarchy_n, time)
的pd.DataFrame
有关数据格式的更多详细信息,请参阅关于 mtype 的术语表。 有关用法,请参阅预测教程
examples/01_forecasting.ipynb
fhint, 列表, pd.Index 可强制转换类型, 或
ForecastingHorizon
, 默认值=None- 编码要预测时间戳的预测期。 如果
self.get_tag("requires-fh-in-fit")
为True
,则必须在fit
中传递,不可选 The forecasting horizon encoding the time stamps to forecast at. Should not be passed if has already been passed in
fit
. If has not been passed in fit, must be passed, not optional- Xtime series in sktime compatible format, optional (default=None)
Exogeneous time series for updating and forecasting Should be of same scitype (
Series
,Panel
, orHierarchical
) asy
infit
. Ifself.get_tag("X-y-must-have-same-index")
,X.index
must containfh
index reference.- update_paramsbool, optional (default=True)
whether model parameters should be updated. If
False
, only the cutoff is updated, model parameters (e.g., coefficients) are not updated.
- 如果传递了
- 返回值:
- y_predsktime 兼容数据容器格式的时间序列
在
fh
处的点预测,具有与fh
相同的索引。y_pred
具有与最近传递的y
相同的类型:Series
、Panel
、Hierarchical
scitype,相同格式(见上文)