Spaces:
Runtime error
Runtime error
Upload 3 files
Browse filesFiles changed (3)
- ann_model.ipynbAdded+188
- construction_data_augmented.csvAdded
- gradio.ipynbAdded+157
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "14298abc", "metadata": {}, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: '/construction_data_augmented.csv'", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mFileNotFoundError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[1]\u001b[39m\u001b[32m, line 35\u001b[39m\n\u001b[32m 32\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33m - val_r2: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mr2\u001b[38;5;132;01m:\u001b[39;00m\u001b[33m.4f\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m\"\u001b[39m, end=\u001b[33m'\u001b[39m\u001b[33m'\u001b[39m)\n\u001b[32m 34\u001b[39m \u001b[38;5;66;03m# --- 2. Load Data and Select Core Features ---\u001b[39;00m\n\u001b[32m---> \u001b[39m\u001b[32m35\u001b[39m df = \u001b[43mpd\u001b[49m\u001b[43m.\u001b[49m\u001b[43mread_csv\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43m/construction_data_augmented.csv\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[32m 36\u001b[39m X = df[CORE_FEATURES]\n\u001b[32m 37\u001b[39m y = df[\u001b[33m'\u001b[39m\u001b[33mTotal_Estimate_PKR\u001b[39m\u001b[33m'\u001b[39m]\n", "\u001b[36mFile \u001b[39m\u001b[32mc:\\Users\\GB\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\pandas\\io\\parsers\\readers.py:1026\u001b[39m, in \u001b[36mread_csv\u001b[39m\u001b[34m(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)\u001b[39m\n\u001b[32m 1013\u001b[39m kwds_defaults = _refine_defaults_read(\n\u001b[32m 1014\u001b[39m dialect,\n\u001b[32m 1015\u001b[39m delimiter,\n\u001b[32m (...)\u001b[39m\u001b[32m 1022\u001b[39m dtype_backend=dtype_backend,\n\u001b[32m 1023\u001b[39m )\n\u001b[32m 1024\u001b[39m kwds.update(kwds_defaults)\n\u001b[32m-> \u001b[39m\u001b[32m1026\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43m_read\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfilepath_or_buffer\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkwds\u001b[49m\u001b[43m)\u001b[49m\n", "\u001b[36mFile \u001b[39m\u001b[32mc:\\Users\\GB\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\pandas\\io\\parsers\\readers.py:620\u001b[39m, in \u001b[36m_read\u001b[39m\u001b[34m(filepath_or_buffer, kwds)\u001b[39m\n\u001b[32m 617\u001b[39m _validate_names(kwds.get(\u001b[33m\"\u001b[39m\u001b[33mnames\u001b[39m\u001b[33m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m))\n\u001b[32m 619\u001b[39m \u001b[38;5;66;03m# Create the parser.\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m620\u001b[39m parser = \u001b[43mTextFileReader\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfilepath_or_buffer\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwds\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 622\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m chunksize \u001b[38;5;129;01mor\u001b[39;00m iterator:\n\u001b[32m 623\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m parser\n", "\u001b[36mFile \u001b[39m\u001b[32mc:\\Users\\GB\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\pandas\\io\\parsers\\readers.py:1620\u001b[39m, in \u001b[36mTextFileReader.__init__\u001b[39m\u001b[34m(self, f, engine, **kwds)\u001b[39m\n\u001b[32m 1617\u001b[39m \u001b[38;5;28mself\u001b[39m.options[\u001b[33m\"\u001b[39m\u001b[33mhas_index_names\u001b[39m\u001b[33m\"\u001b[39m] = kwds[\u001b[33m\"\u001b[39m\u001b[33mhas_index_names\u001b[39m\u001b[33m\"\u001b[39m]\n\u001b[32m 1619\u001b[39m \u001b[38;5;28mself\u001b[39m.handles: IOHandles | \u001b[38;5;28;01mNone\u001b[39;00m = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m1620\u001b[39m \u001b[38;5;28mself\u001b[39m._engine = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_make_engine\u001b[49m\u001b[43m(\u001b[49m\u001b[43mf\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mengine\u001b[49m\u001b[43m)\u001b[49m\n", "\u001b[36mFile \u001b[39m\u001b[32mc:\\Users\\GB\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\pandas\\io\\parsers\\readers.py:1880\u001b[39m, in \u001b[36mTextFileReader._make_engine\u001b[39m\u001b[34m(self, f, engine)\u001b[39m\n\u001b[32m 1878\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[33m\"\u001b[39m\u001b[33mb\u001b[39m\u001b[33m\"\u001b[39m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m mode:\n\u001b[32m 1879\u001b[39m mode += \u001b[33m\"\u001b[39m\u001b[33mb\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m-> \u001b[39m\u001b[32m1880\u001b[39m \u001b[38;5;28mself\u001b[39m.handles = \u001b[43mget_handle\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 1881\u001b[39m \u001b[43m \u001b[49m\u001b[43mf\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1882\u001b[39m \u001b[43m \u001b[49m\u001b[43mmode\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1883\u001b[39m \u001b[43m \u001b[49m\u001b[43mencoding\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43moptions\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mencoding\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1884\u001b[39m \u001b[43m \u001b[49m\u001b[43mcompression\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43moptions\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mcompression\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1885\u001b[39m \u001b[43m \u001b[49m\u001b[43mmemory_map\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43moptions\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmemory_map\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1886\u001b[39m \u001b[43m \u001b[49m\u001b[43mis_text\u001b[49m\u001b[43m=\u001b[49m\u001b[43mis_text\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1887\u001b[39m \u001b[43m \u001b[49m\u001b[43merrors\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43moptions\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mencoding_errors\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mstrict\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1888\u001b[39m \u001b[43m \u001b[49m\u001b[43mstorage_options\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43moptions\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mstorage_options\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1889\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1890\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28mself\u001b[39m.handles \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 1891\u001b[39m f = \u001b[38;5;28mself\u001b[39m.handles.handle\n", "\u001b[36mFile \u001b[39m\u001b[32mc:\\Users\\GB\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\pandas\\io\\common.py:873\u001b[39m, in \u001b[36mget_handle\u001b[39m\u001b[34m(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)\u001b[39m\n\u001b[32m 868\u001b[39m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(handle, \u001b[38;5;28mstr\u001b[39m):\n\u001b[32m 869\u001b[39m \u001b[38;5;66;03m# Check whether the filename is to be opened in binary mode.\u001b[39;00m\n\u001b[32m 870\u001b[39m \u001b[38;5;66;03m# Binary mode does not support 'encoding' and 'newline'.\u001b[39;00m\n\u001b[32m 871\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m ioargs.encoding \u001b[38;5;129;01mand\u001b[39;00m \u001b[33m\"\u001b[39m\u001b[33mb\u001b[39m\u001b[33m\"\u001b[39m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m ioargs.mode:\n\u001b[32m 872\u001b[39m \u001b[38;5;66;03m# Encoding\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m873\u001b[39m handle = \u001b[38;5;28;43mopen\u001b[39;49m\u001b[43m(\u001b[49m\n\u001b[32m 874\u001b[39m \u001b[43m \u001b[49m\u001b[43mhandle\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 875\u001b[39m \u001b[43m \u001b[49m\u001b[43mioargs\u001b[49m\u001b[43m.\u001b[49m\u001b[43mmode\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 876\u001b[39m \u001b[43m \u001b[49m\u001b[43mencoding\u001b[49m\u001b[43m=\u001b[49m\u001b[43mioargs\u001b[49m\u001b[43m.\u001b[49m\u001b[43mencoding\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 877\u001b[39m \u001b[43m \u001b[49m\u001b[43merrors\u001b[49m\u001b[43m=\u001b[49m\u001b[43merrors\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 878\u001b[39m \u001b[43m \u001b[49m\u001b[43mnewline\u001b[49m\u001b[43m=\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m 879\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 880\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m 881\u001b[39m \u001b[38;5;66;03m# Binary mode\u001b[39;00m\n\u001b[32m 882\u001b[39m handle = \u001b[38;5;28mopen\u001b[39m(handle, ioargs.mode)\n", "\u001b[31mFileNotFoundError\u001b[39m: [Errno 2] No such file or directory: '/construction_data_augmented.csv'" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.preprocessing import StandardScaler, OneHotEncoder, MinMaxScaler\n", "from sklearn.metrics import r2_score\n", "from tensorflow.keras.models import Sequential\n", "from tensorflow.keras.layers import Dense\n", "from tensorflow.keras.callbacks import Callback\n", "from joblib import dump, load\n", "import joblib # Needed for saving the OneHotEncoder later\n", "from tensorflow.keras.models import save_model\n", "\n", "# --- CORE FEATURES to be used in model training ---\n", "CORE_FEATURES = [\n", " 'District', 'Settlement_Type', 'Area_sft', 'Land_Type',\n", " 'Building_Type', 'Floor_Count', 'Design_Complexity', 'BBS_kg_per_sft'\n", "]\n", "CATEGORICAL_FEATURES = ['District', 'Settlement_Type', 'Land_Type', 'Building_Type']\n", "NUMERICAL_FEATURES = ['Area_sft', 'Floor_Count', 'Design_Complexity', 'BBS_kg_per_sft']\n", "# -----------------------------------------------------------------\n", "\n", "# --- 1. Custom R2 Callback (Still needed to see accuracy during training) ---\n", "class R2ScoreCallback(Callback):\n", " def __init__(self, validation_data):\n", " super().__init__()\n", " self.X_val, self.y_val = validation_data\n", "\n", " def on_epoch_end(self, epoch, logs=None):\n", " y_pred = self.model.predict(self.X_val, verbose=0)\n", " r2 = r2_score(self.y_val, y_pred)\n", " logs['val_r2'] = r2\n", " print(f\" - val_r2: {r2:.4f}\", end='')\n", "\n", "# --- 2. Load Data and Select Core Features ---\n", "df = pd.read_csv(\"/construction_data_augmented.csv\")\n", "X = df[CORE_FEATURES]\n", "y = df['Total_Estimate_PKR']\n", "\n", "# --- 3. Target (y) Scaling ---\n", "y_scaler = MinMaxScaler()\n", "y_scaled = y_scaler.fit_transform(y.values.reshape(-1, 1))\n", "dump(y_scaler, 'y_scaler_manual.pkl')\n", "print(\"Target scaler saved as y_scaler_manual.pkl\")\n", "\n", "# --- 4. Manual Preprocessing Setup and Training/Test Split ---\n", "\n", "# Split data FIRST\n", "X_train, X_test, y_train_scaled, y_test_scaled = train_test_split(\n", " X, y_scaled, test_size=0.2, random_state=42\n", ")\n", "\n", "# Initialize Scalers/Encoders\n", "scaler = StandardScaler()\n", "encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False) # sparse_output=False makes the output an array\n", "\n", "# --- 5. Fit and Transform Training Data ---\n", "\n", "# 5a. Numerical Scaling\n", "X_train_num = X_train[NUMERICAL_FEATURES]\n", "scaler.fit(X_train_num)\n", "X_train_num_scaled = scaler.transform(X_train_num)\n", "dump(scaler, 'scaler_manual.pkl') # Save the scaler\n", "\n", "# 5b. Categorical Encoding\n", "X_train_cat = X_train[CATEGORICAL_FEATURES]\n", "encoder.fit(X_train_cat)\n", "X_train_cat_encoded = encoder.transform(X_train_cat)\n", "joblib.dump(encoder, 'encoder_manual.pkl') # Save the encoder\n", "\n", "# 5c. Combine everything for training\n", "X_train_processed = np.hstack([X_train_num_scaled, X_train_cat_encoded])\n", "\n", "# --- 6. Transform Test Data (DO NOT CALL .fit() on test data) ---\n", "\n", "# 6a. Numerical Scaling\n", "X_test_num = X_test[NUMERICAL_FEATURES]\n", "X_test_num_scaled = scaler.transform(X_test_num)\n", "\n", "# 6b. Categorical Encoding\n", "X_test_cat = X_test[CATEGORICAL_FEATURES]\n", "X_test_cat_encoded = encoder.transform(X_test_cat)\n", "\n", "# 6c. Combine everything for testing\n", "X_test_processed = np.hstack([X_test_num_scaled, X_test_cat_encoded])\n", "\n", "print(\"Data preparation complete. Input shape:\", X_train_processed.shape[1])\n", "\n", "# --- 7. Build ANN Model ---\n", "input_shape = X_train_processed.shape[1]\n", "model = Sequential([\n", " Dense(128, activation='relu', input_shape=(input_shape,)),\n", " Dense(64, activation='relu'),\n", " Dense(32, activation='relu'),\n", " Dense(1)\n", "])\n", "\n", "model.compile(optimizer='adam', loss='mse')\n", "\n", "# --- 8. Train Model ---\n", "val_split_index = int(0.9 * len(X_train_processed))\n", "X_train_for_fit = X_train_processed[:val_split_index]\n", "y_train_for_fit = y_train_scaled[:val_split_index]\n", "X_val_for_callback = X_train_processed[val_split_index:]\n", "y_val_for_callback = y_train_scaled[val_split_index:]\n", "\n", "r2_callback = R2ScoreCallback(validation_data=(X_val_for_callback, y_val_for_callback))\n", "\n", "print(\"\\nTraining ANN model with manual preprocessing...\")\n", "model.fit(\n", " X_train_for_fit,\n", " y_train_for_fit,\n", " epochs=50,\n", " batch_size=32,\n", " validation_data=(X_val_for_callback, y_val_for_callback),\n", " callbacks=[r2_callback],\n", " verbose=1\n", ")\n", "\n", "# --- 9. Final Evaluation and Save Model ---\n", "loss = model.evaluate(X_test_processed, y_test_scaled, verbose=0)\n", "y_pred_scaled = model.predict(X_test_processed, verbose=0)\n", "r2 = r2_score(y_test_scaled, y_pred_scaled)\n", "\n", "print(f\"\\n--- MANUAL Model Final Evaluation ---\")\n", "print(f\"Test Loss (Scaled MSE): {loss:.6f}\")\n", "print(f\"Test R-squared (Accuracy): {r2:.4f}\")\n", "\n", "save_model(model, 'ann_model_manual.h5')\n", "print(\"Trained MANUAL ANN model saved as ann_model_manual.h5\")" ] }, { "cell_type": "code", "execution_count": null, "id": "f6c8b30a", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.13.9" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "823524c2", "metadata": {}, "outputs": [], "source": [ "import gradio as gr\n", "import pandas as pd\n", "import numpy as np\n", "from tensorflow.keras.models import load_model\n", "from tensorflow.keras.losses import MeanSquaredError\n", "from joblib import load\n", "import joblib\n", "import os\n", "\n", "# --- FEATURE DEFINITIONS (Must match the training script) ---\n", "CATEGORICAL_FEATURES = ['District', 'Settlement_Type', 'Land_Type', 'Building_Type']\n", "NUMERICAL_FEATURES = ['Area_sft', 'Floor_Count', 'Design_Complexity', 'BBS_kg_per_sft']\n", "# -----------------------------------------------------------------\n", "\n", "# --- 1. Load Model and Preprocessor Artifacts ---\n", "# We check if all required files exist before attempting to load\n", "required_files = ['y_scaler_manual.pkl', 'scaler_manual.pkl', 'encoder_manual.pkl', 'ann_model_manual.h5']\n", "missing_files = [f for f in required_files if not os.path.exists(f)]\n", "\n", "if missing_files:\n", " print(f\"FATAL ERROR: The following model files are missing: {', '.join(missing_files)}.\")\n", " print(\"Please ensure you ran 'train_ann_manual.py' successfully first.\")\n", " # In a real app, you would exit or raise an error here.\n", " # For this demonstration, we'll try to load, expecting failure if files are missing.\n", "\n", "try:\n", " # Load the manual artifacts\n", " y_scaler = load('y_scaler_manual.pkl')\n", " scaler = load('scaler_manual.pkl') # Standard Scaler for numerical features\n", " encoder = joblib.load('encoder_manual.pkl') # OneHotEncoder for categorical features\n", "\n", " # Load the model\n", " custom_objects = {'mse': MeanSquaredError()}\n", " model = load_model('ann_model_manual.h5', custom_objects=custom_objects)\n", "\n", " print(\"All manual model artifacts loaded successfully.\")\n", "except Exception as e:\n", " print(f\"An error occurred during model loading: {e}\")\n", " exit()\n", "\n", "\n", "# --- 2. Define Prediction Function ---\n", "def predict_estimate(\n", " District, Settlement_Type, Area_sft, Land_Type, Building_Type,\n", " Floor_Count, Design_Complexity, BBS_kg_per_sft\n", "):\n", " \"\"\"\n", " Takes 8 simple user inputs, manually preprocesses them (scales/encodes),\n", " and predicts the total estimate cost using the ANN model.\n", " \"\"\"\n", "\n", " # Create a DataFrame from the 8 simple inputs\n", " input_data = pd.DataFrame({\n", " 'District': [District],\n", " 'Settlement_Type': [Settlement_Type],\n", " 'Area_sft': [Area_sft],\n", " 'Land_Type': [Land_Type],\n", " 'Building_Type': [Building_Type],\n", " 'Floor_Count': [Floor_Count],\n", " 'Design_Complexity': [Design_Complexity],\n", " 'BBS_kg_per_sft': [BBS_kg_per_sft]\n", " })\n", "\n", " # --- Manual Preprocessing Steps (Mirroring the training script) ---\n", "\n", " # 2a. Separate features\n", " X_num = input_data[NUMERICAL_FEATURES]\n", " X_cat = input_data[CATEGORICAL_FEATURES]\n", "\n", " # 2b. Transform Numerical (Scale)\n", " # The scaler object was saved during training and is loaded above\n", " X_num_scaled = scaler.transform(X_num)\n", "\n", " # 2c. Transform Categorical (Encode)\n", " # The encoder object was saved during training and is loaded above\n", " X_cat_encoded = encoder.transform(X_cat)\n", "\n", " # 2d. Combine and prepare for prediction (Numerical first, then Categorical)\n", " input_processed = np.hstack([X_num_scaled, X_cat_encoded])\n", "\n", " # --- Prediction ---\n", "\n", " # Step 1: Make the prediction (output is scaled, 0 to 1)\n", " prediction_scaled = model.predict(input_processed, verbose=0)[0][0]\n", "\n", " # Step 2: Convert the scaled prediction back to the real PKR amount (Inverse Transform)\n", " prediction_pkr = y_scaler.inverse_transform([[prediction_scaled]])[0][0]\n", "\n", " # Handle potential negative prediction due to inverse transform if prediction is outside training bounds\n", " if prediction_pkr < 0:\n", " prediction_pkr = 0\n", "\n", " return f\"Estimated Total Cost: PKR {prediction_pkr:,.2f}\"\n", "\n", "# --- 3. Setup Gradio Interface Components ---\n", "DISTRICTS = ['Ghanche', 'Ghizer', 'Nagar', 'Astore', 'Diamer', 'Skardu', 'Shigar', 'Hunza', 'Gilgit', 'Roundu']\n", "SETTLEMENT_TYPES = ['Rural', 'Sub-Rural', 'Urban']\n", "LAND_TYPES = ['Commercial', 'Uncultivated', 'Cultivated']\n", "BUILDING_TYPES = ['Commercial', 'Road', 'Residential']\n", "\n", "# These 8 fields are what the user sees\n", "inputs = [\n", " gr.Dropdown(DISTRICTS, label=\"1. District (Location)\", value='Gilgit'),\n", " gr.Dropdown(SETTLEMENT_TYPES, label=\"2. Settlement Type (Urban/Rural)\", value='Urban'),\n", " gr.Number(label=\"3. Area (sq ft)\", value=2500, minimum=100, step=1),\n", " gr.Dropdown(LAND_TYPES, label=\"4. Land Type\", value='Commercial'),\n", " gr.Dropdown(BUILDING_TYPES, label=\"5. Building Type\", value='Residential'),\n", " gr.Number(label=\"6. Floor Count\", value=3, minimum=1, step=1),\n", " gr.Number(label=\"7. Design Complexity (1=Simple, 5=Complex)\", value=3, minimum=1, maximum=5, step=1),\n", " gr.Number(label=\"8. Steel/Rebar per sq ft (BBS kg/sft)\", value=0, minimum=0, step=0.1)\n", "]\n", "\n", "# --- 4. Launch Gradio Interface ---\n", "iface = gr.Interface(\n", " fn=predict_estimate,\n", " inputs=inputs,\n", " outputs=gr.Text(label=\"Predicted Total Estimate\"),\n", " title=\"Simplified Construction Cost Predictor (Manual ANN)\",\n", " description=\"This predictive tool uses an Artificial Neural Network trained only on 8 core structural and location features. Note: All underlying cost factors are fixed based on typical values from the training data.\",\n", " allow_flagging=\"never\"\n", ")\n", "\n", "iface.launch(inbrowser=True)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.13.9" } }, "nbformat": 4, "nbformat_minor": 5}ann_model.ipynbAdded+188
construction_data_augmented.csvAdded
gradio.ipynbAdded+157