当调用 train_on_batch 函数时,我想在每个批次之后显示损失。
以下是我到目前为止所做的:
import tensorflow as tf
from keras.layers import *
from keras.models import Model
inputs = Input(shape=(784,), name="digits")
x1 = Dense(64, activation="relu")(inputs)
x2 = Dense(64, activation="relu")(x1)
outputs = Dense(10, name="predictions")(x2)
model = Model(inputs=inputs, outputs=outputs)
from keras.optimizers import SGD
from keras.losses import SparseCategoricalCrossentropy
import numpy as np
from keras.callbacks import Callback, CallbackList
batch_end_loss = list()
class ShowBatchLoss(tf.keras.callbacks.Callback):
def on_train_batch_end(self, batch, logs=None):
if 'loss' in logs:
batch_end_loss.append(logs['loss'])
callbacks=[]
callbacks.append(ShowBatchLoss())
clist = CallbackList(callbacks=callbacks)
optimizer = SGD(learning_rate=1e-3)
loss_fn = SparseCategoricalCrossentropy(from_logits=True)
model.compile(optimizer, loss_fn)
# Prepare the training dataset.
batch_size = 64
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = np.reshape(x_train, (-1, 784))
x_test = np.reshape(x_test, (-1, 784))
# Reserve 10,000 samples for validation.
x_val = x_train[-10000:]
y_val = y_train[-10000:]
x_train = x_train[:-10000]
y_train = y_train[:-10000]
# Prepare the training dataset.
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = train_dataset.shuffle(buffer_size=1024).batch(batch_size)
# Prepare the validation dataset.
val_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))
val_dataset = val_dataset.batch(batch_size)
clist.set_model(model)
epochs = 2
#clist.on_train_begin()
logs = {}
for epoch in range(epochs):
print("\nStart of epoch %d" % (epoch,))
# Iterate over the batches of the dataset.
for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):
model.train_on_batch(x_batch_train, y_batch_train)
clist.on_train_batch_end(step, logs)
但我得到了:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-42-4e65310120b7> in <cell line: 5>()
9 for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):
10 model.train_on_batch(x_batch_train, y_batch_train)
---> 11 clist.on_train_batch_end(step, logs)
12
/usr/local/lib/python3.10/dist-packages/keras/callbacks.py in _call_batch_end_hook(self, mode, batch, logs)
340
341 if self._check_timing and batch >= 1:
--> 342 batch_time = time.time() - self._batch_start_time
343 self._batch_times.append(batch_time)
344
TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'
我已经通过其他职位,但我找不到一个解决方案,为这种情况(iidoe.com)。当使用train_on_batch函数时)。
((I需要添加一些文本,否则我无法发布,所以在这里...))
你知道吗?
您可以使用代码here进行测试
谢谢
1条答案
按热度按时间vx6bjr1n1#
好的
我刚刚删除了clist.on_train_开始()部分,现在它可以工作了