Files
CSIROBoeingPhase5-Vietnam/.ipynb_checkpoints/01.train_ODC_XGBoost-checkpoint.ipynb
T
2026-04-04 02:16:36 +00:00

406 lines
12 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "912ed572-1658-406b-976c-cd6de2d4e89e",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": []
},
"outputs": [],
"source": [
"%%time\n",
"%matplotlib inline\n",
"\n",
"import importlib\n",
"import new_import_ODC \n",
"\n",
"importlib.reload(new_import_ODC)\n",
"\n",
"from new_import_ODC import *"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d824dc4f-994b-4d1c-8d24-ce6674da141c",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"%%time\n",
"# Cấu hình Daskgateway\n",
"cluster, client = notebook_utils.initialize_dask(use_gateway=True, workers=(1, 10))\n",
"# Khai báo 1 Datacube là dc\n",
"dc = datacube.Datacube()\n",
"\n",
"# Cấu hình truy cập dịch vụ S3\n",
"configure_s3_access(aws_unsigned=False, requester_pays=True, client=client)\n",
"\n",
"client"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fbed4c80-bbf8-4ea8-aa45-2460b2ba04c7",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"## cấu hình thời gian lấy ảnh và tọa độ\n",
"date_range = (\"2022-09-01\", \"2023-10-01\")\n",
"longtitude_range = (105.5, 106.4)\n",
"latitude_range = (9.2, 10.0)\n",
"\n",
"coordinates = (longtitude_range, latitude_range)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6b90c49b-0665-4478-a23b-d111ef88eb79",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"## truy vấn ảnh vệ tinh sen2\n",
"data = load_data(dc, date_range, longtitude_range, latitude_range)\n",
"notebook_utils.heading(notebook_utils.xarray_object_size(data))\n",
"display(data)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2f6938b6-82e2-4916-bc1d-719c169e25e4",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"%%time\n",
"# Tiến hành loại bỏ các vị trí bị mây ảnh hưởng\n",
"result = mask_clean(data)\n",
"progress(result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "435f9f78-a9a4-4226-86ca-d4bec42d454e",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Tiến hành tính toán NDVI\n",
"ds1 = calculate_indices(result, index=\"NDVI\", satellite_mission=\"s2\")\n",
"ndvi = ds1[\"NDVI\"]\n",
"display(ndvi)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "84992d28-8e3f-468e-be08-ded511f2c662",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"## Hiển thị ảnh NDVI chưa điền các giá trị mây (chưa fill nan)\n",
"plt.imshow(ndvi.isel(time=6))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "72318b60-532a-4f08-a5f7-94762d08a42c",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Thiết lập giá trị trung bình mùa vụ để xử lý các điểm ảnh bị mây dựa vào sự thay đổi theo mùa\n",
"time_split = [\n",
" slice(\"2022-09-01\", \"2023-01-01\"),\n",
" slice(\"2023-01-01\", \"2023-05-01\"),\n",
" slice(\"2023-05-01\", \"2023-07-01\"),\n",
" slice(\"2023-07-01\", \"2023-10-01\"),\n",
"]\n",
"\n",
"# Điền mây ở các vị trí mang giá trị nan (fill nan)\n",
"fill_nan_ndvi = fill_nan(ndvi, time_split)\n",
"\n",
"# In kết quả ảnh NDVI đã điền mây (đã fill nan)\n",
"plt.imshow(fill_nan_ndvi.isel(time=6))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "375b1cfb-37f5-49fe-8061-ea32eb47f9f6",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"%%time\n",
"## tính ndvi theo tháng\n",
"average_ndvi = fill_nan_ndvi.resample(time=\"1M\").mean().persist()\n",
"progress(average_ndvi)\n",
"\n",
"# compute average_ndvi\n",
"average_ndvi = average_ndvi.compute()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "187cc640-aef9-476b-91fc-b63f4d3ff2e3",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"#Load dữ liệu ảnh Sentinel 1\n",
"dsvh, dsvv = load_data_sen1(dc, date_range, coordinates)\n",
"average_vv = calculate_average(dsvv, time_pattern='1M')\n",
"average_vh = calculate_average(dsvh, time_pattern='1M')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d2585562-88aa-4c7d-bf70-1f6affcf65d4",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"## cấu hình bộ dữ liệu điểm huấn luyện mô hình (train file)\n",
"train_path = \"train/ST_training data_updated_1130points_new.shp\" # đường dẫn shp file train\n",
"\n",
"## load dữ liệu điểm huấn luyện mô hình (train file)\n",
"train = load_train_data(train_path)\n",
"train.head()\n",
"\n",
"# cấu hình nhãn dữ liệu \n",
"label_mapping = {\n",
" \"Lua tom\": \"0\",\n",
" \"Lua\": \"1\",\n",
" \"CHN\": \"2\",\n",
" \"CLN\": \"3\",\n",
" \"TS\": \"4\",\n",
" \"Song\": \"5\",\n",
" \"Dat xay dung\": \"6\",\n",
" \"Rung\": \"7\",\n",
"}\n",
"\n",
"# xây dựng tập dữ liệu (dataset) chứa dữ liệu VH, VV, NDVI\n",
"datasets = get_data_sen1_and_sen2(train, average_ndvi, average_vh, average_vv)\n",
"\n",
"# chia tập dữ liệu thành các phần theo tỉ lệ 80(80-20)-20 tương ứng với tập train, validate, test\n",
"X_train, X_val, X_test, y_train, y_val, y_test = split_train_data(\n",
" train, label_mapping, datasets\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2e955884-d4af-422d-a8e6-d436199540e0",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"%%time\n",
"# Import XGBoost\n",
"import xgboost as xgb\n",
"from sklearn.metrics import accuracy_score\n",
"import numpy as np\n",
"\n",
"# Convert to numpy arrays\n",
"X_train_np = np.asarray(X_train, dtype=np.float32)\n",
"X_val_np = np.asarray(X_val, dtype=np.float32)\n",
"y_train_np = np.asarray(y_train, dtype=np.int32)\n",
"y_val_np = np.asarray(y_val, dtype=np.int32)\n",
"\n",
"print(\"🚀 Training XGBoost model...\")\n",
"print(f\" Train samples: {len(X_train_np)}\")\n",
"print(f\" Val samples: {len(X_val_np)}\")\n",
"print(f\" Features: {X_train_np.shape[1]}\")\n",
"print(f\" Classes: 8\\n\")\n",
"\n",
"# XGBoost parameters\n",
"params = {\n",
" 'objective': 'multi:softmax', # Multi-class classification\n",
" 'num_class': 8, # 8 land use classes\n",
" 'max_depth': 6, # Maximum tree depth\n",
" 'learning_rate': 0.1, # Learning rate\n",
" 'n_estimators': 200, # Number of trees\n",
" 'subsample': 0.8, # Subsample ratio\n",
" 'colsample_bytree': 0.8, # Feature sampling ratio\n",
" 'random_state': 42,\n",
" 'n_jobs': -1, # Use all CPU cores\n",
" 'eval_metric': 'mlogloss' # Multi-class log loss\n",
"}\n",
"\n",
"# Train XGBoost model\n",
"model = xgb.XGBClassifier(**params)\n",
"\n",
"model.fit(\n",
" X_train_np, y_train_np,\n",
" eval_set=[(X_train_np, y_train_np), (X_val_np, y_val_np)],\n",
" verbose=True\n",
")\n",
"\n",
"# Validation accuracy\n",
"y_val_pred = model.predict(X_val_np)\n",
"val_accuracy = accuracy_score(y_val_np, y_val_pred)\n",
"print(f\"\\n✅ Training completed!\")\n",
"print(f\" Validation Accuracy: {val_accuracy:.4f} ({val_accuracy*100:.2f}%)\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b2a1e42c-cf1b-4d82-a6af-b06e3496918f",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"%%time\n",
"# Evaluate on test set\n",
"X_test_np = np.asarray(X_test, dtype=np.float32)\n",
"y_test_np = np.asarray(y_test, dtype=np.int32)\n",
"\n",
"print(\"📊 Evaluating XGBoost model on test set...\\n\")\n",
"\n",
"# Predictions\n",
"y_pred_test = model.predict(X_test_np)\n",
"\n",
"# Metrics\n",
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n",
"\n",
"test_accuracy = accuracy_score(y_test_np, y_pred_test)\n",
"precision = precision_score(y_test_np, y_pred_test, average='weighted', zero_division=0)\n",
"recall = recall_score(y_test_np, y_pred_test, average='weighted', zero_division=0)\n",
"f1 = f1_score(y_test_np, y_pred_test, average='weighted', zero_division=0)\n",
"\n",
"print(f\"📈 Test Results:\")\n",
"print(f\" Accuracy: {test_accuracy:.4f} ({test_accuracy*100:.2f}%)\")\n",
"print(f\" Precision: {precision:.4f}\")\n",
"print(f\" Recall: {recall:.4f}\")\n",
"print(f\" F1-Score: {f1:.4f}\\n\")\n",
"\n",
"# Confusion Matrix\n",
"from sklearn.metrics import ConfusionMatrixDisplay\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Create figure first\n",
"fig, ax = plt.subplots(figsize=(10, 8))\n",
"\n",
"class_names = list(label_mapping.keys())\n",
"cm = confusion_matrix(y_test_np, y_pred_test)\n",
"disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=class_names)\n",
"disp.plot(cmap='Blues', ax=ax)\n",
"plt.xticks(rotation=45, ha='right')\n",
"plt.title('XGBoost Confusion Matrix')\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f1a14379-ed6e-4897-9ca4-2669743fab40",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Lưu mô hình huấn luyện\n",
"import json\n",
"import joblib\n",
"\n",
"# Save XGBoost model\n",
"model_path = \"model_xgboost.joblib\"\n",
"joblib.dump(model, model_path)\n",
"print(f\"✅ Model saved to {model_path}\")\n",
"\n",
"# Save model info\n",
"info = {\n",
" \"model_type\": \"XGBoost\",\n",
" \"num_classes\": 8,\n",
" \"classes\": list(label_mapping.keys()),\n",
" \"num_features\": X_train_np.shape[1],\n",
" \"params\": params,\n",
" \"accuracy\": float(test_accuracy),\n",
" \"precision\": float(precision),\n",
" \"recall\": float(recall),\n",
" \"f1_score\": float(f1),\n",
"}\n",
"\n",
"with open(\"model_xgboost_info.json\", \"w\") as f:\n",
" json.dump(info, f, indent=2)\n",
"\n",
"print(f\"✅ Model info saved to model_xgboost_info.json\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "33dd516d-9824-499e-96b9-5cd9224c194c",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# đóng client, cluster\n",
"client.close()\n",
"cluster.close()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ee0ecd6a-733b-4655-8864-bc037a539ce2",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}