def trainmodelwithreplayandewc(model, traindataset, valdataset, numepochs, oldmodelpath,…
- User
def train_model_with_replay_and_ewc(model, train_dataset, val_dataset, num_epochs, old_model_path, filename, anomaly_files, replay_buffer ):
ewc = EWC(model, train_dataset) temp_filepath = f'{work_model_path}/{model_rev}_temp.weights.h5' best_val_loss = np.inf early_stopping_callback = callbacks.EarlyStopping( monitor='val_loss', patience=10, restore_best_weights=True, verbose=1, min_delta=0.0001, ) lr_scheduler = callbacks.LearningRateScheduler(scheduler, verbose=1) for epoch in tqdm(range(num_epochs)): total_epoch_loss = 0.0 epoch_batch_count = 0 for x_batch, y_batch in train_dataset: with tf.GradientTape() as tape: preds = model(x_batch, training=True) loss = model.compiled_loss(y_batch, preds) loss += ewc.penalty() gradients = tape.gradient(loss, model.trainable_variables) model.optimizer.apply_gradients(zip(gradients, model.trainable_variables)) total_epoch_loss += loss.numpy() epoch_batch_count += 1 if filename in anomaly_files: replay_buffer.add((x_batch, y_batch)) for replay_data in replay_buffer.get_data(): x_replay, y_replay = replay_data with tf.GradientTape() as tape: preds_replay = model(x_replay, training=True) loss_replay = model.compiled_loss(y_replay, preds_replay) loss_replay += ewc.penalty() gradients_replay = tape.gradient(loss_replay, model.trainable_variables) model.optimizer.apply_gradients(zip(gradients_replay, model.trainable_variables)) avg_epoch_loss = total_epoch_loss / epoch_batch_count val_loss = model.evaluate(val_dataset, verbose=0) logging.info(f"Epoch {epoch + 1}, Train Loss: {avg_epoch_loss}, Val Loss: {val_loss}") if val_loss < best_val_loss: best_val_loss = val_loss model.save_weights(temp_filepath) early_stopping_callback.on_epoch_end(epoch, logs={'val_loss': val_loss}) lr_scheduler.on_epoch_end(epoch, logs={'val_loss': val_loss}) if early_stopping_callback.stopped_epoch > 0: logging.info("Сработали условия ранней остановы") try: model.save_weights(old_model_path) except Exception as e: logging.error(f'Ошибка при сохранении весов новой модели после обучения: {e}') break model.save_weights(old_model_path)AttributeError Traceback (most recent call last) Cell In[28], line 61 58 logging.error("Не найдена лучшая модель в директории") 60 logging.info(f'Старт обучения модели на датафрейме в папке {work_signals_path} с файлом {filename}') ---> 61 train_model_with_replay_and_ewc(old_model, 62 train_dataset, 63 val_dataset, 64 num_epochs, 65 best_model_path, 66 filename, 67 anomaly_files, 68 replay_buffer 69 ) 70 logging.info(f'Закончено обучения модели на датафрейме в папке {work_signals_path} с файлом № {filename}') 72 trainable_df_counter += 1
- Assistant
- User
AttributeError Traceback (most recent call last) Cell In[30], line 61 58 logging.error("Не найдена лучшая модель в директории") 60 logging.info(f'Старт обучения модели на датафрейме в папке {work_signals_path} с файлом {filename}') ---> 61 train_model_with_replay_and_ewc(old_model, 62 train_dataset, 63 val_dataset, 64 num_epochs, 65 best_model_path, 66 filename, 67 anomaly_files, 68 replay_buffer 69 ) 70 logging.info(f'Закончено обучения модели на датафрейме в папке {work_signals_path} с файлом № {filename}') 72 trainable_df_counter += 1
Cell In[29], line 68, in train_model_with_replay_and_ewc(model, train_dataset, val_dataset, num_epochs, old_model_path, filename, anomaly_files, replay_buffer) 65 best_val_loss = val_loss 66 model.save_weights(temp_filepath) ---> 68 early_stopping_callback.on_epoch_end(epoch, logs={'val_loss': val_loss}) 69 lr_scheduler.on_epoch_end(epoch, logs={'val_loss': val_loss}) 71 if early_stopping_callback.stopped_epoch > 0:
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.