Python NameError: name 'future_scaled' is not defined 错误解决
Python NameError: name 'future_scaled' is not defined 错误解决
在进行时间序列预测时,您可能会遇到 NameError: name 'future_scaled' is not defined 错误。该错误表明您的代码中缺少对 future_scaled 变量的定义。
此错误通常出现在使用机器学习模型进行预测,并尝试对未来数据进行缩放以获得准确预测结果的情况下。
以下是修正后的代码示例,其中包含了定义和使用 future_scaled 的部分,以及计算预测置信区间的步骤:
# 构建未来10年的特征矩阵
future_features = np.zeros((10, len(data[0])-1))
current_data = data[-1, :-1] # 使用最后一行数据作为当前数据
# 根据模型预测未来十年的特征
for i in range(10):
feature = model.predict(current_data.reshape(1, -1)) # 使用模型预测特征
future_features[i] = feature # 更新特征矩阵
current_data = np.concatenate((current_data[1:], feature)) # 更新当前数据
# 归一化未来的特征数据
future_scaled = scaler.transform(future_features.reshape(-1, len(data[0])-1))
# 使用TSK_FLS模型预测未来十年的目标变量
future_pred = model.predict(future_scaled)
# 计算置信区间
residuals = y_test - y_pred
mean_residuals = np.mean(residuals)
std_residuals = np.std(residuals)
n_samples = len(future_pred)
z_score = 1.96 # 对应于95%的置信区间
margin_of_error = z_score * std_residuals / np.sqrt(n_samples)
lower_bound = future_pred - margin_of_error
upper_bound = future_pred + margin_of_error
# 输出未来十年的预测置信区间
print('未来十年的预测置信区间:')
for i in range(len(future_pred)):
print(f'年份: {i+1}, 下界: {lower_bound[i]}, 上界: {upper_bound[i]}')
代码解释:
-
定义
future_scaled: 代码首先创建了一个名为future_features的数组,用于存储未来十年的特征数据。然后,使用循环迭代计算未来的特征,并将结果存储在future_features中。最后,使用scaler.transform()方法对future_features进行归一化,并将结果赋值给future_scaled。 -
使用
future_scaled进行预测: 使用训练好的模型对future_scaled进行预测,得到未来十年的预测结果future_pred。 -
计算置信区间: 根据预测结果和测试集数据计算置信区间,并输出预测结果和置信区间范围。
通过定义 future_scaled 并按照上述步骤进行操作,您就可以解决 NameError: name 'future_scaled' is not defined 错误,并成功进行时间序列预测和置信区间计算。
原文地址: https://www.cveoy.top/t/topic/54i 著作权归作者所有。请勿转载和采集!