深度学习入门基于python的理论与实现 4章gradient_simplenet.py 完全解析

# coding: utf-8
#深度学习入门基于python的理论与实现 4章gradient_simplenet.py 完全解析
import sys, os
sys.path.append(os.pardir)  # 为了导入父目录中的文件而进行的设定
import numpy as np
from common.functions import softmax, cross_entropy_error
from common.gradient import numerical_gradient

class simpleNet:
    def __init__(self):
        self.W = np.random.randn(2,3)#用高斯分布进行初始化 维度2*3

    def predict(self, x):
        return np.dot(x, self.W)#点积

    def loss(self, x, t):
        z = self.predict(x)#x点积W
        y = softmax(z)#将多个神经元的输出,映射到(0,1)区间内
        loss = cross_entropy_error(y, t)#交叉熵代价函数 y:输出结果。t:监督数据

        return loss

x = np.array([0.6, 0.9])#输入数据
t = np.array([0, 0, 1])#正确结果,监督数据

net = simpleNet()

f = lambda w: net.loss(x, t)#匿名函数输入w输出net.loss(x, t)
dW = numerical_gradient(f, net.W)#求函数梯度(f,net.W)

print(dW)
#函数:交叉熵 对权重W求偏导数即求正确解和输出参数最小值

[ 0.46320449 0.04464085 -0.50784534]
[ 0.69480673 0.06696128 -0.76176801]

猜你喜欢

转载自blog.csdn.net/weixin_33595571/article/details/83552306