假如,我们现在手上有了 用于训练的数据 和 标签,还有一个简单的神经网络(他的权重w是随机产生的)我们可以做什么。
x是0.6 ,0.9
t是0,0,1
w是随机产生的2行3列的矩阵
损失函数是交叉熵误差 带 log的那个
我们可以求损失函数的梯度,(让损失函数沿着梯度的方向变小,就可以提高正确率了。当然这是后话)(先求一下损失函数的梯度)。
求的是损失函数在 w(网络权重)处的梯度
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)
def predict(self,x):
return np.dot(x,self.W)
def loss(self,x,t):
z = self.predict(x) #输入和权重相乘 即可得出这层网络的结果,然后激活一下
y = softmax(z)
loss = cross_entropy_error(y,t)
return loss
net = simpleNet()
print("w is :",net.W)
x = np.array([0.6,0.9])
p = net.predict(x)
print("predict is :",p)
print('max-num\'s index is :',np.argmax(p)) #找出最大值的索引
t = np.array([0,0,1]) #(看心情)给定正确解
print("the loss is :", net.loss(x,t) ) #loss函数里面还有一个predict 所以 看看算的结果和正确解之间有多大差距
def f(W):
return net.loss(x,t)
'''
f也可以写成:
f = lambda w: net.loss(x, t)
'''
#求梯度
dw = numerical_gradient(f,net.W) # 对损失函数求偏导,带入的值是 原来网络的w(权重)
print("dw is :",dw)
'''
这个函数在其他文件里写好了,课本直接调用的
def numerical_gradient(f, x):
h = 1e-4 # 0.0001
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
idx = it.multi_index
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x) # f(x+h)
x[idx] = tmp_val - h
fxh2 = f(x) # f(x-h)
grad[idx] = (fxh1 - fxh2) / (2*h)
x[idx] = tmp_val # 还原值
it.iternext()
return grad
'''