{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"**This notebook is an exercise in the [Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning) course.  You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/xgboost).**\n\n---\n","metadata":{}},{"cell_type":"markdown","source":"In this exercise, you will use your new knowledge to train a model with **gradient boosting**.\n\n# Setup\n\nThe questions below will give you feedback on your work. Run the following cell to set up the feedback system.","metadata":{}},{"cell_type":"code","source":"# Set up code checking\nimport os\nif not os.path.exists(\"../input/train.csv\"):\n    os.symlink(\"../input/home-data-for-ml-course/train.csv\", \"../input/train.csv\")  \n    os.symlink(\"../input/home-data-for-ml-course/test.csv\", \"../input/test.csv\") \nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.ml_intermediate.ex6 import *\nprint(\"Setup Complete\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"You will work with the [Housing Prices Competition for Kaggle Learn Users](https://www.kaggle.com/c/home-data-for-ml-course) dataset from the previous exercise. \n\n![Ames Housing dataset image](https://i.imgur.com/lTJVG4e.png)\n\nRun the next code cell without changes to load the training and validation sets in `X_train`, `X_valid`, `y_train`, and `y_valid`.  The test set is loaded in `X_test`.","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n# Read the data\nX_full = pd.read_csv('../input/train.csv', index_col='Id')\nX_test_full = pd.read_csv('../input/test.csv', index_col='Id')\n\n# Remove rows with missing target, separate target from predictors\nX_full.dropna(axis=0, subset=['SalePrice'], inplace=True)\ny = X_full.SalePrice\nX_full.drop(['SalePrice'], axis=1, inplace=True)\n\n# Break off validation set from training data\nX_train_full, X_valid_full, y_train, y_valid = train_test_split(X_full, y, \n                                                                train_size=0.8, test_size=0.2,\n                                                                random_state=0)\n\n# \"Cardinality\" means the number of unique values in a column\n# Select categorical columns with relatively low cardinality (convenient but arbitrary)\ncategorical_cols = [cname for cname in X_train_full.columns if\n                    X_train_full[cname].nunique() < 10 and \n                    X_train_full[cname].dtype == \"object\"]\n\n# Select numerical columns\nnumerical_cols = [cname for cname in X_train_full.columns if \n                X_train_full[cname].dtype in ['int64', 'float64']]\n\n# Keep selected columns only\nmy_cols = categorical_cols + numerical_cols\nX_train = X_train_full[my_cols].copy()\nX_valid = X_valid_full[my_cols].copy()\nX_test = X_test_full[my_cols].copy()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 1: Build model\n\n### Part A\n\nIn this step, you'll build and train your first model with gradient boosting.\n\n- Begin by setting `my_model_1` to an XGBoost model.  Use the [XGBRegressor](https://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.XGBRegressor) class, and set the random seed to 0 (`random_state=0`).  **Leave all other parameters as default.**\n- Then, fit the model to the training data in `X_train` and `y_train`.","metadata":{}},{"cell_type":"code","source":"from xgboost import XGBRegressor\n\n# Define the model\n#my_model_1 = XGBRegressor() # Your code here\n\n# Fit the model\n#my_model_1.fit(X_train,y_train) # Your code here\n\n# Check your answer\n#step_1.a.check()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lines below will give you a hint or solution code\n#step_1.a.hint()\n#step_1.a.solution()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Part B\n\nSet `predictions_1` to the model's predictions for the validation data.  Recall that the validation features are stored in `X_valid`.","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import mean_absolute_error\n\n# Get predictions\n#predictions_1 = my_model_1.predict(X_valid) # Your code here\n\n# Check your answer\n#step_1.b.check()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lines below will give you a hint or solution code\n#step_1.b.hint()\n#step_1.b.solution()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Part C\n\nFinally, use the `mean_absolute_error()` function to calculate the mean absolute error (MAE) corresponding to the predictions for the validation set.  Recall that the labels for the validation data are stored in `y_valid`.","metadata":{}},{"cell_type":"code","source":"# Calculate MAE\n#mae_1 = mean_absolute_error(y_valid,predictions_1) # Your code here\n\n# Uncomment to print MAE\n#print(\"Mean Absolute Error:\" , mae_1)\n\n# Check your answer\n#step_1.c.check()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lines below will give you a hint or solution code\n#step_1.c.hint()\n#step_1.c.solution()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 2: Improve the model\n\nNow that you've trained a default model as baseline, it's time to tinker with the parameters, to see if you can get better performance!\n- Begin by setting `my_model_2` to an XGBoost model, using the [XGBRegressor](https://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.XGBRegressor) class.  Use what you learned in the previous tutorial to figure out how to change the default parameters (like `n_estimators` and `learning_rate`) to get better results.\n- Then, fit the model to the training data in `X_train` and `y_train`.\n- Set `predictions_2` to the model's predictions for the validation data.  Recall that the validation features are stored in `X_valid`.\n- Finally, use the `mean_absolute_error()` function to calculate the mean absolute error (MAE) corresponding to the predictions on the validation set.  Recall that the labels for the validation data are stored in `y_valid`.\n\nIn order for this step to be marked correct, your model in `my_model_2` must attain lower MAE than the model in `my_model_1`. ","metadata":{}},{"cell_type":"code","source":"# Define the model\nmy_model_2 = XGBRegressor(n_estimators=1000, learning_rate=0.05) # Your code here\n\n# Fit the model\n#my_model_2.fit(X_train, y_train, \n             #early_stopping_rounds=5, \n            # eval_set=[(X_valid, y_valid)], \n            # verbose=False)\n\n# Get predictions\n#predictions_2 = my_model_2.predict(X_valid) # Your code here\n\n# Calculate MAE\n#mae_2 = mean_absolute_error(y_valid,predictions_2) # Your code here\n\n# Uncomment to print MAE\n#print(\"Mean Absolute Error:\" , mae_2)\n\n# Check your answer\n#step_2.check()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lines below will give you a hint or solution code\n#step_2.hint()\n#step_2.solution()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 3: Break the model\n\nIn this step, you will create a model that performs worse than the original model in Step 1.  This will help you to develop your intuition for how to set parameters.  You might even find that you accidentally get better performance, which is ultimately a nice problem to have and a valuable learning experience!\n- Begin by setting `my_model_3` to an XGBoost model, using the [XGBRegressor](https://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.XGBRegressor) class.  Use what you learned in the previous tutorial to figure out how to change the default parameters (like `n_estimators` and `learning_rate`) to design a model to get high MAE.\n- Then, fit the model to the training data in `X_train` and `y_train`.\n- Set `predictions_3` to the model's predictions for the validation data.  Recall that the validation features are stored in `X_valid`.\n- Finally, use the `mean_absolute_error()` function to calculate the mean absolute error (MAE) corresponding to the predictions on the validation set.  Recall that the labels for the validation data are stored in `y_valid`.\n\nIn order for this step to be marked correct, your model in `my_model_3` must attain higher MAE than the model in `my_model_1`. ","metadata":{}},{"cell_type":"code","source":"# Define the model\n#my_model_3 = XGBRegressor(n_estimators=50, learning_rate=0.005) # Your code here\n\n# Fit the model\n#my_model_3.fit(X_train, y_train, \n             #early_stopping_rounds=2, \n             #eval_set=[(X_valid, y_valid)], \n             #verbose=False)\n\n# Get predictions\n#predictions_3 = my_model_3.predict(X_valid) # Your code here\n\n# Calculate MAE\n#mae_3 = mean_absolute_error(y_valid,predictions_3) # Your code here\n\n# Uncomment to print MAE\n#print(\"Mean Absolute Error:\" , mae_3)\n\n# Check your answer\n#step_3.check()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lines below will give you a hint or solution code\n#step_3.hint()\n#step_3.solution()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBRegressor\nfrom sklearn.metrics import mean_absolute_error\n\n# Read the data\nX_full = pd.read_csv('../input/train.csv', index_col='Id')\nX_test_full = pd.read_csv('../input/test.csv', index_col='Id')\n\n# Remove rows with missing target, separate target from predictors\nX_full.dropna(axis=0, subset=['SalePrice'], inplace=True)\ny = X_full.SalePrice\nX_full.drop(['SalePrice'], axis=1, inplace=True)\n\n# Break off validation set from training data\nX_train_full, X_valid_full, y_train, y_valid = train_test_split(X_full, y, \n                                                                train_size=0.8, test_size=0.2,\n                                                                random_state=0)\n\n# \"Cardinality\" means the number of unique values in a column\n# Select categorical columns with relatively low cardinality (convenient but arbitrary)\ncategorical_cols = [cname for cname in X_train_full.columns if\n                    X_train_full[cname].nunique() < 10 and \n                    X_train_full[cname].dtype == \"object\"]\n\n# Select numerical columns\nnumerical_cols = [cname for cname in X_train_full.columns if \n                X_train_full[cname].dtype in ['int64', 'float64']]\n\n# Keep selected columns only\nmy_cols = categorical_cols + numerical_cols\nX_train = X_train_full[my_cols].copy()\nX_valid = X_valid_full[my_cols].copy()\nX_test = X_test_full[my_cols].copy()\n\n#construccion del modelo XGB\nmy_model_2 = XGBRegressor(n_estimators=1000, learning_rate=0.05)\n\n# Preprocessing for numerical data\nnumerical_transformer = SimpleImputer(strategy='mean') # esta modulo es para llenar los valores nulos con la media\n              \n# Preprocessing for categorical data                #este modulo realiza la transformacion de variables\n                                                    #categoricas y la imputación de nulos en un solo paso\n                                                    #Se puede adicionar el método OrdinalEncoder para las variables con alta\n                                                    #cardinalidad\ncategorical_transformer = Pipeline(steps=[\n    ('imputer', SimpleImputer(strategy='most_frequent')),\n    ('onehot', OneHotEncoder(handle_unknown='ignore'))\n]) # Your code here\n\n# Bundle preprocessing for numerical and categorical data      #en este codigo se hace la transformacion de las variables\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num', numerical_transformer, numerical_cols),\n        ('cat', categorical_transformer, categorical_cols)\n    ])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Bundle preprocessing and modeling code in a pipeline\nmy_pipeline = Pipeline(steps=[('preprocessor', preprocessor), #con este codigo se vincula el proceso de transformacion\n                              ('model', my_model_2)           #de variables con el modelo, de esta manera en un pipeline \n                             ])                               #unicamente se cambia el dataframe y se ejecuta un modelo nuevo\n\n# Preprocessing of training data, fit model \nmy_pipeline.fit(X_train, y_train,                            #con este codigo se entrena el modelo\n             early_stopping_rounds=5, \n             eval_set=[(X_valid, y_valid)], \n             verbose=False)\n\n# Preprocessing of validation data, get predictions\npreds = my_pipeline.predict(X_valid)                        #devuelve los predictos\n\n# Evaluate the model\nscore = mean_absolute_error(y_valid, preds)                 #se evalua el modelo con el MAE\nprint('MAE:', score)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save test predictions to file\npreds_test = my_pipeline.predict(X_test)\noutput = pd.DataFrame({'Id': X_test.index,\n                       'SalePrice': preds_test})\noutput.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Keep going\n\nContinue to learn about **[data leakage](https://www.kaggle.com/alexisbcook/data-leakage)**.  This is an important issue for a data scientist to understand, and it has the potential to ruin your models in subtle and dangerous ways!","metadata":{}},{"cell_type":"markdown","source":"---\n\n\n\n\n*Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum/161289) to chat with other Learners.*","metadata":{}}]}