用Numpy实现卷积和反卷积操作

import numpy as np
batch_size = 1
stride = 1
padding = "VALID"
input_channel = 1
input_size = 5
output_channel = 1
filter_size = 3
output_size = 3

input_np = np.reshape(np.arange(input_size*input_size, dtype="float32"),newshape=[input_size,input_size])
print(f"input_np = {input_np}")
print("input_up.shape = %s" % str(input_np.shape))

input_np_flattern = np.reshape(input_np, newshape=[input_size*input_size, 1])
print(f"input_np_flattern = {input_np_flattern}")
print("input_np_flattern = %s" % str(input_np_flattern.shape))

filter_np = np.reshape(np.arange(filter_size*filter_size, dtype="float32"),newshape=[filter_size,filter_size])
print(f"filter_np = {filter_np}")
print("filter_np.shape = %s" % str(filter_np.shape))

filter_np_matrix = np.zeros((output_size,output_size,input_size,input_size))
print(filter_np_matrix.shape)
# 卷积
for h in range(output_size):
    for w in range(output_size):
        start_h = h*stride
        start_w = w*stride
        end_h = start_h + filter_size
        end_w = start_w + filter_size
        filter_np_matrix[h, w, start_h:end_h, start_w:end_w] = filter_np
filter_np_matrix = np.reshape(filter_np_matrix,newshape=[output_size*output_size, input_size*input_size])
print(f"filter_np_matrix = {filter_np_matrix}")
print("filter_np_matrix.shape = %s" % str(filter_np_matrix.shape))
# 相乘
output_np = np.dot(filter_np_matrix, input_np_flattern)
output_np = np.reshape(output_np, newshape=[output_size, output_size])
print(f"output_np = {output_np}")
print("output_np.shape = %s" % str(output_np.shape))
# 反卷积
output_np_flattern = np.reshape(output_np, newshape=[output_size*output_size, 1])
output_np_transpose = np.dot(filter_np_matrix.T, output_np_flattern)
output_np_transpose = np.reshape(output_np_transpose, newshape=[input_size,input_size])
print(f"output_np_transpose = {output_np_transpose}")
print("output_np_transpose.shape = %s" % str(output_np_transpose.shape))


你可能感兴趣的:(深度学习,numpy,卷积,深度学习)