在每次迭代训练模型时打印输入
Print input while training model on every iteration
我想检查输入中有什么数据,或者检查某个层的输出。为此,我执行以下操作:
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])
所以每批(一个训练样本)它都会打印输入张量。但是,我得到一个错误:
You must feed a value for placeholder tensor 'input_1' with dtype
float and shape [?,2]
请帮助我了解如何在我的代码中放置占位符。是否有任何可能的解决方案来每次迭代打印信息? (例如,当批次为 10 时?)
一种选择是使用[自定义回调][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),
)
我想检查输入中有什么数据,或者检查某个层的输出。为此,我执行以下操作:
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])
所以每批(一个训练样本)它都会打印输入张量。但是,我得到一个错误:
You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,2]
请帮助我了解如何在我的代码中放置占位符。是否有任何可能的解决方案来每次迭代打印信息? (例如,当批次为 10 时?)
一种选择是使用[自定义回调][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),
)