在本文中,我们将通过使用Python的Numpy库,从头开始构建一个简单的神经网络模型,以此来深入理解深度学习的基本原理。我们将涵盖神经网络的基础、前向传播与反向传播过程、损失函数以及梯度下降法等核心概念,并通过代码示例展示如何利用Numpy实现这些概念。最后,我们还将探讨如何保存与加载模型。
神经网络基础
神经网络是一种模拟人脑神经元工作方式的计算模型,它由多个层次的节点(神经元)组成,每个神经元接收输入、进行加权求和并经过非线性激活函数转换后输出到下一层或作为最终输出。
构建神经网络组件
首先,我们定义两个关键类:Dense
(全连接层)和Activation
(激活函数)。
-
Dense Layer (
Dense
类): 负责线性变换,包括权重初始化、前向传播及反向传播更新权重。 -
Activation Function (
Activation
类): 引入非线性,这里以Sigmoid函数为例。
前向传播
前向传播是输入数据通过网络每一层的过程,每一层的输出是下一层的输入。
反向传播
反向传播用于计算损失函数关于每个权重的梯度,进而更新权重以减小损失。
模型训练与评估
-
Model Class: 综合上述组件,定义模型结构,包含添加层、前向传播预测、训练(基于梯度下降的损失函数优化)等功能。
-
Loss Function: 采用均方误差(Mean Squared Error, MSE)作为损失函数,衡量模型预测值与真实值之间的差距。
模型持久化
- Save & Load: 实现模型参数的保存与加载功能,利用Numpy的
.npz
格式保存权重和偏置矩阵。
Mermaid流程图
示例代码解析
以下是整个神经网络模型的代码概述,包括如何构建模型、训练、预测以及模型的保存与加载。
import numpy as np
class Dense:
def __init__(self, input_units, output_units):
self.weights = np.random.randn(input_units, output_units)
self.bias = np.zeros((1, output_units))
def forward(self, inputs):
self.inputs=inputs
return np.dot(inputs, self.weights) + self.bias
def backward(self, grad_output, learning_rate):
grad_inputs = np.dot(grad_output, self.weights.T)
grad_weights = np.dot(self.inputs.T, grad_output)
grad_bias = np.sum(grad_output, axis=0, keepdims=True)
self.weights -= learning_rate * grad_weights
self.bias -= learning_rate * grad_bias
return grad_inputs
class Activation:
@staticmethod
def sigmoid(x):
return 1 / (1 + np.exp(-x))
@staticmethod
def sigmoid_derivative(x):
return x * (1 - x)
class SigmoidActivation:
def forward( x):
return 1 / (1 + np.exp(-x))
def backward( x,LR):
return x * (1 - x)
class Loss:
@staticmethod
def mse(y_true, y_pred):
return np.mean(np.square(y_true - y_pred))
@staticmethod
def mse_derivative(y_true, y_pred):
return y_pred - y_true
class Model:
def __init__(self):
self.layers = []
self.loss_function = Loss.mse
self.loss_derivative = Loss.mse_derivative
def add(self, layer):
self.layers.append(layer)
def predict(self, inputs):
for layer in self.layers:
inputs = layer.forward(inputs)
return inputs
def fit(self, X_train, y_train, epochs=100, learning_rate=0.001):
for epoch in range(epochs):
predictions = self.predict(X_train)
loss = self.loss_function(y_train, predictions)
if epoch % 10 == 0:
print(f"Epoch {epoch}, Loss: {loss}")
grad = self.loss_derivative(y_train, predictions)
for layer in reversed(self.layers):
grad = layer.backward(grad, learning_rate)
def save(self, filename):
with open(filename, 'wb') as f:
# 使用列表推导式筛选出有weights属性的层
weight_layers = [layer for layer in self.layers if hasattr(layer, 'weights')]
bias_layers = [layer for layer in self.layers if hasattr(layer, 'bias')]
# 将权重和偏置分别保存
if weight_layers and bias_layers:
np.savez(f, *[layer.weights for layer in weight_layers], *[layer.bias for layer in bias_layers])
elif weight_layers: # 如果只有权重没有偏置的情况
np.savez(f, *[layer.weights for layer in weight_layers])
else:
print("No layers with weights to save.")
@staticmethod
def load(filename):
with np.load(filename) as data:
weights = [data[f'arr_{i}'] for i in range(0, len(data), 2)]
biases = [data[f'arr_{i}'] for i in range(1, len(data), 2)]
model = Model()
for w, b in zip(weights, biases):
model.add(Dense(w.shape[0], w.shape[1]))
model.layers[-1].weights = w
model.layers[-1].bias = b
return model
# Example usage:
# Assume we have a binary classification problem with 4 features
X_train = np.random.rand(100, 4)
y_train = np.random.randint(0, 2, size=(100, 1))
model = Model()
model.add(Dense(4, 8)) # Input to hidden layer
model.add(SigmoidActivation) # Activation function
model.add(Dense(8, 1)) # Hidden to output layer
model.fit(X_train, y_train)
# Saving and loading the model
model.save('model.npz')
loaded_model = Model.load('model.npz')
# Predict using loaded model
predictions = model.predict(X_train[0])
print(predictions)
通过以上步骤,我们不仅理解了深度学习的基本原理,还实践了如何使用Numpy从零开始构建和训练一个简单的神经网络模型,以及如何保存和加载模型参数,为更复杂的机器学习任务打下了坚实的基础。