有人能帮我吗?
Matlab代码
test = 300
f = @(u) 2+3*u-2*u.^3+u.^6-4*u.^8;
rng(12354)
u_test = unifrnd(-1,1,[test,1]);
y_test = f(u_test);
xt0 = 1*ones(test, 1);
xt1 = u_test;
xt2 = u_test.^2;
xt3 = u_test.^3;
xt4 = u_test.^4;
xt5 = u_test.^5;
xt6 = u_test.^6;
xt7 = u_test.^7;
xt8 = u_test.^8;
xt9 = u_test.^9;
x_test = [xt0 xt1 xt2 xt3 xt4 xt5 xt6 xt7 xt8 xt9];
theta_test = (x_test'*x_test)^-1*x_test'*y_test;
Python代码
import numpy as np
test = 3
min_test = -1
max_test = 1
f = lambda u: 2+3*u-2*u**3+u**6-4*u**8
np.random.seed(12345)
u_test = np.random.uniform(min_test, max_test, [test, 1])
y_test = f(u_test)
xt0 = np.ones([test, 1])
xt1 = u_test
xt2 = u_test ** 2
xt3 = u_test ** 3
xt4 = u_test ** 4
xt5 = u_test ** 5
xt6 = u_test ** 6
xt7 = u_test ** 7
xt8 = u_test ** 8
xt9 = u_test ** 9
x_test = np.array([xt0, xt1, xt2, xt3, xt4, xt5, xt6, xt7, xt8, xt9])
theta_test = (x_test.T * x_test) ** -1 * x_test.T * y_test
MATLAB代码中θ的最终答案也是正确答案,是10*1矩阵。它总共有10个数字,但Python代码中的theta答案是10*30矩阵。我们的输出中有300个数字。
如何用Numpy进行乘法运算,使最终答案与MATLAB代码的答案相同?
正如对您的问题的评论所说,最好使用数组而不是变量列表来编写此代码。
也就是说,问题是您使用的是*
,在Python中,它表示入口乘法,而不是矩阵乘法。你应该试试
theta_test = (x_test.T @ x_test) ** -1 * x_test.T @ y_test
您的numpy
代码生成:
In [3]: x_test.shape
Out[3]: (10, 3, 1)
In [4]: y_test.shape
Out[4]: (3, 1)
剥离最后一个x_test
维度:
In [11]: x1 = x_test[:,:,0]
In [12]: (x1.T@x1).shape
Out[12]: (3, 3)
In [13]: np.linalg.inv(x1.T@x1)
Out[13]:
array([[ 0.34307216, -0.63513713, 0.36347551],
[-0.63513713, 8.44935183, -6.36062978],
[ 0.36347551, -6.36062978, 5.43319377]])
转换转置产生一个(10,10(数组,但它是奇异的
In [14]: np.linalg.inv(x1@x1.T)
Traceback (most recent call last):
...
LinAlgError: Singular matrix
(10,3(可以乘以(3,1(以产生(10,1(
In [18]: (x1@y_test).shape
Out[18]: (10, 1)
我在Octave中运行MATLAB代码时遇到了问题,所以无法生成等效代码来查看您试图复制的内容。