我正在编写一个机器学习代码,计算成本函数和梯度下降, 我分别编写了每个函数,如图所示:
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'
那我该怎么修呢
减号操作数是计算θ时的错误,应使用numpy.subtract(arr1,arr2) 旧代码:
新的:
在
gradiantDescent
函数中尝试以下操作:您会得到一个
nan
值,因为某些计算出错相关问题 更多 >
编程相关推荐