Python边缘服务器负载预测代码报错:矩阵乘法维度不匹配
问题排查与解决
错误根源
执行model = np.linalg.inv(X.T @ X) @ X.T @ y时出现维度不匹配,核心原因是:
- 代码中
future_resources = resource_array[i:i+prediction_horizon]的切片长度会在i接近num_steps时变短。当i + prediction_horizon > num_steps(比如i=91,num_steps=100,prediction_horizon=10),切片结果长度为100-91=9,而X是固定长度为10的数组(np.arange(prediction_horizon))。 - 此时
y的行数为9,X的行数为10,矩阵乘法要求X.T的列数与y的行数必须一致,两者不匹配导致报错。
修复方案
核心目标是确保预测时future_resources的长度始终等于prediction_horizon,以下两种方案均可解决问题:
方案1:拆分填充与预测逻辑(更清晰)
先完整填充资源数组,再单独处理预测,避免切片越界:
import numpy as np import matplotlib.pyplot as plt np.random.seed(42) def edge_resources(t): return 100*np.exp(-0.01*t) num_steps = 100 time_step = 0.1 prediction_horizon = 10 resource_array = np.zeros(num_steps) prediction_array = np.zeros(num_steps - prediction_horizon) # 先填充所有时间步的资源数据 for i in range(num_steps): t = i*time_step resource_array[i] = edge_resources(t) # 仅在有足够未来数据时执行预测 for i in range(prediction_horizon, num_steps - prediction_horizon + 1): future_resources = resource_array[i:i+prediction_horizon] X = np.arange(prediction_horizon).reshape(-1, 1) y = future_resources.reshape(-1, 1) model = np.linalg.inv(X.T @ X) @ X.T @ y prediction_array[i-prediction_horizon] = model[0, 0] # 绘制结果 plt.plot(np.arange(num_steps)*time_step, resource_array, label='Edge Resources') plt.plot(np.arange(prediction_horizon, num_steps - prediction_horizon + 1)*time_step, prediction_array[:len(np.arange(prediction_horizon, num_steps - prediction_horizon + 1))], label='Prediction') plt.legend() plt.xlabel('Time (s)') plt.ylabel('Edge Resources') plt.show()
方案2:调整原循环的判断条件
在原循环中新增判断,仅当存在足够未来数据时执行预测:
import numpy as np import matplotlib.pyplot as plt np.random.seed(42) def edge_resources(t): return 100*np.exp(-0.01*t) num_steps = 100 time_step = 0.1 prediction_horizon = 10 resource_array = np.zeros(num_steps) prediction_array = np.zeros(num_steps - prediction_horizon) for i in range(num_steps): t = i*time_step resource_array[i] = edge_resources(t) # 仅当有足够历史和未来数据时预测 if i >= prediction_horizon and i + prediction_horizon <= num_steps: future_resources = resource_array[i:i+prediction_horizon] X = np.arange(prediction_horizon).reshape(-1, 1) y = future_resources.reshape(-1, 1) model = np.linalg.inv(X.T @ X) @ X.T @ y prediction_array[i-prediction_horizon] = model[0, 0] # 绘制结果 plt.plot(np.arange(num_steps)*time_step, resource_array, label='Edge Resources') plt.plot(np.arange(prediction_horizon, num_steps - prediction_horizon + 1)*time_step, prediction_array[:len(np.arange(prediction_horizon, num_steps - prediction_horizon + 1))], label='Prediction') plt.legend() plt.xlabel('Time (s)') plt.ylabel('Edge Resources') plt.show()
额外优化提示
- 推荐使用
np.linalg.lstsq代替手动求逆计算线性回归参数,更稳定且能避免矩阵不可逆问题:model, _, _, _ = np.linalg.lstsq(X, y, rcond=None) - 原代码中
past_resources变量未被使用,可根据实际需求用其构建特征X,提升预测合理性。
内容的提问来源于stack exchange,提问作者user13238656
相关产品推荐
相关产品推荐

