LeNet-5
LeNet-5被认为是卷积神经网络(CNN)的开山之作,主要用于手写数字识别。它包含了卷积层、池化层和全连接层,是现代CNN的雏形。
卷积
卷积神经网络(convolutional neural network)简称CNN。卷积神经网络的核心是卷积核,卷积核在图像处理领域可以用来提取图像的纵向和横向特征。
卷积核的大小一般为奇数,如3x3,5x5,7x7等,卷积核通常与图像处理(over padding)后的图像进行卷积操作,卷积核在图像上滑动,每次滑动一个像素,对应位置的像素值与卷积核对应位置的值相乘,然后求和,最后将求和的结果作为卷积核中心像素的值,这样就得到了一个新的图像。
新的图像可以用更少的数据反应出图像的特征。这个过程就是特征提取。
我们从一个6x6的矩阵开始:
我们的卷积核是一个3x3的矩阵:
我们假设卷积核位于原始矩阵的左上角,覆盖的区域如下:
此时,输出矩阵的第一个元素的计算为:
整个输出矩阵
卷积核在整个6x6矩阵上滑动(从左至右,从上至下),生成一个4x4的输出矩阵。输出矩阵的每个元素都按照上述方式计算。
点击查看卷积核动画
// 你可以尝试更改矩阵尺寸与卷积核的尺寸来感受卷积过程
function example(props) {
// 使用 XPath 查询选择输出框
const xpathSelector =
"/html/body/div/div[2]/div/div/main/div/div/div/div/article/div[2]/div[1]/div[4]";
const myElement = document.evaluate(
xpathSelector,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;
// 矩阵尺寸
const matrixSize = 6;
// 卷积核尺寸
const kernelSize = 3;
const matrix = Array.from({ length: matrixSize }, (_, i) =>
Array.from({ length: matrixSize }, (_, j) => `a${i + 1}${j + 1}`)
);
const [position, setPosition] = useState([0, 0]);
useEffect(() => {
const positions = [];
for (let i = 0; i <= matrixSize - kernelSize; i++) {
for (let j = 0; j <= matrixSize - kernelSize; j++) {
positions.push([i, j]);
}
}
let index = 0;
const interval = setInterval(() => {
setPosition(positions[index]);
index = (index + 1) % positions.length;
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', backgroundColor: '#f0f0f0' }}>
<div style={{ display: 'grid', gridTemplateColumns: `repeat(${matrixSize}, 50px)`, gridGap: '5px', position: 'relative' }}>
{matrix.map((row, i) =>
row.map((cell, j) => (
<div
key={`${i}-${j}`}
style={{
width: '50px',
height: '50px',
backgroundColor: '#fff',
border: '1px solid #ccc',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontSize: '18px',
backgroundColor: i >= position[0] && i < position[0] + kernelSize && j >= position[1] && j < position[1] + kernelSize ? 'yellow' : '#fff'
}}
>
{cell}
</div>
))
)}
</div>
</div>
);
}
最终输出矩阵为:
每个的具体计算方法如前所述,通过卷积核在原始矩阵上的滑动和计算得到。
通过这个例子,可以清晰地看到卷积核是如何对矩阵进行操作并生成输出的。
常见卷积核
-
水平边缘检测:
用途:检测水平边缘。
-
垂直边缘检测:
用途:检测垂直边缘。
-
Sobel算子(水平):
用途:检测水平边缘和梯度。
-
Sobel算子(垂直):
用途:检测垂直边缘和梯度。
-
拉普拉斯算子:
用途:检测图像的二阶导数,强调边缘。
-
锐化:
用途:提高图像的清晰度。
-
高斯模糊(3x3):
用途:平滑图像,减少噪声。
-
高斯模糊(5x5):
用途:更强的平滑效果。
-
边缘增强:
用途:增强边缘,使图像轮廓更加明显。
-
均值滤波:
用途:均匀地平滑图像。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import cv2
# 设置中文字体
# 替换为你系统中支持中文的字体路径(windows)
font_path = r'C:\Windows\Fonts\simhei.ttf'
# mac(如果有的话)
# font_path = '/System/Library/Fonts/STHeiti Light.ttc'
font_prop = FontProperties(fname=font_path)
# 读取灰度图像
image = np.array(cv2.imread('data/people.bmp',cv2.IMREAD_GRAYSCALE))
# 定义卷积核
kernels = {
'水平边缘': np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]),
'垂直边缘': np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]),
'Sobel水平': np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]),
'Sobel垂直': np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]),
'拉普拉斯': np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]),
'锐化': np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]),
'高斯模糊3x3': np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]]) / 16,
'高斯模糊5x5': np.array([[1, 4, 6, 4, 1], [4, 16, 24, 16, 4], [6, 24, 36, 24, 6], [4, 16, 24, 16, 4], [1, 4, 6, 4, 1]]) / 256,
'边缘增强': np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]),
'均值滤波': np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) / 9
}
# 使用NumPy实现卷积操作
def convolve2d(image, kernel):
# 获取图像和卷积核的尺寸
i_height, i_width = image.shape
k_height, k_width = kernel.shape
# 计算输出图像的尺寸
o_height = i_height - k_height + 1
o_width = i_width - k_width + 1
# 创建输出图像
output = np.zeros((o_height, o_width))
# 执行卷积操作
for y in range(o_height):
for x in range(o_width):
# 提取图像区域
region = image[y:y+k_height, x:x+k_width]
# 计算卷积值
output[y, x] = np.sum(region * kernel)
return output
# 应用卷积核
results = {}
for name, kernel in kernels.items():
# 为了处理边界,先对图像进行填充
if kernel.shape[0] == 5: # 对于5x5卷积核
pad_width = 2
else: # 对于3x3卷积核
pad_width = 1
padded_image = np.pad(image, pad_width, mode='constant')
filtered_image = convolve2d(padded_image, kernel)
# 归一化处理,确保像素值在有效范围内
filtered_image = np.clip(filtered_image, 0, 255).astype(np.uint8)
results[name] = filtered_image
# 显示结果
plt.figure(figsize=(15, 8))
for i, (name, result) in enumerate(results.items()):
plt.subplot(3, 4, i + 1)
plt.imshow(result, cmap='gray')
plt.title(name, fontproperties=font_prop)
plt.axis('off')
plt.tight_layout()
plt.show()
池化
池化(Pooling)是一种用于减少卷积神经网络(CNN)中特征图大小的操作。它通过将特征图上的局部区域进行聚合,得到一个更小的特征图。
池化操作类似卷积操作,使用的也是一个很小的矩阵,叫做池化核,但是池化核本身没有参数,只是通过对输入特征矩阵本身进行运算,它的大小通常是2x2、3x3、4x4等,然后将池化核在卷积得到的输出特征图中进行池化操作,需要注意的是,池化的过程中也有Padding方式以及步长的概念,与卷积不同的是,池化的步长往往等于池化核的大小。 最常见的池化操作为最大值池化(Max Pooling)和平均值池化(Average Pooling)两种。
import numpy as np
def pooling(input_array, pool_size=(2, 2), stride=None, mode='max'):
"""
池化操作函数
参数:
input_array: 输入数组,形状为[height, width]或[batch, height, width, channels]
pool_size: 池化窗口大小,默认为(2, 2)
stride: 步长,默认与pool_size相同
mode: 池化类型,'max'表示最大池化,'avg'表示平均池化
返回:
池化后的数组
"""
# 如果未指定stride,则默认与pool_size相同
if stride is None:
stride = pool_size
# 确保输入是numpy数组
input_array = np.asarray(input_array)
# 处理不同维度的输入
if input_array.ndim == 2: # 单通道2D输入
h, w = input_array.shape
d = 1
input_array = input_array.reshape(1, h, w, 1)
elif input_array.ndim == 3: # 带批次或通道的3D输入
raise ValueError("输入数组维度应为2D或4D")
elif input_array.ndim == 4: # 标准4D输入 [batch, height, width, channels]
pass
else:
raise ValueError("输入数组维度应为2D或4D")
# 获取输入尺寸
batch_size, height, width, channels = input_array.shape
# 计算输出尺寸
out_height = (height - pool_size[0]) // stride[0] + 1
out_width = (width - pool_size[1]) // stride[1] + 1
# 初始化输出数组
output = np.zeros((batch_size, out_height, out_width, channels))
# 执行池化操作
for b in range(batch_size):
for c in range(channels):
for i in range(out_height):
for j in range(out_width):
h_start = i * stride[0]
h_end = h_start + pool_size[0]
w_start = j * stride[1]
w_end = w_start + pool_size[1]
pool_region = input_array[b, h_start:h_end, w_start:w_end, c]
if mode == 'max':
output[b, i, j, c] = np.max(pool_region)
elif mode == 'avg':
output[b, i, j, c] = np.mean(pool_region)
else:
raise ValueError("支持的模式为'max'或'avg'")
# 如果输入是2D,则返回2D输出
if input_array.shape[0] == 1 and input_array.shape[3] == 1:
return output[0, :, :, 0]
return output
# 示例使用
if __name__ == "__main__":
# 创建测试数据
test_data = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
])
# 最大池化
max_pooled = pooling(test_data, pool_size=(2, 2), mode='max')
print("最大池化结果:")
print(max_pooled)
# 平均池化
avg_pooled = pooling(test_data, pool_size=(2, 2), mode='avg')
print("平均池化结果:")
print(avg_pooled)
'''
最大池化结果:
[[ 6. 8.]
[14. 16.]]
平均池化结果:
[[ 3.5 5.5]
[11.5 13.5]]
'''
- over padding(填充)
有时图像的特征在边缘上,例如
import numpy as np
import matplotlib.pyplot as plt
# 读取图像
inputs = np.array([
[255,1,2],
[255,1,2],
[255,1,2],]
)
# 用于提取纵向特征的卷积核
kernel = np.array([
[0,1,0],
[0,1,0],
[0,1,0]]
)
# 卷积操作结果,没能正确获取边缘的特征
'''
[[0. 2. 0.]
[0. 2. 0.]
[0. 2. 0.]]
'''
# 对输入图像进行填充
# array: 需要填充的数组
# pad_width: 填充的宽度(上下左右都填充)
# mode: 填充的方式,通常为'constant',
# 有0、空、最大、平均、中位等11种参数可以选,点击方法进入查看
# constant_values: 填充的值,通常为0
inputs = np.pad(
array=inputs,
pad_width=1,
mode='constant',
constant_values=0
)
# 卷积操作
out_put = np.zeros((inputs.shape[0] - kernel.shape[0] + 1, inputs.shape[1] - kernel.shape[1] + 1))
out_put_w = out_put.shape[0]
out_put_h = out_put.shape[1]
for i in range(out_put_w):
for j in range(out_put_h):
conv_result = np.sum(inputs[i:i+kernel.shape[0], j:j+kernel.shape[1]] * kernel)
out_put[i][j] = conv_result
# 卷积操作结果,正确的获取到了边缘的特征
print(out_put)
'''
[[510. 2. 4.]
[765. 3. 6.]
[510. 2. 4.]]
'''