实现成本函数+激活函数-返回的值不正确

时间:2018-10-05 23:48:26

标签: python numpy machine-learning logistic-regression activation-function

我正在通过机器学习教程进行工作,我陷入了逻辑回归的一部分,该部分需要计算激活值并将其提供给成本函数。

我被困住了,因为代码不再返回错误,并且据我所知,我编写的代码与类似文章中的代码几乎相同(请参见下文),但输出不正确。

这是我的代码:

#define a sigmoid function
def sigmoid(z):
     a = 1/(1+np.exp(-z))
     return a

    #define an empty array w, and integer b
def init_zeros(dim):
     w = np.zeros((dim,1))
     b = 0
     return w, b

   #define a function to perform forward and backwards passes of logistic regression

def forward_backward(X, Y, w, b):

    m = X.shape[1]
    A=sigmoid(np.dot(w.T,X)+b)
    cost =-1/m * np.sum(Y * np.log(A) + (1-Y) * (np.log(1-A)))

    dZ = A-Y
    dw = 1/m*np.dot(X,dZ.T)
    db = (1/m)*np.sum(dZ)

    cost = np.squeeze(cost)

    grads = {'dw': dw, 'db': db}

    return grads, cost

   #here is the data to be used for testing the results of the forward_backward function
X = np.array([[1,2,-3,0],[0.5,6,-5,0]])
Y = np.array([[1,0,1,0]])
w = np.array([[1],[2]])
b = 0
grads, cost = forward_backward(X, Y, w, b)

print('dw = {}'.format(grads['dw']))
print('db = {}'.format(grads['db']))
print('cost = {}'.format(cost))

输出应为: dw = [[1.22019716] [2.73509556]]

db = 0.09519962669353813

成本= 6.9550195708335805

但是我得到:

dw = [[0.]  [0。]]

db = 0.0

成本= 27.8200782833

很抱歉提出一个与以前的问题非常相似的问题,但我真的很困惑。 这是我用来生成上述代码的类似文章的链接-

https://datascience.stackexchange.com/questions/22470/python-implementation-of-cost-function-in-logistic-regression-why-dot-multiplic

Logisitic Regression Cost Function

Implementing sigmoid function in python

0 个答案:

没有答案