Python函数在调用时获得不同的值

时间:2019-01-19 12:46:39

标签: python function numpy

这是我的功能

def linearRegCostFunction(X,y,theta,lamda):
[m,n] = X.shape

#hypothesis
h_theta = X*theta

#CostFunction
J = 1/(2*m)*((h_theta-y).transpose())*(h_theta - y)
JReg = (lamda/(2*m)) * (theta[1:,:].transpose()) * theta[1:,:]
CostFun = J + JReg

#GradientDescent
thetaZero = theta
thetaZero[0] = 0
G = (1/m) * ((h_theta-y).transpose()) * X
JGrad = lamda/m * thetaZero.transpose()
gradientDescent = G + JGrad

return(CostFun,gradientDescent)

我这样打:linearRegCostFunction(biasX,y,theta,lamda)

然后我得到:(matrix([[303.99319222]]), matrix([[-15.30301567, 598.25074417]]))

当我尝试回忆时:

[C,G] = linearRegCostFunction(biasX,y,theta,lamda)
print('CostFunction\n',C)
print('GradientDescent\n',G)

然后我得到不同的值:

CostFunction[[319.79620789]]
GradientDescent[[-16.30301567 603.33617052]]

我认为是因为尚未在函数的第一行中将CostFunction和GradientDescent定义为零。如何在函数中定义?

1 个答案:

答案 0 :(得分:0)

由于theta似乎是一个列表,因此您在操作theta之前必须复制thetaZero。请注意,在thetaZero = theta之后,thetathetaZero引用了同一对象。这导致thetaZero[0] = 0操纵theta

thetaZero = theta.copy()
thetaZero[0] = 0

如果theta是一个numpy数组:

thetaZero = np.copy(theta)
thetaZero[0] = 0