Skip to main content
 首页 » 编程设计

python之tf.layers.Dense 之后张量的形状

2024年09月07日9mate10pro

我正在制作一个解决回归问题的 DNN。

首先我加载了一个预训练的 VGG16 网络,然后我制作了几个完全连接的隐藏层。最后一层有一个输出标量的节点。

我认为输出的形状应该类似于 [batch_size] 或 [batch_size, 1]。

但是当我调用...

... 
 
fc5 = tf.layers.dense(inputs=fc4, units=1) 
 
print(tf.shape(fc5)) 
print(fc5.get_shape()) 

...我得到:

> Tensor("Shape:0", shape=(4,), dtype=int32)

> (?, ?, ?, 1)

有人可以解释一下吗?为什么形状具有前三个维度,tf.layers.dense 不应该将其设为标量或标量列表?


编辑:

vgg_layer7_out 形状:

> Tensor("Shape:0", shape=(4,), dtype=int32)

> (?, ?, ?, 4096)

fc1 形状:

> Tensor("Shape:0", shape=(4,), dtype=int32)

> (?, ?, ?, 1024)

...

fc4 形状:

> Tensor("Shape:0", shape=(4,), dtype=int32)

> (?, ?, ?, 10)


fc层代码:

fc1 = tf.layers.dense(inputs=vgg_layer7_out, units=1024, activation=tf.nn.elu, bias_initializer=init, kernel_initializer=init, kernel_regularizer=reg, bias_regularizer=reg) 
 
drop1 = tf.nn.dropout(fc1, keep_prob) 
 
fc2 = tf.contrib.layers.fully_connected(drop1, 128, activation_fn=tf.nn.elu, weights_initializer=init, weights_regularizer=reg) 
 
drop2 = tf.nn.dropout(fc2, keep_prob) 
 
fc3 = tf.contrib.layers.fully_connected(drop2, 50, activation_fn=tf.nn.elu, weights_initializer=init, weights_regularizer=reg) 
 
drop3 = tf.nn.dropout(fc3, keep_prob) 
 
fc4 = tf.contrib.layers.fully_connected(drop3, 10, activation_fn=tf.nn.elu, weights_initializer=init, weights_regularizer=reg) 
 
drop2 = tf.nn.dropout(fc4, keep_prob) 
 
fc5 = tf.layers.dense(inputs=drop2, units=1, activation=None) 

请您参考如下方法:

正如 Dimitiry 所说,我忘了将其展平...您也可以在调用 loss func laster 之前使用 tf.squeeze 函数。