神经网络|神经网络原来这么简单,机器学习入门贴送给你( 二 )


本文插图

我们仍以上个示例的条件为例 。
神经网络|神经网络原来这么简单,机器学习入门贴送给你
本文插图

一个神经网络可以包含任意数量的层和任意数量的神经元 。
以Python代码示例如下:
import numpy as np
# ... code from previous section here
class OurNeuralNetwork:
'''
A neural network with:
- 2 inputs
- a hidden layer with 2 neurons (h1, h2)
- an output layer with 1 neuron (o1)
Each neuron has the same weights and bias:
- w = [0, 1]
- b = 0
'''
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.feedforward(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 = OurNeuralNetwork()
x = np.array([2, 3])
print(network.feedforward(x)) # 0.7216325609518421
训练神经网路——计算损失函数
假设 , 我们正在处理以下这个项目 。 通过人员的体重和身高来判断性别 。
神经网络|神经网络原来这么简单,机器学习入门贴送给你
本文插图

以weight、height作为输入 , 以gender作为输出 。
神经网络|神经网络原来这么简单,机器学习入门贴送给你
本文插图

将Male设置为0 , Female设置为1 , 还对其余数据进行了简化 。
神经网络|神经网络原来这么简单,机器学习入门贴送给你
本文插图

在训练神经网络之前 , 首先需要一个方法来量化它做得有多“好” , 是否能够做得“更好” , 那就是损失函数(loss) 。
这里 , 我们将使用损失函数的一种——均方误差来计算 。
神经网络|神经网络原来这么简单,机器学习入门贴送给你
本文插图

预测结果越好 , 说明损失也就会越低 。 而训练神经网络的目的 , 就在于尽可能的减少损失 。
如果我们确信所有的人都是Male , 也就是说预测值为0 , 会出现什么样的结果?
神经网络|神经网络原来这么简单,机器学习入门贴送给你
本文插图

Python示例:
import numpy as np
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 。
那么 , 它的损失函数就是这样 。
神经网络|神经网络原来这么简单,机器学习入门贴送给你
本文插图


推荐阅读