import tensorflow as tf import numpy as np import tensorflow as keras from tensorflow.keras import layers,optimizers,losses #创建X矩阵,高宽各位5*5 x=tf.range(16)+1 #调整为合法的维度张量 x=tf.reshape(x,[1,4,4,1]) x=tf.cast(x,dtype=tf.float32) #创建固定内容的卷积核矩阵 w=tf.constant([[-1,2,-3],[4,-5,6],[-7,8,-9]],dtype=tf.float32) #调整为合法维度的张量 w=tf.expand_dims(w,axis=2) w=tf.expand_dims(w,axis=3) #运行普通卷积运算 out=tf.nn.conv2d(x,w,strides=1,padding='VALID') print(out) #普通卷积运算的输出作为转置卷积的输入,进行转置卷积运算 outs=tf.nn.conv2d_transpose(out,w,strides=1,padding='VALID',output_shape=[1,4,4,1]) print(outs) tf.Tensor( [[[[-56.][-61.]][[-76.][-81.]]]], shape=(1, 2, 2, 1), dtype=float32) tf.Tensor( [[[[ 56.][ -51.][ 46.][ 183.]][[-148.][ -35.][ 35.][-123.]][[ 88.][ 35.][ -35.][ 63.]][[ 532.][ -41.][ 36.][ 729.]]]], shape=(1, 4, 4, 1), dtype=float32)