TensorFlow训练中如何将[3751,4]数据集转为[1,6]输出格式?
解决TensorFlow输出形状调整为[1,6]的问题
嘿,我来帮你搞定这个输出形状的问题!首先得搞清楚为什么现在输出是[?,11,11,31,6]——因为tf.layers.dense默认只会对输入的最后一个维度做变换,前面的维度(比如这里的11、11、31)会原封不动保留下来,所以经过两次Dense层后,这些空间维度还在,导致输出带着一堆多余的维度。
要得到[1,6]的输出,核心是把这些多余的空间维度(11、11、31)压缩成一个维度,再连接到输出层。这里有两种常用的方法,你可以根据需求选:
方法1:使用Flatten层扁平化所有空间维度
这种方法会把除了batch维度之外的所有维度直接摊平成一维,适合需要利用所有空间特征的场景。修改后的代码如下:
import tensorflow as tf # 你的原始输入处理 input_layer = tf.reshape(features["x"], [-1, 11, 11, 31, 4]) first_hidden_layer = tf.layers.dense(input_layer, 4, activation=tf.nn.relu) second_hidden_layer = tf.layers.dense(first_hidden_layer, 5, activation=tf.nn.relu) # 新增Flatten层:把[1,11,11,31,5]摊平成[1, 11*11*31*5] = [1, 18755] flatten_layer = tf.layers.flatten(second_hidden_layer) # 连接输出层,得到[1,6]的结果 output_layer = tf.layers.dense(flatten_layer, 6)
方法2:使用全局池化层压缩空间维度
这种方法会对空间维度(11、11、31)做平均/最大池化,只保留每个通道的全局统计特征,参数更少,不容易过拟合,适合空间特征冗余的场景。修改后的代码如下:
import tensorflow as tf # 你的原始输入处理 input_layer = tf.reshape(features["x"], [-1, 11, 11, 31, 4]) first_hidden_layer = tf.layers.dense(input_layer, 4, activation=tf.nn.relu) second_hidden_layer = tf.layers.dense(first_hidden_layer, 5, activation=tf.nn.relu) # 全局平均池化3D:对11、11、31三个维度取平均,得到[1,5] global_pool_layer = tf.layers.global_average_pooling3d(second_hidden_layer, data_format='channels_last') # 连接输出层,得到[1,6]的结果 output_layer = tf.layers.dense(global_pool_layer, 6)
两种方法都能帮你得到想要的[1,6]输出形状,你可以根据自己的任务需求选择~
内容的提问来源于stack exchange,提问作者yuonger741
相关产品推荐
相关产品推荐

