2、神经网络的推理

神经网络的推理的全貌图

这里考虑输入层有2个神经元、隐藏层有4个神经元、输出层有3个神经元的情况

import numpy as np
# 激活函数
def sigmoid(x):
  return 1 / (1 + np.exp(-x))

x = np.random.randn(10, 2)  # 每个批次训练10笔数据,输入为2个神经元
W1 = np.random.randn(2, 4)  # 输入层到隐藏层的权重。维度考虑输入层有两个神经元,隐藏层有4个神经元
b1 = np.random.randn(4)     # 输入层到隐藏层的偏置。维度考虑到隐藏层有4个神经元
W2 = np.random.randn(4, 3)  # 隐藏层到输出层的权重。维度考虑到隐藏层有4个神经元,输出层有3个神经元
b2 = np.random.randn(3)     # 隐藏层到输出层的偏置。维度考虑到输出层有3个神经元

h = np.dot(x, W1) + b1  # 计算隐藏层的信号
a = sigmoid(h)          # 对流经隐藏层的信号进行非线性变换
s = np.dot(a, W2) + b2  # 计算输出层的信号
print(s)

层的类化及正向传播的实现

下面使用类来实现神经网络:

import numpy as np

# 激活层,用于非线性变换
class Sigmoid:
  def __init__(self):
    self.params = []
  def forward(self, x):
    return 1 / (1 + np.exp(-x))

# 全连接层,用于计算信号
class Affine:
  def __init__(self, W, b):
    self.params = [W, b]
  def forward(self, x):
    W, b = self.params
    out = np.dot(x, W) + b
    return out

class TwoLayerNet:
  def __init__(self, input_size, hidden_size, output_size):
    I, H, O = input_size, hidden_size, output_size
    # 初始化权重和偏置
    W1 = np.random.randn(I, H)
    b1 = np.random.randn(H)
    W2 = np.random.randn(H, O)
    b2 = np.random.randn(O)
    # 生成层
    self.layers = [
      Affine(W1, b1),
      Sigmoid(),
      Affine(W2, b2)
    ]
    # 将所有的权重整理到列表中
    self.params = []
    for layer in self.layers:
      self.params += layer.params

  def predict(self, x):
    for layer in self.layers:
      x = layer.forward(x)
    return x

x = np.random.randn(10, 2)    # 随机生成输入数据
model = TwoLayerNet(2, 4, 3)  # 实例化模型,并设置输入层有2个神经元、隐藏层有4个神经元、输出层有3个神经元
s = model.predict(x)
print(s)
posted @ 2022-07-21 23:42  tiansz  阅读(295)  评论(0编辑  收藏  举报