Skip to content

Commit 0a2579f

Browse files
authored
Add files via upload
1 parent 1181a12 commit 0a2579f

6 files changed

+6
-0
lines changed

exercise-5-random-forests.ipynb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"**This notebook is an exercise in the [Introduction to Machine Learning](https://www.kaggle.com/learn/intro-to-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/dansbecker/random-forests).**\n\n---\n","metadata":{}},{"cell_type":"markdown","source":"## Recap\nHere's the code you've written so far.","metadata":{}},{"cell_type":"code","source":"# Code you have previously used to load data\nimport pandas as pd\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\n\n\n# Path of the file to read\niowa_file_path = '../input/home-data-for-ml-course/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\n# Set up code checking\nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.machine_learning.ex6 import *\nprint(\"\\nSetup complete\")","metadata":{"execution":{"iopub.status.busy":"2021-12-12T15:12:24.431519Z","iopub.execute_input":"2021-12-12T15:12:24.431916Z","iopub.status.idle":"2021-12-12T15:12:25.657602Z","shell.execute_reply.started":"2021-12-12T15:12:24.431816Z","shell.execute_reply":"2021-12-12T15:12:25.656639Z"},"trusted":true},"execution_count":1,"outputs":[]},{"cell_type":"markdown","source":"# Exercises\nData science isn't always this easy. But replacing the decision tree with a Random Forest is going to be an easy win.","metadata":{}},{"cell_type":"markdown","source":"## Step 1: Use a Random Forest","metadata":{}},{"cell_type":"code","source":"from sklearn.ensemble import RandomForestRegressor\n\n# Define the model. Set random_state to 1\nrf_model = RandomForestRegressor()\n\n# fit your model\nrf_model.fit(train_X, train_y)\n\n\n# Calculate the mean absolute error of your Random Forest model on the validation data\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: {}\".format(rf_val_mae))\n\n# Check your answer\nstep_1.check()","metadata":{"execution":{"iopub.status.busy":"2021-12-12T15:13:24.392239Z","iopub.execute_input":"2021-12-12T15:13:24.392569Z","iopub.status.idle":"2021-12-12T15:13:24.922913Z","shell.execute_reply.started":"2021-12-12T15:13:24.392538Z","shell.execute_reply":"2021-12-12T15:13:24.921925Z"},"trusted":true},"execution_count":2,"outputs":[]},{"cell_type":"code","source":"# The lines below will show you a hint or the solution.\n# step_1.hint() \n# step_1.solution()\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"So far, you have followed specific instructions at each step of your project. This helped learn key ideas and build your first model, but now you know enough to try things on your own. \n\nMachine Learning competitions are a great way to try your own ideas and learn more as you independently navigate a machine learning project. \n\n# Keep Going\n\nYou are ready for **[Machine Learning Competitions](https://www.kaggle.com/alexisbcook/machine-learning-competitions).**\n","metadata":{}},{"cell_type":"markdown","source":"---\n\n\n\n\n*Have questions or comments? Visit the [course discussion forum](https://www.kaggle.com/learn/intro-to-machine-learning/discussion) to chat with other learners.*","metadata":{}}]}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"**This notebook is an exercise in the [Introduction to Machine Learning](https://www.kaggle.com/learn/intro-to-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/machine-learning-competitions).**\n\n---\n","metadata":{}},{"cell_type":"markdown","source":"# Introduction\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 apply what you've learned and move up the leaderboard.\n\nBegin by running the code cell below to set up code checking and the filepaths for the dataset.","metadata":{}},{"cell_type":"code","source":"# Set up code checking\nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.machine_learning.ex7 import *\n\n# Set up filepaths\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\") ","metadata":{"execution":{"iopub.status.busy":"2021-12-12T15:14:57.573266Z","iopub.execute_input":"2021-12-12T15:14:57.573878Z","iopub.status.idle":"2021-12-12T15:14:57.637712Z","shell.execute_reply.started":"2021-12-12T15:14:57.573762Z","shell.execute_reply":"2021-12-12T15:14:57.637057Z"},"trusted":true},"execution_count":1,"outputs":[]},{"cell_type":"markdown","source":"Here's some of the code you've written so far. Start by running it again.","metadata":{}},{"cell_type":"code","source":"# Import helpful libraries\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\n\n# Load the data, and separate the target\niowa_file_path = '../input/train.csv'\nhome_data = pd.read_csv(iowa_file_path)\ny = home_data.SalePrice\n\n# Create X (After completing the exercise, you can return to modify this line!)\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\n\n# Select columns corresponding to features, and preview the data\nX = home_data[features]\nX.head()\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# Define a random forest model\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":"2021-12-12T15:15:08.999706Z","iopub.execute_input":"2021-12-12T15:15:09.000185Z","iopub.status.idle":"2021-12-12T15:15:10.861311Z","shell.execute_reply.started":"2021-12-12T15:15:09.000146Z","shell.execute_reply":"2021-12-12T15:15:10.860701Z"},"trusted":true},"execution_count":2,"outputs":[]},{"cell_type":"markdown","source":"# Train a model for the competition\n\nThe code cell above trains a Random Forest model on **`train_X`** and **`train_y`**. \n\nUse the code cell below to build 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()\n\n# fit rf_model_on_full_data on all data from the training data\nrf_model_on_full_data.fit(X, y)\n","metadata":{"execution":{"iopub.status.busy":"2021-12-12T15:15:33.364423Z","iopub.execute_input":"2021-12-12T15:15:33.364692Z","iopub.status.idle":"2021-12-12T15:15:33.983763Z","shell.execute_reply.started":"2021-12-12T15:15:33.364663Z","shell.execute_reply":"2021-12-12T15:15:33.983186Z"},"trusted":true},"execution_count":3,"outputs":[]},{"cell_type":"markdown","source":"Now, read 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 = test_data = pd.read_csv(test_data_path)\n\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\ntest_X = test_data[features]\n\n# make predictions which we will submit. \ntest_preds = rf_model_on_full_data.predict(test_X)\n","metadata":{"execution":{"iopub.status.busy":"2021-12-12T15:23:30.870866Z","iopub.execute_input":"2021-12-12T15:23:30.871644Z","iopub.status.idle":"2021-12-12T15:23:30.944195Z","shell.execute_reply.started":"2021-12-12T15:23:30.871599Z","shell.execute_reply":"2021-12-12T15:23:30.943584Z"},"trusted":true},"execution_count":5,"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 (To get credit for completing the exercise, you must get a \"Correct\" result!)\nstep_1.check()\n# step_1.solution()","metadata":{"execution":{"iopub.status.busy":"2021-12-12T15:23:34.078801Z","iopub.execute_input":"2021-12-12T15:23:34.079076Z","iopub.status.idle":"2021-12-12T15:23:34.087494Z","shell.execute_reply.started":"2021-12-12T15:23:34.079047Z","shell.execute_reply":"2021-12-12T15:23:34.086469Z"},"trusted":true},"execution_count":6,"outputs":[]},{"cell_type":"markdown","source":"# Generate a submission\n\nRun the code cell below to generate a CSV file with your predictions that you can use to submit to the competition.","metadata":{}},{"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":"2021-12-12T15:23:58.412230Z","iopub.execute_input":"2021-12-12T15:23:58.412523Z","iopub.status.idle":"2021-12-12T15:23:58.424860Z","shell.execute_reply.started":"2021-12-12T15:23:58.412492Z","shell.execute_reply":"2021-12-12T15:23:58.424195Z"},"trusted":true},"execution_count":8,"outputs":[]},{"cell_type":"markdown","source":"# Submit to the competition\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/axBzctl.png)\n\nNext, follow the instructions below:\n1. Begin by clicking on the **Save Version** button in the top right corner of the window. This will generate a pop-up window. \n2. Ensure that the **Save and Run All** option is selected, and then click on the **Save** button.\n3. This generates a window in the bottom left corner of the notebook. After it has finished running, click on the number to the right of the **Save Version** button. This pulls up a list of versions on the right of the screen. Click on the ellipsis **(...)** to the right of the most recent version, and select **Open in Viewer**. This brings you into view mode of the same page. You will need to scroll down to get back to these instructions.\n4. Click on the **Output** tab on the right of the screen. Then, click on the file you would like to submit, and click on the **Submit** button to submit your results to the leaderboard.\n\nYou have now successfully submitted to the competition!\n\nIf you want to keep working to improve your performance, select the **Edit** button in the top right of the screen. Then you can change your code and repeat the process. There's a lot of room to improve, and you will climb up the leaderboard as you work.\n\n\n# Continue 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. To add more features to the data, revisit the first code cell, and change this line of code to include more column names:\n```python\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\n```\n\nSome features will cause errors because of issues like missing values or non-numeric data types. Here is a complete list of potential columns that you might like to use, and that won't throw errors:\n- 'MSSubClass'\n- 'LotArea'\n- 'OverallQual' \n- 'OverallCond' \n- 'YearBuilt'\n- 'YearRemodAdd' \n- '1stFlrSF'\n- '2ndFlrSF' \n- 'LowQualFinSF' \n- 'GrLivArea'\n- 'FullBath'\n- 'HalfBath'\n- 'BedroomAbvGr' \n- 'KitchenAbvGr' \n- 'TotRmsAbvGrd' \n- 'Fireplaces' \n- 'WoodDeckSF' \n- 'OpenPorchSF'\n- 'EnclosedPorch' \n- '3SsnPorch' \n- 'ScreenPorch' \n- 'PoolArea' \n- 'MiscVal' \n- 'MoSold' \n- 'YrSold'\n\nLook at the list of columns and think about what might affect home prices. To learn more about each of these features, take a look at the data description on the **[competition page](https://www.kaggle.com/c/home-data-for-ml-course/data)**.\n\nAfter updating the code cell above that defines the features, re-run all of the code cells to evaluate the model and generate a new submission file. \n\n\n# What's next?\n\nAs mentioned above, some of the features will throw an error if you try to use them to train your model. The **[Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning)** 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\nThe **[Pandas](https://kaggle.com/Learn/Pandas)** 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/intro-to-Deep-Learning)** course, where you will build models with better-than-human level performance at computer vision tasks.","metadata":{}},{"cell_type":"markdown","source":"---\n\n\n\n\n*Have questions or comments? Visit the [course discussion forum](https://www.kaggle.com/learn/intro-to-machine-learning/discussion) to chat with other learners.*","metadata":{}}]}

0 commit comments

Comments
 (0)