由于Python操作而使TensorBoard图变得稀疏

问题描述 投票:0回答:1

此问题与TensorFlow(和TensorBoard)的2.2rc3版本有关,但是我在2.1中也遇到了同样的问题。

考虑以下奇怪的代码:

from datetime import datetime

import tensorflow as tf
from tensorflow import keras

inputs = keras.layers.Input(shape=(784, ))    

x1 = keras.layers.Dense(32, activation='relu', name='Model/Block1/relu')(inputs)
x1 = keras.layers.Dropout(0.2, name='Model/Block1/dropout')(x1)
x1 = keras.layers.Dense(10, activation='softmax', name='Model/Block1/softmax')(x1)

x2 = keras.layers.Dense(32, activation='relu', name='Model/Block2/relu')(inputs)
x2 = keras.layers.Dropout(0.2, name='Model/Block2/dropout')(x2)
x2 = keras.layers.Dense(10, activation='softmax', name='Model/Block2/softmax')(x2)

x3 = keras.layers.Dense(32, activation='relu', name='Model/Block3/relu')(inputs)
x3 = keras.layers.Dropout(0.2, name='Model/Block3/dropout')(x3)
x3 = keras.layers.Dense(10, activation='softmax', name='Model/Block3/softmax')(x3)

x4 = keras.layers.Dense(32, activation='relu', name='Model/Block4/relu')(inputs)
x4 = keras.layers.Dropout(0.2, name='Model/Block4/dropout')(x4)
x4 = keras.layers.Dense(10, activation='softmax', name='Model/Block4/softmax')(x4)

outputs = x1 + x2 + x3 + x4

model = tf.keras.Model(inputs=inputs, outputs=outputs)
model.summary()

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') / 255
x_test = x_test.reshape(10000, 784).astype('float32') / 255

model.compile(loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              optimizer=keras.optimizers.RMSprop(),
              metrics=['accuracy'])

logdir = "logs/" + datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)
model.fit(x_train, y_train,
          batch_size=64,
          epochs=5,
          validation_split=0.2,
          callbacks=[tensorboard_callback])

[运行它并查看在TensorBoard中创建的图形时you will see the following

可以看出,加法运算确实很丑。

更换线时

outputs = x1 + x2 + x3 + x4

与行:

outputs = keras.layers.add([x1, x2], name='Model/add/add1')
outputs = keras.layers.add([outputs, x3], name='Model/add/add2')
outputs = keras.layers.add([outputs, x4], name='Model/add/add3')

[a much nicer graph is created by TensorBoard(在第二个屏幕截图中,详细显示了模型以及内部模块之一)。

模型的两种表示形式之间的区别在于,在第二种表示形式中,我们可以命名加法运算并将其分组。

除非使用keras.layers.add(),否则我找不到任何方法来命名这些操作。在此模型中,该问题看起来并不那么关键,因为该模型很简单,并且很容易用+替换keras.layers.add()。但是,在更复杂的模型中,这可能会成为真正的痛苦。例如,诸如t[:, start:end]之类的操作应转换为对tf.strided_slice()的复杂调用。因此,我的模型表示非常混乱,包含大量神秘的收集,跨步和合并操作。

我想知道是否有一种方法可以将这样的操作包装/分组以允许TensorBoard中更好的图。

keras tensorboard tensorflow2.x
1个回答
0
投票

[outputs = keras.layers.Add()([x1, x2, x3, x4])有效吗?

© www.soinside.com 2019 - 2024. All rights reserved.