Skip to content

Commit 76d9aa7

Browse files
author
Vitalii Aleksashin
committed
translate all doc-strings
1 parent 4368f11 commit 76d9aa7

5 files changed

Lines changed: 251 additions & 252 deletions

File tree

examples/basic_usage.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@
1616
from hyperphoenixcv import HyperPhoenixCV
1717

1818
# Load dataset
19-
print("Загрузка данных...")
19+
print("Loading data...")
2020
categories = ['alt.atheism', 'soc.religion.christian']
2121
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)
2222
X, y = newsgroups_train.data, newsgroups_train.target
2323

2424
# Create a pipeline
25-
print("Создание пайплайна...")
25+
print("Creating pipeline...")
2626
pipeline = Pipeline([
2727
('tfidf', TfidfVectorizer()),
2828
('clf', LogisticRegression(max_iter=1000))
@@ -37,7 +37,7 @@
3737
}
3838

3939
# Create HyperPhoenixCV
40-
print("Настройка HyperPhoenixCV...")
40+
print("Configuring HyperPhoenixCV...")
4141
hp = HyperPhoenixCV(
4242
estimator=pipeline,
4343
param_grid=param_grid,
@@ -50,18 +50,18 @@
5050
)
5151

5252
# Run hyperparameter search
53-
print("\nЗапуск поиска гиперпараметров...")
53+
print("\nStarting hyperparameter search...")
5454
hp.fit(X, y)
5555

5656
# Print results
57-
print("\nЛучшие параметры:", hp.best_params_)
58-
print("Лучший f1 score:", hp.best_score_)
57+
print("\nBest parameters:", hp.best_params_)
58+
print("Best f1 score:", hp.best_score_)
5959

6060
# Get top 5 results
6161
top_5 = hp.get_top_results(5)
62-
print("\nТоп-5 результатов:")
62+
print("\nTop-5 results:")
6363
print(top_5)
6464

6565
# Clean up checkpoints after successful run
6666
hp.clear_checkpoint()
67-
print("\nЧекпоинт успешно удален.")
67+
print("\nCheckpoint successfully deleted.")

examples/bayesian_optimization_example.py

Lines changed: 42 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@
1818
from sklearn.ensemble import RandomForestRegressor
1919

2020
# Load dataset
21-
print("Загрузка данных...")
21+
print("Loading data...")
2222
categories = ['alt.atheism', 'sci.space', 'comp.graphics', 'rec.sport.baseball']
2323
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)
2424
X, y = newsgroups_train.data, newsgroups_train.target
2525

2626
# Create a pipeline
27-
print("Создание пайплайна...")
27+
print("Creating pipeline...")
2828
pipeline = Pipeline([
2929
('tfidf', TfidfVectorizer()),
3030
('clf', LogisticRegression(max_iter=1000))
@@ -42,7 +42,7 @@
4242
custom_optimizer = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1)
4343

4444
# Create HyperPhoenixCV with Bayesian optimization
45-
print("\nНастройка HyperPhoenixCV с байесовской оптимизацией...")
45+
print("\nConfiguring HyperPhoenixCV with Bayesian optimization...")
4646
hp_bayesian = HyperPhoenixCV(
4747
estimator=pipeline,
4848
param_grid=param_grid,
@@ -58,9 +58,9 @@
5858

5959
# Run Bayesian-optimized hyperparameter search
6060
print("\n" + "="*60)
61-
print("ЗАПУСК ПОИСКА С БАЙЕСОВСКОЙ ОПТИМИЗАЦИЕЙ")
62-
print("Байесовская оптимизация анализирует предыдущие результаты")
63-
print("и предсказывает, какие параметры могут дать лучшие результаты")
61+
print("RUNNING SEARCH WITH BAYESIAN OPTIMIZATION")
62+
print("Bayesian optimization analyzes previous results")
63+
print("and predicts which parameters may yield better results")
6464
print("="*60)
6565
hp_bayesian.fit(X, y)
6666

@@ -69,17 +69,17 @@
6969
bayesian_top_results = hp_bayesian.get_top_results(5)
7070

7171
print("\n" + "="*50)
72-
print("РЕЗУЛЬТАТЫ БАЙЕСОВСКОЙ ОПТИМИЗАЦИИ")
72+
print("BAYESIAN OPTIMIZATION RESULTS")
7373
print("="*50)
74-
print(f"Лучший f1_macro score: {bayesian_best_score:.4f}")
75-
print("\nТоп-5 комбинаций параметров:")
74+
print(f"Best f1_macro score: {bayesian_best_score:.4f}")
75+
print("\nTop-5 parameter combinations:")
7676
print(bayesian_top_results[['tfidf__max_features', 'tfidf__ngram_range',
7777
'clf__C', 'clf__penalty', 'mean_test_f1_macro']])
7878

7979
# For comparison, let's run random search with the same number of iterations
8080
print("\n" + "="*50)
81-
print("ЗАПУСК СЛУЧАЙНОГО ПОИСКА ДЛЯ СРАВНЕНИЯ")
82-
print(f"Будет выполнено {len(hp_bayesian.cv_results_['params'])} итераций")
81+
print("RUNNING RANDOM SEARCH FOR COMPARISON")
82+
print(f"Will perform {len(hp_bayesian.cv_results_['params'])} iterations")
8383
print("="*50)
8484

8585
hp_random = HyperPhoenixCV(
@@ -99,20 +99,20 @@
9999
random_best_score = hp_random.best_score_
100100

101101
print("\n" + "="*50)
102-
print("СРАВНЕНИЕ РЕЗУЛЬТАТОВ")
102+
print("RESULTS COMPARISON")
103103
print("="*50)
104-
print(f"Байесовская оптимизация: {bayesian_best_score:.4f}")
105-
print(f"Случайный поиск: {random_best_score:.4f}")
104+
print(f"Bayesian optimization: {bayesian_best_score:.4f}")
105+
print(f"Random search: {random_best_score:.4f}")
106106

107107
if bayesian_best_score > random_best_score:
108-
print("✅ Байесовская оптимизация превзошла случайный поиск!")
109-
print(f" Улучшение: {(bayesian_best_score - random_best_score) * 100:.2f} процентных пунктов")
108+
print("✅ Bayesian optimization outperformed random search!")
109+
print(f" Improvement: {(bayesian_best_score - random_best_score) * 100:.2f} percentage points")
110110
else:
111-
print("⚠️ Случайный поиск оказался лучше в этом запуске")
112-
print(" Это может происходить на ранних этапах оптимизации")
111+
print("⚠️ Random search performed better in this run")
112+
print(" This can happen in early stages of optimization")
113113

114114
# Visualize the optimization process
115-
print("\nСоздание графика прогресса оптимизации...")
115+
print("\nCreating optimization progress plot...")
116116
try:
117117
# Get scores in order of evaluation
118118
bayesian_scores = [r[f'mean_test_f1_macro'] for r in hp_bayesian.cv_results_['params']]
@@ -123,17 +123,17 @@
123123
random_cummax = np.maximum.accumulate(random_scores)
124124

125125
plt.figure(figsize=(10, 6))
126-
plt.plot(bayesian_cummax, 'b-', label='Байесовская оптимизация', linewidth=2)
127-
plt.plot(random_cummax, 'r--', label='Случайный поиск', linewidth=2)
126+
plt.plot(bayesian_cummax, 'b-', label='Bayesian optimization', linewidth=2)
127+
plt.plot(random_cummax, 'r--', label='Random search', linewidth=2)
128128

129-
plt.xlabel('Количество оцененных комбинаций')
130-
plt.ylabel('Лучший F1-макро скор')
131-
plt.title('Прогресс поиска гиперпараметров')
129+
plt.xlabel('Number of evaluated combinations')
130+
plt.ylabel('Best F1-macro score')
131+
plt.title('Hyperparameter search progress')
132132
plt.legend()
133133
plt.grid(True, linestyle='--', alpha=0.7)
134134

135135
plt.savefig('optimization_progress.png', dpi=300, bbox_inches='tight')
136-
print("График сохранен как 'optimization_progress.png'")
136+
print("Plot saved as 'optimization_progress.png'")
137137

138138
# Show plot in notebook environment (optional)
139139
try:
@@ -144,29 +144,29 @@
144144
pass
145145

146146
except Exception as e:
147-
print(f"⚠️ Не удалось создать график: {e}")
147+
print(f"⚠️ Failed to create plot: {e}")
148148

149149
# Insights and recommendations
150150
print("\n" + "="*50)
151-
print("ИНСАЙТЫ И РЕКОМЕНДАЦИИ")
151+
print("INSIGHTS AND RECOMMENDATIONS")
152152
print("="*50)
153-
print("Как работает байесовская оптимизация в HyperPhoenixCV:")
154-
print("1. На первых итерациях исследует пространство параметров")
155-
print("2. По мере накопления данных строит модель зависимости параметров от метрики")
156-
print("3. Использует эту модель для выбора наиболее перспективных параметров")
157-
print("4. Со временем фокусируется на самых многообещающих областях пространства")
158-
159-
print("\nРекомендации по использованию:")
160-
print("- Используйте байесовскую оптимизацию, когда пространство параметров велико")
161-
print("- Для небольших пространств параметров может быть достаточно полного перебора")
162-
print("- Сочетайте с чекпоинтами для продолжения поиска после прерываний")
163-
print("- Настройте bayesian_optimizer под свои задачи (количество деревьев и т.д.)")
153+
print("How Bayesian optimization works in HyperPhoenixCV:")
154+
print("1. Explores parameter space in early iterations")
155+
print("2. Builds a model of parameter-metric relationship as data accumulates")
156+
print("3. Uses this model to select the most promising parameters")
157+
print("4. Over time focuses on the most promising regions of the space")
158+
159+
print("\nUsage recommendations:")
160+
print("- Use Bayesian optimization when parameter space is large")
161+
print("- For small parameter spaces, exhaustive search may suffice")
162+
print("- Combine with checkpoints to resume search after interruptions")
163+
print("- Customize bayesian_optimizer for your tasks (number of trees, etc.)")
164164

165165
# Clean up checkpoints
166166
hp_bayesian.clear_checkpoint()
167-
print("\nЧекпоинт байесовской оптимизации успешно удален.")
167+
print("\nBayesian optimization checkpoint successfully deleted.")
168168

169169
# Tip for users
170-
print("\nСовет: Байесовская оптимизация особенно эффективна, когда оценка одной")
171-
print("комбинации параметров занимает много времени (например, обучение глубоких моделей).")
172-
print("В таких случаях экономия даже нескольких итераций может сэкономить часы вычислений!")
170+
print("\nTip: Bayesian optimization is especially effective when evaluating a single")
171+
print("parameter combination takes a long time (e.g., training deep models).")
172+
print("In such cases, saving even a few iterations can save hours of computation!")

examples/random_search_example.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@
1616
from hyperphoenixcv import HyperPhoenixCV
1717

1818
# Load dataset
19-
print("Загрузка данных...")
19+
print("Loading data...")
2020
categories = ['alt.atheism', 'comp.graphics']
2121
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)
2222
X, y = newsgroups_train.data, newsgroups_train.target
2323

2424
# Create a pipeline
25-
print("Создание пайплайна...")
25+
print("Creating pipeline...")
2626
pipeline = Pipeline([
2727
('tfidf', TfidfVectorizer()),
2828
('clf', LogisticRegression(max_iter=1000, solver='saga', penalty='l1'))
@@ -44,63 +44,63 @@
4444
total_combinations = 1
4545
for v in param_grid.values():
4646
total_combinations *= len(v)
47-
print(f"\nОбщее количество возможных комбинаций: {total_combinations}")
48-
print("Полный перебор займет слишком много времени!")
49-
print("Случайный поиск проверит только небольшую часть из них.\n")
47+
print(f"\nTotal possible combinations: {total_combinations}")
48+
print("Exhaustive search would take too long!")
49+
print("Random search will test only a small fraction of them.\n")
5050

5151
# Create HyperPhoenixCV with random search
52-
print("Настройка HyperPhoenixCV с случайным поиском...")
52+
print("Configuring HyperPhoenixCV with random search...")
5353
hp = HyperPhoenixCV(
5454
estimator=pipeline,
5555
param_grid=param_grid,
5656
scoring='f1',
5757
cv=5,
5858
n_jobs=-1,
59-
random_search=True, # Включаем случайный поиск
60-
n_iter=50, # Количество случайных комбинаций для проверки
61-
random_state=42, # Для воспроизводимости
59+
random_search=True, # Enable random search
60+
n_iter=50, # Number of random combinations to test
61+
random_state=42, # For reproducibility
6262
checkpoint_path="random_search_checkpoint.pkl",
6363
results_csv="random_search_results.csv",
6464
verbose=True
6565
)
6666

6767
# Run hyperparameter search
68-
print("\nЗапуск случайного поиска гиперпараметров...")
68+
print("\nStarting random hyperparameter search...")
6969
hp.fit(X, y)
7070

7171
# Print results
7272
print("\n" + "="*50)
73-
print("РЕЗУЛЬТАТЫ СЛУЧАЙНОГО ПОИСКА")
73+
print("RANDOM SEARCH RESULTS")
7474
print("="*50)
75-
print(f"Проверено {hp.n_iter} случайных комбинаций из {total_combinations} возможных")
76-
print(f"Это всего {hp.n_iter/total_combinations*100:.4f}% от полного перебора!")
77-
print("\nЛучшие параметры:", hp.best_params_)
78-
print("Лучший f1 score:", hp.best_score_)
75+
print(f"Tested {hp.n_iter} random combinations out of {total_combinations} possible")
76+
print(f"That's only {hp.n_iter/total_combinations*100:.4f}% of exhaustive search!")
77+
print("\nBest parameters:", hp.best_params_)
78+
print("Best f1 score:", hp.best_score_)
7979

8080
# Get top 5 results
8181
top_5 = hp.get_top_results(5)
82-
print("\nТоп-5 результатов:")
82+
print("\nTop-5 results:")
8383
print(top_5)
8484

8585
# Compare with theoretical full grid search time
86-
estimated_full_grid_time = hp.n_iter / total_combinations * 100 * 2 # Предположим 2 минуты на комбинацию
86+
estimated_full_grid_time = hp.n_iter / total_combinations * 100 * 2 # Assume 2 minutes per combination
8787
if estimated_full_grid_time > 60:
8888
hours = estimated_full_grid_time / 60
89-
time_str = f"{hours:.1f} часов"
89+
time_str = f"{hours:.1f} hours"
9090
else:
91-
time_str = f"{estimated_full_grid_time:.1f} минут"
91+
time_str = f"{estimated_full_grid_time:.1f} minutes"
9292

9393
print("\n" + "="*50)
94-
print(f"ЭКОНОМИЯ ВРЕМЕНИ")
94+
print(f"TIME SAVINGS")
9595
print("="*50)
96-
print(f"Полный перебор всех комбинаций занял бы примерно {time_str}")
97-
print(f"Случайный поиск выполнился за {hp.n_iter} комбинаций и нашел хорошие параметры!")
96+
print(f"Exhaustive search of all combinations would take approximately {time_str}")
97+
print(f"Random search completed in {hp.n_iter} combinations and found good parameters!")
9898
print("="*50)
9999

100100
# Clean up checkpoints after successful run
101101
hp.clear_checkpoint()
102-
print("\nЧекпоинт успешно удален.")
102+
print("\nCheckpoint successfully deleted.")
103103

104104
# Tip for users
105-
print("\nСовет: Для очень больших пространств параметров начните со случайного поиска,")
106-
print("затем используйте найденные лучшие параметры как основу для более детального поиска.")
105+
print("\nTip: For very large parameter spaces, start with random search,")
106+
print("then use the found best parameters as a basis for more detailed search.")

0 commit comments

Comments
 (0)