Python中ETS预测函数出现UnboundLocalError问题求助
ETS预测函数UnboundLocalError错误修复
问题描述
我编写了用于ETS预测的函数,但运行时出现UnboundLocalError错误,代码和报错信息如下:
原代码
# evaluate an ETS model for a given parameters (t,d,s,p,b,r) def train_ets_model(train, test, cfg): t,d,s,p,b,r = cfg # prepare training dataset history = [x for x in train.values] # make predictions predictions = list() for t in range(len(test.values)): model = ExponentialSmoothing(history, trend=t, damped=d, seasonal=s, seasonal_periods=p, use_boxcox=b) # fit model model_fit = model.fit(optimized=True, remove_bias=r) #one-step prediction yhat = model_fit.predict(len(history), len(history))[0] predictions.append(yhat) history.append(test.values[t]) # calculate out of sample error error = np.round(mean_squared_error(test, predictions),2) return error, predictions #evaluate configurations for ETS model def evaluate_ets_models(train, test, cfg_list): best_score, best_cfg = float("inf"), None for cfg in cfg_list: try: mse, predictions = train_ets_model(train, test, cfg) if mse < best_score: best_score, best_cfg = mse, cfg #print('ETS%s RMSE=%.3f' % (order,rmse)) except: continue return best_cfg, best_score, predictions #print('Best ETS%s RMSE=%.3f' % (best_cfg, best_score))
报错信息
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) Cell In[38], line 1 ----> 1 evaluate_ets_models(train, test, cfg_list) Cell In[37], line 32, in evaluate_ets_models(train, test, cfg_list) 30 except: 31 continue ---> 32 return best_cfg, best_score, predictions UnboundLocalError: local variable 'predictions' referenced before assignment
错误原因与修复方案
错误原因
predictions变量仅在try代码块内赋值,如果所有配置都触发异常(比如cfg_list为空,或每个配置运行都报错),predictions会从未被定义,返回时触发未绑定变量错误。- 原逻辑中
predictions仅保存最后一次循环的结果,而非最优配置对应的预测值,属于逻辑漏洞。
修改后的evaluate_ets_models函数
# evaluate configurations for ETS model def evaluate_ets_models(train, test, cfg_list): best_score, best_cfg, best_predictions = float("inf"), None, [] for cfg in cfg_list: try: mse, predictions = train_ets_model(train, test, cfg) if mse < best_score: best_score, best_cfg = mse, cfg best_predictions = predictions # 保存最优配置对应的预测结果 #print('ETS%s RMSE=%.3f' % (order,rmse)) except: continue return best_cfg, best_score, best_predictions
修改说明
- 初始化
best_predictions为空列表,确保无论是否有成功运行的配置,返回时变量都已定义。 - 每次找到更优MSE的模型时,同步更新
best_predictions,保证返回的是最优模型的预测结果,而非最后一次循环的结果。 - 若所有配置运行失败,返回的
best_predictions为空列表,best_cfg为None,best_score为inf,可根据需求添加额外的异常提示逻辑。
内容的提问来源于stack exchange,提问作者Mridul Bhardwaj
相关产品推荐
相关产品推荐

