Matlab对python的不同结果,不能用s

2024-09-30 03:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试将下面的matlab代码转换成python,我在构建矩阵代数时遇到了困难。你知道吗

python代码的乘积与matlab有很大的不同,我无法解决这个问题(我假设它在矩阵乘法中)。你知道吗

只是提供一些背景信息:使用数据集,我试图用一个虚拟变量“D1”创建一个预测

以下是matlab代码:

load 'AUSRetail.csv'

y = AUSRetail(:,1); Q = AUSRetail(:,2);
T = length(y); t = (1:T)';
D4 = (Q == 4);
T0 = 15;
h = 1; % h−step−ahead forecast
syhat = zeros(T-h-T0+1,1);
ytph = y(T0+h:end); % observed y {t+h}
for t = T0:T-h
    yt = y(1:t);
    D4t = D4(1:t);
    Xt = [ones(t,1) (1:t)' D4t];
    beta2 = (Xt'*Xt)\(Xt'*yt);
    yhat2 = [1 t+h D4(t+h)]*beta2;
    syhat(t-T0+1) = yhat2;
end
MSFE2 = mean((ytph-syhat).^2);

plot([1:T], y)
hold on 
plot([T0 + h:T], syhat)

下面是我的python代码尝试:

data = pd.read_csv("dataretail.csv").dropna()

D4 = np.asarray(data["Dummy4"])
dataValues = np.asarray(data["Value"])
T = len(D4)
T0 = 15
h = 1

syhat = []
ytph = np.asarray(dataValues) # Real values to test against
for t in range(T0,T-1):
    yt = dataValues[:t].reshape(t,1)

    D4t = D4[:t]

    #Construction of Xt
    xt1 = np.ones((t,1))
    xt2 = np.arange(1,t+1).reshape(t,1)
    xt3 = D4t.reshape(t,1)
    Xt = np.column_stack((xt1,xt2,xt3))
    Xt2 = np.transpose(Xt)

    A = Xt2 @ Xt
    b = Xt2 @ yt
    beta2 = np.transpose(A) @ b
    yhat2 = np.array([1, t+h, D4[t+h]]) @ beta2
    syhat.append(int(yhat2))


fig = plt.figure()
axes = fig.add_axes([0.2, 0.2, 0.8, 1])
axes.set_xlabel("T (time)")
axes.set_ylabel("Yhat2")
axes.plot(range(25), abc)
axes.set_title("Model")

Tags: csv代码npxtytmatlabaxesbeta2

热门问题