当我在另一个函数循环中调用Python函数时,它的行为不同

2024-06-28 19:49:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个机器学习代码,计算成本函数和梯度下降, 我分别编写了每个函数,如图所示:

def costFunction(theta, X, y):
    
    m = y.size

    J = (1/m) * ( np.dot(-y,np.log(sigmoid(np.dot(X,theta))))  -  np.dot((1-y),(np.log(1-sigmoid(np.dot(X,theta))))) ) 
    
    return J
def gradiantDescent(alpha , theta , X , y , num_itr):

    m = y.shape[0]
    J_history = []
    theta = theta.copy()

    for _ in range(num_itr):
        
        tempZero = theta[0]

        theta -= (alpha/m) * (np.dot(X.T , (sigmoid(np.dot(X,theta))-y)))
        theta[0] = tempZero -  ( (alpha/m) * np.sum((sigmoid(np.dot(X,theta))-y)))

        J_history.append(costFunction(theta, X, y))

    return theta , J_history

当我单独调用“成本函数”时,它的工作原理与我预期的一样:

intial_theta = np.zeros(X.shape[1])

J = costFunction(intial_theta, X, y):

print(J) # works as expected

但当我在梯度下降函数中调用它时,所有J_历史都将是'nan'值:

theta , Jvec = gradiantDescent(0.05, intial_theta , X , y , 500)

print(Jvec) #all values are 'nan'

那我该怎么修呢


Tags: 函数alphalogreturndefnphistorynum
2条回答

减号操作数是计算θ时的错误,应使用numpy.subtract(arr1,arr2) 旧代码:

theta -= (alpha/m) * (np.dot(X.T , (sigmoid(np.dot(X,theta))-y)))

新的:

np.subtract( theta ,(alpha/m) * (np.dot(X.T , (sigmoid(np.dot(X,theta))-y))) )

gradiantDescent函数中尝试以下操作:

for _ in range(num_itr):
    theta = theta - (alpha / m) * np.dot(X.T, (np.dot(X, theta) - y))
    J_history.append(costFunction(theta, X, y))
return theta, J_history

您会得到一个nan值,因为某些计算出错

相关问题 更多 >