用python编写神经网络_用Python实现神经网络(第5周)的代价函数

基于Coursera的机器学习课程,我试图用python实现神经网络的代价函数。有一个question类似于这个——有一个可接受的答案——但答案中的代码是用八度音阶编写的。为了不偷懒,我已经尝试将答案的相关概念与我的案例相适应,而且据我所知,我正在正确地实现函数。但是,我产出的成本与预期成本不同,所以我做错了什么。在

下面是一个可重复使用的小例子:

下面的链接指向一个.npz文件,可以加载该文件(如下所示)以获取相关数据。请重命名文件"arrays.npz",如果您使用它。在if __name__ == "__main__":

with np.load("arrays.npz") as data:

thrLayer = data['thrLayer'] # The final layer post activation; you

# can derive this final layer, if verification needed, using weights below

thetaO = data['thetaO'] # The weight array between layers 1 and 2

thetaT = data['thetaT'] # The weight array between layers 2 and 3

Ynew = data['Ynew'] # The output array with a 1 in position i and 0s elsewhere

#class i is the class that the data described by X[i,:] belongs to

X = data['X'] #Raw data with 1s appended to the first column

Y = data['Y'] #One dimensional column vector; entry i contains the class of entry i

import numpy as np

m = len(thrLayer)

k = thrLayer.shape[1]

cost = 0

for i in range(m):

for j in range(k):

cost += -Ynew[i,j]*np.log(thrLayer[i,j]) - (1 - Ynew[i,j])*np.log(1 - thrLayer[i,j])

print(cost)

cost /= m

'''

Regularized Cost Component

'''

regCost = 0

for i in range(len(thetaO)):

for j in range(1,len(thetaO[0])):

regCost += thetaO[i,j]**2

for i in range(len(thetaT)):

for j in range(1,len(thetaT[0])):

regCost += thetaT[i,j]**2

regCost *= lam/(2*m)

print(cost)

print(regCost)

实际上,cost应该是0.287629,cost + newCost应该是0.383770。在

这是上述问题中公布的成本函数,供参考:

WvX7X.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值