|
7 | 7 | "outputs": [], |
8 | 8 | "source": [ |
9 | 9 | "import sys\n", |
10 | | - "sys.path.append('../src')\n", |
| 10 | + "\n", |
| 11 | + "sys.path.append(\"../src\")\n", |
11 | 12 | "from linearboost.linear_boost import LinearBoostClassifier" |
12 | 13 | ] |
13 | 14 | }, |
|
55 | 56 | "metadata": {}, |
56 | 57 | "outputs": [], |
57 | 58 | "source": [ |
58 | | - "from ucimlrepo import fetch_ucirepo \n", |
| 59 | + "from ucimlrepo import fetch_ucirepo\n", |
59 | 60 | "from sklearn.preprocessing import LabelEncoder\n", |
60 | 61 | "\n", |
61 | 62 | "# The Huberman's Survival's id on UCI Machine Learning Repository\n", |
62 | 63 | "dataset_id = 43\n", |
63 | 64 | "\n", |
64 | | - "dataset = fetch_ucirepo(id=dataset_id) \n", |
65 | | - " \n", |
66 | | - "# data (as pandas dataframes) \n", |
| 65 | + "dataset = fetch_ucirepo(id=dataset_id)\n", |
| 66 | + "\n", |
| 67 | + "# data (as pandas dataframes)\n", |
67 | 68 | "X = dataset.data.features.copy()\n", |
68 | 69 | "y = dataset.data.targets\n", |
69 | 70 | "\n", |
|
78 | 79 | "metadata": {}, |
79 | 80 | "outputs": [], |
80 | 81 | "source": [ |
81 | | - "\n", |
82 | 82 | "import pandas as pd\n", |
83 | 83 | "\n", |
84 | 84 | "# Identify categorical columns\n", |
85 | | - "categorical_cols = X.select_dtypes(include=['object']).columns.tolist()\n", |
| 85 | + "categorical_cols = X.select_dtypes(include=[\"object\"]).columns.tolist()\n", |
86 | 86 | "\n", |
87 | 87 | "# Convert categorical columns to 'category' dtype\n", |
88 | 88 | "for col in categorical_cols:\n", |
89 | | - " X[col] = X[col].astype('category')\n", |
| 89 | + " X[col] = X[col].astype(\"category\")\n", |
90 | 90 | "\n", |
91 | 91 | "# Handle missing values\n", |
92 | 92 | "# Fill numeric columns with median\n", |
93 | | - "numeric_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()\n", |
| 93 | + "numeric_cols = X.select_dtypes(include=[\"int64\", \"float64\"]).columns.tolist()\n", |
94 | 94 | "for col in numeric_cols:\n", |
95 | 95 | " X[col] = X[col].fillna(X[col].median())\n", |
96 | 96 | "\n", |
97 | 97 | "# Fill categorical columns with mode\n", |
98 | 98 | "for col in categorical_cols:\n", |
99 | | - " X[col] = X[col].fillna(X[col].mode()[0])\n" |
| 99 | + " X[col] = X[col].fillna(X[col].mode()[0])" |
100 | 100 | ] |
101 | 101 | }, |
102 | 102 | { |
|
355 | 355 | "import numpy as np\n", |
356 | 356 | "from sklearn.model_selection import StratifiedKFold, cross_val_score\n", |
357 | 357 | "\n", |
| 358 | + "\n", |
358 | 359 | "def custom_loss(y_true, y_pred, weights):\n", |
359 | 360 | " return np.mean(weights * (y_true - y_pred) ** 2)\n", |
360 | 361 | "\n", |
| 362 | + "\n", |
361 | 363 | "df = X\n", |
362 | 364 | "\n", |
363 | 365 | "# One-hot encoding\n", |
364 | | - "cat_features = list(df.select_dtypes(include=['object', 'category']).columns)\n", |
| 366 | + "cat_features = list(df.select_dtypes(include=[\"object\", \"category\"]).columns)\n", |
365 | 367 | "for col in cat_features:\n", |
366 | 368 | " df_onehot = pd.get_dummies(df[col], prefix=col)\n", |
367 | 369 | " df = df.drop(col, axis=1)\n", |
|
370 | 372 | "\n", |
371 | 373 | "def objective(trial):\n", |
372 | 374 | " params = {\n", |
373 | | - " 'n_estimators': trial.suggest_int('n_estimators', 10, 500),\n", |
374 | | - " 'learning_rate': trial.suggest_float('learning_rate', 0.01, 1.0, log=True),\n", |
375 | | - " 'algorithm': trial.suggest_categorical('algorithm', ['SAMME', 'SAMME.R']),\n", |
376 | | - " 'scaler': trial.suggest_categorical('scaler', [\n", |
377 | | - " 'minmax', 'robust', 'quantile-uniform', 'quantile-normal'\n", |
378 | | - " ]),\n", |
379 | | - " 'kernel': trial.suggest_categorical('kernel', ['linear', 'rbf', 'poly', 'sigmoid']),\n", |
| 375 | + " \"n_estimators\": trial.suggest_int(\"n_estimators\", 10, 500),\n", |
| 376 | + " \"learning_rate\": trial.suggest_float(\"learning_rate\", 0.01, 1.0, log=True),\n", |
| 377 | + " \"algorithm\": trial.suggest_categorical(\"algorithm\", [\"SAMME\", \"SAMME.R\"]),\n", |
| 378 | + " \"scaler\": trial.suggest_categorical(\n", |
| 379 | + " \"scaler\", [\"minmax\", \"robust\", \"quantile-uniform\", \"quantile-normal\"]\n", |
| 380 | + " ),\n", |
| 381 | + " \"kernel\": trial.suggest_categorical(\n", |
| 382 | + " \"kernel\", [\"linear\", \"rbf\", \"poly\", \"sigmoid\"]\n", |
| 383 | + " ),\n", |
380 | 384 | " }\n", |
381 | 385 | "\n", |
382 | | - " if params['kernel'] != 'linear':\n", |
383 | | - " params['gamma'] = trial.suggest_float('gamma', 1e-3, 10.0, log=True)\n", |
384 | | - " if params['kernel'] == 'poly':\n", |
385 | | - " params['degree'] = trial.suggest_int('degree', 2, 5)\n", |
386 | | - " if params['kernel'] in ['poly', 'sigmoid']:\n", |
387 | | - " params['coef0'] = trial.suggest_float('coef0', 0.0, 1.0)\n", |
388 | | - " \n", |
| 386 | + " if params[\"kernel\"] != \"linear\":\n", |
| 387 | + " params[\"gamma\"] = trial.suggest_float(\"gamma\", 1e-3, 10.0, log=True)\n", |
| 388 | + " if params[\"kernel\"] == \"poly\":\n", |
| 389 | + " params[\"degree\"] = trial.suggest_int(\"degree\", 2, 5)\n", |
| 390 | + " if params[\"kernel\"] in [\"poly\", \"sigmoid\"]:\n", |
| 391 | + " params[\"coef0\"] = trial.suggest_float(\"coef0\", 0.0, 1.0)\n", |
| 392 | + "\n", |
389 | 393 | " # Using a custom loss function here\n", |
390 | | - " #params['loss_function'] = custom_loss\n", |
| 394 | + " # params['loss_function'] = custom_loss\n", |
391 | 395 | "\n", |
392 | 396 | " model = LinearBoostClassifier(**params)\n", |
393 | 397 | "\n", |
394 | 398 | " scores = cross_val_score(\n", |
395 | 399 | " estimator=model,\n", |
396 | 400 | " X=df,\n", |
397 | 401 | " y=y,\n", |
398 | | - " scoring='f1_weighted',\n", |
| 402 | + " scoring=\"f1_weighted\",\n", |
399 | 403 | " cv=StratifiedKFold(n_splits=10, shuffle=True, random_state=42),\n", |
400 | 404 | " )\n", |
401 | 405 | "\n", |
402 | 406 | " return scores.mean()\n", |
403 | 407 | "\n", |
| 408 | + "\n", |
404 | 409 | "# Create an Optuna study and optimize the objective function\n", |
405 | | - "study = optuna.create_study(direction='maximize')\n", |
| 410 | + "study = optuna.create_study(direction=\"maximize\")\n", |
406 | 411 | "study.optimize(objective, n_trials=200)\n", |
407 | 412 | "\n", |
408 | 413 | "# Display the best trial's results\n", |
409 | | - "print('Best trial:')\n", |
| 414 | + "print(\"Best trial:\")\n", |
410 | 415 | "trial = study.best_trial\n", |
411 | 416 | "\n", |
412 | | - "print(f'F1 Score: {trial.value}')\n", |
413 | | - "print('Parameters: ')\n", |
| 417 | + "print(f\"F1 Score: {trial.value}\")\n", |
| 418 | + "print(\"Parameters: \")\n", |
414 | 419 | "for key, value in trial.params.items():\n", |
415 | | - " print(f'{key}: {value}')" |
| 420 | + " print(f\"{key}: {value}\")" |
416 | 421 | ] |
417 | 422 | }, |
418 | 423 | { |
|
654 | 659 | } |
655 | 660 | ], |
656 | 661 | "source": [ |
657 | | - "\n", |
658 | 662 | "import xgboost as xgb\n", |
659 | 663 | "\n", |
| 664 | + "\n", |
660 | 665 | "def objective(trial):\n", |
661 | 666 | " params = {\n", |
662 | | - " 'objective': 'binary:logistic',\n", |
663 | | - " 'use_label_encoder': False,\n", |
664 | | - " 'n_estimators': trial.suggest_int('n_estimators', 20, 1000),\n", |
665 | | - " 'max_depth': trial.suggest_int('max_depth', 1, 20),\n", |
666 | | - " 'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.7),\n", |
667 | | - " 'gamma': trial.suggest_float('gamma', 1e-8, 1.0, log=True),\n", |
668 | | - " 'min_child_weight': trial.suggest_int('min_child_weight', 1, 10),\n", |
669 | | - " 'subsample': trial.suggest_float('subsample', 0.5, 1.0),\n", |
670 | | - " 'colsample_bytree': trial.suggest_float('colsample_bytree', 0.5, 1.0),\n", |
671 | | - " 'reg_alpha': trial.suggest_float('reg_alpha', 1e-8, 1.0, log=True),\n", |
672 | | - " 'reg_lambda': trial.suggest_float('reg_lambda', 1e-8, 1.0, log=True),\n", |
673 | | - " 'enable_categorical': True,\n", |
674 | | - " 'eval_metric': 'logloss',\n", |
675 | | - " 'verbosity': 0\n", |
| 667 | + " \"objective\": \"binary:logistic\",\n", |
| 668 | + " \"use_label_encoder\": False,\n", |
| 669 | + " \"n_estimators\": trial.suggest_int(\"n_estimators\", 20, 1000),\n", |
| 670 | + " \"max_depth\": trial.suggest_int(\"max_depth\", 1, 20),\n", |
| 671 | + " \"learning_rate\": trial.suggest_float(\"learning_rate\", 0.01, 0.7),\n", |
| 672 | + " \"gamma\": trial.suggest_float(\"gamma\", 1e-8, 1.0, log=True),\n", |
| 673 | + " \"min_child_weight\": trial.suggest_int(\"min_child_weight\", 1, 10),\n", |
| 674 | + " \"subsample\": trial.suggest_float(\"subsample\", 0.5, 1.0),\n", |
| 675 | + " \"colsample_bytree\": trial.suggest_float(\"colsample_bytree\", 0.5, 1.0),\n", |
| 676 | + " \"reg_alpha\": trial.suggest_float(\"reg_alpha\", 1e-8, 1.0, log=True),\n", |
| 677 | + " \"reg_lambda\": trial.suggest_float(\"reg_lambda\", 1e-8, 1.0, log=True),\n", |
| 678 | + " \"enable_categorical\": True,\n", |
| 679 | + " \"eval_metric\": \"logloss\",\n", |
| 680 | + " \"verbosity\": 0,\n", |
676 | 681 | " }\n", |
677 | 682 | "\n", |
678 | 683 | " model = xgb.XGBClassifier(**params)\n", |
|
681 | 686 | " estimator=model,\n", |
682 | 687 | " X=X,\n", |
683 | 688 | " y=y,\n", |
684 | | - " scoring='f1_weighted',\n", |
| 689 | + " scoring=\"f1_weighted\",\n", |
685 | 690 | " cv=StratifiedKFold(n_splits=10, shuffle=True, random_state=42),\n", |
686 | | - " n_jobs=-1\n", |
| 691 | + " n_jobs=-1,\n", |
687 | 692 | " )\n", |
688 | 693 | "\n", |
689 | 694 | " return scores.mean()\n", |
690 | 695 | "\n", |
691 | 696 | "\n", |
692 | | - "study = optuna.create_study(direction='maximize')\n", |
| 697 | + "study = optuna.create_study(direction=\"maximize\")\n", |
693 | 698 | "study.optimize(objective, n_trials=200)\n", |
694 | 699 | "\n", |
695 | 700 | "best_trial = study.best_trial\n", |
696 | 701 | "\n", |
697 | | - "print('Best trial:')\n", |
698 | | - "print(f'F1 Score: {best_trial.value:.6f}')\n", |
699 | | - "print('Parameters:')\n", |
| 702 | + "print(\"Best trial:\")\n", |
| 703 | + "print(f\"F1 Score: {best_trial.value:.6f}\")\n", |
| 704 | + "print(\"Parameters:\")\n", |
700 | 705 | "for k, v in best_trial.params.items():\n", |
701 | | - " print(f'{k}: {v}')\n" |
| 706 | + " print(f\"{k}: {v}\")" |
702 | 707 | ] |
703 | 708 | }, |
704 | 709 | { |
|
946 | 951 | "source": [ |
947 | 952 | "import lightgbm as lgb\n", |
948 | 953 | "\n", |
| 954 | + "\n", |
949 | 955 | "def objective(trial):\n", |
950 | 956 | " params = {\n", |
951 | | - " 'objective': 'binary',\n", |
952 | | - " 'metric': 'binary_logloss',\n", |
953 | | - " 'boosting_type': trial.suggest_categorical('boosting_type', ['gbdt', 'dart', 'goss']),\n", |
954 | | - " 'num_leaves': trial.suggest_int('num_leaves', 2, 256),\n", |
955 | | - " 'learning_rate': trial.suggest_float('learning_rate', 1e-3, 0.1, log=True),\n", |
956 | | - " 'n_estimators': trial.suggest_int('n_estimators', 20, 1000),\n", |
957 | | - " 'max_depth': trial.suggest_int('max_depth', 1, 20),\n", |
958 | | - " 'min_child_samples': trial.suggest_int('min_child_samples', 1, 100),\n", |
959 | | - " 'subsample': trial.suggest_float('subsample', 0.5, 1.0),\n", |
960 | | - " 'colsample_bytree': trial.suggest_float('colsample_bytree', 0.5, 1.0),\n", |
961 | | - " 'reg_alpha': trial.suggest_float('reg_alpha', 1e-8, 10.0, log=True),\n", |
962 | | - " 'reg_lambda': trial.suggest_float('reg_lambda', 1e-8, 10.0, log=True),\n", |
963 | | - " 'min_split_gain': trial.suggest_float('min_split_gain', 1e-8, 1.0, log=True),\n", |
964 | | - " 'cat_smooth': trial.suggest_int('cat_smooth', 1, 100),\n", |
965 | | - " 'cat_l2': trial.suggest_float('cat_l2', 1e-8, 10.0, log=True),\n", |
966 | | - " 'verbosity': -1\n", |
| 957 | + " \"objective\": \"binary\",\n", |
| 958 | + " \"metric\": \"binary_logloss\",\n", |
| 959 | + " \"boosting_type\": trial.suggest_categorical(\n", |
| 960 | + " \"boosting_type\", [\"gbdt\", \"dart\", \"goss\"]\n", |
| 961 | + " ),\n", |
| 962 | + " \"num_leaves\": trial.suggest_int(\"num_leaves\", 2, 256),\n", |
| 963 | + " \"learning_rate\": trial.suggest_float(\"learning_rate\", 1e-3, 0.1, log=True),\n", |
| 964 | + " \"n_estimators\": trial.suggest_int(\"n_estimators\", 20, 1000),\n", |
| 965 | + " \"max_depth\": trial.suggest_int(\"max_depth\", 1, 20),\n", |
| 966 | + " \"min_child_samples\": trial.suggest_int(\"min_child_samples\", 1, 100),\n", |
| 967 | + " \"subsample\": trial.suggest_float(\"subsample\", 0.5, 1.0),\n", |
| 968 | + " \"colsample_bytree\": trial.suggest_float(\"colsample_bytree\", 0.5, 1.0),\n", |
| 969 | + " \"reg_alpha\": trial.suggest_float(\"reg_alpha\", 1e-8, 10.0, log=True),\n", |
| 970 | + " \"reg_lambda\": trial.suggest_float(\"reg_lambda\", 1e-8, 10.0, log=True),\n", |
| 971 | + " \"min_split_gain\": trial.suggest_float(\"min_split_gain\", 1e-8, 1.0, log=True),\n", |
| 972 | + " \"cat_smooth\": trial.suggest_int(\"cat_smooth\", 1, 100),\n", |
| 973 | + " \"cat_l2\": trial.suggest_float(\"cat_l2\", 1e-8, 10.0, log=True),\n", |
| 974 | + " \"verbosity\": -1,\n", |
967 | 975 | " }\n", |
968 | 976 | "\n", |
969 | 977 | " model = lgb.LGBMClassifier(**params)\n", |
|
972 | 980 | " estimator=model,\n", |
973 | 981 | " X=X,\n", |
974 | 982 | " y=y,\n", |
975 | | - " scoring='f1_weighted',\n", |
| 983 | + " scoring=\"f1_weighted\",\n", |
976 | 984 | " cv=StratifiedKFold(n_splits=10, shuffle=True, random_state=42),\n", |
977 | | - " n_jobs=-1\n", |
| 985 | + " n_jobs=-1,\n", |
978 | 986 | " )\n", |
979 | 987 | "\n", |
980 | 988 | " return scores.mean()\n", |
981 | 989 | "\n", |
982 | | - "study = optuna.create_study(direction='maximize')\n", |
| 990 | + "\n", |
| 991 | + "study = optuna.create_study(direction=\"maximize\")\n", |
983 | 992 | "study.optimize(objective, n_trials=200)\n", |
984 | 993 | "\n", |
985 | 994 | "best_trial = study.best_trial\n", |
986 | 995 | "\n", |
987 | | - "print('Best trial:')\n", |
988 | | - "print(f'F1 Score: {best_trial.value:.6f}')\n", |
989 | | - "print('Parameters:')\n", |
| 996 | + "print(\"Best trial:\")\n", |
| 997 | + "print(f\"F1 Score: {best_trial.value:.6f}\")\n", |
| 998 | + "print(\"Parameters:\")\n", |
990 | 999 | "for k, v in best_trial.params.items():\n", |
991 | | - " print(f'{k}: {v}')\n", |
992 | | - "\n" |
| 1000 | + " print(f\"{k}: {v}\")" |
993 | 1001 | ] |
994 | 1002 | }, |
995 | 1003 | { |
|
1234 | 1242 | "source": [ |
1235 | 1243 | "from catboost import CatBoostClassifier\n", |
1236 | 1244 | "\n", |
| 1245 | + "\n", |
1237 | 1246 | "def objective(trial):\n", |
1238 | 1247 | " params = {\n", |
1239 | | - " 'iterations': trial.suggest_int('iterations', 50, 500),\n", |
1240 | | - " 'depth': trial.suggest_int('depth', 1, 16),\n", |
1241 | | - " 'learning_rate': trial.suggest_float('learning_rate', 1e-3, 0.5, log=True),\n", |
1242 | | - " 'l2_leaf_reg': trial.suggest_float('l2_leaf_reg', 1e-8, 10.0, log=True),\n", |
1243 | | - " 'random_strength': trial.suggest_float('random_strength', 1e-8, 10.0, log=True),\n", |
1244 | | - " 'bagging_temperature': trial.suggest_float('bagging_temperature', 0.1, 10.0, log=True),\n", |
1245 | | - " 'border_count': trial.suggest_int('border_count', 32, 255),\n", |
1246 | | - " 'grow_policy': trial.suggest_categorical('grow_policy', ['SymmetricTree', 'Depthwise', 'Lossguide']),\n", |
1247 | | - " 'min_data_in_leaf': trial.suggest_int('min_data_in_leaf', 1, 100),\n", |
1248 | | - " 'rsm': trial.suggest_float('rsm', 0.1, 1.0),\n", |
1249 | | - " 'loss_function': 'Logloss',\n", |
1250 | | - " 'eval_metric': 'F1',\n", |
1251 | | - " 'cat_features': categorical_cols,\n", |
1252 | | - " 'verbose': 0\n", |
| 1248 | + " \"iterations\": trial.suggest_int(\"iterations\", 50, 500),\n", |
| 1249 | + " \"depth\": trial.suggest_int(\"depth\", 1, 16),\n", |
| 1250 | + " \"learning_rate\": trial.suggest_float(\"learning_rate\", 1e-3, 0.5, log=True),\n", |
| 1251 | + " \"l2_leaf_reg\": trial.suggest_float(\"l2_leaf_reg\", 1e-8, 10.0, log=True),\n", |
| 1252 | + " \"random_strength\": trial.suggest_float(\"random_strength\", 1e-8, 10.0, log=True),\n", |
| 1253 | + " \"bagging_temperature\": trial.suggest_float(\n", |
| 1254 | + " \"bagging_temperature\", 0.1, 10.0, log=True\n", |
| 1255 | + " ),\n", |
| 1256 | + " \"border_count\": trial.suggest_int(\"border_count\", 32, 255),\n", |
| 1257 | + " \"grow_policy\": trial.suggest_categorical(\n", |
| 1258 | + " \"grow_policy\", [\"SymmetricTree\", \"Depthwise\", \"Lossguide\"]\n", |
| 1259 | + " ),\n", |
| 1260 | + " \"min_data_in_leaf\": trial.suggest_int(\"min_data_in_leaf\", 1, 100),\n", |
| 1261 | + " \"rsm\": trial.suggest_float(\"rsm\", 0.1, 1.0),\n", |
| 1262 | + " \"loss_function\": \"Logloss\",\n", |
| 1263 | + " \"eval_metric\": \"F1\",\n", |
| 1264 | + " \"cat_features\": categorical_cols,\n", |
| 1265 | + " \"verbose\": 0,\n", |
1253 | 1266 | " }\n", |
1254 | 1267 | "\n", |
1255 | 1268 | " model = CatBoostClassifier(**params)\n", |
|
1258 | 1271 | " estimator=model,\n", |
1259 | 1272 | " X=X,\n", |
1260 | 1273 | " y=y,\n", |
1261 | | - " scoring='f1_weighted',\n", |
| 1274 | + " scoring=\"f1_weighted\",\n", |
1262 | 1275 | " cv=StratifiedKFold(n_splits=10, shuffle=True, random_state=42),\n", |
1263 | | - " n_jobs=-1\n", |
| 1276 | + " n_jobs=-1,\n", |
1264 | 1277 | " )\n", |
1265 | 1278 | "\n", |
1266 | 1279 | " return scores.mean()\n", |
1267 | 1280 | "\n", |
1268 | | - "study = optuna.create_study(direction='maximize')\n", |
| 1281 | + "\n", |
| 1282 | + "study = optuna.create_study(direction=\"maximize\")\n", |
1269 | 1283 | "study.optimize(objective, n_trials=200)\n", |
1270 | 1284 | "\n", |
1271 | 1285 | "best_trial = study.best_trial\n", |
1272 | 1286 | "\n", |
1273 | | - "print('Best trial:')\n", |
1274 | | - "print(f'F1 Score: {best_trial.value:.6f}')\n", |
1275 | | - "print('Parameters:')\n", |
| 1287 | + "print(\"Best trial:\")\n", |
| 1288 | + "print(f\"F1 Score: {best_trial.value:.6f}\")\n", |
| 1289 | + "print(\"Parameters:\")\n", |
1276 | 1290 | "for k, v in best_trial.params.items():\n", |
1277 | | - " print(f'{k}: {v}')" |
| 1291 | + " print(f\"{k}: {v}\")" |
1278 | 1292 | ] |
1279 | 1293 | } |
1280 | 1294 | ], |
|
0 commit comments