展平与全连接得到特征值
import numpy as np
# 1、定义输入图片:4x4的图片,0表示白色,1表示黑色
image = np.array([
[0, 0, 1, 1],
[0, 0, 1, 1],
[1, 1, 0, 0],
[1, 1, 0, 0]
])
print('输入图片: \n', image)
# 2、卷积:用2x2滤波找对角特征
filter_simple = np.array([
[1, 0],
[0, 1]
])
print('滤波器: \n', filter_simple)
# 计算卷积结果
conv_result = np.zeros((3, 3))
for i in range(3):
for j in range(3):
conv_result[i, j] = np.sum(image[i:i+2, j:j+2] * filter_simple)
print('卷积结果: \n', conv_result)
# 3、池化: 2x2最大池化,缩小特征图
pooled = np.zeros((1, 1))
pooled[0, 0] = np.max(conv_result[0:2, 0:2])
print('池化结果: \n', pooled)
# 4、展平:把矩阵变一维数组
flattened = pooled.flatten()
print('展平: ', flattened)
# 5、全连接:用权重计算得分
weights = np.array([2])
output = np.dot(flattened, weights)
print('权重:', weights)
print('输出:', output)
# 6、判断:根据得分得出结论
threshold = 3 # 阈值
if output > threshold:
print(f"结论:有对角线特征(得分:{output} > {threshold})")
else:
print(f"结论:无对角线特征(得分:{output} <= {threshold})")
输出结果:
输入图片:
[[0 0 1 1]
[0 0 1 1]
[1 1 0 0]
[1 1 0 0]]
滤波器:
[[0 1]
[1 0]]
卷积结果:
[[0. 1. 2.]
[1. 2. 1.]
[2. 1. 0.]]
池化结果:
[[2.]]
展平: [2.]
权重: [2]
输出: 4.0
结论:有对角线特征(得分:4.0 > 3)