基于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。在
这是上述问题中公布的成本函数,供参考: