【发布时间】:2017-03-12 11:50:54
【问题描述】:
好的,所以我正在 python 中编写一个线性最小二乘函数,它几乎只是一个方程。然而由于某种原因,我得到了一个 ValueError。我最好的猜测是它与.reshape 函数有关,因为在这个问题中我有a very similar problem 并且重塑是解决方案。我已经阅读了它,从我收集的内容来看,我的函数中的 w 格式为 (n,),结果将在 (n,1) 中,如我之前提到的问题中所示。我尝试重塑x_train 和y_train,但我只得到一个错误,我无法更改数组的大小。我猜我的参数设置错了。现在我迷路了,我还有更多这样的功能要完成——我希望我能理解我的代码中缺少什么。这个等式似乎是有序的,所以我想我每次都应该添加一些东西——可能是reshape 函数,因为我仍在使用与上一种情况相同的模型。我希望这是发布这个问题的正确地方,我不知道还能做什么,但我真的很想了解,所以我以后不会遇到这些问题,谢谢。
代码(np.代表numpy):
def least_squares(x_train, y_train, M):
'''
:param x_train: training input vector Nx1
:param y_train: training output vector Nx1
:param M: polynomial degree
:return: tuple (w,err), where w are model parameters and err mean squared error of fitted polynomial
'''
w = np.linalg.inv(design_matrix(x_train, M). * design_matrix(x_train, M)) * design_matrix(x_train, M).T * y_train
err = mean_squared_error(x_train, y_train, w)
return (w, err)
design_matrix 和 mean_squared_error 工作正常。
追溯:
ERROR: test_least_squares_err (test.TestLeastSquares)
----------------------------------------------------------------------
Traceback (most recent call last):
File "\content.py", line 48, in least_squares
w = np.linalg.inv(design_matrix(x_train, M).T * design_matrix(x_train, M)) * design_matrix(x_train, M).T * y_train
ValueError: operands could not be broadcast together with shapes (7,20) (20,7)
【问题讨论】:
-
看起来您使用的是逐分量乘法
*而不是矩阵-矩阵、矩阵-向量积np.dot -
您可能还想看看使用
np.linalg.lstsq,它可能更快且数值更稳定 -
@Eric 谢谢你,会检查的!将来可能会派上用场。这次我应该自己编写函数,但当我不得不再次使用它时我不会拒绝它:)
标签: python numpy linear-regression