{"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":"none","dataSources":[{"sourceId":84253,"databundleVersionId":9421888,"sourceType":"competition"}],"dockerImageVersionId":30761,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression, Ridge\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, HistGradientBoostingRegressor, StackingRegressor\nfrom sklearn import feature_selection\nfrom sklearn.model_selection import KFold, GridSearchCV\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\n\n\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-08-24T12:48:51.163379Z","iopub.execute_input":"2024-08-24T12:48:51.163797Z","iopub.status.idle":"2024-08-24T12:48:51.174167Z","shell.execute_reply.started":"2024-08-24T12:48:51.163760Z","shell.execute_reply":"2024-08-24T12:48:51.172777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/first-steps-in-data-science-new/train (7).csv')\ntest = pd.read_csv('/kaggle/input/first-steps-in-data-science-new/test (4).csv')","metadata":{"execution":{"iopub.status.busy":"2024-08-24T12:16:33.014821Z","iopub.execute_input":"2024-08-24T12:16:33.015368Z","iopub.status.idle":"2024-08-24T12:16:36.037791Z","shell.execute_reply.started":"2024-08-24T12:16:33.015323Z","shell.execute_reply":"2024-08-24T12:16:36.036905Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape","metadata":{"execution":{"iopub.status.busy":"2024-08-24T12:16:36.039155Z","iopub.execute_input":"2024-08-24T12:16:36.039592Z","iopub.status.idle":"2024-08-24T12:16:36.048026Z","shell.execute_reply.started":"2024-08-24T12:16:36.039535Z","shell.execute_reply":"2024-08-24T12:16:36.046751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.describe().iloc[:, [0, -1]]","metadata":{"execution":{"iopub.status.busy":"2024-08-24T12:16:36.050344Z","iopub.execute_input":"2024-08-24T12:16:36.050847Z","iopub.status.idle":"2024-08-24T12:16:36.481611Z","shell.execute_reply.started":"2024-08-24T12:16:36.050799Z","shell.execute_reply":"2024-08-24T12:16:36.480456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_folds = 30\nweights = []\nkf = KFold(n_splits=n_folds, shuffle=True, random_state=42)\ntrain_data = train.iloc[:, :-1]\ntrain_target = train.iloc[:, -1]\nmodel = RandomForestRegressor(n_estimators=100, random_state=42)\nestimator = LinearRegression()\nselector = feature_selection.RFECV(estimator)\nselector.fit(train_data, train_target)\nrfe_train_data = train_data.iloc[:, selector.support_]\ntest_data = test.iloc[:, selector.support_]\ntest_preds = np.zeros((test_data.shape[0],))\n","metadata":{"execution":{"iopub.status.busy":"2024-08-24T12:50:06.385427Z","iopub.execute_input":"2024-08-24T12:50:06.387003Z","iopub.status.idle":"2024-08-24T12:52:20.584761Z","shell.execute_reply.started":"2024-08-24T12:50:06.386942Z","shell.execute_reply":"2024-08-24T12:52:20.583578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_models = [\n    ('ridge', Ridge(alpha=1.0)),\n    ('rf', RandomForestRegressor(n_estimators=100, random_state=42)),\n]\nmeta_model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42)\nstacking_model = StackingRegressor(estimators=base_models, final_estimator=meta_model)\nfor fold, (train_idx, val_idx) in enumerate(kf.split(train)):\n    X_train, y_train = rfe_train_data.iloc[train_idx], train_target.iloc[train_idx]\n    X_val, y_val = rfe_train_data.iloc[val_idx], train_target.iloc[val_idx]\n\n    stacking_model.fit(X_train, y_train)\n\n    val_preds = stacking_model.predict(X_val)\n    fold_rmse = mean_squared_error(y_val, val_preds, squared=False)\n    \n    weights.append(1 / fold_rmse)\n    \n    print(f'Fold {fold+1} RMSE: {fold_rmse}')\n    \n    test_preds += stacking_model.predict(test_data) * weights[fold]\n\ntest_preds /= sum(weights)\n\nprint(test_preds)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv('/kaggle/input/first-steps-in-data-science-new/sample.csv')\nsubmission['target'] = test_preds\nsubmission.to_csv('submission.csv', index = False)","metadata":{"execution":{"iopub.status.busy":"2024-08-24T12:35:33.037139Z","iopub.execute_input":"2024-08-24T12:35:33.037564Z","iopub.status.idle":"2024-08-24T12:35:33.100353Z","shell.execute_reply.started":"2024-08-24T12:35:33.037514Z","shell.execute_reply":"2024-08-24T12:35:33.099370Z"},"trusted":true},"execution_count":null,"outputs":[]}]}