【问题标题】:How do I print out input KerasTensor如何打印输入 KerasTensor
【发布时间】:2021-09-22 08:09:14
【问题描述】:

我正在使用以下代码使用我自己的自定义损失函数在 Keras 中训练一个 NN。但是,我真的不知道输入是什么(它的类型是 KerasTensor)。我怎样才能打印出它的价值?我需要访问作为网络输入的训练数据点(例如 [1,2,3,4])、其真实标签(例如 [1])及其预测标签(例如 [-1])。我怎样才能做到这一点?

    def custom_loss(input):

        def loss(y_true, y_pred):
            return ...
        return loss

    def custom_model():
        input = Input(shape=(16,))
        x = Dense(8, kernel_initializer='glorot_uniform', activation='linear')(i)
        output = Dense(1, kernel_initializer='normal', activation='linear')(x)
        model = Model(input, output)
        model.compile(loss=custom_loss(input), optimizer='adam')
        return model

还有一个小问题:为什么我们总是通过 shape=(16,) 而不是简单地通过 shape = 16 来指定层中的神经元数量?这有什么不同吗?另外,使用第一种表示法的逻辑原因是什么?

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    好的,这个问题并不完全清楚,因为我们不知道您希望什么时候打印出来。尽管如此,要在拟合期间打印一个值,您始终可以使用回调,该回调将在训练期间激活:link to doc

    class PrintingCallback(tf.keras.callbacks.Callback):
      def __init__(self, train_data):
            self.train_data_x, self.train_data_y = train_data
    
      def on_train_batch_end(self, batch, logs=None):
            for index in range(len(self.train_data_x)):
                input_value = self.train_data_x[index]
                label = self.train_data_y[index]
                predicted = self.model.predict(np.expand_dims(input_value, axis=0))
                print("input value : {}, real label : {}, predicted : {}".format(input_value, label, predicted))
    

    然后在合适的时候你给回调,

    x_train = np.zeros((150, 16))
    y_train = np.zeros((150, 1))
    ...
    
    model.fit(
        x_train,
        y_train,
        ...
        callbacks=[PrintingCallback((x_train,
        y_train))],
    )
    
    

    在拟合期间,您将打印输入值、真实标签并在每批结束时进行预测。

    请记住,您还可以使用 Tensorboard 打印这些值,然后使用编写器获取它并将标量打印到仪表板:https://www.tensorflow.org/tensorboard/scalars_and_keras

    【讨论】:

    • 感谢您的回复。我试过这个,但是我发现了以下错误:TypeError: 'int' object is not iterable
    • 是的对不起我的错我虽然批次是批次值但它只是索引,我改变了我的答案,你可能需要根据你的情况将你的数据调整到网络中,这就是我添加的原因一个 np.expand_dims
    猜你喜欢
    • 2020-09-08
    • 2020-11-05
    • 1970-01-01
    • 2018-11-09
    • 2021-12-21
    • 2019-02-02
    • 1970-01-01
    • 2019-12-24
    • 2021-12-23
    相关资源
    最近更新 更多