{"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":"**[Introduction to Machine Learning Home Page](https://www.kaggle.com/learn/intro-to-machine-learning)**\n\n---\n","metadata":{}},{"cell_type":"markdown","source":"# Introduction\nMachine learning competitions are a great way to improve your data science skills and measure your progress. \n\nIn this exercise, you will create and submit predictions for a Kaggle competition. You can then improve your model (e.g. by adding features) to improve and see how you stack up to others taking this micro-course.\n\nThe steps in this notebook are:\n1. Build a Random Forest model with all of your data (**X** and **y**)\n2. Read in the \"test\" data, which doesn't include values for the target.  Predict home values in the test data with your Random Forest model.\n3. Submit those predictions to the competition and see your score.\n4. Optionally, come back to see if you can improve your model by adding features or changing your model. Then you can resubmit to see how that stacks up on the competition leaderboard.","metadata":{}},{"cell_type":"markdown","source":"## Recap\nHere's the code you've written so far. Start by running it again.","metadata":{}},{"cell_type":"code","source":"# Code you have previously used to load data\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\n\n# 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.machine_learning.ex7 import *\n\n# Path of the file to read. We changed the directory structure to simplify submitting to a competition\niowa_file_path = '../input/train.csv'\n\nhome_data = pd.read_csv(iowa_file_path)\n# Create target object and call it y\ny = home_data.SalePrice\n# Create X\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\nX = home_data[features]\n\n# Split into validation and training data\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)\n\n# Specify Model\niowa_model = DecisionTreeRegressor(random_state=1)\n# Fit Model\niowa_model.fit(train_X, train_y)\n\n# Make validation predictions and calculate mean absolute error\nval_predictions = iowa_model.predict(val_X)\nval_mae = mean_absolute_error(val_predictions, val_y)\nprint(\"Validation MAE when not specifying max_leaf_nodes: {:,.0f}\".format(val_mae))\n\n# Using best value for max_leaf_nodes\niowa_model = DecisionTreeRegressor(max_leaf_nodes=100, random_state=1)\niowa_model.fit(train_X, train_y)\nval_predictions = iowa_model.predict(val_X)\nval_mae = mean_absolute_error(val_predictions, val_y)\nprint(\"Validation MAE for best value of max_leaf_nodes: {:,.0f}\".format(val_mae))\n\n# Define the model. Set random_state to 1\nrf_model = RandomForestRegressor(random_state=1)\nrf_model.fit(train_X, train_y)\nrf_val_predictions = rf_model.predict(val_X)\nrf_val_mae = mean_absolute_error(rf_val_predictions, val_y)\n\nprint(\"Validation MAE for Random Forest Model: {:,.0f}\".format(rf_val_mae))","metadata":{"execution":{"iopub.status.busy":"2022-08-03T14:02:00.972497Z","iopub.execute_input":"2022-08-03T14:02:00.972814Z","iopub.status.idle":"2022-08-03T14:02:03.780600Z","shell.execute_reply.started":"2022-08-03T14:02:00.972766Z","shell.execute_reply":"2022-08-03T14:02:03.779728Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating a Model For the Competition\n\nBuild a Random Forest model and train it on all of **X** and **y**.","metadata":{}},{"cell_type":"code","source":"# To improve accuracy, create a new Random Forest model which you will train on all training data\nrf_model_on_full_data = RandomForestRegressor(random_state=1)\n\n# fit rf_model_on_full_data on all data from the training data\nrf_model.fit(X, y)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T14:05:04.967810Z","iopub.execute_input":"2022-08-03T14:05:04.968162Z","iopub.status.idle":"2022-08-03T14:05:05.038966Z","shell.execute_reply.started":"2022-08-03T14:05:04.968105Z","shell.execute_reply":"2022-08-03T14:05:05.037673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Make Predictions\nRead the file of \"test\" data. And apply your model to make predictions","metadata":{}},{"cell_type":"code","source":"# path to file you will use for predictions\ntest_data_path = '../input/test.csv'\n\n# read test data file using pandas\ntest_data = pd.read_csv(test_data_path)\n\n# create test_X which comes from test_data but includes only the columns you used for prediction.\n# The list of columns is stored in a variable called features\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\ntest_X = test_data[features]\n\n# make predictions which we will submit. \ntest_preds = rf_model.predict(test_X)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T14:05:18.464706Z","iopub.execute_input":"2022-08-03T14:05:18.465186Z","iopub.status.idle":"2022-08-03T14:05:18.515980Z","shell.execute_reply.started":"2022-08-03T14:05:18.465134Z","shell.execute_reply":"2022-08-03T14:05:18.515113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Before submitting, run a check to make sure your `test_preds` have the right format.","metadata":{}},{"cell_type":"code","source":"# Check your answer\nstep_1.check()\n# step_1.solution()","metadata":{"execution":{"iopub.status.busy":"2022-08-03T14:05:29.763674Z","iopub.execute_input":"2022-08-03T14:05:29.764283Z","iopub.status.idle":"2022-08-03T14:05:29.770366Z","shell.execute_reply.started":"2022-08-03T14:05:29.764232Z","shell.execute_reply":"2022-08-03T14:05:29.769783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Run the code to save predictions in the format used for competition scoring\n\noutput = pd.DataFrame({'Id': test_data.Id,\n                       'SalePrice': test_preds})\noutput.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-03T14:07:19.559172Z","iopub.execute_input":"2022-08-03T14:07:19.559556Z","iopub.status.idle":"2022-08-03T14:07:19.571569Z","shell.execute_reply.started":"2022-08-03T14:07:19.559492Z","shell.execute_reply":"2022-08-03T14:07:19.570746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Test Your Work\n\nTo test your results, you'll need to join the competition (if you haven't already).  So open a new window by clicking on [this link](https://www.kaggle.com/c/home-data-for-ml-course).  Then click on the **Join Competition** button.\n\n![join competition image](https://i.imgur.com/wLmFtH3.png)\n\nNext, follow the instructions below:\n1. Begin by clicking on the blue **COMMIT** button in the top right corner of this window.  This will generate a pop-up window.  \n2. After your code has finished running, click on the blue **Open Version** button in the top right of the pop-up window.  This brings you into view mode of the same page. You will need to scroll down to get back to these instructions.\n3. Click on the **Output** tab on the left of the screen.  Then, click on the **Submit to Competition** button to submit your results to the leaderboard.\n\nYou have now successfully submitted to the competition!\n\n4. If you want to keep working to improve your performance, select the blue **Edit** button in the top right of the screen. Then you can change your model and repeat the process. There's a lot of room to improve your model, and you will climb up the leaderboard as you work.\n\n# Continuing Your Progress\nThere are many ways to improve your model, and **experimenting is a great way to learn at this point.**\n\nThe best way to improve your model is to add features.  Look at the list of columns and think about what might affect home prices.  Some features will cause errors because of issues like missing values or non-numeric data types. \n\nThe **[Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning)** micro-course will teach you how to handle these types of features. You will also learn to use **xgboost**, a technique giving even better accuracy than Random Forest.\n\n\n# Other Micro-Courses\nThe **[Pandas](https://kaggle.com/Learn/Pandas)** micro-course will give you the data manipulation skills to quickly go from conceptual idea to implementation in your data science projects. \n\nYou are also ready for the **[Deep Learning](https://kaggle.com/Learn/Deep-Learning)** micro-course, where you will build models with better-than-human level performance at computer vision tasks.","metadata":{}},{"cell_type":"markdown","source":"---\n**[Introduction to Machine Learning Home Page](https://www.kaggle.com/learn/intro-to-machine-learning)**\n\n\n\n\n\n*Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum) to chat with other Learners.*","metadata":{}}]}