Python 3.x **和pow函数的使用差异

Python 3.x **和pow函数的使用差异,python-3.x,numpy,linear-regression,Python 3.x,Numpy,Linear Regression,尝试为线性回归编写成本函数时,在成本函数中用pow函数替换**时会出现错误: 原始成本函数 def cost_function(x,y,theta): m = np.size(y) j = (1/(2*m))*np.sum(np.power(np.matmul(x,theta)-y),2) return j 给出错误的成本函数: def cost_function(x,y,theta): m = np.size(y) j = (1/(2*

尝试为线性回归编写成本函数时,在成本函数中用pow函数替换**时会出现错误:

原始成本函数

def cost_function(x,y,theta):
    m = np.size(y)
    j = (1/(2*m))*np.sum(np.power(np.matmul(x,theta)-y),2)
    return j
给出错误的成本函数:

def cost_function(x,y,theta):
        m = np.size(y)
        j = (1/(2*m))*np.sum((np.matmul(x,theta)-y)**2)
        return j
梯度下降

def gradient_descent(x,y,theta,learn_rate,iters):
    x = np.mat(x);y = np.mat(y); theta= np.mat(theta);
    m = np.size(y)
    j_hist = np.zeros(iters)
    for i in range(0,iters):
        temp = theta - (learn_rate/m)*(x.T*(x*theta-y))
        theta = temp
        j_hist[i] = cost_function(x,y,theta)
    return (theta),j_hist
可变值

theta  = np.zeros((2,1))
learn_rate = 0.01
iters = 1000
x is (97,2) matrix
y is (97,1) matrix
成本函数的计算值为32.0727 在梯度下降中使用相同的函数时会出现错误


我得到的误差是线性误差:数组的最后两个维度必须是正方形

首先,让我们区分
pow
**
np.power
pow
是Python函数,根据文档,当与2个参数一起使用时,它相当于
**

其次,将
np.mat
应用于数组,生成
np.matrix
对象。根据其文件:

它具有某些特殊运算符,例如
*
(矩阵乘法)和
**
(矩阵幂)

矩阵幂:

In [475]: np.mat([[1,2],[3,4]])**2
Out[475]: 
matrix([[ 7, 10],
        [15, 22]])
In [478]: arr = np.array([[1,2],[3,4]])
In [479]: arr@arr            # np.matmul
Out[479]: 
array([[ 7, 10],
       [15, 22]])
元素方:

In [476]: np.array([[1,2],[3,4]])**2
Out[476]: 
array([[ 1,  4],
       [ 9, 16]])
In [477]: np.power(np.mat([[1,2],[3,4]]),2)
Out[477]: 
matrix([[ 1,  4],
        [ 9, 16]])
矩阵幂:

In [475]: np.mat([[1,2],[3,4]])**2
Out[475]: 
matrix([[ 7, 10],
        [15, 22]])
In [478]: arr = np.array([[1,2],[3,4]])
In [479]: arr@arr            # np.matmul
Out[479]: 
array([[ 7, 10],
       [15, 22]])
对于非平方矩阵:

In [480]: np.power(np.mat([[1,2]]),2)
Out[480]: matrix([[1, 4]])             # elementwise
In [481]: np.mat([[1,2]])**2
---------------------------------------------------------------------------
LinAlgError                               Traceback (most recent call last)
<ipython-input-481-18e19d5a9d6c> in <module>()
----> 1 np.mat([[1,2]])**2

/usr/local/lib/python3.6/dist-packages/numpy/matrixlib/defmatrix.py in __pow__(self, other)
    226 
    227     def __pow__(self, other):
--> 228         return matrix_power(self, other)
    229 
    230     def __ipow__(self, other):

/usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py in matrix_power(a, n)
    600     a = asanyarray(a)
    601     _assertRankAtLeast2(a)
--> 602     _assertNdSquareness(a)
    603 
    604     try:

/usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py in _assertNdSquareness(*arrays)
    213         m, n = a.shape[-2:]
    214         if m != n:
--> 215             raise LinAlgError('Last 2 dimensions of the array must be square')
    216 
    217 def _assertFinite(*arrays):

LinAlgError: Last 2 dimensions of the array must be square
试图在非方矩阵上执行矩阵幂运算:

In [480]: np.power(np.mat([[1,2]]),2)
Out[480]: matrix([[1, 4]])             # elementwise
In [481]: np.mat([[1,2]])**2
---------------------------------------------------------------------------
LinAlgError                               Traceback (most recent call last)
<ipython-input-481-18e19d5a9d6c> in <module>()
----> 1 np.mat([[1,2]])**2

/usr/local/lib/python3.6/dist-packages/numpy/matrixlib/defmatrix.py in __pow__(self, other)
    226 
    227     def __pow__(self, other):
--> 228         return matrix_power(self, other)
    229 
    230     def __ipow__(self, other):

/usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py in matrix_power(a, n)
    600     a = asanyarray(a)
    601     _assertRankAtLeast2(a)
--> 602     _assertNdSquareness(a)
    603 
    604     try:

/usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py in _assertNdSquareness(*arrays)
    213         m, n = a.shape[-2:]
    214         if m != n:
--> 215             raise LinAlgError('Last 2 dimensions of the array must be square')
    216 
    217 def _assertFinite(*arrays):

LinAlgError: Last 2 dimensions of the array must be square
[481]中的
:np.mat([[1,2]])**2
---------------------------------------------------------------------------
LinalError回溯(最近一次调用上次)
在()
---->1 np.mat([[1,2]])**2
/usr/local/lib/python3.6/dist-packages/numpy/matrixlib/defmatrix.py in_uuuuuupow_uuuuu(self,other)
226
227定义功率(自身、其他):
-->228返回矩阵_功率(自身、其他)
229
230 def_uuuipow_uuu(自身、其他):
/矩阵幂中的usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py(a,n)
600 a=asanyarray(a)
601资产负债表2(a)
-->602 _资产平方度(a)
603
604试试:
/usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py in_assertndsquares(*数组)
213米,n=a.形状[-2:]
214如果m!=n:
-->215 raise LinAlgError('数组的最后两个维度必须是正方形')
216
217 def_assertFinite(*数组):
LinalError:数组的最后两个维度必须是正方形
请注意,整个回溯列表
matrix\u power
。这就是为什么我们经常要求查看整个回溯

为什么要将
x
y
theta
设置为
np.mat
cost\u函数使用
matmul
。有了这个函数和它的
@
操作符,使用
np.matrix
的理由就很少了


尽管有主题行,但您没有尝试使用
pow
。这让我和至少另一位评论员感到困惑。我试图找到一个
np.pow
或一个
scipy
版本。

这可能与数据有关,请您在您的问题中添加少量数据,以便于说明。
pow(x,y)
应等同于
x**y
,如图中所示。你能发布你的错误代码吗?@Mstaino我已经编辑了这个问题,请再次检查是否有任何错误fault@Mstaino,他不使用
pow
,尽管主题行不同。起作用的是
np.power
,这对于
np.matrix
对象是不同的。