深度学习之神经网络入门
今天心血来潮,想把之前老师讲得神经网络的ppt整理一下,感觉讲的特别清楚,让我大致明白了神经网络到底是什么
开头先讲了深度学习和机器学习的联系和区别,提到机器学习是实现人工智能的方法之一,而深度学习是实现机器学习算法的一类技术
接着介绍很多基本知识,如下:
神经网络
- 神经元
- 神经网络训练
介绍一个最简单的神经元
这个神经元,输入经历了3步运算:
1、先将三个输入乘以权重(weight):
x1 -> x1 * w1
x2 -> x2 * w2
x3 -> x3 * w3
2、把三个结果相加,再加上一个偏置(bias):
(x1 * w1) + (x2 * w2) + (x3 * w3) + b
3、最后将它们经过激活函数处理得到输出:
y = f(x1 * w1 + x2 * w2 + x3 * w3 + b)
激活函数
激活函数的作用是将无限制的输入转换成可预测形式的输出。一种常用的激活函数是sigmoid函数:
sigmoid函数的输出介于0和1,我们可以理解为它把(
−
∞
-\infty
−∞,
+
∞
+\infty
+∞)范围内的数压缩到(0,1)以内。正值越大输出越接近1,负向数值越大输出越接近0。
举个神经元的例子
权重: w = [0,1,1]
偏置: b = 4
输入: x = [2,3,4]
w * x + b = x1 * w1 + x2 * w2 + x3 * w3 + b = 0 * 2 + 1 * 3 +1 * 4 + 4 = 11
y = f(w*x+b) = f(11) = 0.999
代码实现神经元
import numpy as np
def sigmoid(x):
# Our activation function: f(x) = 1 / (1 + e^(-x))
return 1 / (1 + np.exp(-x))
class Neuron:
def __init__(self, weights, bias):
self.weights = weights
self.bias = bias
def feedforward(self, inputs): # 前馈
# Weight inputs, add bias
# then use the activation function
total = np.dot(self.weights, inputs) + self.bias
return sigmoid(total)
weights = np.array([0, 1, 1]) # w1 = 0, w2 = 1, w3 = 1
bias = 4 # b = 4
n = Neuron(weights, bias)
x = np.array([2, 3, 4]) # x1 = 2, x2 = 3, x3 = 4
print(n.feedforward(x))
神经网络
神经网络是把一堆神经元连接在一起
- 这个网络有2个输入、一个包含2个两个神经元的隐藏层(h1和h2)、包含1个神经元的输出层o1。
- 隐藏层是夹在输入层和输出层之间的部分,一个神经网络可以有多个隐藏层。
- 把神经元的输入向前传递获得输出的过程称为前馈
搭建神经网络
假设上面的网络里所有神经元都具有相同的权重w=[0,1]和偏置b=0,激活函数都是sigmoid
h1 = h2 = f(w * x + b) = f(0 * 2) + (1 * 3) + 0) = f(3) = 0.9526
o1 = f(w*[h1, h2] + b) = f((0 * h1) + (1 * h2) + 0) = f(0.9526) = 0.7216
代码实现
class OurNeuralNetword:
def __init__(self):
weights = np.array([0, 1])
bias = 0
# The Neuron class here is from the previous section
self.h1 = Neuron(weights, bias)
self.h2 = Neuron(weights, bias)
self.o1 = Neuron(weights, bias)
def feedforward(self, x):
out_h1 = self.h1.feedforward(x)
out_h2 = self.h2.feedforword(x)
# The inputs for o1 are the outputs from h1 and h2
out_o1 = self.o1.feedforward(np.array([out_h1, out_h2]))
return out_o1
network = OurNeuronNetword()
x = np.array([2, 3])
print(network.feedforward(x)) # 0.7216325609518421
训练神经网络
有一个数据集, 包含4个人的身高、体重和性别:
目标是训练一个网络,根据体重和身高来推测某人的性别。
为了简便起见,我们将每个人的身高、体重减去一个固定的数值,把性别男定义为1、性别女定义为0。
损失
在训练神经网络之前,我们需要有一个标准定义它到底好不好,以便我们进行改进,这就是损失(loss)
比如用均方误差(MSE)来定义损失:
n是样本的数量,在上面的数据集中是4;
y代表人的性别,男性是1,女性是0;
ytrue是变量的真实值,ypred是变量的预测值
损失函数
均方误差就算所有数据方差的平均值,我们不妨就把它定义为损失函数。
预测结果越好,损失就越低,训练神经网络就是将损失最小化。
MSE = 1 / 4 + (1+0+0+1) = 0.5
损失函数代码
def mse_loss(y_true, y_pred):
# y_true and y_pred are numpy arrays of the same length
return ((y_true - y_pred) ** 2).mean()
y_true = np.array([1, 0, 0, 1])
y_pred = np.array([0, 0, 0, 0])
print(mse_loss(y_true, y_pred)) # 0.5
减少神经网络损失
这个神经网络不够好,还要不断优化,尽量减少损失。
改变网络的权重和偏置可以影响预测值,问题是怎么调整权重和偏置
为了简单起见,我们把数据集缩减到只包含Alice一个人的数据。于是损失函数就剩下Alice一个人的方差
训练网络
预测值是由一系列网络权重和偏置计算出来的:
所以损失函数实际上是包含多个权重、偏置的多元函数:
链式求导法则
如果调整一下w1,损失函数是会变大还是变小?我们需要知道偏导数
∂
L
/
∂
w
1
{\partial L}/{\partial w1}
∂L/∂w1是正是负才能回答这个问题。
比如L = (1 - y_pred)^ 2, 可以求得第一项偏导数:
接下来我们要想办法获得ypred和w1的关系,我们已经知道神经元h1、h2和o1的数学运算规则:
实际上只有神经元h1中包含权重w1, 所以我们再次运行链式求导法则:
然后求
∂
h
1
/
∂
w
1
{\partial h1}/{\partial w1}
∂h1/∂w1
我们在上面的计算中遇到了2次激活函数sigmoid的导数f’(x),sigmoid函数的导数很容易求得:
总的链式求导公式:
反向传播
这种向后计算偏导数的系统称为反向传播(backpropagation)。
实际数值来计算一下。h1、h2和o1
h1 = f(x1 * w1 + x2 * w2 + b1) = f(-2 + -1 + 0) = 0.0474
h2 = f(w3 * x3 + w4 * x4 + b2) = 0.0474
o1 = f(w5 * h1 + w6 * h2 + b3) = f(0.0474 + 0.0474 + 0) = f(0.0948) = 0.524
神经网络的输出y = 0.524,没有显示出强烈的是男(1)是女(0)的证据。现在的预测效果还很不好。
调整参数
计算一下当前网络的偏导数
∂
L
/
∂
w
1
{\partial L}/{\partial w1}
∂L/∂w1:
结果表明: 如果增大w1, 损失函数L会有一个非常小的增长
随机梯度下降
随机梯度下降(SGD)的优化算法,来训练网络SGD定义了改变权重和偏置的方法:
- η {\eta} η是一个常数,称为学习率(learning rate), 它决定了我们训练网络速率的快慢。
- 将w1减去 η {\eta} η* ∂ L {\partial L} ∂L/ ∂ w 1 {\partial w1} ∂w1, 就等到了新的权重w1。
- 当 ∂ L {\partial L} ∂L/ ∂ w 1 {\partial w1} ∂w1是正数时,w1会变小
- 当 ∂ L {\partial L} ∂L/ ∂ w 1 {\partial w1} ∂w1是负数时,w1会变大
- 如果我们用这种方法去逐步改变网络的权重w和偏置b,损失函数会缓慢地降低,从而改进我们的神经网络。
训练流程如下:
- 从数据集中选择一个样本
- 计算损失函数对所有权重和偏置的偏导数
- 使用更新公式更新每个权重和偏置
- 回到第1步
代码实现
import numpy as np
def sigmoid(x):
# Sigmoid activation function: f(x) = 1 / (1 + e^(-x))
return 1 / (1 + np.exp(-x))
def deriv_sigmoid(x):
# Derivative of sigmoid: f'(x) = f(x) * (1 - f(x))
fx = sigmoid(x)
return fx * (1 - f(x))
def mse_loss(y_true, y_pred):
# y_true and y_pred are numpy arrays of the same length
return ((y_true - y_pred) ** 2).mean()
class OurNeuralNetword:
def __init__(self):
# Weights
self.w1 = np.random.normal()
self.w2 = np.random.normal()
self.w3 = np.random.normal()
self.w4 = np.random.normal()
self.w5 = np.random.normal()
self.w6 = np.random.normal()
# Biases
self.b1 = np.random.normal()
self.b2 = np.random.normal()
self.b3 = np.random.normal()
def feedforward(self, x):
# x is a numpy array with 2 elements.
h1 = sigmoid(self.w1 * x[0] + self.w2 * x[1] + self.b1)
h2 = sigmoid(self.w3 * x[0] + self.w4 * x[1] + self.b2)
o1 = sigmoid(self.w5 * x[0] + self.w6 * x[1] + self.b3)
return o1
def train(self, data, all_y_trues):
learn_rate = 0.1
epochs = 1000 # number of times to loop through the entries
for epoch in range(epochs):
for x, y_true in zip(data, all_y_trues):
# --- Do a feedforward (we'll these values later)
sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.b1
h1 = sigmoid(sum_h1)
sum_h2 = self.w3 * x[0] + self.w4 * x[1] + self.b2
h2 = sigmoid(sum_h2)
sum_o1 = self.w5 * h1 + self*w6 * h2 + self.b3
o1 = sigmoid(sum_o1)
y_pred = o1
# --- Calculate partial derivatives
# --- Naming: d_L_d_w1 represents "partial L / partial w1"
d_L_d_ypred = -2 * (y_true - y_pred)
# Neuron o1
d_ypred_d_w5 = h1 * deriv_sigmoid(sum_o1)
d_ypred_d_w6 = h2 * deriv_sigmoid(sum_o1)
d_ypred_d_b3 = deriv_sigmoid(sum_o1)
d_ypred_d_h1 = self.w5 * deriv_sigmoid(sum_o1)
d_ypred_d_h2 = self.w6 * deriv_sigmoid(sum_o1)
# Neuron h1
d_h1_d_w1 = x[0] * deriv_sigmoid(sum_h1)
d_h1_d_w2 = x[1] * deriv_sigmoid(sum_h1)
d_h1_d_b1 = deriv_sigmoid(sum_h1)
# Neuron h2
d_h2_d_w3 = x[0] * deriv_sigmoid(sum_h2)
d_h2_d_w4 = x[1] * deriv_sigmoid(sum_h2)
d_h2_d_b2 = deriv_sigmoid(sum_h2)
# --- Update weights and biases
# Neuron h1
self.w1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1
self.w2 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2
self.b1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_b1
# Neuron h2
self.w3 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h1_d_w3
self.w4 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h1_d_w4
self.b2 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h1_d_b2
# Neuron o1
self.w5 -= learn_rate * d_L_d_ypred * d_ypred_d_w5
self.w6 -= learn_rate * d_L_d_ypred * d_ypred_d_w6
self.b3 -= learn_rate * d_L_d_ypred * d_ypred_d_b3
# --- Calculate total loss at the end of each epoch
if epoch % 10 == 0:
y_preds = np.apply_along_axis(self.feedforward, 1, data)
loss = mse_loss(all_y_trues, y_preds)
print("Epoch %d loss: %.3f"% (epoch, loss))
# define dataset
data = np.array([
[-2, -1], # Alice
[25, 6], # Bob
[17, 4], # Charlie
[-15, -6] # Diana
])
all_y_trues = np.array([
1, # Alice
0, # Bob
0, # Charlie
1 # Diana
])
# Train our neural network!
network = OurNeuralNetwork()
network.train(data, all_y_trues)
随着学习过程的进行,损失函数逐渐减小
# Make some predictions
emily = np.array([-7, -3]) # 128 pounds, 63 inches
frank = np.array([20, 2]) # 155 pounds, 68 inches
print("Emily: %.3f"% network.feedforward(emily)) # 0.951 - F
print("Frank: %.3f"% network.feedforward(frank)) # 0.039 - M