【问题标题】:Matlab to Python translation of design matrix functionMatlab到Python设计矩阵函数的翻译
【发布时间】: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 的?
  • 它现在在上面

标签: python matlab numpy


【解决方案1】:

你可以试试这个:

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
    '''
    x_train = np.asarray(x_train)
    desm = np.zeros(shape =(len(x_train), M+1))
    for i in range(0, M+1):
        desm[:,i] = np.power(x_train, i).reshape(x_train.shape[0],)
    return desm

错误来自不兼容的 Numpy 数组维度。 desm[:,i] 的形状为 (n,),但您尝试存储的值的形状为 (n,1),因此您需要将其重塑为 (n,)。此外,正如 GLR 所提到的,Python 索引从 0 开始,因此您需要修改索引,并且函数执行在返回行处停止,因此根本没有到达 pass 行。

【讨论】:

  • 我试过了,理解了变化,但我一直收到和以前一样的错误:(
  • 嗯。所以你仍然收到 ValueError: could not broadcast input array from shape (20,1) into shape (20)?
  • 是的,正是这个。
  • 你能试试 desm[:,i] = np.power(x_train, i).reshape(x_train.shape[0], 1) 吗?
  • 唉,什么都没有改变。相同的值仍然是相同的错误,(20, 1) 和 (20)
【解决方案2】:

我看到三个错误:

  • 在 Python 中,索引从零开始。

  • 要为数组的所有项供电,可以使用** 运算符。

  • pass 什么都不做,因为它放在return 语句之后。该函数永远不会到达这一点。

我会试试这个:

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(0, M+1):
        desm[:,i] = x_train.squeeze() ** (i-1)
    return desm

【讨论】:

  • 我试过了,但得到了和以前一样的错误。下次尝试时,我将保持传递被删除并将索引为零。
  • 请尝试编辑。问题是 x_train 是一个矩阵(它有两个维度),当你做desm[:, i] 时,你正在访问一个数组。要摆脱不必要的维度,您可以使用squeeze
  • 不幸的是仍然不起作用,我试过了,但现在它说这是失败而不是错误,我得到了这个回溯:文件“...\test.py”,第 63 行,在 test_design_matrix self.assertAlmostEqual(max_diff, 0, 8) AssertionError: 22357.537052901051 != 0 在 8 个地方。我猜是计算错误?
  • 引发此错误是因为max_diff 与零非常不同。我会尝试在交互式 Python 会话中加载 dm(在 test.py 中),看看那里发生了什么。
  • 对不起,我对python真的很陌生......你是说问题出在那个函数的test.py文件中吗?我开始认为可能是这种情况。
【解决方案3】:

您可能有兴趣知道您可以使用 patsy 语言和模块为多项式回归创建正交设计矩阵。

>>> import numpy as np
>>> from patsy import dmatrices, dmatrix, demo_data, Poly
>>> data = demo_data("a", "b", "x1", "x2", "y", "z column")
>>> dmatrix('C(x1, Poly)', data)
DesignMatrix with shape (8, 8)
Columns:
['Intercept', 'C(x1, Poly).Linear', 'C(x1, Poly).Quadratic', 'C(x1, Poly).Cubic', 'C(x1, Poly)^4', 'C(x1, Poly)^5', 'C(x1, Poly)^6', 'C(x1, Poly)^7']
Terms:
'Intercept' (column 0), 'C(x1, Poly)' (columns 1:8)
(to view full data, use np.asarray(this_obj))
>>> dm = dmatrix('C(x1, Poly)', data)
>>> np.asarray(dm)
array([[ 1.        ,  0.23145502, -0.23145502, -0.43082022, -0.12087344,
         0.36376642,  0.55391171,  0.35846409],
       [ 1.        , -0.23145502, -0.23145502,  0.43082022, -0.12087344,
        -0.36376642,  0.55391171, -0.35846409],
       [ 1.        ,  0.07715167, -0.38575837, -0.18463724,  0.36262033,
         0.32097037, -0.30772873, -0.59744015],
       [ 1.        ,  0.54006172,  0.54006172,  0.43082022,  0.28203804,
         0.14978617,  0.06154575,  0.01706972],
       [ 1.        ,  0.38575837,  0.07715167, -0.30772873, -0.52378493,
        -0.49215457, -0.30772873, -0.11948803],
       [ 1.        , -0.54006172,  0.54006172, -0.43082022,  0.28203804,
        -0.14978617,  0.06154575, -0.01706972],
       [ 1.        , -0.07715167, -0.38575837,  0.18463724,  0.36262033,
        -0.32097037, -0.30772873,  0.59744015],
       [ 1.        , -0.38575837,  0.07715167,  0.30772873, -0.52378493,
         0.49215457, -0.30772873,  0.11948803]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    相关资源
    最近更新 更多