{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[![Open in Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/justmarkham/scikit-learn-tips/master?filepath=notebooks%2F45_feature_interactions.ipynb)\n", "\n", "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/justmarkham/scikit-learn-tips/blob/master/notebooks/45_feature_interactions.ipynb)\n", "\n", "# 🤖⚡ scikit-learn tip #45 ([video](https://www.youtube.com/watch?v=unP3rCfzROk&list=PL5-da3qGB5ID7YYAqireYEew2mWVvgmj6&index=45))\n", "\n", "Want to include \"feature interactions\" in your model? Use PolynomialFeatures!\n", "\n", "See example 👇\n", "\n", "P.S. This is impractical if you have lots of features, and unnecessary if you're using a tree-based model." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "X = pd.DataFrame({'A':[1, 2, 3], 'B':[4, 4, 4], 'C':[0, 10, 100]})" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from sklearn.preprocessing import PolynomialFeatures\n", "poly = PolynomialFeatures(include_bias=False, interaction_only=True)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ABC
0140
12410
234100
\n", "
" ], "text/plain": [ " A B C\n", "0 1 4 0\n", "1 2 4 10\n", "2 3 4 100" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[ 1., 4., 0., 4., 0., 0.],\n", " [ 2., 4., 10., 8., 20., 40.],\n", " [ 3., 4., 100., 12., 300., 400.]])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Output columns: A, B, C, A*B, A*C, B*C\n", "poly.fit_transform(X)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Want more tips? [View all tips on GitHub](https://github.com/justmarkham/scikit-learn-tips) or [Sign up to receive 2 tips by email every week](https://scikit-learn.tips) 💌\n", "\n", "© 2020 [Data School](https://www.dataschool.io). All rights reserved." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.4" } }, "nbformat": 4, "nbformat_minor": 4 }