{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "validation.ipynb", "version": "0.3.2", "views": {}, "default_view": {}, "provenance": [], "collapsed_sections": [ "4Xp9NhOCYSuz", "pECTKgw5ZvFK", "dER2_43pWj1T", "I-La4N9ObC1x", "yTghc_5HkJDW", "copyright-notice" ] }, "kernelspec": { "name": "python3", "display_name": "Python 3" } }, "cells": [ { "source": [ "#### Copyright 2017 Google LLC." ], "metadata": { "colab_type": "text", "id": "copyright-notice" }, "cell_type": "markdown" }, { "outputs": [], "source": [ "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ], "metadata": { "colab": { "autoexec": { "wait_interval": 0, "startup": false } }, "cellView": "both", "colab_type": "code", "id": "copyright-notice2" }, "cell_type": "code", "execution_count": 0 }, { "cell_type": "markdown", "metadata": { "id": "zbIgBK-oXHO7", "colab_type": "text" }, "source": [ " # \u9a8c\u8bc1" ] }, { "cell_type": "markdown", "metadata": { "id": "WNX0VyBpHpCX", "colab_type": "text" }, "source": [ " **\u5b66\u4e60\u76ee\u6807\uff1a**\n", " * \u4f7f\u7528\u591a\u4e2a\u7279\u5f81\u800c\u975e\u5355\u4e2a\u7279\u5f81\u6765\u8fdb\u4e00\u6b65\u63d0\u9ad8\u6a21\u578b\u7684\u6709\u6548\u6027\n", " * \u8c03\u8bd5\u6a21\u578b\u8f93\u5165\u6570\u636e\u4e2d\u7684\u95ee\u9898\n", " * \u4f7f\u7528\u6d4b\u8bd5\u6570\u636e\u96c6\u68c0\u67e5\u6a21\u578b\u662f\u5426\u8fc7\u62df\u5408\u9a8c\u8bc1\u6570\u636e" ] }, { "cell_type": "markdown", "metadata": { "id": "za0m1T8CHpCY", "colab_type": "text" }, "source": [ " \u4e0e\u5728\u4e4b\u524d\u7684\u7ec3\u4e60\u4e2d\u4e00\u6837\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u52a0\u5229\u798f\u5c3c\u4e9a\u5dde\u4f4f\u623f\u6570\u636e\u96c6\uff0c\u5c1d\u8bd5\u6839\u636e 1990 \u5e74\u7684\u4eba\u53e3\u666e\u67e5\u6570\u636e\u5728\u57ce\u5e02\u8857\u533a\u7ea7\u522b\u9884\u6d4b `median_house_value`\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "r2zgMfWDWF12", "colab_type": "text" }, "source": [ " ## \u8bbe\u7f6e" ] }, { "cell_type": "markdown", "metadata": { "id": "8jErhkLzWI1B", "colab_type": "text" }, "source": [ " \u6211\u4eec\u9996\u5148\u52a0\u8f7d\u5e76\u51c6\u5907\u6570\u636e\u3002\u8fd9\u4e00\u6b21\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u591a\u4e2a\u7279\u5f81\uff0c\u56e0\u6b64\u6211\u4eec\u4f1a\u5c06\u903b\u8f91\u6a21\u5757\u5316\uff0c\u4ee5\u5bf9\u7279\u5f81\u8fdb\u884c\u9884\u5904\u7406\uff1a" ] }, { "metadata": { "id": "PwS5Bhm6HpCZ", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "from __future__ import print_function\n", "\n", "import math\n", "\n", "from IPython import display\n", "from matplotlib import cm\n", "from matplotlib import gridspec\n", "from matplotlib import pyplot as plt\n", "import numpy as np\n", "import pandas as pd\n", "from sklearn import metrics\n", "import tensorflow as tf\n", "from tensorflow.python.data import Dataset\n", "\n", "tf.logging.set_verbosity(tf.logging.ERROR)\n", "pd.options.display.max_rows = 10\n", "pd.options.display.float_format = '{:.1f}'.format\n", "\n", "california_housing_dataframe = pd.read_csv(\"https://download.mlcc.google.cn/mledu-datasets/california_housing_train.csv\", sep=\",\")\n", "\n", "# california_housing_dataframe = california_housing_dataframe.reindex(\n", "# np.random.permutation(california_housing_dataframe.index))" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "metadata": { "id": "J2ZyTzX0HpCc", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "def preprocess_features(california_housing_dataframe):\n", " \"\"\"Prepares input features from California housing data set.\n", "\n", " Args:\n", " california_housing_dataframe: A Pandas DataFrame expected to contain data\n", " from the California housing data set.\n", " Returns:\n", " A DataFrame that contains the features to be used for the model, including\n", " synthetic features.\n", " \"\"\"\n", " selected_features = california_housing_dataframe[\n", " [\"latitude\",\n", " \"longitude\",\n", " \"housing_median_age\",\n", " \"total_rooms\",\n", " \"total_bedrooms\",\n", " \"population\",\n", " \"households\",\n", " \"median_income\"]]\n", " processed_features = selected_features.copy()\n", " # Create a synthetic feature.\n", " processed_features[\"rooms_per_person\"] = (\n", " california_housing_dataframe[\"total_rooms\"] /\n", " california_housing_dataframe[\"population\"])\n", " return processed_features\n", "\n", "def preprocess_targets(california_housing_dataframe):\n", " \"\"\"Prepares target features (i.e., labels) from California housing data set.\n", "\n", " Args:\n", " california_housing_dataframe: A Pandas DataFrame expected to contain data\n", " from the California housing data set.\n", " Returns:\n", " A DataFrame that contains the target feature.\n", " \"\"\"\n", " output_targets = pd.DataFrame()\n", " # Scale the target to be in units of thousands of dollars.\n", " output_targets[\"median_house_value\"] = (\n", " california_housing_dataframe[\"median_house_value\"] / 1000.0)\n", " return output_targets" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "sZSIaDiaHpCf", "colab_type": "text" }, "source": [ " \u5bf9\u4e8e**\u8bad\u7ec3\u96c6**\uff0c\u6211\u4eec\u4ece\u5171 17000 \u4e2a\u6837\u672c\u4e2d\u9009\u62e9\u524d 12000 \u4e2a\u6837\u672c\u3002" ] }, { "metadata": { "id": "P9wejvw7HpCf", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "training_examples = preprocess_features(california_housing_dataframe.head(12000))\n", "training_examples.describe()" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "metadata": { "id": "JlkgPR-SHpCh", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "training_targets = preprocess_targets(california_housing_dataframe.head(12000))\n", "training_targets.describe()" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "5l1aA2xOHpCj", "colab_type": "text" }, "source": [ " \u5bf9\u4e8e**\u9a8c\u8bc1\u96c6**\uff0c\u6211\u4eec\u4ece\u5171 17000 \u4e2a\u6837\u672c\u4e2d\u9009\u62e9\u540e 5000 \u4e2a\u6837\u672c\u3002" ] }, { "metadata": { "id": "fLYXLWAiHpCk", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "validation_examples = preprocess_features(california_housing_dataframe.tail(5000))\n", "validation_examples.describe()" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "metadata": { "id": "oVPcIT3BHpCm", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))\n", "validation_targets.describe()" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "z3TZV1pgfZ1n", "colab_type": "text" }, "source": [ " ## \u4efb\u52a1 1\uff1a\u68c0\u67e5\u6570\u636e\n", "\u597d\u7684\uff0c\u6211\u4eec\u770b\u4e00\u4e0b\u4e0a\u9762\u7684\u6570\u636e\u3002\u53ef\u4ee5\u4f7f\u7528\u7684\u8f93\u5165\u7279\u5f81\u6709 `9` \u4e2a\u3002\n", "\n", "\u5feb\u901f\u6d4f\u89c8\u4e00\u4e0b\u8868\u683c\u4e2d\u7684\u503c\u3002\u4e00\u5207\u770b\u8d77\u6765\u6b63\u5e38\u5417\uff1f\u770b\u4e00\u4e0b\u60a8\u53ef\u4ee5\u53d1\u73b0\u591a\u5c11\u95ee\u9898\u3002\u5982\u679c\u60a8\u6ca1\u6709\u7edf\u8ba1\u5b66\u65b9\u9762\u7684\u80cc\u666f\u77e5\u8bc6\uff0c\u4e5f\u4e0d\u5fc5\u62c5\u5fc3\uff1b\u60a8\u53ef\u4ee5\u8fd0\u7528\u5e38\u8bc6\u3002\n", "\n", "\u6709\u673a\u4f1a\u4eb2\u81ea\u4ed4\u7ec6\u67e5\u770b\u6570\u636e\u540e\uff0c\u8bf7\u67e5\u770b\u89e3\u51b3\u65b9\u6848\uff0c\u4e86\u89e3\u6709\u5173\u5982\u4f55\u9a8c\u8bc1\u6570\u636e\u7684\u5176\u4ed6\u601d\u8def\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "4Xp9NhOCYSuz", "colab_type": "text" }, "source": [ " ### \u89e3\u51b3\u65b9\u6848\n", "\n", "\u70b9\u51fb\u4e0b\u65b9\u5373\u53ef\u67e5\u770b\u89e3\u51b3\u65b9\u6848\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "gqeRmK57YWpy", "colab_type": "text" }, "source": [ " \u6211\u4eec\u6839\u636e\u57fa\u51c6\u9884\u671f\u60c5\u51b5\u68c0\u67e5\u4e00\u4e0b\u6211\u4eec\u7684\u6570\u636e\uff1a\n", "\n", "* \u5bf9\u4e8e\u4e00\u4e9b\u503c\uff08\u4f8b\u5982 `median_house_value`\uff09\uff0c\u6211\u4eec\u53ef\u4ee5\u68c0\u67e5\u8fd9\u4e9b\u503c\u662f\u5426\u4f4d\u4e8e\u5408\u7406\u7684\u8303\u56f4\u5185\uff08\u8bf7\u6ce8\u610f\uff0c\u8fd9\u662f 1990 \u5e74\u7684\u6570\u636e\uff0c\u4e0d\u662f\u73b0\u5728\u7684\uff01\uff09\u3002\n", "\n", "* \u5bf9\u4e8e `latitude` \u548c `longitude` \u7b49\u5176\u4ed6\u503c\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7 Google \u8fdb\u884c\u5feb\u901f\u641c\u7d22\uff0c\u5e76\u5feb\u901f\u68c0\u67e5\u4e00\u4e0b\u5b83\u4eec\u4e0e\u9884\u671f\u503c\u662f\u5426\u4e00\u81f4\u3002\n", "\n", "\u5982\u679c\u60a8\u4ed4\u7ec6\u770b\uff0c\u53ef\u80fd\u4f1a\u53d1\u73b0\u4e0b\u5217\u5f02\u5e38\u60c5\u51b5\uff1a\n", "\n", "* `median_income` \u4f4d\u4e8e 3 \u5230 15 \u7684\u8303\u56f4\u5185\u3002\u6211\u4eec\u5b8c\u5168\u4e0d\u6e05\u695a\u6b64\u8303\u56f4\u7a76\u7adf\u6307\u7684\u662f\u4ec0\u4e48\uff0c\u770b\u8d77\u6765\u53ef\u80fd\u662f\u67d0\u5bf9\u6570\u5c3a\u5ea6\uff1f\u65e0\u6cd5\u627e\u5230\u76f8\u5173\u8bb0\u5f55\uff1b\u6211\u4eec\u6240\u80fd\u5047\u8bbe\u7684\u53ea\u662f\uff0c\u503c\u8d8a\u9ad8\uff0c\u76f8\u5e94\u7684\u6536\u5165\u8d8a\u9ad8\u3002\n", "\n", "* `median_house_value` \u7684\u6700\u5927\u503c\u662f 500001\u3002\u8fd9\u770b\u8d77\u6765\u50cf\u662f\u67d0\u79cd\u4eba\u4e3a\u8bbe\u5b9a\u7684\u4e0a\u9650\u3002\n", "\n", "* `rooms_per_person` \u7279\u5f81\u901a\u5e38\u5728\u6b63\u5e38\u8303\u56f4\u5185\uff0c\u5176\u4e2d\u7b2c 75 \u767e\u5206\u4f4d\u6570\u7684\u503c\u7ea6\u4e3a 2\u3002\u4f46\u4e5f\u6709\u4e00\u4e9b\u975e\u5e38\u5927\u7684\u503c\uff08\u4f8b\u5982 18 \u6216 55\uff09\uff0c\u8fd9\u53ef\u80fd\u8868\u660e\u6570\u636e\u6709\u4e00\u5b9a\u7a0b\u5ea6\u7684\u635f\u574f\u3002\n", "\n", "\u6211\u4eec\u5c06\u6682\u65f6\u4f7f\u7528\u63d0\u4f9b\u7684\u8fd9\u4e9b\u7279\u5f81\u3002\u4f46\u5e0c\u671b\u8fd9\u4e9b\u793a\u4f8b\u53ef\u5e2e\u52a9\u60a8\u8f83\u4e3a\u76f4\u89c2\u5730\u4e86\u89e3\u5982\u4f55\u68c0\u67e5\u6765\u81ea\u672a\u77e5\u6765\u6e90\u7684\u6570\u636e\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "fXliy7FYZZRm", "colab_type": "text" }, "source": [ " ## \u4efb\u52a1 2\uff1a\u7ed8\u5236\u7eac\u5ea6/\u7ecf\u5ea6\u4e0e\u623f\u5c4b\u4ef7\u503c\u4e2d\u4f4d\u6570\u7684\u66f2\u7ebf\u56fe" ] }, { "cell_type": "markdown", "metadata": { "id": "aJIWKBdfsDjg", "colab_type": "text" }, "source": [ " \u6211\u4eec\u6765\u8be6\u7ec6\u4e86\u89e3\u4e00\u4e0b **`latitude`** \u548c **`longitude`** \u8fd9\u4e24\u4e2a\u7279\u5f81\u3002\u5b83\u4eec\u662f\u76f8\u5173\u57ce\u5e02\u8857\u533a\u7684\u5730\u7406\u5750\u6807\u3002\n", "\n", "\u5229\u7528\u8fd9\u4e24\u4e2a\u7279\u5f81\u53ef\u4ee5\u63d0\u4f9b\u51fa\u8272\u7684\u53ef\u89c6\u5316\u7ed3\u679c - \u6211\u4eec\u6765\u7ed8\u5236 `latitude` \u548c `longitude` \u7684\u66f2\u7ebf\u56fe\uff0c\u7136\u540e\u7528\u989c\u8272\u6807\u6ce8 `median_house_value`\u3002" ] }, { "metadata": { "id": "5_LD23bJ06TW", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 }, "test": { "output": "ignore", "timeout": 600 } }, "cellView": "both" }, "source": [ "plt.figure(figsize=(13, 8))\n", "\n", "ax = plt.subplot(1, 2, 1)\n", "ax.set_title(\"Validation Data\")\n", "\n", "ax.set_autoscaley_on(False)\n", "ax.set_ylim([32, 43])\n", "ax.set_autoscalex_on(False)\n", "ax.set_xlim([-126, -112])\n", "plt.scatter(validation_examples[\"longitude\"],\n", " validation_examples[\"latitude\"],\n", " cmap=\"coolwarm\",\n", " c=validation_targets[\"median_house_value\"] / validation_targets[\"median_house_value\"].max())\n", "\n", "ax = plt.subplot(1,2,2)\n", "ax.set_title(\"Training Data\")\n", "\n", "ax.set_autoscaley_on(False)\n", "ax.set_ylim([32, 43])\n", "ax.set_autoscalex_on(False)\n", "ax.set_xlim([-126, -112])\n", "plt.scatter(training_examples[\"longitude\"],\n", " training_examples[\"latitude\"],\n", " cmap=\"coolwarm\",\n", " c=training_targets[\"median_house_value\"] / training_targets[\"median_house_value\"].max())\n", "_ = plt.plot()" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "32_DbjnfXJlC", "colab_type": "text" }, "source": [ " \u7a0d\u7b49\u7247\u523b\u2026\u73b0\u5728\u5e94\u8be5\u5df2\u7ecf\u5448\u73b0\u51fa\u4e00\u5e45\u4e0d\u9519\u7684\u52a0\u5229\u798f\u5c3c\u4e9a\u5dde\u5730\u56fe\u4e86\uff0c\u5176\u4e2d\u65e7\u91d1\u5c71\u548c\u6d1b\u6749\u77f6\u7b49\u4f4f\u623f\u6210\u672c\u9ad8\u6602\u7684\u5730\u533a\u7528\u7ea2\u8272\u8868\u793a\u3002\n", "\n", "\u6839\u636e\u8bad\u7ec3\u96c6\u5448\u73b0\u7684\u5730\u56fe\u6709\u51e0\u5206\u50cf[\u771f\u6b63\u7684\u5730\u56fe](https://www.google.com/maps/place/California/@37.1870174,-123.7642688,6z/data=!3m1!4b1!4m2!3m1!1s0x808fb9fe5f285e3d:0x8b5109a227086f55)\uff0c\u4f46\u6839\u636e\u9a8c\u8bc1\u96c6\u5448\u73b0\u7684\u660e\u663e\u4e0d\u50cf\u3002\n", "\n", "**\u8fd4\u56de\u4e0a\u9762\u7684\u90e8\u5206\uff0c\u518d\u6b21\u67e5\u770b\u4efb\u52a1 1 \u4e2d\u7684\u6570\u636e\u3002**\n", "\n", "\u60a8\u770b\u51fa\u8bad\u7ec3\u6570\u636e\u548c\u9a8c\u8bc1\u6570\u636e\u4e4b\u95f4\u7684\u7279\u5f81\u6216\u76ee\u6807\u5206\u5e03\u6709\u4efb\u4f55\u5176\u4ed6\u5dee\u5f02\u4e86\u5417\uff1f" ] }, { "cell_type": "markdown", "metadata": { "id": "pECTKgw5ZvFK", "colab_type": "text" }, "source": [ " ### \u89e3\u51b3\u65b9\u6848\n", "\n", "\u70b9\u51fb\u4e0b\u65b9\u5373\u53ef\u67e5\u770b\u89e3\u51b3\u65b9\u6848\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "49NC4_KIZxk_", "colab_type": "text" }, "source": [ " \u67e5\u770b\u4e0a\u9762\u7684\u6458\u8981\u7edf\u8ba1\u4fe1\u606f\u8868\u683c\u65f6\uff0c\u5f88\u5bb9\u6613\u4ea7\u751f\u60f3\u77e5\u9053\u5982\u4f55\u8fdb\u884c\u6709\u7528\u7684\u6570\u636e\u68c0\u67e5\u7684\u60f3\u6cd5\u3002\u6bcf\u4e2a\u8857\u533a total_rooms \u7684\u7b2c 75 \u767e\u5206\u4f4d\u7684\u6b63\u786e\u503c\u662f\u4ec0\u4e48\uff1f\n", "\n", "\u9700\u8981\u6ce8\u610f\u7684\u5173\u952e\u4e00\u70b9\u662f\uff0c\u5bf9\u4e8e\u4efb\u4f55\u6307\u5b9a\u7279\u5f81\u6216\u5217\uff0c\u8bad\u7ec3\u96c6\u548c\u9a8c\u8bc1\u96c6\u4e4b\u95f4\u7684\u503c\u7684\u5206\u5e03\u5e94\u8be5\u5927\u81f4\u76f8\u540c\u3002\n", "\n", "\u6211\u4eec\u771f\u6b63\u9700\u8981\u62c5\u5fc3\u7684\u662f\uff0c\u771f\u5b9e\u60c5\u51b5\u5e76\u975e\u8fd9\u6837\uff0c\u8fd9\u4e00\u4e8b\u5b9e\u8868\u660e\u6211\u4eec\u521b\u5efa\u8bad\u7ec3\u96c6\u548c\u9a8c\u8bc1\u96c6\u7684\u62c6\u5206\u65b9\u5f0f\u5f88\u53ef\u80fd\u5b58\u5728\u95ee\u9898\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "025Ky0Dq9ig0", "colab_type": "text" }, "source": [ " ## \u4efb\u52a1 3\uff1a\u8fd4\u56de\u6765\u770b\u6570\u636e\u5bfc\u5165\u548c\u9884\u5904\u7406\u4ee3\u7801\uff0c\u770b\u4e00\u4e0b\u60a8\u662f\u5426\u53d1\u73b0\u4e86\u4efb\u4f55\u9519\u8bef\n", "\u5982\u679c\u60a8\u53d1\u73b0\u4e86\u9519\u8bef\uff0c\u8bf7\u4fee\u590d\u8be5\u9519\u8bef\u3002\u5c06\u67e5\u770b\u65f6\u95f4\u63a7\u5236\u5728\u4e00\u5230\u4e24\u5206\u949f\u4e4b\u5185\u3002\u5982\u679c\u60a8\u672a\u53d1\u73b0\u4efb\u4f55\u9519\u8bef\uff0c\u8bf7\u67e5\u770b\u89e3\u51b3\u65b9\u6848\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "JFsd2eWHAMdy", "colab_type": "text" }, "source": [ " \u53d1\u73b0\u5e76\u89e3\u51b3\u95ee\u9898\u540e\uff0c\u91cd\u65b0\u8fd0\u884c\u4e0a\u9762\u7684 `latitude`/`longitude` \u7ed8\u56fe\u5355\u5143\u683c\uff0c\u5e76\u786e\u8ba4\u6211\u4eec\u7684\u5065\u5168\u6027\u68c0\u67e5\u7684\u7ed3\u679c\u770b\u4e0a\u53bb\u66f4\u597d\u4e86\u3002\n", "\n", "\u987a\u4fbf\u63d0\u4e00\u4e0b\uff0c\u5728\u8fd9\u4e00\u6b65\u4e2d\uff0c\u6211\u4eec\u4f1a\u5b66\u5230\u4e00\u9879\u91cd\u8981\u7ecf\u9a8c\u3002\n", "\n", "**\u673a\u5668\u5b66\u4e60\u4e2d\u7684\u8c03\u8bd5\u901a\u5e38\u662f*\u6570\u636e\u8c03\u8bd5*\u800c\u4e0d\u662f\u4ee3\u7801\u8c03\u8bd5\u3002**\n", "\n", "\u5982\u679c\u6570\u636e\u6709\u8bef\uff0c\u5373\u4f7f\u6700\u9ad8\u7ea7\u7684\u673a\u5668\u5b66\u4e60\u4ee3\u7801\u4e5f\u633d\u6551\u4e0d\u4e86\u5c40\u9762\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "dER2_43pWj1T", "colab_type": "text" }, "source": [ " ### \u89e3\u51b3\u65b9\u6848\n", "\n", "\u70b9\u51fb\u4e0b\u65b9\u5373\u53ef\u67e5\u770b\u89e3\u51b3\u65b9\u6848\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "BnEVbYJvW2wu", "colab_type": "text" }, "source": [ " \u6211\u4eec\u6765\u770b\u4e00\u4e0b\u5728\u8bfb\u5165\u6570\u636e\u65f6\uff0c\u6211\u4eec\u662f\u5982\u4f55\u5bf9\u6570\u636e\u8fdb\u884c\u968f\u673a\u5316\u5904\u7406\u7684\u3002\n", "\n", "\u5982\u679c\u6211\u4eec\u5728\u521b\u5efa\u8bad\u7ec3\u96c6\u548c\u9a8c\u8bc1\u96c6\u4e4b\u524d\uff0c\u6ca1\u6709\u5bf9\u6570\u636e\u8fdb\u884c\u6b63\u786e\u7684\u968f\u673a\u5316\u5904\u7406\uff0c\u90a3\u4e48\u4ee5\u67d0\u79cd\u7279\u5b9a\u987a\u5e8f\u63a5\u6536\u6570\u636e\u53ef\u80fd\u4f1a\u5bfc\u81f4\u51fa\u73b0\u95ee\u9898\uff08\u4f3c\u4e4e\u5c31\u662f\u6b64\u65f6\u7684\u95ee\u9898\uff09\u3002" ] }, { "cell_type": "markdown", "metadata": { "id": "xCdqLpQyAos2", "colab_type": "text" }, "source": [ " ## \u4efb\u52a1 4\uff1a\u8bad\u7ec3\u548c\u8bc4\u4f30\u6a21\u578b\n", "\n", "**\u82b1\u8d39\u7ea6 5 \u5206\u949f\u7684\u65f6\u95f4\u5c1d\u8bd5\u4e0d\u540c\u7684\u8d85\u53c2\u6570\u8bbe\u7f6e\u3002\u5c3d\u53ef\u80fd\u83b7\u53d6\u6700\u4f73\u9a8c\u8bc1\u6548\u679c\u3002**\n", "\n", "\u7136\u540e\uff0c\u6211\u4eec\u4f1a\u4f7f\u7528\u6570\u636e\u96c6\u4e2d\u7684\u6240\u6709\u7279\u5f81\u8bad\u7ec3\u4e00\u4e2a\u7ebf\u6027\u56de\u5f52\u5668\uff0c\u770b\u770b\u5176\u8868\u73b0\u5982\u4f55\u3002\n", "\n", "\u6211\u4eec\u6765\u5b9a\u4e49\u4e00\u4e0b\u4ee5\u524d\u5c06\u6570\u636e\u52a0\u8f7d\u5230 TensorFlow \u6a21\u578b\u4e2d\u65f6\u6240\u4f7f\u7528\u7684\u540c\u4e00\u8f93\u5165\u51fd\u6570\u3002\n" ] }, { "metadata": { "id": "rzcIPGxxgG0t", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n", " \"\"\"Trains a linear regression model of multiple features.\n", " \n", " Args:\n", " features: pandas DataFrame of features\n", " targets: pandas DataFrame of targets\n", " batch_size: Size of batches to be passed to the model\n", " shuffle: True or False. Whether to shuffle the data.\n", " num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely\n", " Returns:\n", " Tuple of (features, labels) for next data batch\n", " \"\"\"\n", " \n", " # Convert pandas data into a dict of np arrays.\n", " features = {key:np.array(value) for key,value in dict(features).items()} \n", " \n", " # Construct a dataset, and configure batching/repeating.\n", " ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit\n", " ds = ds.batch(batch_size).repeat(num_epochs)\n", " \n", " # Shuffle the data, if specified.\n", " if shuffle:\n", " ds = ds.shuffle(10000)\n", " \n", " # Return the next batch of data.\n", " features, labels = ds.make_one_shot_iterator().get_next()\n", " return features, labels" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "CvrKoBmNgRCO", "colab_type": "text" }, "source": [ " \u7531\u4e8e\u6211\u4eec\u73b0\u5728\u4f7f\u7528\u7684\u662f\u591a\u4e2a\u8f93\u5165\u7279\u5f81\uff0c\u56e0\u6b64\u9700\u8981\u628a\u7528\u4e8e\u5c06\u7279\u5f81\u5217\u914d\u7f6e\u4e3a\u72ec\u7acb\u51fd\u6570\u7684\u4ee3\u7801\u6a21\u5757\u5316\u3002\uff08\u76ee\u524d\u6b64\u4ee3\u7801\u76f8\u5f53\u7b80\u5355\uff0c\u56e0\u4e3a\u6211\u4eec\u7684\u6240\u6709\u7279\u5f81\u90fd\u662f\u6570\u503c\uff0c\u4f46\u5f53\u6211\u4eec\u5728\u4eca\u540e\u7684\u7ec3\u4e60\u4e2d\u4f7f\u7528\u5176\u4ed6\u7c7b\u578b\u7684\u7279\u5f81\u65f6\uff0c\u4f1a\u57fa\u4e8e\u6b64\u4ee3\u7801\u8fdb\u884c\u6784\u5efa\u3002\uff09" ] }, { "metadata": { "id": "wEW5_XYtgZ-H", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "def construct_feature_columns(input_features):\n", " \"\"\"Construct the TensorFlow Feature Columns.\n", "\n", " Args:\n", " input_features: The names of the numerical input features to use.\n", " Returns:\n", " A set of feature columns\n", " \"\"\" \n", " return set([tf.feature_column.numeric_column(my_feature)\n", " for my_feature in input_features])" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "D0o2wnnzf8BD", "colab_type": "text" }, "source": [ " \u63a5\u4e0b\u6765\uff0c\u7ee7\u7eed\u5b8c\u6210\u4e0b\u9762\u7684 `train_model()` \u4ee3\u7801\uff0c\u4ee5\u8bbe\u7f6e\u8f93\u5165\u51fd\u6570\u548c\u8ba1\u7b97\u9884\u6d4b\u3002\n", "\n", "**\u6ce8\u610f**\uff1a\u53ef\u4ee5\u53c2\u8003\u4ee5\u524d\u7684\u7ec3\u4e60\u4e2d\u7684\u4ee3\u7801\uff0c\u4f46\u8981\u786e\u4fdd\u9488\u5bf9\u76f8\u5e94\u6570\u636e\u96c6\u8c03\u7528 `predict()`\u3002\n", "\n", "\u6bd4\u8f83\u8bad\u7ec3\u6570\u636e\u548c\u9a8c\u8bc1\u6570\u636e\u7684\u635f\u5931\u3002\u4f7f\u7528\u4e00\u4e2a\u539f\u59cb\u7279\u5f81\u65f6\uff0c\u6211\u4eec\u5f97\u5230\u7684\u6700\u4f73\u5747\u65b9\u6839\u8bef\u5dee (RMSE) \u7ea6\u4e3a 180\u3002\n", "\n", "\u73b0\u5728\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528\u591a\u4e2a\u7279\u5f81\uff0c\u4e0d\u59a8\u770b\u4e00\u4e0b\u53ef\u4ee5\u83b7\u5f97\u591a\u597d\u7684\u7ed3\u679c\u3002\n", "\n", "\u4f7f\u7528\u6211\u4eec\u4e4b\u524d\u4e86\u89e3\u7684\u4e00\u4e9b\u65b9\u6cd5\u68c0\u67e5\u6570\u636e\u3002\u8fd9\u4e9b\u65b9\u6cd5\u53ef\u80fd\u5305\u62ec\uff1a\n", "\n", " * \u6bd4\u8f83\u9884\u6d4b\u503c\u548c\u5b9e\u9645\u76ee\u6807\u503c\u7684\u5206\u5e03\u60c5\u51b5\n", "\n", " * \u7ed8\u5236\u9884\u6d4b\u503c\u548c\u76ee\u6807\u503c\u7684\u6563\u70b9\u56fe\n", "\n", " * \u4f7f\u7528 `latitude` \u548c `longitude` \u7ed8\u5236\u4e24\u4e2a\u9a8c\u8bc1\u6570\u636e\u6563\u70b9\u56fe\uff1a\n", " * \u4e00\u4e2a\u6563\u70b9\u56fe\u5c06\u989c\u8272\u6620\u5c04\u5230\u5b9e\u9645\u76ee\u6807 `median_house_value`\n", " * \u53e6\u4e00\u4e2a\u6563\u70b9\u56fe\u5c06\u989c\u8272\u6620\u5c04\u5230\u9884\u6d4b\u7684 `median_house_value`\uff0c\u5e76\u6392\u8fdb\u884c\u6bd4\u8f83\u3002" ] }, { "metadata": { "id": "UXt0_4ZTEf4V", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 }, "test": { "output": "ignore", "timeout": 600 } }, "cellView": "both" }, "source": [ "def train_model(\n", " learning_rate,\n", " steps,\n", " batch_size,\n", " training_examples,\n", " training_targets,\n", " validation_examples,\n", " validation_targets):\n", " \"\"\"Trains a linear regression model of multiple features.\n", " \n", " In addition to training, this function also prints training progress information,\n", " as well as a plot of the training and validation loss over time.\n", " \n", " Args:\n", " learning_rate: A `float`, the learning rate.\n", " steps: A non-zero `int`, the total number of training steps. A training step\n", " consists of a forward and backward pass using a single batch.\n", " batch_size: A non-zero `int`, the batch size.\n", " training_examples: A `DataFrame` containing one or more columns from\n", " `california_housing_dataframe` to use as input features for training.\n", " training_targets: A `DataFrame` containing exactly one column from\n", " `california_housing_dataframe` to use as target for training.\n", " validation_examples: A `DataFrame` containing one or more columns from\n", " `california_housing_dataframe` to use as input features for validation.\n", " validation_targets: A `DataFrame` containing exactly one column from\n", " `california_housing_dataframe` to use as target for validation.\n", " \n", " Returns:\n", " A `LinearRegressor` object trained on the training data.\n", " \"\"\"\n", "\n", " periods = 10\n", " steps_per_period = steps / periods\n", " \n", " # Create a linear regressor object.\n", " my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n", " my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n", " linear_regressor = tf.estimator.LinearRegressor(\n", " feature_columns=construct_feature_columns(training_examples),\n", " optimizer=my_optimizer\n", " )\n", " \n", " # 1. Create input functions.\n", " training_input_fn = # YOUR CODE HERE\n", " predict_training_input_fn = # YOUR CODE HERE\n", " predict_validation_input_fn = # YOUR CODE HERE\n", " \n", " # Train the model, but do so inside a loop so that we can periodically assess\n", " # loss metrics.\n", " print(\"Training model...\")\n", " print(\"RMSE (on training data):\")\n", " training_rmse = []\n", " validation_rmse = []\n", " for period in range (0, periods):\n", " # Train the model, starting from the prior state.\n", " linear_regressor.train(\n", " input_fn=training_input_fn,\n", " steps=steps_per_period,\n", " )\n", " # 2. Take a break and compute predictions.\n", " training_predictions = # YOUR CODE HERE\n", " validation_predictions = # YOUR CODE HERE\n", " \n", " # Compute training and validation loss.\n", " training_root_mean_squared_error = math.sqrt(\n", " metrics.mean_squared_error(training_predictions, training_targets))\n", " validation_root_mean_squared_error = math.sqrt(\n", " metrics.mean_squared_error(validation_predictions, validation_targets))\n", " # Occasionally print the current loss.\n", " print(\" period %02d : %0.2f\" % (period, training_root_mean_squared_error))\n", " # Add the loss metrics from this period to our list.\n", " training_rmse.append(training_root_mean_squared_error)\n", " validation_rmse.append(validation_root_mean_squared_error)\n", " print(\"Model training finished.\")\n", "\n", " # Output a graph of loss metrics over periods.\n", " plt.ylabel(\"RMSE\")\n", " plt.xlabel(\"Periods\")\n", " plt.title(\"Root Mean Squared Error vs. Periods\")\n", " plt.tight_layout()\n", " plt.plot(training_rmse, label=\"training\")\n", " plt.plot(validation_rmse, label=\"validation\")\n", " plt.legend()\n", "\n", " return linear_regressor" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "metadata": { "id": "zFFRmvUGh8wd", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "linear_regressor = train_model(\n", " # TWEAK THESE VALUES TO SEE HOW MUCH YOU CAN IMPROVE THE RMSE\n", " learning_rate=0.00001,\n", " steps=100,\n", " batch_size=1,\n", " training_examples=training_examples,\n", " training_targets=training_targets,\n", " validation_examples=validation_examples,\n", " validation_targets=validation_targets)" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "I-La4N9ObC1x", "colab_type": "text" }, "source": [ " ### \u89e3\u51b3\u65b9\u6848\n", "\n", "\u70b9\u51fb\u4e0b\u65b9\u5373\u53ef\u67e5\u770b\u89e3\u51b3\u65b9\u6848\u3002" ] }, { "metadata": { "id": "Xyz6n1YHbGef", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "def train_model(\n", " learning_rate,\n", " steps,\n", " batch_size,\n", " training_examples,\n", " training_targets,\n", " validation_examples,\n", " validation_targets):\n", " \"\"\"Trains a linear regression model of multiple features.\n", " \n", " In addition to training, this function also prints training progress information,\n", " as well as a plot of the training and validation loss over time.\n", " \n", " Args:\n", " learning_rate: A `float`, the learning rate.\n", " steps: A non-zero `int`, the total number of training steps. A training step\n", " consists of a forward and backward pass using a single batch.\n", " batch_size: A non-zero `int`, the batch size.\n", " training_examples: A `DataFrame` containing one or more columns from\n", " `california_housing_dataframe` to use as input features for training.\n", " training_targets: A `DataFrame` containing exactly one column from\n", " `california_housing_dataframe` to use as target for training.\n", " validation_examples: A `DataFrame` containing one or more columns from\n", " `california_housing_dataframe` to use as input features for validation.\n", " validation_targets: A `DataFrame` containing exactly one column from\n", " `california_housing_dataframe` to use as target for validation.\n", " \n", " Returns:\n", " A `LinearRegressor` object trained on the training data.\n", " \"\"\"\n", "\n", " periods = 10\n", " steps_per_period = steps / periods\n", " \n", " # Create a linear regressor object.\n", " my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n", " my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n", " linear_regressor = tf.estimator.LinearRegressor(\n", " feature_columns=construct_feature_columns(training_examples),\n", " optimizer=my_optimizer\n", " )\n", " \n", " # Create input functions.\n", " training_input_fn = lambda: my_input_fn(\n", " training_examples, \n", " training_targets[\"median_house_value\"], \n", " batch_size=batch_size)\n", " predict_training_input_fn = lambda: my_input_fn(\n", " training_examples, \n", " training_targets[\"median_house_value\"], \n", " num_epochs=1, \n", " shuffle=False)\n", " predict_validation_input_fn = lambda: my_input_fn(\n", " validation_examples, validation_targets[\"median_house_value\"], \n", " num_epochs=1, \n", " shuffle=False)\n", "\n", " # Train the model, but do so inside a loop so that we can periodically assess\n", " # loss metrics.\n", " print(\"Training model...\")\n", " print(\"RMSE (on training data):\")\n", " training_rmse = []\n", " validation_rmse = []\n", " for period in range (0, periods):\n", " # Train the model, starting from the prior state.\n", " linear_regressor.train(\n", " input_fn=training_input_fn,\n", " steps=steps_per_period,\n", " )\n", " # Take a break and compute predictions.\n", " training_predictions = linear_regressor.predict(input_fn=predict_training_input_fn)\n", " training_predictions = np.array([item['predictions'][0] for item in training_predictions])\n", " \n", " validation_predictions = linear_regressor.predict(input_fn=predict_validation_input_fn)\n", " validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])\n", " \n", " \n", " # Compute training and validation loss.\n", " training_root_mean_squared_error = math.sqrt(\n", " metrics.mean_squared_error(training_predictions, training_targets))\n", " validation_root_mean_squared_error = math.sqrt(\n", " metrics.mean_squared_error(validation_predictions, validation_targets))\n", " # Occasionally print the current loss.\n", " print(\" period %02d : %0.2f\" % (period, training_root_mean_squared_error))\n", " # Add the loss metrics from this period to our list.\n", " training_rmse.append(training_root_mean_squared_error)\n", " validation_rmse.append(validation_root_mean_squared_error)\n", " print(\"Model training finished.\")\n", "\n", " # Output a graph of loss metrics over periods.\n", " plt.ylabel(\"RMSE\")\n", " plt.xlabel(\"Periods\")\n", " plt.title(\"Root Mean Squared Error vs. Periods\")\n", " plt.tight_layout()\n", " plt.plot(training_rmse, label=\"training\")\n", " plt.plot(validation_rmse, label=\"validation\")\n", " plt.legend()\n", "\n", " return linear_regressor" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "metadata": { "id": "i1imhjFzbWwt", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "linear_regressor = train_model(\n", " learning_rate=0.00003,\n", " steps=500,\n", " batch_size=5,\n", " training_examples=training_examples,\n", " training_targets=training_targets,\n", " validation_examples=validation_examples,\n", " validation_targets=validation_targets)" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "65sin-E5NmHN", "colab_type": "text" }, "source": [ " ## \u4efb\u52a1 5\uff1a\u57fa\u4e8e\u6d4b\u8bd5\u6570\u636e\u8fdb\u884c\u8bc4\u4f30\n", "\n", "**\u5728\u4ee5\u4e0b\u5355\u5143\u683c\u4e2d\uff0c\u8f7d\u5165\u6d4b\u8bd5\u6570\u636e\u96c6\u5e76\u636e\u6b64\u8bc4\u4f30\u6a21\u578b\u3002**\n", "\n", "\u6211\u4eec\u5df2\u5bf9\u9a8c\u8bc1\u6570\u636e\u8fdb\u884c\u4e86\u5927\u91cf\u8fed\u4ee3\u3002\u63a5\u4e0b\u6765\u786e\u4fdd\u6211\u4eec\u6ca1\u6709\u8fc7\u62df\u5408\u8be5\u7279\u5b9a\u6837\u672c\u96c6\u7684\u7279\u6027\u3002\n", "\n", "\u6d4b\u8bd5\u6570\u636e\u96c6\u4f4d\u4e8e[\u6b64\u5904](https://download.mlcc.google.cn/mledu-datasets/california_housing_test.csv)\u3002\n", "\n", "\u60a8\u7684\u6d4b\u8bd5\u6548\u679c\u4e0e\u9a8c\u8bc1\u6548\u679c\u7684\u5bf9\u6bd4\u60c5\u51b5\u5982\u4f55\uff1f\u5bf9\u6bd4\u60c5\u51b5\u8868\u660e\u60a8\u6a21\u578b\u7684\u6cdb\u5316\u6548\u679c\u5982\u4f55\uff1f" ] }, { "metadata": { "id": "icEJIl5Vp51r", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 }, "test": { "output": "ignore", "timeout": 600 } }, "cellView": "both" }, "source": [ "california_housing_test_data = pd.read_csv(\"https://download.mlcc.google.cn/mledu-datasets/california_housing_test.csv\", sep=\",\")\n", "#\n", "# YOUR CODE HERE\n", "#" ], "cell_type": "code", "execution_count": 0, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "yTghc_5HkJDW", "colab_type": "text" }, "source": [ " ### \u89e3\u51b3\u65b9\u6848\n", "\n", "\u70b9\u51fb\u4e0b\u65b9\u5373\u53ef\u67e5\u770b\u89e3\u51b3\u65b9\u6848\u3002" ] }, { "metadata": { "id": "_xSYTarykO8U", "colab_type": "code", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } } }, "source": [ "california_housing_test_data = pd.read_csv(\"https://download.mlcc.google.cn/mledu-datasets/california_housing_test.csv\", sep=\",\")\n", "\n", "test_examples = preprocess_features(california_housing_test_data)\n", "test_targets = preprocess_targets(california_housing_test_data)\n", "\n", "predict_test_input_fn = lambda: my_input_fn(\n", " test_examples, \n", " test_targets[\"median_house_value\"], \n", " num_epochs=1, \n", " shuffle=False)\n", "\n", "test_predictions = linear_regressor.predict(input_fn=predict_test_input_fn)\n", "test_predictions = np.array([item['predictions'][0] for item in test_predictions])\n", "\n", "root_mean_squared_error = math.sqrt(\n", " metrics.mean_squared_error(test_predictions, test_targets))\n", "\n", "print(\"Final RMSE (on test data): %0.2f\" % root_mean_squared_error)" ], "cell_type": "code", "execution_count": 0, "outputs": [] } ] }