{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":82611,"databundleVersionId":9553358,"sourceType":"competition"}],"dockerImageVersionId":30775,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n# Setup Cell\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.impute import SimpleImputer\nimport xgboost as xgb  \n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-09-30T11:23:40.740691Z","iopub.execute_input":"2024-09-30T11:23:40.741013Z","iopub.status.idle":"2024-09-30T11:23:43.206777Z","shell.execute_reply.started":"2024-09-30T11:23:40.740968Z","shell.execute_reply":"2024-09-30T11:23:43.205641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"[https://www.kaggle.com/code/twobob/bloodglucosepredictiongpu-xgboost?cellIds=1-2&kernelSessionId=198006770](http://)\n*Acknowledgements for the preprocessing*","metadata":{}},{"cell_type":"code","source":"train=pd.read_csv(\"/kaggle/input/brist1d/train.csv\")\ntest=pd.read_csv(\"/kaggle/input/brist1d/test.csv\")\nsubmission_df = pd.read_csv('/kaggle/input/brist1d/sample_submission.csv')\nprint(f\"len(train):{len(train)},len(test):{len(test)}\")\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:23:43.208755Z","iopub.execute_input":"2024-09-30T11:23:43.209303Z","iopub.status.idle":"2024-09-30T11:23:56.238685Z","shell.execute_reply.started":"2024-09-30T11:23:43.209257Z","shell.execute_reply":"2024-09-30T11:23:56.237682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train['time'] = pd.to_datetime(train['time'], format='%H:%M:%S')\ntest['time'] = pd.to_datetime(test['time'], format='%H:%M:%S')\n","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:23:56.239814Z","iopub.execute_input":"2024-09-30T11:23:56.240126Z","iopub.status.idle":"2024-09-30T11:23:56.289584Z","shell.execute_reply.started":"2024-09-30T11:23:56.240070Z","shell.execute_reply":"2024-09-30T11:23:56.288653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Extract hour and minute as numerical features\ntrain['hour'] = train['time'].dt.hour\ntrain['minute'] = train['time'].dt.minute\ntest['hour'] = test['time'].dt.hour\ntest['minute'] = test['time'].dt.minute\n\n# Drop 'time' column\ntrain.drop('time', axis=1, inplace=True)\ntest.drop('time', axis=1, inplace=True)\n\n# Identify numerical and categorical columns\nnumerical_cols = train.select_dtypes(include=['float64', 'int64']).columns.tolist()\nnumerical_cols.remove('bg+1:00')  # Remove target variable from features\ncategorical_cols = [col for col in train.columns if 'activity' in col]","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:23:56.292006Z","iopub.execute_input":"2024-09-30T11:23:56.292351Z","iopub.status.idle":"2024-09-30T11:23:56.834908Z","shell.execute_reply.started":"2024-09-30T11:23:56.292316Z","shell.execute_reply":"2024-09-30T11:23:56.833914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Impute missing numerical values\nimputer = SimpleImputer(strategy='mean')\ntrain[numerical_cols] = imputer.fit_transform(train[numerical_cols])\ntest[numerical_cols] = imputer.transform(test[numerical_cols])\n","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:23:56.836219Z","iopub.execute_input":"2024-09-30T11:23:56.836616Z","iopub.status.idle":"2024-09-30T11:23:59.242124Z","shell.execute_reply.started":"2024-09-30T11:23:56.836573Z","shell.execute_reply":"2024-09-30T11:23:59.241300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Encode categorical variables\nfor col in categorical_cols:\n    train[col] = train[col].fillna('None')\n    test[col] = test[col].fillna('None')\n    le = LabelEncoder()\n    combined_data = pd.concat([train[col], test[col]], axis=0)\n    le.fit(combined_data)\n    train[col] = le.transform(train[col])\n    test[col] = le.transform(test[col])\n\n# Scale numerical features\nscaler = StandardScaler()\ntrain[numerical_cols] = scaler.fit_transform(train[numerical_cols])\ntest[numerical_cols] = scaler.transform(test[numerical_cols])\n\n# Prepare data for modeling\nX_train = train.drop(['id', 'p_num', 'bg+1:00'], axis=1)\ny_train = train['bg+1:00']\nX_test = test.drop(['id', 'p_num'], axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:23:59.243208Z","iopub.execute_input":"2024-09-30T11:23:59.243500Z","iopub.status.idle":"2024-09-30T11:24:05.942876Z","shell.execute_reply.started":"2024-09-30T11:23:59.243468Z","shell.execute_reply":"2024-09-30T11:24:05.942079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom xgboost import XGBRegressor\n\n# Split data into training and validation sets\nX_train_split, X_val_split, y_train_split, y_val_split = train_test_split(\n    X_train, y_train, test_size=0.2, random_state=42\n)","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:24:05.943947Z","iopub.execute_input":"2024-09-30T11:24:05.944258Z","iopub.status.idle":"2024-09-30T11:24:07.392048Z","shell.execute_reply.started":"2024-09-30T11:24:05.944220Z","shell.execute_reply":"2024-09-30T11:24:07.391225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom xgboost import XGBRegressor\n\n# Split data into training and validation sets\nX_train_split, X_val_split, y_train_split, y_val_split = train_test_split(\n    X_train, y_train, test_size=0.2, random_state=42\n)\n\n\n# Train a Linear Regression model\nlr_model = LinearRegression()\nlr_model.fit(X_train_split, y_train_split)\nlr_predictions = lr_model.predict(X_val_split)\nlr_rmse = np.sqrt(mean_squared_error(y_val_split, lr_predictions))\nprint(f\"Linear Regression RMSE: {lr_rmse}\")\n\n# Train a Random Forest model\nrf_model = RandomForestRegressor(n_estimators=100, random_state=42)\nrf_model.fit(X_train_split, y_train_split)\nrf_predictions = rf_model.predict(X_val_split)\nrf_rmse = np.sqrt(mean_squared_error(y_val_split, rf_predictions))\nprint(f\"Random Forest RMSE: {rf_rmse}\")\n\n# Train an XGBoost model\nxgb_model = XGBRegressor(objective='reg:squarederror', n_estimators=100, random_state=42)\nxgb_model.fit(X_train_split, y_train_split)\nxgb_predictions = xgb_model.predict(X_val_split)\nxgb_rmse = np.sqrt(mean_squared_error(y_val_split, xgb_predictions))\nprint(f\"XGBoost RMSE: {xgb_rmse}\")\n\n\n# Choose the best model based on validation performance and make predictions on the test set\nbest_model = xgb_model  # Replace with the model that performed best on the validation set\ntest_predictions = best_model.predict(X_test)\n\n# Create a submission DataFrame\nsubmission_df['bg+1:00'] = test_predictions\n\n# Save the submission file\nsubmission_df.to_csv('submission.csv', index=False)\n'''","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:24:07.393252Z","iopub.execute_input":"2024-09-30T11:24:07.393579Z","iopub.status.idle":"2024-09-30T11:24:07.401472Z","shell.execute_reply.started":"2024-09-30T11:24:07.393546Z","shell.execute_reply":"2024-09-30T11:24:07.400488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\n# Split data into training and validation sets\nX_train_split, X_val_split, y_train_split, y_val_split = train_test_split(\n    X_train, y_train, test_size=0.2, random_state=42\n)\n\n\n# Check if a GPU is available\nif tf.config.list_physical_devices('GPU'):\n    print(\"GPU is available\")\n    # Set the device to use the GPU\n    with tf.device('/GPU:0'):\n        # Define the model with more layers and neurons, dropout, and L2 regularization\n        model = keras.Sequential([\n            layers.Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01), input_shape=(X_train.shape[1],)),\n            layers.Dropout(0.4),\n            layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01)),\n            layers.Dropout(0.4),\n            layers.Dense(128, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01)),\n            layers.Dense(1)  # Output layer for regression\n        ])\n\n        # Compile the model with a different optimizer and learning rate\n        model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.0005), loss='mse', metrics=['mse'])\n\n        # Train the model with more epochs and a different batch size\n        history = model.fit(X_train, y_train, epochs=200, batch_size=128, validation_split=0.2)\n\n        # Evaluate the model\n        loss, mse = model.evaluate(X_val_split, y_val_split)\n        print(f\"ANN MSE: {mse}\")\n        ann_rmse = np.sqrt(mse)\n        print(f\"ANN RMSE: {ann_rmse}\")\n\n        # Make predictions on the test set\n        test_predictions = model.predict(X_test)\n\n        # Create a submission DataFrame\n        submission_df['bg+1:00'] = test_predictions\n\n        # Save the submission file\n        submission_df.to_csv('submission_ann_improved_gpu.csv', index=False)\nelse:\n    print(\"GPU is not available, using CPU\")\n\n    # Define the model with more layers and neurons, dropout, and L2 regularization\n    model = keras.Sequential([\n        layers.Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01), input_shape=(X_train.shape[1],)),\n        layers.Dropout(0.4),\n        layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01)),\n        layers.Dropout(0.4),\n        layers.Dense(128, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01)),\n        layers.Dense(1)  # Output layer for regression\n    ])\n\n    # Compile the model with a different optimizer and learning rate\n    model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.0005), loss='mse', metrics=['mse'])\n\n    # Train the model with more epochs and a different batch size\n    history = model.fit(X_train, y_train, epochs=200, batch_size=128, validation_split=0.2)\n\n    # Evaluate the model\n    loss, mse = model.evaluate(X_val_split, y_val_split)\n    print(f\"ANN MSE: {mse}\")\n    ann_rmse = np.sqrt(mse)\n    print(f\"ANN RMSE: {ann_rmse}\")\n\n    # Make predictions on the test set\n    test_predictions = model.predict(X_test)\n\n    # Create a submission DataFrame\n    submission_df['bg+1:00'] = test_predictions\n\n    # Save the submission file\n    submission_df.to_csv('submission.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:25:18.546277Z","iopub.execute_input":"2024-09-30T11:25:18.546656Z","iopub.status.idle":"2024-09-30T11:32:50.497728Z","shell.execute_reply.started":"2024-09-30T11:25:18.546620Z","shell.execute_reply":"2024-09-30T11:32:50.496963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check if a GPU is available\nif tf.config.list_physical_devices('GPU'):\n    print(\"GPU is available\")\n    # Set the device to use the GPU\n    with tf.device('/GPU:0'):\n        # Define the model with more layers and neurons, dropout, and L2 regularization\n        model = keras.Sequential([\n            layers.Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01), input_shape=(X_train.shape[1],)),\n            layers.Dropout(0.4),\n            layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01)),\n            layers.Dropout(0.4),\n            layers.Dense(128, activation='relu', kernel_regularizer=keras.regularizers.l2(0.01)),\n            layers.Dense(1)  # Output layer for regression\n        ])\n\n        # Compile the model with a different optimizer and learning rate\n        model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.0005), loss='mse', metrics=['mse'])\n\n        # Train the model with more epochs and a different batch size\n        history = model.fit(X_train, y_train, epochs=200, batch_size=128, validation_split=0.2)\n\n        # Evaluate the model\n        loss, mse = model.evaluate(X_val_split, y_val_split)\n        print(f\"ANN MSE: {mse}\")\n        ann_rmse = np.sqrt(mse)\n        print(f\"ANN RMSE: {ann_rmse}\")\n\n        # Make predictions on the test set\n        test_predictions = model.predict(X_test)\n\n        # Create a submission DataFrame\n        submission_df['bg+1:00'] = test_predictions\n\n        # Save the submission file\n        submission_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-09-30T11:32:57.122790Z","iopub.execute_input":"2024-09-30T11:32:57.123185Z","iopub.status.idle":"2024-09-30T11:40:25.318150Z","shell.execute_reply.started":"2024-09-30T11:32:57.123148Z","shell.execute_reply":"2024-09-30T11:40:25.317365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}