Matlab将Python转换为设计矩阵函数 [英] Matlab to Python translation of design matrix function

查看:128
本文介绍了Matlab将Python转换为设计矩阵函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

去年,我已经在Matlab中为线性回归程序中的设计矩阵编写了代码.它工作正常.现在,我需要将其翻译为Python并在Pycharm中运行.我已经使用了好几天了,虽然我是Python的新手,但是我在翻译中找不到任何错误,但是当代码与程序的其余部分一起运行时却出现错误.

Last year I've written a code in Matlab for a design matrix in linear regression program. It works just fine. Now, I need to translate it to Python and run in Pycharm. I've been at it for days, and while I'm really new to Python, I can't find any mistakes in my translation, but I get an error while the code is run with the rest of the program.

matlab中的代码:

Code in 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,已导入):

and my translation in Python (np stands for numpy, which is imported):

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,但由于它对我不起作用,因此它似乎已过时.如果我的翻译中有任何明显的错误,有人可以向我解释吗?我知道这是更大程序的一部分,但是我要问的只是语法翻译本身.如果是正确的话,尽管到目前为止我没有提出任何建议,但我会尝试查找其他任何错误.谢谢.

The error points to this line: desm[:,i] = np.power(x_train, (i-1)) and it's a value error. I tried using the online translator ompc but it seems to be outdated since it didn't work for me. Could anyone kindly explain to me if there're any obvious mistakes in my translation? I know it's a part of a bigger program, but what I'm asking is just the syntax translation itself. If it's correct, I'll try to find any other mistakes, though I didn't come up with any so far. Thank you.

编辑:回溯

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文件,它是提供给我的,无法更改,因此我仅依靠第二个错误.

I'm not able to change the test.py file, it's provided to me and can't be changed, so I'm only relying on the second error.

给出错误的函数的test.py摘录:

Excerpt from test.py of the function that gives the error:

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)

推荐答案

可以尝试一下:

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开始,因此您需要修改索引,并且函数执行在返回行处停止,因此根本无法到达传递行.

The error comes from incompatible Numpy array dimensions. desm[:,i] has the shape (n,), but the value you are trying to store to it has the shape (n,1), so you need to reshape it to (n,). Also, as GLR mentioned, Python indexing starts at 0 so you need to modify your indices, and function execution stops at the return line, so the pass line is not reached at all.

这篇关于Matlab将Python转换为设计矩阵函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆