在每次迭代中训练模型时打印输入

时间:2019-04-26 20:10:58

标签: python-3.x tensorflow keras placeholder

我想检查输入中有什么数据,或者检查某层的输出。为此,我执行以下操作:

import tensorflow.keras.backend as K
import tensorflow as tf
import numpy as np

x = [[i, i * 3 + 1] for i in range(100)]
y = [2 * i + 1 for i in range(100)]
x = np.array(x)
y = np.array(y)

print_weights = tf.keras.callbacks.LambdaCallback(
    on_batch_end=lambda batch, logs: print(K.get_value(model.layers[1].input)))


def sobaka():
    a = tf.keras.Input(shape=(2,))
    b = tf.keras.layers.Dense(1)
    c = b(a)
    model = tf.keras.models.Model(a, c)
    optimizer = tf.keras.optimizers.Adam(lr=0.1)
    model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['accuracy'])
    return model


kek = tf.placeholder(tf.float32, shape=(2,))
model = sobaka()
model.fit(x, y, batch_size=1, epochs=2, callbacks=[print_weights])

因此,每一批(一个训练样本)都将打印输入张量。但是,我遇到了一个错误:

  

您必须使用dtype输入占位符张量'input_1'的值   漂浮和形状[?,2]

请帮助我了解如何在代码中放入占位符。有没有可能的解决方案可以在每次迭代中打印信息? (例如,批次为10?)

1 个答案:

答案 0 :(得分:3)

一种选择是使用[自定义回调] [1]

像这样:

class MyCallback(tf.keras.callbacks.Callback):

    def __init__(self, patience=0):
        super(MyCallback, self).__init__()

    def on_epoch_begin(self, epoch, logs=None):
        tf.print(self.model.get_weights())

model.fit(
        x_train, 
        y_train, 
        epochs=epochs,
        batch_size=batch_size,
        callbacks=[MyCallback()],
        validation_data=(x_test, y_test),
    )
相关问题