Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在C+中实现numpy.polyfit和numpy.polyval+;犰狳 我试图用.来重现C++中的结果和以下应用程序。_Python_C++_Numpy_Linear Regression_Armadillo - Fatal编程技术网

Python 在C+中实现numpy.polyfit和numpy.polyval+;犰狳 我试图用.来重现C++中的结果和以下应用程序。

Python 在C+中实现numpy.polyfit和numpy.polyval+;犰狳 我试图用.来重现C++中的结果和以下应用程序。,python,c++,numpy,linear-regression,armadillo,Python,C++,Numpy,Linear Regression,Armadillo,这是我的尝试: using namespace arma; vec fastLm(const vec& y, const mat& X, int order) { mat extended_X(X); // Column bind the higher order regressors to the initial matrix for(int i = 2; i < order + 1; ++i) {

这是我的尝试:

using namespace arma;

vec fastLm(const vec& y,
           const mat& X,
           int order)
{
  mat extended_X(X);
  
  // Column bind the higher order regressors to the initial matrix
  for(int i = 2; i < order + 1; ++i)
  {
    extended_X = join_rows(extended_X, pow(X, i));
  }
  
  // Join another column, made of '1', in order to have the intercept
  extended_X = join_rows(mat(X.n_rows, 1, fill::ones), extended_X);
  
  // Solve the linear regression by OLS
  colvec coef = solve(extended_X, y);

  // Return the fit
  return extended_X * coef;
}

然而,我的测试显示了差异和奇怪的结果,我很难找到和调试它们的原因。你能告诉我我的“翻译”是正确的还是修复了它吗?

对我来说,一切看起来都很好,我已经试过你的功能了

int main()
{
  mat x=linspace(0,1,5);
  vec y=1/(1+x);
  y.print("Y");
  mat Yhat = fastLm(y,x,3);
  Yhat.print("Yhat");
}
给出结果

Y
   1.0000
   0.8000
   0.6667
   0.5714
   0.5000
Yhat
   0.9998
   0.8008
   0.6654
   0.5722
   0.4998
python代码的相应结果是

[1.         0.8        0.66666667 0.57142857 0.5       ]
[0.99979592 0.80081633 0.66544218 0.5722449  0.49979592]
。。。和Matlab

>> Y
Y =

   1.00000   0.80000   0.66667   0.57143   0.50000

>> Yhat
Yhat =

   0.99980   0.80082   0.66544   0.57224   0.49980

>> 

为什么要重新实施?犰狳已经有了它的功能,真的吗?我不知道:(
>> Y
Y =

   1.00000   0.80000   0.66667   0.57143   0.50000

>> Yhat
Yhat =

   0.99980   0.80082   0.66544   0.57224   0.49980

>>