KeyError: ‘Failed to format this callback filepath: “./saved_models/model_batch{batch}.h5“. Reason:

Environment: Win10 + tensorflow2.3.1 + python3.6 


  File "C:\Users\12575\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\keras\callbacks.py", line 1330, in _get_file_path
    file_path = self.filepath.format(epoch=epoch + 1, **logs)
KeyError: 'batch'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/WData/Development/table_direction_detection/4_directions/Derection-Classify/train.py", line 168, in <module>
    trainer.train()
  File "D:/WData/Development/table_direction_detection/4_directions/Derection-Classify/train.py", line 131, in train
    callbacks=callbacks)
  File "C:\Users\12575\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\keras\engine\training.py", line 108, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\12575\AppData\Roaming\Pytho
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你可以将最佳权重保存路径添加到代码中,如下所示: ```python import numpy as np import tensorflow as tf import os # 加载数据集 with open('poems.txt', 'r', encoding='utf-8') as f: data = f.read() # 构建词典 vocab = sorted(set(data)) char2idx = {char: idx for idx, char in enumerate(vocab)} idx2char = np.array(vocab) # 将文本数据转换为数字 text_as_int = np.array([char2idx[c] for c in data]) # 定义训练数据和标签 seq_length = 100 examples_per_epoch = len(data) // (seq_length + 1) char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int) sequences = char_dataset.batch(seq_length + 1, drop_remainder=True) def split_input_target(chunk): input_text = chunk[:-1] target_text = chunk[1:] return input_text, target_text dataset = sequences.map(split_input_target) BATCH_SIZE = 128 BUFFER_SIZE = 10000 dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True) # 构建模型 vocab_size = len(vocab) embedding_dim = 256 rnn_units = 1024 def build_model(vocab_size, embedding_dim, rnn_units, batch_size): model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, batch_input_shape=[batch_size, None]), tf.keras.layers.GRU(rnn_units, return_sequences=True, stateful=True, recurrent_initializer='glorot_uniform'), tf.keras.layers.Dense(vocab_size) ]) return model model = build_model( vocab_size=len(vocab), embedding_dim=embedding_dim, rnn_units=rnn_units, batch_size=BATCH_SIZE) # 定义损失函数 def loss(labels, logits): return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True) # 编译模型 model.compile(optimizer='adam', loss=loss) # 定义检查点 checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}") checkpoint_callback=tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_prefix, save_weights_only=True) # 定义最佳权重检查点 BEST_MODEL_PATH = './best_model.h5' best_checkpoint = tf.keras.callbacks.ModelCheckpoint(BEST_MODEL_PATH, monitor='val_loss', save_best_only=True, mode='min', save_weights_only=True) # 训练模型 EPOCHS = 50 history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback, best_checkpoint]) # 生成诗歌 def generate_text(model, start_string): num_generate = 100 input_eval = [char2idx[s] for s in start_string] input_eval = tf.expand_dims(input_eval, 0) text_generated = [] temperature = 1.0 model.reset_states() for i in range(num_generate): predictions = model(input_eval) predictions = tf.squeeze(predictions, 0) predictions = predictions / temperature predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy() input_eval = tf.expand_dims([predicted_id], 0) text_generated.append(idx2char[predicted_id]) return (start_string + ''.join(text_generated)) # 加载检查点 model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1) model.load_weights(BEST_MODEL_PATH) model.build(tf.TensorShape([1, None])) # 生成一首诗 print(generate_text(model, start_string=u"山中")) ``` 现在,模型将保存最佳的权重到文件 `best_model.h5`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值