【发布时间】:2017-03-11 15:53:00
【问题描述】:
去年我在 Matlab 中为线性回归程序中的设计矩阵编写了代码。它工作得很好。现在,我需要将它翻译成 Python 并在 Pycharm 中运行。我已经使用它好几天了,虽然我对 Python 很陌生,但我在翻译中找不到任何错误,但是当代码与程序的其余部分一起运行时,我得到了一个错误。
matlab中的代码:
function DesignMatrix = design_matrix( xTrain, M )
% This function calculates the Design Matrix for
% a M-th degree polynomial
% xTrain - training set Nx1
% M - polynomial degree 0,1,2,...
N = size(xTrain,1);
DesignMatrix = zeros(N,M+1);
for i=1:M+1
DesignMatrix(:,i)=xTrain.^(i-1)
end
end
还有我在 Python 中的翻译(np 代表 numpy,是导入的):
def design_matrix(x_train,M):
'''
:param x_train: input vector Nx1
:param M: polynomial degree 0,1,2,...
:return: Design Matrix Nx(M+1) for M degree polynomial
'''
desm = np.zeros(shape =(len(x_train), M+1))
for i in range(1, M+1):
desm[:,i] = np.power(x_train, (i-1))
return desm
pass
错误指向这一行:desm[:,i] = np.power(x_train, (i-1)),这是一个值错误。我尝试使用在线翻译器 ompc,但它似乎已经过时,因为它对我不起作用。如果我的翻译中有任何明显的错误,谁能给我解释一下?我知道这是一个更大程序的一部分,但我要问的只是语法翻译本身。如果它是正确的,我会尝试找出任何其他错误,尽管我到目前为止还没有想出任何错误。谢谢。
编辑:追溯
ERROR: test_design_matrix (test.TestDesignMatrix)
----------------------------------------------------------------------
Traceback (most recent call last):
File "...\test.py", line 61, in test_design_matrix
dm_computed = design_matrix(x_train, M)
File "...\content.py", line 34, in design_matrix
desm[:,i] = np.power(x_train, (i-1))
ValueError: could not broadcast input array from shape (20,1) into shape (20)
我无法更改 test.py 文件,它是提供给我的,无法更改,所以我只依赖第二个错误。
来自给出错误的函数的 test.py 的摘录:
def test_design_matrix(self):
x_train = TEST_DATA['design_matrix']['x_train']
M = TEST_DATA['design_matrix']['M']
dm = TEST_DATA['design_matrix']['dm']
dm_computed = design_matrix(x_train, M)
max_diff = np.max(np.abs(dm - dm_computed))
self.assertAlmostEqual(max_diff, 0, 8)
【问题讨论】:
-
能否添加回溯,以便我们查看有关错误的更多详细信息?
-
当然,刚刚添加。
-
您能否也添加 test_design_matrix 的代码块,以便我们了解您是如何调用 design_matrix 的?
-
它现在在上面