can anyone help me with this?
Matlab Code
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 Code
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
The final answer of theta in MATLAB code, which is also the correct answer, is a 10 * 1 matrix. It has 10 numbers in total, but the theta answer in the Python code is a 10 * 30 matrix. We have 300 numbers in the output.
How to do this multiplication with Numpy so that the final answer is the same as the MATLAB code answer?
CodePudding user response:
As the comment on your question has said, it's better to write this code using an array rather than a list of variables.
That said, the issue is that you are using * which, in Python, denotes entrywise multiplication rather than matrix multiplication. What you should try instead is
theta_test = (x_test.T @ x_test) ** -1 * x_test.T @ y_test
CodePudding user response:
Your numpy code produces:
In [3]: x_test.shape
Out[3]: (10, 3, 1)
In [4]: y_test.shape
Out[4]: (3, 1)
Stripping off the last x_test dimension:
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]])
Switching the transpose produces a (10,10) array, but it's singular
In [14]: np.linalg.inv([email protected])
Traceback (most recent call last):
...
LinAlgError: Singular matrix
The (10,3) can multiply the (3,1) to produce a (10,1)
In [18]: (x1@y_test).shape
Out[18]: (10, 1)
I'm having troubles running your MATLAB code in Octave, so can't generate its equivalent to see what you are trying to reproduce.
