я добавил в функцию train аргумент pattern_slices_path. добавь ввод данных для него по аналогии с output_path
мой код:
import os
import clearml
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout,
QLabel, QPushButton, QFormLayout, QLineEdit, QComboBox, QListWidget,
QMessageBox, QSpinBox, QDoubleSpinBox, QFileDialog, QScrollArea,
QListWidgetItem
from PySide6.QtCore import Qt
import sys
if os.path.realpath('.') not in sys.path:
sys.path.append(os.path.realpath('.'))
from qt_app.utils import get_wells_names
from src.train import train
WAVELET_TRAINING_OPTIONS = {
'импульс Рикера с фиксированными параметрами': 'ricker_fix',
'импульс Рикера с обучением параметров': 'ricker_train',
'обучение произвольного импульса': 'random_train'
}
class TrainApp(QWidget):
def init(self):
super().init()
self.setWindowTitle('Обучение модели предсказания импеданса')
layout = QVBoxLayout()
# Create scroll area
scroll_area = QScrollArea()
scroll_area.setWidgetResizable(True)
# Create a widget to hold the form content
scroll_widget = QWidget()
scroll_layout = QVBoxLayout(scroll_widget)
form_layout = QFormLayout()
self.x_data_path_line_edit = QLineEdit()
self.y_data_path_line_edit = QLineEdit()
self.wells_data_path_line_edit = QLineEdit()
self.val_wellnames_list_widget = QListWidget()
self.train_wellnames_list_widget = QListWidget()
self.val_wellnames_list_widget.setSelectionMode(QListWidget.NoSelection)
self.train_wellnames_list_widget.setSelectionMode(QListWidget.NoSelection)
# Подключаем обработчики изменений чекбоксов
self.val_wellnames_list_widget.itemChanged.connect(self.on_val_item_changed)
self.train_wellnames_list_widget.itemChanged.connect(self.on_train_item_changed)
self._updating_well_checkboxes = False # Флаг для предотвращения рекурсивных вызовов
self.save_path_line_edit = QLineEdit()
self.n_epochs_spin_box = QSpinBox(value=50)
self.patch_size_spin_box = QSpinBox(value=128)
self.batch_size_spin_box = QSpinBox(value=32)
self.os_size_spin_box = QSpinBox(value=64)
self.val_size_spin_box = QSpinBox(value=100)
self.learning_rate_double_spin_box = QDoubleSpinBox(value=1e-4, decimals=6)
self.global_loss_coef_double_spin_box = QDoubleSpinBox(value=0.05, decimals=6)
self.train_wavelet_mode_combo_box = QComboBox()
self.train_wavelet_mode_combo_box.addItems(WAVELET_TRAINING_OPTIONS.keys())
self.wavelet_freq_double_spin_box = QDoubleSpinBox(value=10)
self.wavelet_length_double_spin_box = QDoubleSpinBox(value=0.128, decimals=6)
self.wavelet_dt_double_spin_box = QDoubleSpinBox(value=0.004, decimals=6)
self.max_n_wells_on_plot_spin_box = QSpinBox(value=0)
self.training_axes_combo_box = QComboBox()
self.training_axes_combo_box.addItems(['0', '1'])
self.clearml_project_name_line_edit = QLineEdit()
form_layout.addRow('Имя файла датасете (x_data):', self.x_data_path_line_edit)
select_x_data_file_button = QPushButton('Выбрать файл x_data')
select_x_data_file_button.clicked.connect(lambda: self.select_file(self.x_data_path_line_edit, ext_filter="*.npy"))
form_layout.addRow(select_x_data_file_button)
form_layout.addRow(QLabel('Имя файла импеданса (y_data)'), self.y_data_path_line_edit)
select_y_data_file_button = QPushButton('Выбрать файл y_data')
select_y_data_file_button.clicked.connect(lambda: self.select_file(self.y_data_path_line_edit, ext_filter="*.npy"))
form_layout.addRow(select_y_data_file_button)
form_layout.addRow(QLabel('Имя файла скважин (wells_data)'), self.wells_data_path_line_edit)
select_wells_data_file_button = QPushButton('Выбрать файл скважин (wells_data)')
select_wells_data_file_button.clicked.connect(self.select_wells_data_and_load_names)
form_layout.addRow(select_wells_data_file_button)
form_layout.addRow('Валидационные скважины:', self.val_wellnames_list_widget)
form_layout.addRow('Обучающие скважины:', self.train_wellnames_list_widget)
form_layout.addRow(QLabel('Путь для сохранения весов модели'), self.save_path_line_edit)
select_save_path_button = QPushButton('Выбрать путь для сохранения')
select_save_path_button.clicked.connect(lambda: self.select_directory(self.save_path_line_edit))
form_layout.addRow(select_save_path_button)
form_layout.addRow('Количество эпох обучения', self.n_epochs_spin_box)
form_layout.addRow('patch_size', self.patch_size_spin_box)
form_layout.addRow('batch_size', self.batch_size_spin_box)
form_layout.addRow('os_size', self.os_size_spin_box)
form_layout.addRow('val_size', self.val_size_spin_box)
form_layout.addRow(QLabel('learning_rate'), self.learning_rate_double_spin_box)
form_layout.addRow('global_loss_coef', self.global_loss_coef_double_spin_box)
form_layout.addRow(QLabel('Режим обучения импульса'), self.train_wavelet_mode_combo_box)
form_layout.addRow('wavelet_freq', self.wavelet_freq_double_spin_box)
form_layout.addRow('wavelet_length', self.wavelet_length_double_spin_box)
form_layout.addRow('wavelet_dt', self.wavelet_dt_double_spin_box)
form_layout.addRow(QLabel('Максимальное количество скважин на рисунке'), self.max_n_wells_on_plot_spin_box)
form_layout.addRow(QLabel('Выбрать ось куба для обучения'), self.training_axes_combo_box)
form_layout.addRow('Имя проекта для сохранения в ClearML', self.clearml_project_name_line_edit)
# Add form layout to scroll widget
scroll_layout.addLayout(form_layout)
# Set the scroll widget as the widget for scroll area
scroll_area.setWidget(scroll_widget)
# Add scroll area to main layout
layout.addWidget(scroll_area)
# layout.addLayout(form_layout)
run_button = QPushButton('Начать обучение')
run_button.clicked.connect(self.start_training)
layout.addWidget(run_button)
self.setLayout(layout)
def select_file(self, widget, ext_filter="*"):
file_path, _ = QFileDialog.getOpenFileName(self, "Выбрать файл", "", ext_filter)
if file_path:
widget.setText(file_path)
def select_directory(self, widget):
directory_path = QFileDialog.getExistingDirectory(self, 'Выбрать директорию')
if directory_path:
widget.setText(directory_path)
def select_wells_data_and_load_names(self):
"""
Выбирает файл wells_data и загружает имена скважин в списки
"""
file_path, _ = QFileDialog.getOpenFileName(self, "Выбрать файл скважин", "", "*.pickle")
if file_path:
# Установить путь к файлу
self.wells_data_path_line_edit.setText(file_path)
try:
# Получить имена скважин
well_names = get_wells_names(file_path)
self._updating_well_checkboxes = True
# Очистить существующие списки
self.val_wellnames_list_widget.clear()
self.train_wellnames_list_widget.clear()
# Добавляем скважины в список валидации с чекбоксами
for name in well_names:
item = QListWidgetItem(name)
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Unchecked) # По умолчанию не выбрано
self.val_wellnames_list_widget.addItem(item)
# Добавляем скважины в список обучения с чекбоксами
for name in well_names:
item = QListWidgetItem(name)
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Checked) # По умолчанию выбрано
self.train_wellnames_list_widget.addItem(item)
self._updating_well_checkboxes = False
except Exception as e:
QMessageBox.warning(self, "Ошибка", f"Не удалось загрузить имена скважин: {str(e)}")
def on_train_item_changed(self, item):
if self._updating_well_checkboxes:
return
if item.checkState() == Qt.Checked:
self._updating_well_checkboxes = True
for i in range(self.val_wellnames_list_widget.count()):
val_item = self.val_wellnames_list_widget.item(i)
if val_item.text() == item.text():
val_item.setCheckState(Qt.Unchecked)
break
self._updating_well_checkboxes = False
def on_val_item_changed(self, item):
if self._updating_well_checkboxes:
return
if item.checkState() == Qt.Checked:
self._updating_well_checkboxes = True
for i in range(self.train_wellnames_list_widget.count()):
train_item = self.train_wellnames_list_widget.item(i)
if train_item.text() == item.text():
train_item.setCheckState(Qt.Unchecked)
break
self._updating_well_checkboxes = False
def start_training(self):
# Получаем выбранные валидационные скважины
val_wells = []
for i in range(self.val_wellnames_list_widget.count()):
item = self.val_wellnames_list_widget.item(i)
if item.checkState() == Qt.Checked:
val_wells.append(item.text())
# Получаем выбранные обучающие скважины
train_wells = []
for i in range(self.train_wellnames_list_widget.count()):
item = self.train_wellnames_list_widget.item(i)
if item.checkState() == Qt.Checked:
train_wells.append(item.text())
if not val_wells:
QMessageBox.warning(self, 'Ошибка', 'Не выбраны скважины для валидации!')
return
if not train_wells:
QMessageBox.warning(self, 'Ошибка', 'Не выбраны скважины для обучения!')
return
save_path = os.path.abspath(self.save_path_line_edit.text())
if not os.path.exists(save_path):
os.makedirs(save_path)
clearml_project_name = self.clearml_project_name_line_edit.text()
if clearml_project_name:
clearml.Task.ignore_requirements('pywin32')
clearml_task = clearml.Task.init(
project_name='wells/' + clearml_project_name,
auto_connect_frameworks={'matplotlib': False},
)
print('log_page: {}'.format(clearml_task.get_output_log_web_page()))
clearml_task.set_resource_monitor_iteration_timeout()
clearml_task.execute_remotely(queue_name='test_queue')
else:
clearml_task = None
print('global_loss_coef_double_spin_box.value:', self.global_loss_coef_double_spin_box.value())
train(
n_epochs=int(self.n_epochs_spin_box.text()),
x_data_path=self.x_data_path_line_edit.text(),
y_data_path=self.y_data_path_line_edit.text(),
wells_labels_path=self.wells_data_path_line_edit.text(),
train_wells=train_wells,
val_wells=val_wells,
output_path=save_path,
batch_size=int(self.batch_size_spin_box.text()),
patch_size=int(self.patch_size_spin_box.text()),
os_size=int(self.os_size_spin_box.text()),
val_size=int(self.val_size_spin_box.text()),
learning_rate=self.learning_rate_double_spin_box.value(),
global_coef=self.global_loss_coef_double_spin_box.value(),
train_wavelet_mode=self.train_wavelet_mode_combo_box.currentText(),
max_n_wells_on_plot=int(self.max_n_wells_on_plot_spin_box.text()),
training_axes=self.training_axes_combo_box.currentText(),
clearml_task=clearml_task
)
if name == 'main':
app = QApplication(sys.argv)
train_app = TrainApp()
train_app.show()
sys.exit(app.exec_())