|
18 | 18 | from sklearn.ensemble import RandomForestRegressor |
19 | 19 |
|
20 | 20 | # Load dataset |
21 | | -print("Загрузка данных...") |
| 21 | +print("Loading data...") |
22 | 22 | categories = ['alt.atheism', 'sci.space', 'comp.graphics', 'rec.sport.baseball'] |
23 | 23 | newsgroups_train = fetch_20newsgroups(subset='train', categories=categories) |
24 | 24 | X, y = newsgroups_train.data, newsgroups_train.target |
25 | 25 |
|
26 | 26 | # Create a pipeline |
27 | | -print("Создание пайплайна...") |
| 27 | +print("Creating pipeline...") |
28 | 28 | pipeline = Pipeline([ |
29 | 29 | ('tfidf', TfidfVectorizer()), |
30 | 30 | ('clf', LogisticRegression(max_iter=1000)) |
|
42 | 42 | custom_optimizer = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1) |
43 | 43 |
|
44 | 44 | # Create HyperPhoenixCV with Bayesian optimization |
45 | | -print("\nНастройка HyperPhoenixCV с байесовской оптимизацией...") |
| 45 | +print("\nConfiguring HyperPhoenixCV with Bayesian optimization...") |
46 | 46 | hp_bayesian = HyperPhoenixCV( |
47 | 47 | estimator=pipeline, |
48 | 48 | param_grid=param_grid, |
|
58 | 58 |
|
59 | 59 | # Run Bayesian-optimized hyperparameter search |
60 | 60 | 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") |
64 | 64 | print("="*60) |
65 | 65 | hp_bayesian.fit(X, y) |
66 | 66 |
|
|
69 | 69 | bayesian_top_results = hp_bayesian.get_top_results(5) |
70 | 70 |
|
71 | 71 | print("\n" + "="*50) |
72 | | -print("РЕЗУЛЬТАТЫ БАЙЕСОВСКОЙ ОПТИМИЗАЦИИ") |
| 72 | +print("BAYESIAN OPTIMIZATION RESULTS") |
73 | 73 | 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:") |
76 | 76 | print(bayesian_top_results[['tfidf__max_features', 'tfidf__ngram_range', |
77 | 77 | 'clf__C', 'clf__penalty', 'mean_test_f1_macro']]) |
78 | 78 |
|
79 | 79 | # For comparison, let's run random search with the same number of iterations |
80 | 80 | 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") |
83 | 83 | print("="*50) |
84 | 84 |
|
85 | 85 | hp_random = HyperPhoenixCV( |
|
99 | 99 | random_best_score = hp_random.best_score_ |
100 | 100 |
|
101 | 101 | print("\n" + "="*50) |
102 | | -print("СРАВНЕНИЕ РЕЗУЛЬТАТОВ") |
| 102 | +print("RESULTS COMPARISON") |
103 | 103 | 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}") |
106 | 106 |
|
107 | 107 | 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") |
110 | 110 | else: |
111 | | - print("⚠️ Случайный поиск оказался лучше в этом запуске") |
112 | | - print(" Это может происходить на ранних этапах оптимизации") |
| 111 | + print("⚠️ Random search performed better in this run") |
| 112 | + print(" This can happen in early stages of optimization") |
113 | 113 |
|
114 | 114 | # Visualize the optimization process |
115 | | -print("\nСоздание графика прогресса оптимизации...") |
| 115 | +print("\nCreating optimization progress plot...") |
116 | 116 | try: |
117 | 117 | # Get scores in order of evaluation |
118 | 118 | bayesian_scores = [r[f'mean_test_f1_macro'] for r in hp_bayesian.cv_results_['params']] |
|
123 | 123 | random_cummax = np.maximum.accumulate(random_scores) |
124 | 124 |
|
125 | 125 | 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) |
128 | 128 |
|
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') |
132 | 132 | plt.legend() |
133 | 133 | plt.grid(True, linestyle='--', alpha=0.7) |
134 | 134 |
|
135 | 135 | plt.savefig('optimization_progress.png', dpi=300, bbox_inches='tight') |
136 | | - print("График сохранен как 'optimization_progress.png'") |
| 136 | + print("Plot saved as 'optimization_progress.png'") |
137 | 137 |
|
138 | 138 | # Show plot in notebook environment (optional) |
139 | 139 | try: |
|
144 | 144 | pass |
145 | 145 |
|
146 | 146 | except Exception as e: |
147 | | - print(f"⚠️ Не удалось создать график: {e}") |
| 147 | + print(f"⚠️ Failed to create plot: {e}") |
148 | 148 |
|
149 | 149 | # Insights and recommendations |
150 | 150 | print("\n" + "="*50) |
151 | | -print("ИНСАЙТЫ И РЕКОМЕНДАЦИИ") |
| 151 | +print("INSIGHTS AND RECOMMENDATIONS") |
152 | 152 | 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.)") |
164 | 164 |
|
165 | 165 | # Clean up checkpoints |
166 | 166 | hp_bayesian.clear_checkpoint() |
167 | | -print("\nЧекпоинт байесовской оптимизации успешно удален.") |
| 167 | +print("\nBayesian optimization checkpoint successfully deleted.") |
168 | 168 |
|
169 | 169 | # 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!") |
0 commit comments