梯度下降法
抽取一個(gè)公共函數(shù)模塊: common_functions.py
import numpy as np
def sigmoid(x):
return 1/(1 + np.exp(-x))
def softmax(a):
c = np.max(a) # 為了方式溢出亚再,取信號(hào)的最大值
exp_a = np.exp(a - c)
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y
def cross_entropy_error(y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
batch_size2 = y.shape[0]
return -np.sum(t * np.log(y + 1e-7)) / batch_size2
def numeric_diff(f, x):
h = 1e-4 # 0.0001
return (f(x + h) - f(x - h)) / 2 * h
def numeric_gradient(f, x):
h = 1e-4 # 0.0001
grad = np.zeros_like(x) # 生成 和x形狀相同的數(shù)組
for idx in range(x.size):
tmp_val = x[idx]
# 計(jì)算f(x+h)
x[idx] = tmp_val + h
fxh1 = f(x)
# 計(jì)算f(x-h)
x[idx] = tmp_val - h
fxh2 = f(x)
grad[idx] = (fxh1 - fxh2) / (2 * h)
x[idx] = tmp_val # 還原值
return grad
def gradient_descent(f, init_x, lr=0.01, step_num=100):
x = init_x
for i in range(step_num):
grad = numeric_gradient(f, x)
x -= lr * grad
return x
使用梯度法求函數(shù)最小值
from common_functions import gradient_descent
def function_2(x):
return x[0] ** 2 + x[1] ** 2
init_x = np.array([-3.0, 4.0])
print(gradient_descent(function_2, init_x = init_x, lr = 0.1)) # [-6.11110793e-10 8.14814391e-10]
神經(jīng)網(wǎng)絡(luò)的梯度
這里的梯度是說(shuō): 損失函數(shù)關(guān)于權(quán)重參數(shù)的梯度
例如:損失函數(shù)用L表示帚湘,權(quán)重參數(shù)用 W 表示
定義一個(gè)類(lèi),實(shí)現(xiàn)求梯度
import numpy as np
from common_functions import softmax, cross_entropy_error, numeric_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
測(cè)試代碼
import sys, os
import numpy as np
from simpleNet import simpleNet # 導(dǎo)入類(lèi)
from common_functions import cross_entropy_error, gradient_descent, numeric_gradient
net = simpleNet()
# print(net) # <simpleNet.simpleNet object at 0x000001B917A2D940>
print(net.W)
# [[-0.35629671 0.13281832 -0.30492983]
# [ 0.4057684 -0.61784676 2.64085429]]
x = np.array([0.6, 0.9])
p = net.predict(x)
print(p) # [-0.7061077 1.25578435 -1.02561033]
print(np.argmax(p)) # 2
t = np.array([0, 0, 1])
print(net.loss(x, t)) # 0.3955737658935095
f = lambda w: net.loss(x, t)
print(f) # <function <lambda> at 0x000001B9194D3280>
dW = numeric_gradient(f, net.W)
print(dW)
神經(jīng)網(wǎng)絡(luò)的學(xué)習(xí)步驟
- 從訓(xùn)練數(shù)據(jù)中隨機(jī)選出來(lái)一部分?jǐn)?shù)據(jù)先舷,稱(chēng)之為mini-batch, 目標(biāo)是減小mini-batch的損失函數(shù)的值
- 為了減小mini-batch的損失函數(shù)的值蕊苗,需要求出來(lái)各個(gè)權(quán)重參數(shù)的梯度察署,梯度表示損失函數(shù)的值減小最多的方向
- 將權(quán)重參數(shù)沿梯度方向進(jìn)行微小更新
- 重復(fù)步驟1期升,2,3
2層神經(jīng)網(wǎng)絡(luò)的類(lèi) ()
import sys, os
import numpy as np
from common_functions import sigmoid, softmax, cross_entropy_error, numeric_gradient
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
# 初始化值
self.param = {}
self.param['W1'] = weight_init_std / np.random.randn(input_size, hidden_size)
self.param['b1'] = np.zeros(hidden_size)
self.param['W2'] = weight_init_std / np.random.randn(hidden_size, output_size)
self.param['b2'] = np.zeros(output_size)
def predict(self, x):
W1, W2 = self.param("W1"), self.param("W2")
b1, b2 = self.param("b1"), self.param("b2")
a1 = np.dot(x, W1) + b1
z1 = sigmoid(a1)
a2 = np.dot(z1, W2) + b2
y = softmax(a2)
return y
## x: 輸入數(shù)據(jù) t: 監(jiān)督數(shù)據(jù)
def loss(self, x, t):
y = predict(self, x)
return cross_entropy_error(y, t)
def accuracy(self, x, t):
y = predict(self, x)
y = np.argmax(y, axis=1)
t = np.argmax(t, axis=1)
accuracy = np.sum(y == t) / float(x.shape[0])
return accuracy
## x: 輸入數(shù)據(jù) t: 監(jiān)督數(shù)據(jù)
def numerical_gradient(self, x, t):
loss_W = lambda W: self.loss(x, t)
grads = {}
grads['W1'] = numeric_gradient(loss_W, self.param('W1'))
grads['b1'] = numeric_gradient(loss_W, self.param('b1'))
grads['W2'] = numeric_gradient(loss_W, self.param('W2'))
grads['b2'] = numeric_gradient(loss_W, self.param('b2'))
return grads
mini-batch的實(shí)現(xiàn)
import sys, os
print(os.getcwd())
sys.path.append(os.getcwd())
from mnist import load_mnist
import numpy as np
from two_layer_net import TwoLayerNet # 導(dǎo)入類(lèi)
from common_functions import cross_entropy_error, gradient_descent, numeric_gradient
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=False, one_hot_label=True)
train_loss_list = []
# 超參數(shù)
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
for i in range(iters_num):
#獲取mini-batch的數(shù)據(jù)
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_size]
t_batch = t_train[batch_size]
#計(jì)算梯度
grad = network.numerical_gradient(x_batch, t_batch)
#更新參數(shù)
for key in ['W1', 'b1', 'W2', 'b2']:
network.param[key] -= learning_rate * grad[key]
#記錄學(xué)習(xí)過(guò)程
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
print(train_loss_list)