{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25757137",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "# Initialize Otter\n",
    "import otter\n",
    "grader = otter.Notebook(\"practice09.ipynb\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-001",
   "metadata": {},
   "source": [
    "**Student names and e-mails:**\n",
    "\n",
    "_YOUR NAME — your@calvin.edu_\n",
    "\n",
    "_YOUR NAME — your@calvin.edu_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-002",
   "metadata": {},
   "source": [
    "# Practice 09 — Name That Genre: Logistic Regression, Random Forests and AdaBoost\n",
    "\n",
    "Open a playlist called \"Rock Classics\" and you know what to expect. But what makes a song *sound* like rock, or rap, or latin? Spotify describes every song with a handful of numbers: how danceable it is, how loud, how much of it is spoken words. Can a model hear the genre in those numbers?\n",
    "\n",
    "This practice trains the three models from this week's classes on the same songs, and compares them.\n",
    "\n",
    "| SLO | Description |\n",
    "|-----|-------------|\n",
    "| **11A** | Train and interpret logistic regression models for binary and multiclass classification |\n",
    "| **11B** | Train ensemble models (random forests, gradient boosting) and explain how they improve on a single decision tree |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-003",
   "metadata": {},
   "source": [
    "---\n",
    "## The Dataset: 6,000 Songs, Six Genres\n",
    "\n",
    "Kaylin Pavlik collected about 5,000 songs from each of six genres through Spotify's API, and in January 2020 the TidyTuesday project shared her data (CC0). Each song came from a playlist, and **the playlist's genre is the label**. Songs that showed up in playlists of two or more genres (like \"Despacito\", in pop, latin and edm playlists) were dropped. Then 1,000 songs were drawn per genre.\n",
    "\n",
    "Spotify's software computed the audio numbers from each recording. We see the numbers, not how they were made.\n",
    "\n",
    "| Column | What it holds |\n",
    "|---|---|\n",
    "| `song`, `artist` | the title and the artist |\n",
    "| `year` | the album's release year (the models won't use it) |\n",
    "| `danceability` | 0 to 1: how suitable for dancing (tempo, steady rhythm, strong beat) |\n",
    "| `energy` | 0 to 1: intensity; energetic songs feel fast, loud and noisy |\n",
    "| `loudness` | average loudness, in decibels (dB): from about −60 (quiet) to 0 (loud) |\n",
    "| `speechiness` | 0 to 1: how much of the track is spoken words |\n",
    "| `acousticness` | 0 to 1: how sure Spotify is that the track is acoustic |\n",
    "| `instrumentalness` | 0 to 1: how sure Spotify is that the track has no vocals |\n",
    "| `liveness` | 0 to 1: how sure Spotify is that an audience is present (a live recording) |\n",
    "| `valence` | 0 to 1: how positive (happy, cheerful) the track sounds |\n",
    "| `tempo` | beats per minute |\n",
    "| `duration_min` | length, in minutes |\n",
    "| `genre` | **the label**: edm, latin, pop, r&b, rap or rock |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-004",
   "metadata": {},
   "source": [
    "### Setup (given — just run it)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-005",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import plotly.express as px\n",
    "from sklearn.model_selection import train_test_split, cross_validate\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\n",
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "songs = pd.read_csv(\"https://cs.calvin.edu/courses/data/202/26fa/datasets/songs.csv\")\n",
    "print(len(songs), \"songs |\", songs[\"genre\"].nunique(), \"genres\")\n",
    "songs.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-006",
   "metadata": {},
   "source": [
    "The features are the ten audio numbers. The split is given: 25% of the songs for testing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-007",
   "metadata": {},
   "outputs": [],
   "source": [
    "features = [\"danceability\", \"energy\", \"loudness\", \"speechiness\", \"acousticness\",\n",
    "            \"instrumentalness\", \"liveness\", \"valence\", \"tempo\", \"duration_min\"]\n",
    "X = songs[features]\n",
    "y = songs[\"genre\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1, stratify=y)\n",
    "print(len(X_train), \"training songs |\", len(X_test), \"test songs\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-008",
   "metadata": {},
   "source": [
    "`stratify=y` keeps the genres balanced: 750 training songs and 250 test songs per genre. So a lazy model that always guesses the same genre is right 1 time in 6: **16.7%**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-009",
   "metadata": {},
   "source": [
    "---\n",
    "## Part 1 — Logistic Regression with Six Genres (SLO 11A)\n",
    "\n",
    "On Monday, logistic regression had two classes: one score, squeezed into one probability. With six genres, it learns **one score per genre**, each with its own slopes. Softmax then turns the six scores into six probabilities that add up to 1.\n",
    "\n",
    "As on Monday, the numbers are scaled first, so that every slope is \"per standard deviation\" of its column."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-011",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 11A.1 — Train and Score Logistic Regression *(2 pts)*\n",
    "\n",
    "1. Build a pipeline that scales the columns, then runs logistic regression: `make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))`. Store it in `logistic`. (`max_iter` gives the solver enough steps to settle.)\n",
    "2. Score it with 5-fold cross-validation on the training songs: `cross_validate`, with `cv=5` and `return_train_score=True`. Store the result in `logistic_scores`.\n",
    "\n",
    "The printout is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-013",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "logistic = ...\n",
    "logistic_scores = ...\n",
    "\n",
    "print(f\"logistic regression | folds it learned from: {logistic_scores['train_score'].mean():.3f}\"\n",
    "      f\" | held-out fold: {logistic_scores['test_score'].mean():.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3881c689",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"11A.1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-020",
   "metadata": {},
   "source": [
    "About **46%** right on the held-out fold: nearly three times the lazy 16.7%, but far from perfect. The two scores are close (46.4% on the folds it learned from), so logistic regression is **not overfitting**. If anything, it **underfits**: each genre's score is a weighted sum of the columns, so a slope can only say \"the faster, the more likely\" (or the less likely). It can't learn \"a medium tempo\".\n",
    "\n",
    "> 📌 **One split:** cross-validation averages 5 folds, but they all come from these 4,500 songs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-021",
   "metadata": {},
   "source": [
    "> 🎯 **Predict First:** Which column do you think pushes a song most **toward rap**? Which pushes a song most **away from rock**?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-023",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 11A.2 — Read the Slopes *(2 pts)*\n",
    "\n",
    "1. Fit `logistic` on the training songs.\n",
    "2. `logistic[-1].coef_` holds the slopes: one row per genre (in the order of `logistic.classes_`) and one column per feature. Store them as a table: `slopes = pd.DataFrame(logistic[-1].coef_, index=logistic.classes_, columns=features)`.\n",
    "3. Store the name of the column with the **largest** slope for rap in `rap_top`, and the column with the **most negative** slope for rock in `rock_bottom`. (*Hint:* `slopes.loc[\"rap\"]` is one row; `.idxmax()` and `.idxmin()` give the name of its largest and smallest entry.)\n",
    "\n",
    "The heatmap is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-025",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "...\n",
    "slopes = ...\n",
    "rap_top = ...\n",
    "rock_bottom = ...\n",
    "\n",
    "print(\"pushes most toward rap:\", rap_top, \"| pushes most away from rock:\", rock_bottom)\n",
    "px.imshow(slopes.round(2), text_auto=True, aspect=\"auto\", color_continuous_scale=\"RdBu\", color_continuous_midpoint=0,\n",
    "          labels={\"color\": \"slope\"}, title=\"Logistic Regression: One Row of Slopes per Genre\").show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a72a10d2",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"11A.2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-032",
   "metadata": {},
   "source": [
    "A positive slope (blue) raises that genre's score; a negative one (red) lowers it. Read one row at a time:\n",
    "\n",
    "* **Rap:** speechiness, +0.83. Spoken words push hardest toward rap.\n",
    "* **Rock:** danceability, −1.29, the biggest slope in the table: the more danceable the song, the less likely it is rock. Rock songs also have few spoken words (−0.85) and plenty of energy (+0.59).\n",
    "* **edm:** energetic (+0.53), without vocals (+0.55) and not cheerful (valence −0.71).\n",
    "* **Pop:** no slope beyond ±0.37. The model finds no sound that says \"pop\". Keep that in mind for Part 4."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-033",
   "metadata": {},
   "source": [
    "### Six Probabilities for One Song\n",
    "\n",
    "\"Mi Gente\", by J Balvin, was a worldwide latin hit in 2017. It is one of the test songs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-035",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 11A.3 — What Does the Model Hear? *(2 pts)*\n",
    "\n",
    "`mi_gente` (given) is the song's row of 10 numbers.\n",
    "\n",
    "1. Store the model's six probabilities for this song in `probs`, as a Series indexed by genre. `predict_proba` returns one row per song and one column per genre (in the order of `logistic.classes_`), so take row `[0]`: `pd.Series(logistic.predict_proba(mi_gente)[0], index=logistic.classes_)`.\n",
    "2. Store the model's guess, a single genre, in `guess`. (*Hint:* `predict` returns an array, so take element `[0]`.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-037",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "test_songs = songs.loc[X_test.index]                     # the test songs, with their names and genres\n",
    "mi_gente = X_test[test_songs[\"song\"] == \"Mi Gente\"]      # one row: the song's 10 numbers\n",
    "\n",
    "probs = ...\n",
    "guess = ...\n",
    "\n",
    "print(probs.round(3).to_string())\n",
    "print(\"sum:\", round(probs.sum(), 3), \"| guess:\", guess, \"| playlist genre:\", test_songs.loc[mi_gente.index, \"genre\"].iloc[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef41248d",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"11A.3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-044",
   "metadata": {},
   "source": [
    "The guess is simply the genre with the highest probability: **edm**, at 31%. Latin, the song's playlist genre, gets only 16%. All six add up to 1: softmax shares one unit of belief among the genres, and a top guess at 31% is a model that isn't sure. To the model, a loud song that is neither acoustic (0.02) nor cheerful (valence 0.31) sounds like edm.\n",
    "\n",
    "Seven more test songs (given):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-045",
   "metadata": {},
   "outputs": [],
   "source": [
    "famous = [\"Scentless Apprentice\", \"Wanted Dead Or Alive\", \"Hypnotize\", \"Paparazzi\",\n",
    "          \"Whenever, Wherever\", \"Aerodynamic\", \"In My Life - Remastered 2009\"]\n",
    "some = test_songs[test_songs[\"song\"].isin(famous)]\n",
    "table = pd.DataFrame(logistic.predict_proba(X_test.loc[some.index]), columns=logistic.classes_,\n",
    "                     index=some[\"song\"] + \" (\" + some[\"artist\"] + \")\").round(2)\n",
    "table[\"guess\"] = logistic.predict(X_test.loc[some.index])\n",
    "table[\"playlist genre\"] = some[\"genre\"].to_numpy()\n",
    "table"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-046",
   "metadata": {},
   "source": [
    "Nirvana and Bon Jovi are easy: 91% and 84% rock. Lady Gaga's \"Paparazzi\" is right, but at only 27%. The Beatles' \"In My Life\", quiet and acoustic, sounds like r&b to the model.\n",
    "\n",
    "Two \"mistakes\" deserve a second look: Shakira's \"Whenever, Wherever\" and Daft Punk's \"Aerodynamic\" are labeled **pop** because they came from pop playlists. The model calls them latin and edm. Who is wrong here?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-047",
   "metadata": {},
   "source": [
    "---\n",
    "## Part 2 — From One Tree to a Forest (SLO 11B)\n",
    "\n",
    "First, one decision tree with no depth limit (given — just run it):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-048",
   "metadata": {},
   "outputs": [],
   "source": [
    "tree = DecisionTreeClassifier(random_state=1)\n",
    "tree_scores = cross_validate(tree, X_train, y_train, cv=5, return_train_score=True)\n",
    "print(f\"one tree, no depth limit | folds it learned from: {tree_scores['train_score'].mean():.3f}\"\n",
    "      f\" | held-out fold: {tree_scores['test_score'].mean():.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-049",
   "metadata": {},
   "source": [
    "A clear case of **overfitting**: the tree memorizes the songs it learned from (100%) but gets only 38% of the held-out songs, worse than logistic regression."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-051",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 11B.1 — A Random Forest *(2 pts)*\n",
    "\n",
    "1. Build a `RandomForestClassifier` with `n_estimators=100` and `random_state=1`. Store it in `forest`. (No scaling needed: a tree only compares one column with a cutoff.)\n",
    "2. Score it as in Task 11A.1, and store the result in `forest_scores`. (This takes a few seconds.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-053",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "forest = ...\n",
    "forest_scores = ...\n",
    "\n",
    "print(f\"random forest, 100 trees | folds it learned from: {forest_scores['train_score'].mean():.3f}\"\n",
    "      f\" | held-out fold: {forest_scores['test_score'].mean():.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80598c6e",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"11B.1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-060",
   "metadata": {},
   "source": [
    "Each of the 100 trees still memorizes its songs, so the forest also scores 100% on the folds it learned from. But on the held-out fold it gets **52%**: 14 points more than one tree, and 6 more than logistic regression.\n",
    "\n",
    "Why? Each tree learns from its own bootstrap sample of songs, and looks at a few random columns at each split. So the trees make **different** mistakes, and the vote cancels many of them. The forest still overfits, but much less than one tree."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-061",
   "metadata": {},
   "source": [
    "---\n",
    "## Part 3 — AdaBoost (SLO 11B)\n",
    "\n",
    "AdaBoost builds its trees **in a row**: each new tree gives more weight to the songs that the earlier trees got wrong, and the better trees get a bigger say in the final vote. Its default tree is a **stump**: a tree with a single split."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-063",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 11B.2 — Boosting Stumps *(2 pts)*\n",
    "\n",
    "1. Build an `AdaBoostClassifier` with `n_estimators=100` and `random_state=1`. Store it in `ada`.\n",
    "2. Score it as before, and store the result in `ada_scores`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-065",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "ada = ...\n",
    "ada_scores = ...\n",
    "\n",
    "print(f\"AdaBoost, 100 stumps | folds it learned from: {ada_scores['train_score'].mean():.3f}\"\n",
    "      f\" | held-out fold: {ada_scores['test_score'].mean():.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16aea318",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"11B.2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-072",
   "metadata": {},
   "source": [
    "About **46%**, no better than logistic regression, and close to its score on the folds it learned from (48%): **underfitting**. A stump splits the songs into just two groups, so each stump names at most two of the six genres. A hundred of them, each that simple, can't sort six overlapping genres. (Reading 9 found the same with seven tree species.)\n",
    "\n",
    "AdaBoost can also boost bigger trees, for example `AdaBoostClassifier(DecisionTreeClassifier(max_depth=4), ...)`, and then the depth of each tree becomes one more knob to tune."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-073",
   "metadata": {},
   "source": [
    "---\n",
    "## Part 4 — The Final Comparison (SLO 11B)\n",
    "\n",
    "Cross-validation ranked the forest first. Now, **once**, open the test set."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-075",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "source": [
    "### Task 11B.3 — Test Accuracy *(2 pts)*\n",
    "\n",
    "Fit each model, `logistic`, `forest` and `ada`, on all the training songs, and store its accuracy on the test songs in `logistic_test`, `forest_test` and `ada_test`. (*Hint:* `model.fit(X_train, y_train).score(X_test, y_test)` does both in one line.)\n",
    "\n",
    "The summary table is given."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-077",
   "metadata": {
    "tags": [
     "otter_answer_cell"
    ]
   },
   "outputs": [],
   "source": [
    "logistic_test = ...\n",
    "forest_test = ...\n",
    "ada_test = ...\n",
    "\n",
    "pd.DataFrame({\"CV: folds it learned from\": [logistic_scores[\"train_score\"].mean(), forest_scores[\"train_score\"].mean(), ada_scores[\"train_score\"].mean()],\n",
    "              \"CV: held-out fold\": [logistic_scores[\"test_score\"].mean(), forest_scores[\"test_score\"].mean(), ada_scores[\"test_score\"].mean()],\n",
    "              \"test songs\": [logistic_test, forest_test, ada_test]},\n",
    "             index=[\"logistic regression\", \"random forest\", \"AdaBoost, 100 stumps\"]).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d6bc78f",
   "metadata": {
    "deletable": false,
    "editable": false
   },
   "outputs": [],
   "source": [
    "grader.check(\"11B.3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-084",
   "metadata": {},
   "source": [
    "The test set agrees with cross-validation: the forest first (52.5%), then logistic regression (46.8%) and AdaBoost (about 45%).\n",
    "\n",
    "> 📌 **One split:** these are 1,500 test songs. Another split would move each score by a point or two.\n",
    "\n",
    "Which genres does the forest mix up? (given)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "p09-085",
   "metadata": {},
   "outputs": [],
   "source": [
    "genres = forest.classes_\n",
    "counts = confusion_matrix(y_test, forest.predict(X_test), labels=genres)\n",
    "px.imshow(counts, x=genres, y=genres, text_auto=True, color_continuous_scale=\"Blues\",\n",
    "          labels={\"x\": \"the forest's guess\", \"y\": \"playlist genre\", \"color\": \"songs\"},\n",
    "          title=\"The Forest on 1,500 Test Songs (250 per Genre)\").show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-086",
   "metadata": {},
   "source": [
    "The diagonal holds the right guesses. Rock (182 of 250), edm (166) and rap (151) are the easiest. **Pop** is the hardest: the forest calls only 76 of its 250 songs pop, and spreads the rest over rock (49), r&b (46), latin (33) and edm (32). Logistic regression found no slope for pop, either.\n",
    "\n",
    "Part of the problem is the label. A song's genre here is the genre of the **playlist** it came from, and a person chose it. Daft Punk sits in a pop playlist; so does Shakira. And 7% of the songs Pavlik collected sat in playlists of two genres or more. As Deborah Stone argues in the first chapter of *Counting*, putting things in a category means deciding which differences to ignore. No model can be more consistent than the labels it learns from."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p09-087",
   "metadata": {},
   "source": [
    "---\n",
    "## Submission\n",
    "\n",
    "Save your notebook, then upload the **`.ipynb` file** directly to our Moodle assignment page. Don't export, zip, or submit anything else — just the notebook."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  },
  "otter": {
   "OK_FORMAT": true,
   "assignment_name": "practice09",
   "tests": {
    "11A.1": {
     "name": "11A.1",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert hasattr(logistic, 'steps') and isinstance(logistic[0], StandardScaler), 'make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))'\n>>> assert isinstance(logistic[-1], LogisticRegression), \"the pipeline's last step should be LogisticRegression(max_iter=1000)\"\n>>> assert 'train_score' in logistic_scores and len(logistic_scores['test_score']) == 5, 'use cross_validate with cv=5 and return_train_score=True'\n>>> assert 0.35 < logistic_scores['test_score'].mean() < 0.6, 'cross-validate on X_train and y_train'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "11A.2": {
     "name": "11A.2",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert slopes.shape == (6, 10), 'one row per genre and one column per feature: fit logistic first'\n>>> assert list(slopes.columns) == features, 'use columns=features'\n>>> assert rap_top in features and rock_bottom in features, \"store a column name, like 'energy'\"\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "11A.3": {
     "name": "11A.3",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert len(probs) == 6 and abs(probs.sum() - 1) < 1e-06, 'six probabilities, one per genre, that add up to 1'\n>>> assert guess in logistic.classes_, \"guess should be one genre, like 'rock'\"\n>>> assert guess == probs.idxmax(), 'use logistic.predict(mi_gente)[0]'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "11B.1": {
     "name": "11B.1",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert isinstance(forest, RandomForestClassifier), 'use RandomForestClassifier'\n>>> assert forest.n_estimators == 100 and forest.random_state == 1, 'use n_estimators=100 and random_state=1'\n>>> assert 'train_score' in forest_scores and len(forest_scores['test_score']) == 5, 'use cross_validate with cv=5 and return_train_score=True'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "11B.2": {
     "name": "11B.2",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert isinstance(ada, AdaBoostClassifier), 'use AdaBoostClassifier'\n>>> assert ada.n_estimators == 100 and ada.random_state == 1, 'use n_estimators=100 and random_state=1'\n>>> assert 'train_score' in ada_scores and len(ada_scores['test_score']) == 5, 'use cross_validate with cv=5 and return_train_score=True'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    },
    "11B.3": {
     "name": "11B.3",
     "points": 2,
     "suites": [
      {
       "cases": [
        {
         "code": ">>> assert 0.3 < logistic_test < 0.7 and 0.3 < forest_test < 0.7 and (0.3 < ada_test < 0.7), 'use .score(X_test, y_test) after fitting on X_train, y_train'\n>>> assert forest_test > logistic_test, 'fit each model on the training songs, then score it on the test songs'\n",
         "hidden": false,
         "locked": false
        }
       ],
       "scored": true,
       "setup": "",
       "teardown": "",
       "type": "doctest"
      }
     ]
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
