如何在 Tensorflow 训练期间将 [3751,4] 数据集密集和重塑为 [1,6] 数据集

How to dense and reshape a [3751,4] dataset to [1,6] dataset during training in Tensorflow

我正在训练一个特征形状为 [3751,4] 的模型,我想使用 Tensorflow 中内置的重塑和层密集函数使输出标签具有 [1,6] 的形状。

现在我的模型中有两个隐藏层,它们将执行以下操作:

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)
output_layer = tf.layers.dense(second_hidden_layer, 6)

所以现在我可以得到 [?,11,11,31,6] 的 output_layer 形状了。

如何进一步塑造训练节点集,使其最终可以将节点连接到形状 [1,6]?

形状 [3751, 4] 无法直接重塑为 [-1,11,11,31,4],因为 3751*4 = 15004 不能被 11*11*31*4 = 14964 整除。


在 OP

发表评论后编辑

您可以展平数据集并将其作为单个示例提供。见下文

假设 tf.shape(input_feat)==[3751, 4]:

input_layer = tf.reshape(input_feat, [1,-1])
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)
output_layer = tf.layers.dense(second_hidden_layer, 6)

原回答

由于您使用的是密集层,因此在网络开始时不重塑输入特征会很好地工作并提供类似的结果。唯一的区别是图层中的权重会移动位置,但这不会影响您的结果。

如果我们假设 tf.shape(input_feat) == [3751, 4],下面的代码片段应该可以正常工作

input_layer = tf.identity(input_feat)
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)
output_layer = tf.layers.dense(second_hidden_layer, 6)