From 42f4ad8ed2bdaf4d990fe81bde4af7d3a789b2b6 Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Tue, 11 Jun 2019 17:02:53 +0900 Subject: [PATCH 01/12] start translation 'linear.ipynb' --- .../ko/beta/tutorials/estimators/linear.ipynb | 656 ++++++++++++++++++ 1 file changed, 656 insertions(+) create mode 100644 site/ko/beta/tutorials/estimators/linear.ipynb diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb new file mode 100644 index 00000000000..f515ee3ae7a --- /dev/null +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -0,0 +1,656 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "OoasdhSAp0zJ" + }, + "source": [ + "##### Copyright 2019 The TensorFlow Authors." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "cellView": "form", + "colab": {}, + "colab_type": "code", + "id": "cIrwotvGqsYh" + }, + "outputs": [], + "source": [ + "#@title 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.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "C81KT2D_j-xR" + }, + "source": [ + "# Build a linear model with Estimators\n", + "\n", + "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", + " \u003ctd\u003e\n", + " \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/alpha/tutorials/estimators/linear\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n", + " \u003c/td\u003e\n", + " \u003ctd\u003e\n", + " \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/estimators/linear.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n", + " \u003c/td\u003e\n", + " \u003ctd\u003e\n", + " \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/estimators/linear.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n", + " \u003c/td\u003e\n", + "\u003c/table\u003e" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "tUP8LMdYtWPz" + }, + "source": [ + "## Overview\n", + "\n", + "This end-to-end walkthrough trains a logistic regression model using the `tf.estimator` API. The model is often used as a baseline for other, more complex, algorithms.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "vkC_j6VpqrDw" + }, + "source": [ + "## Setup" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "rutbJGmpqvm3" + }, + "outputs": [], + "source": [ + "!pip install sklearn" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "54mb4J9PqqDh" + }, + "outputs": [], + "source": [ + "from __future__ import absolute_import, division, print_function, unicode_literals\n", + "\n", + "import os\n", + "import sys\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from IPython.display import clear_output\n", + "from six.moves import urllib" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "fsjkwfsGOBMT" + }, + "source": [ + "## Load the titanic dataset\n", + "You will use the Titanic dataset with the (rather morbid) goal of predicting passenger survival, given characteristics such as gender, age, class, etc." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "bNiwh-APcRVD" + }, + "outputs": [], + "source": [ + "!pip install tensorflow==2.0.0-alpha0\n", + "import tensorflow.compat.v2.feature_column as fc\n", + "\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "DSeMKcx03d5R" + }, + "outputs": [], + "source": [ + "# Load dataset.\n", + "dftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')\n", + "dfeval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv')\n", + "y_train = dftrain.pop('survived')\n", + "y_eval = dfeval.pop('survived')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "jjm4Qj0u7_cp" + }, + "source": [ + "## Explore the data" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "UrQzxKKh4d6u" + }, + "source": [ + "The dataset contains the following features" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "rTjugo3n308g" + }, + "outputs": [], + "source": [ + "dftrain.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "y86q1fj44lZs" + }, + "outputs": [], + "source": [ + "dftrain.describe()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "8JSa_duD4tFZ" + }, + "source": [ + "There are 627 and 264 examples in the training and evaluation sets, respectively." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "Fs3Nu5pV4v5J" + }, + "outputs": [], + "source": [ + "dftrain.shape[0], dfeval.shape[0]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "RxCA4Nr45AfF" + }, + "source": [ + "The majority of passengers are in their 20's and 30's." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "RYeCMm7K40ZN" + }, + "outputs": [], + "source": [ + "dftrain.age.hist(bins=20)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "DItSwJ_B5B0f" + }, + "source": [ + "There are approximately twice as many male passengers as female passengers aboard." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "b03dVV9q5Dv2" + }, + "outputs": [], + "source": [ + "dftrain.sex.value_counts().plot(kind='barh')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rK6WQ29q5Jf5" + }, + "source": [ + "The majority of passengers were in the \"third\" class." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "dgpJVeCq5Fgd" + }, + "outputs": [], + "source": [ + "dftrain['class'].value_counts().plot(kind='barh')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "FXJhGGL85TLp" + }, + "source": [ + "Females have a much higher chance of surviving versus males. This is clearly a predictive feature for the model." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "lSZYa7c45Ttt" + }, + "outputs": [], + "source": [ + "pd.concat([dftrain, y_train], axis=1).groupby('sex').survived.mean().plot(kind='barh').set_xlabel('% survive')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "VqDKQLZn8L-B" + }, + "source": [ + "## Feature Engineering for the Model\n", + "Estimators use a system called [feature columns](https://www.tensorflow.org/guide/feature_columns) to describe how the model should interpret each of the raw input features. An Estimator expects a vector of numeric inputs, and *feature columns* describe how the model should convert each feature.\n", + "\n", + "Selecting and crafting the right set of feature columns is key to learning an effective model. A feature column can be either one of the raw inputs in the original features `dict` (a *base feature column*), or any new columns created using transformations defined over one or multiple base columns (a *derived feature columns*).\n", + "\n", + "The linear estimator uses both numeric and categorical features. Feature columns work with all TensorFlow estimators and their purpose is to define the features used for modeling. Additionally, they provide some feature engineering capabilities like one-hot-encoding, normalization, and bucketization." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "puZFOhTDkblt" + }, + "source": [ + "### Base Feature Columns" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "GpveXYSsADS6" + }, + "outputs": [], + "source": [ + "CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck',\n", + " 'embark_town', 'alone']\n", + "NUMERIC_COLUMNS = ['age', 'fare']\n", + "\n", + "feature_columns = []\n", + "for feature_name in CATEGORICAL_COLUMNS:\n", + " vocabulary = dftrain[feature_name].unique()\n", + " feature_columns.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocabulary))\n", + "\n", + "for feature_name in NUMERIC_COLUMNS:\n", + " feature_columns.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Gt8HMtwOh9lJ" + }, + "source": [ + "The `input_function` specifies how data is converted to a `tf.data.Dataset` that feeds the input pipeline in a streaming fashion. `tf.data.Dataset` take take in multiple sources such as a dataframe, a csv-formatted file, and more." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "qVtrIHFnAe7w" + }, + "outputs": [], + "source": [ + "def make_input_fn(data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):\n", + " def input_function():\n", + " ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df))\n", + " if shuffle:\n", + " ds = ds.shuffle(1000)\n", + " ds = ds.batch(batch_size).repeat(num_epochs)\n", + " return ds\n", + " return input_function\n", + "\n", + "train_input_fn = make_input_fn(dftrain, y_train)\n", + "eval_input_fn = make_input_fn(dfeval, y_eval, num_epochs=1, shuffle=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "P7UMVkQnkrgb" + }, + "source": [ + "You can inspect the dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "8ZcG_3KiCb1M" + }, + "outputs": [], + "source": [ + "ds = make_input_fn(dftrain, y_train, batch_size=10)()\n", + "for feature_batch, label_batch in ds.take(1):\n", + " print('Some feature keys:', list(feature_batch.keys()))\n", + " print()\n", + " print('A batch of class:', feature_batch['class'].numpy())\n", + " print()\n", + " print('A batch of Labels:', label_batch.numpy())" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "lMNBMyodjlW3" + }, + "source": [ + "You can also inspect the result of a specific feature column using the `tf.keras.layers.DenseFeatures` layer:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "IMjlmbPlDmkB" + }, + "outputs": [], + "source": [ + "age_column = feature_columns[7]\n", + "tf.keras.layers.DenseFeatures([age_column])(feature_batch).numpy()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "f4zrAdCIjr3s" + }, + "source": [ + "`DenseFeatures` only accepts dense tensors, to inspect a categorical column you need to transform that to a indicator column first:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "1VXmXFTSFEvv" + }, + "outputs": [], + "source": [ + "gender_column = feature_columns[0]\n", + "tf.keras.layers.DenseFeatures([tf.feature_column.indicator_column(gender_column)])(feature_batch).numpy()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "MEp59g5UkHYY" + }, + "source": [ + "After adding all the base features to the model, let's train the model. Training a model is just a single command using the `tf.estimator` API:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "aGXjdnqqdgIs" + }, + "outputs": [], + "source": [ + "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns)\n", + "linear_est.train(train_input_fn)\n", + "result = linear_est.evaluate(eval_input_fn)\n", + "\n", + "clear_output()\n", + "print(result)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "3tOan4hDsG6d" + }, + "source": [ + "### Derived Feature Columns" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "NOG2FSTHlAMu" + }, + "source": [ + "Now you reached an accuracy of 75%. Using each base feature column separately may not be enough to explain the data. For example, the correlation between gender and the label may be different for different gender. Therefore, if you only learn a single model weight for `gender=\"Male\"` and `gender=\"Female\"`, you won't capture every age-gender combination (e.g. distinguishing between `gender=\"Male\"` AND `age=\"30\"` AND `gender=\"Male\"` AND `age=\"40\"`).\n", + "\n", + "To learn the differences between different feature combinations, you can add *crossed feature columns* to the model (you can also bucketize age column before the cross column):" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "AM-RsDzNfGlu" + }, + "outputs": [], + "source": [ + "age_x_gender = tf.feature_column.crossed_column(['age', 'sex'], hash_bucket_size=100)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "DqDFyPKQmGTN" + }, + "source": [ + "After adding the combination feature to the model, let's train the model again:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "s8FV9oPQfS-g" + }, + "outputs": [], + "source": [ + "derived_feature_columns = [age_x_gender]\n", + "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns+derived_feature_columns)\n", + "linear_est.train(train_input_fn)\n", + "result = linear_est.evaluate(eval_input_fn)\n", + "\n", + "clear_output()\n", + "print(result)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rwfdZj7ImLwb" + }, + "source": [ + "It now achieves an accuracy of 77.6%, which is slightly better than only trained in base features. You can try using more features and transformations to see if you can do better!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "8_eyb9d-ncjH" + }, + "source": [ + "Now you can use the train model to make predictions on a passenger from the evaluation set. TensorFlow models are optimized to make predictions on a batch, or collection, of examples at once. Earlier, the `eval_input_fn` was defined using the entire evaluation set." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "wiScyBcef6Dq" + }, + "outputs": [], + "source": [ + "pred_dicts = list(linear_est.predict(eval_input_fn))\n", + "probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])\n", + "\n", + "probs.plot(kind='hist', bins=20, title='predicted probabilities')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "UEHRCd4sqrLs" + }, + "source": [ + "Finally, look at the receiver operating characteristic (ROC) of the results, which will give us a better idea of the tradeoff between the true positive rate and false positive rate." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "kqEjsezIokIe" + }, + "outputs": [], + "source": [ + "from sklearn.metrics import roc_curve\n", + "from matplotlib import pyplot as plt\n", + "\n", + "fpr, tpr, _ = roc_curve(y_eval, probs)\n", + "plt.plot(fpr, tpr)\n", + "plt.title('ROC curve')\n", + "plt.xlabel('false positive rate')\n", + "plt.ylabel('true positive rate')\n", + "plt.xlim(0,)\n", + "plt.ylim(0,)" + ] + } + ], + "metadata": { + "colab": { + "collapsed_sections": [], + "name": "linear.ipynb", + "private_outputs": true, + "provenance": [], + "toc_visible": true, + "version": "0.3.2" + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} From 49c8479a34c9a2dc1d55351eea31a42c661898c6 Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Wed, 12 Jun 2019 13:14:07 +0900 Subject: [PATCH 02/12] add translation 'linear.ipynb' --- .../ko/beta/tutorials/estimators/linear.ipynb | 1331 +++++++++-------- 1 file changed, 677 insertions(+), 654 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index f515ee3ae7a..c5e62e46806 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -1,656 +1,679 @@ { - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "OoasdhSAp0zJ" - }, - "source": [ - "##### Copyright 2019 The TensorFlow Authors." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "cellView": "form", - "colab": {}, - "colab_type": "code", - "id": "cIrwotvGqsYh" - }, - "outputs": [], - "source": [ - "#@title 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.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "C81KT2D_j-xR" - }, - "source": [ - "# Build a linear model with Estimators\n", - "\n", - "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", - " \u003ctd\u003e\n", - " \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/alpha/tutorials/estimators/linear\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n", - " \u003c/td\u003e\n", - " \u003ctd\u003e\n", - " \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/estimators/linear.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n", - " \u003c/td\u003e\n", - " \u003ctd\u003e\n", - " \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/estimators/linear.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n", - " \u003c/td\u003e\n", - "\u003c/table\u003e" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "tUP8LMdYtWPz" - }, - "source": [ - "## Overview\n", - "\n", - "This end-to-end walkthrough trains a logistic regression model using the `tf.estimator` API. The model is often used as a baseline for other, more complex, algorithms.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "vkC_j6VpqrDw" - }, - "source": [ - "## Setup" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "rutbJGmpqvm3" - }, - "outputs": [], - "source": [ - "!pip install sklearn" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "54mb4J9PqqDh" - }, - "outputs": [], - "source": [ - "from __future__ import absolute_import, division, print_function, unicode_literals\n", - "\n", - "import os\n", - "import sys\n", - "\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from IPython.display import clear_output\n", - "from six.moves import urllib" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "fsjkwfsGOBMT" - }, - "source": [ - "## Load the titanic dataset\n", - "You will use the Titanic dataset with the (rather morbid) goal of predicting passenger survival, given characteristics such as gender, age, class, etc." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "bNiwh-APcRVD" - }, - "outputs": [], - "source": [ - "!pip install tensorflow==2.0.0-alpha0\n", - "import tensorflow.compat.v2.feature_column as fc\n", - "\n", - "import tensorflow as tf" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "DSeMKcx03d5R" - }, - "outputs": [], - "source": [ - "# Load dataset.\n", - "dftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')\n", - "dfeval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv')\n", - "y_train = dftrain.pop('survived')\n", - "y_eval = dfeval.pop('survived')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "jjm4Qj0u7_cp" - }, - "source": [ - "## Explore the data" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "UrQzxKKh4d6u" - }, - "source": [ - "The dataset contains the following features" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "rTjugo3n308g" - }, - "outputs": [], - "source": [ - "dftrain.head()" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "y86q1fj44lZs" - }, - "outputs": [], - "source": [ - "dftrain.describe()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "8JSa_duD4tFZ" - }, - "source": [ - "There are 627 and 264 examples in the training and evaluation sets, respectively." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "Fs3Nu5pV4v5J" - }, - "outputs": [], - "source": [ - "dftrain.shape[0], dfeval.shape[0]" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "RxCA4Nr45AfF" - }, - "source": [ - "The majority of passengers are in their 20's and 30's." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "RYeCMm7K40ZN" - }, - "outputs": [], - "source": [ - "dftrain.age.hist(bins=20)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "DItSwJ_B5B0f" - }, - "source": [ - "There are approximately twice as many male passengers as female passengers aboard." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "b03dVV9q5Dv2" - }, - "outputs": [], - "source": [ - "dftrain.sex.value_counts().plot(kind='barh')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "rK6WQ29q5Jf5" - }, - "source": [ - "The majority of passengers were in the \"third\" class." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "dgpJVeCq5Fgd" - }, - "outputs": [], - "source": [ - "dftrain['class'].value_counts().plot(kind='barh')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "FXJhGGL85TLp" - }, - "source": [ - "Females have a much higher chance of surviving versus males. This is clearly a predictive feature for the model." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "lSZYa7c45Ttt" - }, - "outputs": [], - "source": [ - "pd.concat([dftrain, y_train], axis=1).groupby('sex').survived.mean().plot(kind='barh').set_xlabel('% survive')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "VqDKQLZn8L-B" - }, - "source": [ - "## Feature Engineering for the Model\n", - "Estimators use a system called [feature columns](https://www.tensorflow.org/guide/feature_columns) to describe how the model should interpret each of the raw input features. An Estimator expects a vector of numeric inputs, and *feature columns* describe how the model should convert each feature.\n", - "\n", - "Selecting and crafting the right set of feature columns is key to learning an effective model. A feature column can be either one of the raw inputs in the original features `dict` (a *base feature column*), or any new columns created using transformations defined over one or multiple base columns (a *derived feature columns*).\n", - "\n", - "The linear estimator uses both numeric and categorical features. Feature columns work with all TensorFlow estimators and their purpose is to define the features used for modeling. Additionally, they provide some feature engineering capabilities like one-hot-encoding, normalization, and bucketization." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "puZFOhTDkblt" - }, - "source": [ - "### Base Feature Columns" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "GpveXYSsADS6" - }, - "outputs": [], - "source": [ - "CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck',\n", - " 'embark_town', 'alone']\n", - "NUMERIC_COLUMNS = ['age', 'fare']\n", - "\n", - "feature_columns = []\n", - "for feature_name in CATEGORICAL_COLUMNS:\n", - " vocabulary = dftrain[feature_name].unique()\n", - " feature_columns.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocabulary))\n", - "\n", - "for feature_name in NUMERIC_COLUMNS:\n", - " feature_columns.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32))" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "Gt8HMtwOh9lJ" - }, - "source": [ - "The `input_function` specifies how data is converted to a `tf.data.Dataset` that feeds the input pipeline in a streaming fashion. `tf.data.Dataset` take take in multiple sources such as a dataframe, a csv-formatted file, and more." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "qVtrIHFnAe7w" - }, - "outputs": [], - "source": [ - "def make_input_fn(data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):\n", - " def input_function():\n", - " ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df))\n", - " if shuffle:\n", - " ds = ds.shuffle(1000)\n", - " ds = ds.batch(batch_size).repeat(num_epochs)\n", - " return ds\n", - " return input_function\n", - "\n", - "train_input_fn = make_input_fn(dftrain, y_train)\n", - "eval_input_fn = make_input_fn(dfeval, y_eval, num_epochs=1, shuffle=False)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "P7UMVkQnkrgb" - }, - "source": [ - "You can inspect the dataset:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "8ZcG_3KiCb1M" - }, - "outputs": [], - "source": [ - "ds = make_input_fn(dftrain, y_train, batch_size=10)()\n", - "for feature_batch, label_batch in ds.take(1):\n", - " print('Some feature keys:', list(feature_batch.keys()))\n", - " print()\n", - " print('A batch of class:', feature_batch['class'].numpy())\n", - " print()\n", - " print('A batch of Labels:', label_batch.numpy())" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "lMNBMyodjlW3" - }, - "source": [ - "You can also inspect the result of a specific feature column using the `tf.keras.layers.DenseFeatures` layer:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "IMjlmbPlDmkB" - }, - "outputs": [], - "source": [ - "age_column = feature_columns[7]\n", - "tf.keras.layers.DenseFeatures([age_column])(feature_batch).numpy()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "f4zrAdCIjr3s" - }, - "source": [ - "`DenseFeatures` only accepts dense tensors, to inspect a categorical column you need to transform that to a indicator column first:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "1VXmXFTSFEvv" - }, - "outputs": [], - "source": [ - "gender_column = feature_columns[0]\n", - "tf.keras.layers.DenseFeatures([tf.feature_column.indicator_column(gender_column)])(feature_batch).numpy()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "MEp59g5UkHYY" - }, - "source": [ - "After adding all the base features to the model, let's train the model. Training a model is just a single command using the `tf.estimator` API:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "aGXjdnqqdgIs" - }, - "outputs": [], - "source": [ - "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns)\n", - "linear_est.train(train_input_fn)\n", - "result = linear_est.evaluate(eval_input_fn)\n", - "\n", - "clear_output()\n", - "print(result)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "3tOan4hDsG6d" - }, - "source": [ - "### Derived Feature Columns" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "NOG2FSTHlAMu" - }, - "source": [ - "Now you reached an accuracy of 75%. Using each base feature column separately may not be enough to explain the data. For example, the correlation between gender and the label may be different for different gender. Therefore, if you only learn a single model weight for `gender=\"Male\"` and `gender=\"Female\"`, you won't capture every age-gender combination (e.g. distinguishing between `gender=\"Male\"` AND `age=\"30\"` AND `gender=\"Male\"` AND `age=\"40\"`).\n", - "\n", - "To learn the differences between different feature combinations, you can add *crossed feature columns* to the model (you can also bucketize age column before the cross column):" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "AM-RsDzNfGlu" - }, - "outputs": [], - "source": [ - "age_x_gender = tf.feature_column.crossed_column(['age', 'sex'], hash_bucket_size=100)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "DqDFyPKQmGTN" - }, - "source": [ - "After adding the combination feature to the model, let's train the model again:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "s8FV9oPQfS-g" - }, - "outputs": [], - "source": [ - "derived_feature_columns = [age_x_gender]\n", - "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns+derived_feature_columns)\n", - "linear_est.train(train_input_fn)\n", - "result = linear_est.evaluate(eval_input_fn)\n", - "\n", - "clear_output()\n", - "print(result)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "rwfdZj7ImLwb" - }, - "source": [ - "It now achieves an accuracy of 77.6%, which is slightly better than only trained in base features. You can try using more features and transformations to see if you can do better!" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "8_eyb9d-ncjH" - }, - "source": [ - "Now you can use the train model to make predictions on a passenger from the evaluation set. TensorFlow models are optimized to make predictions on a batch, or collection, of examples at once. Earlier, the `eval_input_fn` was defined using the entire evaluation set." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "wiScyBcef6Dq" - }, - "outputs": [], - "source": [ - "pred_dicts = list(linear_est.predict(eval_input_fn))\n", - "probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])\n", - "\n", - "probs.plot(kind='hist', bins=20, title='predicted probabilities')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "UEHRCd4sqrLs" - }, - "source": [ - "Finally, look at the receiver operating characteristic (ROC) of the results, which will give us a better idea of the tradeoff between the true positive rate and false positive rate." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "kqEjsezIokIe" - }, - "outputs": [], - "source": [ - "from sklearn.metrics import roc_curve\n", - "from matplotlib import pyplot as plt\n", - "\n", - "fpr, tpr, _ = roc_curve(y_eval, probs)\n", - "plt.plot(fpr, tpr)\n", - "plt.title('ROC curve')\n", - "plt.xlabel('false positive rate')\n", - "plt.ylabel('true positive rate')\n", - "plt.xlim(0,)\n", - "plt.ylim(0,)" - ] - } - ], - "metadata": { - "colab": { - "collapsed_sections": [], - "name": "linear.ipynb", - "private_outputs": true, - "provenance": [], - "toc_visible": true, - "version": "0.3.2" - }, - "kernelspec": { - "display_name": "Python 3", - "name": "python3" - } - }, - "nbformat": 4, - "nbformat_minor": 0 + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "OoasdhSAp0zJ" + }, + "source": [ + "##### Copyright 2019 The TensorFlow Authors." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "cellView": "form", + "colab": {}, + "colab_type": "code", + "id": "cIrwotvGqsYh" + }, + "outputs": [], + "source": [ + "#@title 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.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "C81KT2D_j-xR" + }, + "source": [ + "# 추정기(Estimator)로 선형 모델 만들기\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "
\n", + " TensorFlow.org에서 보기\n", + " \n", + " 구글 코랩(Colab)에서 실행하기\n", + " \n", + " 깃허브(GitHub) 소스 보기\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "tUP8LMdYtWPz" + }, + "source": [ + "Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상 정확한 번역과 최신 내용을 반영하기 위해 노력함에도 불구하고 [공식 영문 문서](https://github.com/tensorflow/docs/blob/master/site/en/r2/guide/using_gpu.ipynb)의 내용과 일치하지 않을 수 있습니다. 이 번역에 개선할 부분이 있다면 [tensorflow/docs](https://github.com/tensorflow/docs) 깃헙 저장소로 풀 리퀘스트를 보내주시기 바랍니다. 문서 번역이나 리뷰에 참여하려면 [docs-ko@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ko)로 메일을 보내주시기 바랍니다." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "tUP8LMdYtWPz" + }, + "source": [ + "## 개요\n", + "\n", + "이 문서에서는 `tf.estimator` API를 사용하여 로지스틱 회귀 모델(logistic regression model)을 훈련합니다. 이 모델은 다른 더 복잡한 알고리즘의 기초로 사용할 수 있습니다.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "vkC_j6VpqrDw" + }, + "source": [ + "## 설정" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "rutbJGmpqvm3" + }, + "outputs": [], + "source": [ + "!pip install sklearn" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "54mb4J9PqqDh" + }, + "outputs": [], + "source": [ + "from __future__ import absolute_import, division, print_function, unicode_literals\n", + "\n", + "import os\n", + "import sys\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from IPython.display import clear_output\n", + "from six.moves import urllib" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "fsjkwfsGOBMT" + }, + "source": [ + "## 타이타닉 데이터셋을 불러오기\n", + "타이타닉 데이터셋을 사용할 것입니다. 성별, 나이, 클래스, 기타 등 주어진 정보를 활용하여 승객이 살아남을 것인지 예측하는 것을 목표로 합니다." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "bNiwh-APcRVD" + }, + "outputs": [], + "source": [ + "!pip install tensorflow==2.0.0-alpha0\n", + "import tensorflow.compat.v2.feature_column as fc\n", + "\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "DSeMKcx03d5R" + }, + "outputs": [], + "source": [ + "# 데이터셋 불러오기.\n", + "dftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')\n", + "dfeval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv')\n", + "y_train = dftrain.pop('survived')\n", + "y_eval = dfeval.pop('survived')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "jjm4Qj0u7_cp" + }, + "source": [ + "## Explore the data" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "UrQzxKKh4d6u" + }, + "source": [ + "The dataset contains the following features" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "rTjugo3n308g" + }, + "outputs": [], + "source": [ + "dftrain.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "y86q1fj44lZs" + }, + "outputs": [], + "source": [ + "dftrain.describe()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "8JSa_duD4tFZ" + }, + "source": [ + "There are 627 and 264 examples in the training and evaluation sets, respectively." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "Fs3Nu5pV4v5J" + }, + "outputs": [], + "source": [ + "dftrain.shape[0], dfeval.shape[0]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "RxCA4Nr45AfF" + }, + "source": [ + "대부분의 승객은 20대와 30대 입니다." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "RYeCMm7K40ZN" + }, + "outputs": [], + "source": [ + "dftrain.age.hist(bins=20)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "DItSwJ_B5B0f" + }, + "source": [ + "남자 승객이 여자 승객보다 대략 2배 많습니다." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "b03dVV9q5Dv2" + }, + "outputs": [], + "source": [ + "dftrain.sex.value_counts().plot(kind='barh')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rK6WQ29q5Jf5" + }, + "source": [ + "대부분의 승객은 \"삼등석\" 입니다." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "dgpJVeCq5Fgd" + }, + "outputs": [], + "source": [ + "dftrain['class'].value_counts().plot(kind='barh')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "FXJhGGL85TLp" + }, + "source": [ + "여자는 남자보다 살아남을 확률이 훨씬 높습니다. 이는 모델에서 명확하게 예측가능한 특징입니다." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "lSZYa7c45Ttt" + }, + "outputs": [], + "source": [ + "pd.concat([dftrain, y_train], axis=1).groupby('sex').survived.mean().plot(kind='barh').set_xlabel('% survive')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "VqDKQLZn8L-B" + }, + "source": [ + "## 모델을 위한 특징 공학\n", + "Estimators use a system called [feature columns](https://www.tensorflow.org/guide/feature_columns) to describe how the model should interpret each of the raw input features. An Estimator expects a vector of numeric inputs, and *feature columns* describe how the model should convert each feature.\n", + "\n", + "Selecting and crafting the right set of feature columns is key to learning an effective model. A feature column can be either one of the raw inputs in the original features `dict` (a *base feature column*), or any new columns created using transformations defined over one or multiple base columns (a *derived feature columns*).\n", + "\n", + "The linear estimator uses both numeric and categorical features. Feature columns work with all TensorFlow estimators and their purpose is to define the features used for modeling. Additionally, they provide some feature engineering capabilities like one-hot-encoding, normalization, and bucketization." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "puZFOhTDkblt" + }, + "source": [ + "### Base Feature Columns" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "GpveXYSsADS6" + }, + "outputs": [], + "source": [ + "CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck',\n", + " 'embark_town', 'alone']\n", + "NUMERIC_COLUMNS = ['age', 'fare']\n", + "\n", + "feature_columns = []\n", + "for feature_name in CATEGORICAL_COLUMNS:\n", + " vocabulary = dftrain[feature_name].unique()\n", + " feature_columns.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocabulary))\n", + "\n", + "for feature_name in NUMERIC_COLUMNS:\n", + " feature_columns.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Gt8HMtwOh9lJ" + }, + "source": [ + "The `input_function` specifies how data is converted to a `tf.data.Dataset` that feeds the input pipeline in a streaming fashion. `tf.data.Dataset` take take in multiple sources such as a dataframe, a csv-formatted file, and more." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "qVtrIHFnAe7w" + }, + "outputs": [], + "source": [ + "def make_input_fn(data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):\n", + " def input_function():\n", + " ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df))\n", + " if shuffle:\n", + " ds = ds.shuffle(1000)\n", + " ds = ds.batch(batch_size).repeat(num_epochs)\n", + " return ds\n", + " return input_function\n", + "\n", + "train_input_fn = make_input_fn(dftrain, y_train)\n", + "eval_input_fn = make_input_fn(dfeval, y_eval, num_epochs=1, shuffle=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "P7UMVkQnkrgb" + }, + "source": [ + "You can inspect the dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "8ZcG_3KiCb1M" + }, + "outputs": [], + "source": [ + "ds = make_input_fn(dftrain, y_train, batch_size=10)()\n", + "for feature_batch, label_batch in ds.take(1):\n", + " print('Some feature keys:', list(feature_batch.keys()))\n", + " print()\n", + " print('A batch of class:', feature_batch['class'].numpy())\n", + " print()\n", + " print('A batch of Labels:', label_batch.numpy())" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "lMNBMyodjlW3" + }, + "source": [ + "You can also inspect the result of a specific feature column using the `tf.keras.layers.DenseFeatures` layer:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "IMjlmbPlDmkB" + }, + "outputs": [], + "source": [ + "age_column = feature_columns[7]\n", + "tf.keras.layers.DenseFeatures([age_column])(feature_batch).numpy()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "f4zrAdCIjr3s" + }, + "source": [ + "`DenseFeatures` only accepts dense tensors, to inspect a categorical column you need to transform that to a indicator column first:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "1VXmXFTSFEvv" + }, + "outputs": [], + "source": [ + "gender_column = feature_columns[0]\n", + "tf.keras.layers.DenseFeatures([tf.feature_column.indicator_column(gender_column)])(feature_batch).numpy()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "MEp59g5UkHYY" + }, + "source": [ + "After adding all the base features to the model, let's train the model. Training a model is just a single command using the `tf.estimator` API:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "aGXjdnqqdgIs" + }, + "outputs": [], + "source": [ + "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns)\n", + "linear_est.train(train_input_fn)\n", + "result = linear_est.evaluate(eval_input_fn)\n", + "\n", + "clear_output()\n", + "print(result)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "3tOan4hDsG6d" + }, + "source": [ + "### Derived Feature Columns" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "NOG2FSTHlAMu" + }, + "source": [ + "Now you reached an accuracy of 75%. Using each base feature column separately may not be enough to explain the data. For example, the correlation between gender and the label may be different for different gender. Therefore, if you only learn a single model weight for `gender=\"Male\"` and `gender=\"Female\"`, you won't capture every age-gender combination (e.g. distinguishing between `gender=\"Male\"` AND `age=\"30\"` AND `gender=\"Male\"` AND `age=\"40\"`).\n", + "\n", + "To learn the differences between different feature combinations, you can add *crossed feature columns* to the model (you can also bucketize age column before the cross column):" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "AM-RsDzNfGlu" + }, + "outputs": [], + "source": [ + "age_x_gender = tf.feature_column.crossed_column(['age', 'sex'], hash_bucket_size=100)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "DqDFyPKQmGTN" + }, + "source": [ + "After adding the combination feature to the model, let's train the model again:" + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "s8FV9oPQfS-g" + }, + "outputs": [], + "source": [ + "derived_feature_columns = [age_x_gender]\n", + "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns+derived_feature_columns)\n", + "linear_est.train(train_input_fn)\n", + "result = linear_est.evaluate(eval_input_fn)\n", + "\n", + "clear_output()\n", + "print(result)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rwfdZj7ImLwb" + }, + "source": [ + "It now achieves an accuracy of 77.6%, which is slightly better than only trained in base features. You can try using more features and transformations to see if you can do better!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "8_eyb9d-ncjH" + }, + "source": [ + "Now you can use the train model to make predictions on a passenger from the evaluation set. TensorFlow models are optimized to make predictions on a batch, or collection, of examples at once. Earlier, the `eval_input_fn` was defined using the entire evaluation set." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "wiScyBcef6Dq" + }, + "outputs": [], + "source": [ + "pred_dicts = list(linear_est.predict(eval_input_fn))\n", + "probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])\n", + "\n", + "probs.plot(kind='hist', bins=20, title='predicted probabilities')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "UEHRCd4sqrLs" + }, + "source": [ + "Finally, look at the receiver operating characteristic (ROC) of the results, which will give us a better idea of the tradeoff between the true positive rate and false positive rate." + ] + }, + { + "cell_type": "code", + "execution_count": 0, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "kqEjsezIokIe" + }, + "outputs": [], + "source": [ + "from sklearn.metrics import roc_curve\n", + "from matplotlib import pyplot as plt\n", + "\n", + "fpr, tpr, _ = roc_curve(y_eval, probs)\n", + "plt.plot(fpr, tpr)\n", + "plt.title('ROC curve')\n", + "plt.xlabel('false positive rate')\n", + "plt.ylabel('true positive rate')\n", + "plt.xlim(0,)\n", + "plt.ylim(0,)" + ] + } + ], + "metadata": { + "colab": { + "collapsed_sections": [], + "name": "linear.ipynb", + "private_outputs": true, + "provenance": [], + "toc_visible": true, + "version": "0.3.2" + }, + "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.7.1" + } + }, + "nbformat": 4, + "nbformat_minor": 1 } From fe6659a87801ff1a9117bf572fe05ab16fba8daa Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Wed, 12 Jun 2019 13:56:11 +0900 Subject: [PATCH 03/12] half done 'linear.ipynb' --- site/ko/beta/tutorials/estimators/linear.ipynb | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index c5e62e46806..dfa2697057c 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -144,7 +144,7 @@ }, "outputs": [], "source": [ - "!pip install tensorflow==2.0.0-alpha0\n", + "!pip install tensorflow==2.0.0-beta0\n", "import tensorflow.compat.v2.feature_column as fc\n", "\n", "import tensorflow as tf" @@ -174,7 +174,7 @@ "id": "jjm4Qj0u7_cp" }, "source": [ - "## Explore the data" + "## 데이터 탐험하기" ] }, { @@ -184,7 +184,7 @@ "id": "UrQzxKKh4d6u" }, "source": [ - "The dataset contains the following features" + "데이터셋은 다음의 특징을 가집니다" ] }, { @@ -220,7 +220,7 @@ "id": "8JSa_duD4tFZ" }, "source": [ - "There are 627 and 264 examples in the training and evaluation sets, respectively." + "훈련셋은 627개의 사례로 평가셋은 264개의 사례로 구성되어 있습니다." ] }, { @@ -336,11 +336,11 @@ }, "source": [ "## 모델을 위한 특징 공학\n", - "Estimators use a system called [feature columns](https://www.tensorflow.org/guide/feature_columns) to describe how the model should interpret each of the raw input features. An Estimator expects a vector of numeric inputs, and *feature columns* describe how the model should convert each feature.\n", + "추정기는 [특징열(feature columns)](https://www.tensorflow.org/guide/feature_columns)라는 시스템을 사용하여 모델이 각각의 입력 특징을 어떻게 번역해야 할지 설명합니다. 추정기가 숫자 입력 벡터를 요구하면, *특징열*은 모델이 어떻게 각 특징을 변환해야하는지 설명합니다.\n", "\n", - "Selecting and crafting the right set of feature columns is key to learning an effective model. A feature column can be either one of the raw inputs in the original features `dict` (a *base feature column*), or any new columns created using transformations defined over one or multiple base columns (a *derived feature columns*).\n", + "효과적인 모델 학습에서는 적절한 특징열을 고르고 다듬는 것이 키포인트 입니다. 하나의 특징열이 원래의 특징 `dict` (*기준 특징열*)의 원래 입력 중 하나가 되거나 하나 또는 여러 기준열 (*얻어진 특징열*) 에 정의된 변환을 이용하여 생성된 새로운 열이 될 수 있습니다.\n", "\n", - "The linear estimator uses both numeric and categorical features. Feature columns work with all TensorFlow estimators and their purpose is to define the features used for modeling. Additionally, they provide some feature engineering capabilities like one-hot-encoding, normalization, and bucketization." + "선형 추정기는 수치형, 범주형 특징을 모두 사용할 수 있습니다. 특징열은 모든 텐서플로 추정기와 함께 작동하고 목적은 모델링에 사용되는 특징들을 정의하는 것입니다. 또한 원핫인코딩(one-hot-encoding), 정규화(normalization), 버킷화(bucketization)와 같은 특징 공학 방법을 지원합니다." ] }, { @@ -350,7 +350,7 @@ "id": "puZFOhTDkblt" }, "source": [ - "### Base Feature Columns" + "### 기준 특징열" ] }, { From 9f7f794d86e94f69ff877d9d12b29d9e7d49481c Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Wed, 12 Jun 2019 17:39:14 +0900 Subject: [PATCH 04/12] finish translation 'linear.ipynb' --- .../ko/beta/tutorials/estimators/linear.ipynb | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index dfa2697057c..646ddb5f593 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -383,7 +383,7 @@ "id": "Gt8HMtwOh9lJ" }, "source": [ - "The `input_function` specifies how data is converted to a `tf.data.Dataset` that feeds the input pipeline in a streaming fashion. `tf.data.Dataset` take take in multiple sources such as a dataframe, a csv-formatted file, and more." + "`input_function`은 입력 파이프라인을 스트리밍으로 공급하는 `tf.data.Dataset`으로 데이터를 변환하는 방법을 명시합니다. `tf.data.Dataset`은 데이터 프레임, CSV 형식 파일 등과 같은 여러 소스를 사용합니다." ] }, { @@ -416,7 +416,7 @@ "id": "P7UMVkQnkrgb" }, "source": [ - "You can inspect the dataset:" + "다음과 같이 데이터셋을 점검할 수 있습니다:" ] }, { @@ -431,11 +431,11 @@ "source": [ "ds = make_input_fn(dftrain, y_train, batch_size=10)()\n", "for feature_batch, label_batch in ds.take(1):\n", - " print('Some feature keys:', list(feature_batch.keys()))\n", + " print('특징 키:', list(feature_batch.keys()))\n", " print()\n", - " print('A batch of class:', feature_batch['class'].numpy())\n", + " print('클래스 배치:', feature_batch['class'].numpy())\n", " print()\n", - " print('A batch of Labels:', label_batch.numpy())" + " print('레이블 배치:', label_batch.numpy())" ] }, { @@ -445,7 +445,7 @@ "id": "lMNBMyodjlW3" }, "source": [ - "You can also inspect the result of a specific feature column using the `tf.keras.layers.DenseFeatures` layer:" + "또한 `tf.keras.layers.DenseFeatures` 층을 사용하여 특정한 특징열의 결과를 점검할 수 있습니다:" ] }, { @@ -469,7 +469,7 @@ "id": "f4zrAdCIjr3s" }, "source": [ - "`DenseFeatures` only accepts dense tensors, to inspect a categorical column you need to transform that to a indicator column first:" + "`DenseFeatures`는 조밀한(dense) 텐서만 허용합니다. 우선 범주 열을 지시 열로 변환해야 합니다:" ] }, { @@ -493,7 +493,7 @@ "id": "MEp59g5UkHYY" }, "source": [ - "After adding all the base features to the model, let's train the model. Training a model is just a single command using the `tf.estimator` API:" + "모든 기본 특징을 모델에 추가한 다음에 모델을 훈련해 봅시다. 모델을 훈련하려면 `tf.estimator` API를 이용한 커맨드 하나면 충분합니다:" ] }, { @@ -521,7 +521,7 @@ "id": "3tOan4hDsG6d" }, "source": [ - "### Derived Feature Columns" + "### 도출된 특징 열" ] }, { @@ -531,9 +531,9 @@ "id": "NOG2FSTHlAMu" }, "source": [ - "Now you reached an accuracy of 75%. Using each base feature column separately may not be enough to explain the data. For example, the correlation between gender and the label may be different for different gender. Therefore, if you only learn a single model weight for `gender=\"Male\"` and `gender=\"Female\"`, you won't capture every age-gender combination (e.g. distinguishing between `gender=\"Male\"` AND `age=\"30\"` AND `gender=\"Male\"` AND `age=\"40\"`).\n", + "이제 정확도 75%에 도달했습니다. 별도로 각 기본 특징열을 사용하면 데이터를 설명하기에는 충분치 않을 수 있습니다. 예를 들면, 성별과 레이블간의 상관관계는 성별에 따라 다를 수 있습니다. 따라서 `gender=\"Male\"`과 'gender=\"Female\"`의 단일 모델가중치만 배우면 모든 나이-성별 조합(이를테면 `gender=\"Male\" 그리고 'age=\"30\"` 그리고 `gender=\"Male\"` 그리고 `age=\"40\"`을 구별하는 것)을 포함시킬 수 없습니다.\n", "\n", - "To learn the differences between different feature combinations, you can add *crossed feature columns* to the model (you can also bucketize age column before the cross column):" + "서로 다른 특징 조합들 간의 차이를 학습하기 위해서 모델에 *교차 특징열*을 추가할 수 있습니다(또한 교차 열 이전에 나이 열을 버킷화할 수 있습니다):" ] }, { @@ -556,7 +556,7 @@ "id": "DqDFyPKQmGTN" }, "source": [ - "After adding the combination feature to the model, let's train the model again:" + "조합 특징을 모델에 추가하고 모델을 다시 훈련합니다:" ] }, { @@ -585,7 +585,7 @@ "id": "rwfdZj7ImLwb" }, "source": [ - "It now achieves an accuracy of 77.6%, which is slightly better than only trained in base features. You can try using more features and transformations to see if you can do better!" + "이제 77.6% 정확도에 도달했습니다. 기본 특징만 이용한 학습보다는 약간 더 좋았습니다. 더 많은 특징과 변환을 사용해서 더 잘할 수 있다는 것을 보여주세요!" ] }, { @@ -595,7 +595,7 @@ "id": "8_eyb9d-ncjH" }, "source": [ - "Now you can use the train model to make predictions on a passenger from the evaluation set. TensorFlow models are optimized to make predictions on a batch, or collection, of examples at once. Earlier, the `eval_input_fn` was defined using the entire evaluation set." + "이제 훈련 모델을 이용해서 평가셋에서 승객에 대해 예측을 할 수 있습니다. 텐서플로 모델은 한번에 사례의 한 배치 또는 콜렉션에 대한 예측을 하도록 최적화되어있습니다. 이전에, `eval_input_fn`은 모든 평가셋을 사용하도록 정의되어 있었습니다." ] }, { @@ -611,7 +611,7 @@ "pred_dicts = list(linear_est.predict(eval_input_fn))\n", "probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])\n", "\n", - "probs.plot(kind='hist', bins=20, title='predicted probabilities')" + "probs.plot(kind='hist', bins=20, title='예측 확률')" ] }, { @@ -621,7 +621,7 @@ "id": "UEHRCd4sqrLs" }, "source": [ - "Finally, look at the receiver operating characteristic (ROC) of the results, which will give us a better idea of the tradeoff between the true positive rate and false positive rate." + "마지막으로, 수신자 조작 특성(receiver operating characteristic, ROC)을 살펴보면 정탐률(true positive rate)과 오탐률(false positive rate)의 상충관계에 대해 더 잘 이해할 수 있습니다. " ] }, { @@ -640,8 +640,8 @@ "fpr, tpr, _ = roc_curve(y_eval, probs)\n", "plt.plot(fpr, tpr)\n", "plt.title('ROC curve')\n", - "plt.xlabel('false positive rate')\n", - "plt.ylabel('true positive rate')\n", + "plt.xlabel('오탐률(false positive rate)')\n", + "plt.ylabel('정탐률(true positive rate)')\n", "plt.xlim(0,)\n", "plt.ylim(0,)" ] From da1b9be421b43d82f6e2af09a5de06f959af94a8 Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Wed, 12 Jun 2019 17:46:30 +0900 Subject: [PATCH 05/12] proof reading --- site/ko/beta/tutorials/estimators/linear.ipynb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index 646ddb5f593..067fcf4f6bb 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -335,8 +335,8 @@ "id": "VqDKQLZn8L-B" }, "source": [ - "## 모델을 위한 특징 공학\n", - "추정기는 [특징열(feature columns)](https://www.tensorflow.org/guide/feature_columns)라는 시스템을 사용하여 모델이 각각의 입력 특징을 어떻게 번역해야 할지 설명합니다. 추정기가 숫자 입력 벡터를 요구하면, *특징열*은 모델이 어떻게 각 특징을 변환해야하는지 설명합니다.\n", + "## 모델을 위한 특징 공학(feature engineering)\n", + "추정기는 [특징열(feature columns)](https://www.tensorflow.org/guide/feature_columns)이라는 시스템을 사용하여 모델이 각각의 입력 특징을 어떻게 해석할지 설명합니다. 추정기가 숫자 입력 벡터를 요구하면, *특징열*은 모델이 어떻게 각 특징을 변환해야하는지 설명합니다.\n", "\n", "효과적인 모델 학습에서는 적절한 특징열을 고르고 다듬는 것이 키포인트 입니다. 하나의 특징열이 원래의 특징 `dict` (*기준 특징열*)의 원래 입력 중 하나가 되거나 하나 또는 여러 기준열 (*얻어진 특징열*) 에 정의된 변환을 이용하여 생성된 새로운 열이 될 수 있습니다.\n", "\n", @@ -521,7 +521,7 @@ "id": "3tOan4hDsG6d" }, "source": [ - "### 도출된 특징 열" + "### 도출된 특징열" ] }, { @@ -585,7 +585,7 @@ "id": "rwfdZj7ImLwb" }, "source": [ - "이제 77.6% 정확도에 도달했습니다. 기본 특징만 이용한 학습보다는 약간 더 좋았습니다. 더 많은 특징과 변환을 사용해서 더 잘할 수 있다는 것을 보여주세요!" + "이제 정확도 77.6%에 도달했습니다. 기본 특징만 이용한 학습보다는 약간 더 좋았습니다. 더 많은 특징과 변환을 사용해서 더 잘할 수 있다는 것을 보여주세요!" ] }, { From ff3c51c6baf9a61d1bf07f2545c37a0dc513c736 Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Thu, 13 Jun 2019 18:32:45 +0900 Subject: [PATCH 06/12] applied reviewer's comment --- .../ko/beta/tutorials/estimators/linear.ipynb | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index 067fcf4f6bb..dc3c717967d 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -184,7 +184,7 @@ "id": "UrQzxKKh4d6u" }, "source": [ - "데이터셋은 다음의 특징을 가집니다" + "데이터셋은 다음의 특성을 가집니다" ] }, { @@ -312,7 +312,7 @@ "id": "FXJhGGL85TLp" }, "source": [ - "여자는 남자보다 살아남을 확률이 훨씬 높습니다. 이는 모델에서 명확하게 예측가능한 특징입니다." + "여자는 남자보다 살아남을 확률이 훨씬 높습니다. 이는 모델에서 명확하게 예측가능한 특성입니다." ] }, { @@ -335,12 +335,12 @@ "id": "VqDKQLZn8L-B" }, "source": [ - "## 모델을 위한 특징 공학(feature engineering)\n", - "추정기는 [특징열(feature columns)](https://www.tensorflow.org/guide/feature_columns)이라는 시스템을 사용하여 모델이 각각의 입력 특징을 어떻게 해석할지 설명합니다. 추정기가 숫자 입력 벡터를 요구하면, *특징열*은 모델이 어떻게 각 특징을 변환해야하는지 설명합니다.\n", + "## 모델을 위한 특성 공학(feature engineering)\n", + "추정기는 [특성 열(feature columns)](https://www.tensorflow.org/guide/feature_columns)이라는 시스템을 사용하여 모델이 각각의 입력 특성을 어떻게 해석할지 설명합니다. 추정기가 숫자 입력 벡터를 요구하면, *특성 열*은 모델이 어떻게 각 특성을 변환해야하는지 설명합니다.\n", "\n", - "효과적인 모델 학습에서는 적절한 특징열을 고르고 다듬는 것이 키포인트 입니다. 하나의 특징열이 원래의 특징 `dict` (*기준 특징열*)의 원래 입력 중 하나가 되거나 하나 또는 여러 기준열 (*얻어진 특징열*) 에 정의된 변환을 이용하여 생성된 새로운 열이 될 수 있습니다.\n", + "효과적인 모델 학습에서는 적절한 특성 열을 고르고 다듬는 것이 키포인트 입니다. 하나의 특성 열이 원래의 특성 `dict` (*기준 특성 열*)의 원래 입력 중 하나가 되거나 하나 또는 여러 기준열 (*얻어진 특성 열*) 에 정의된 변환을 이용하여 생성된 새로운 열이 될 수 있습니다.\n", "\n", - "선형 추정기는 수치형, 범주형 특징을 모두 사용할 수 있습니다. 특징열은 모든 텐서플로 추정기와 함께 작동하고 목적은 모델링에 사용되는 특징들을 정의하는 것입니다. 또한 원핫인코딩(one-hot-encoding), 정규화(normalization), 버킷화(bucketization)와 같은 특징 공학 방법을 지원합니다." + "선형 추정기는 수치형, 범주형 특성을 모두 사용할 수 있습니다. 특성 열은 모든 텐서플로 추정기와 함께 작동하고 목적은 모델링에 사용되는 특성들을 정의하는 것입니다. 또한 원핫인코딩(one-hot-encoding), 정규화(normalization), 버킷화(bucketization)와 같은 특성 공학 방법을 지원합니다." ] }, { @@ -350,7 +350,7 @@ "id": "puZFOhTDkblt" }, "source": [ - "### 기준 특징열" + "### 기준 특성 열" ] }, { @@ -431,7 +431,7 @@ "source": [ "ds = make_input_fn(dftrain, y_train, batch_size=10)()\n", "for feature_batch, label_batch in ds.take(1):\n", - " print('특징 키:', list(feature_batch.keys()))\n", + " print('특성 키:', list(feature_batch.keys()))\n", " print()\n", " print('클래스 배치:', feature_batch['class'].numpy())\n", " print()\n", @@ -445,7 +445,7 @@ "id": "lMNBMyodjlW3" }, "source": [ - "또한 `tf.keras.layers.DenseFeatures` 층을 사용하여 특정한 특징열의 결과를 점검할 수 있습니다:" + "또한 `tf.keras.layers.DenseFeatures` 층을 사용하여 특정한 특성 열의 결과를 점검할 수 있습니다:" ] }, { @@ -493,7 +493,7 @@ "id": "MEp59g5UkHYY" }, "source": [ - "모든 기본 특징을 모델에 추가한 다음에 모델을 훈련해 봅시다. 모델을 훈련하려면 `tf.estimator` API를 이용한 커맨드 하나면 충분합니다:" + "모든 기본 특성을 모델에 추가한 다음에 모델을 훈련해 봅시다. 모델을 훈련하려면 `tf.estimator` API를 이용한 커맨드 하나면 충분합니다:" ] }, { @@ -521,7 +521,7 @@ "id": "3tOan4hDsG6d" }, "source": [ - "### 도출된 특징열" + "### 도출된 특성 열" ] }, { @@ -531,9 +531,9 @@ "id": "NOG2FSTHlAMu" }, "source": [ - "이제 정확도 75%에 도달했습니다. 별도로 각 기본 특징열을 사용하면 데이터를 설명하기에는 충분치 않을 수 있습니다. 예를 들면, 성별과 레이블간의 상관관계는 성별에 따라 다를 수 있습니다. 따라서 `gender=\"Male\"`과 'gender=\"Female\"`의 단일 모델가중치만 배우면 모든 나이-성별 조합(이를테면 `gender=\"Male\" 그리고 'age=\"30\"` 그리고 `gender=\"Male\"` 그리고 `age=\"40\"`을 구별하는 것)을 포함시킬 수 없습니다.\n", + "이제 정확도 75%에 도달했습니다. 별도로 각 기본 특성 열을 사용하면 데이터를 설명하기에는 충분치 않을 수 있습니다. 예를 들면, 성별과 레이블간의 상관관계는 성별에 따라 다를 수 있습니다. 따라서 `gender=\"Male\"`과 'gender=\"Female\"`의 단일 모델가중치만 배우면 모든 나이-성별 조합(이를테면 `gender=\"Male\" 그리고 'age=\"30\"` 그리고 `gender=\"Male\"` 그리고 `age=\"40\"`을 구별하는 것)을 포함시킬 수 없습니다.\n", "\n", - "서로 다른 특징 조합들 간의 차이를 학습하기 위해서 모델에 *교차 특징열*을 추가할 수 있습니다(또한 교차 열 이전에 나이 열을 버킷화할 수 있습니다):" + "서로 다른 특성 조합들 간의 차이를 학습하기 위해서 모델에 *교차 특성 열*을 추가할 수 있습니다(또한 교차 열 이전에 나이 열을 버킷화할 수 있습니다):" ] }, { @@ -556,7 +556,7 @@ "id": "DqDFyPKQmGTN" }, "source": [ - "조합 특징을 모델에 추가하고 모델을 다시 훈련합니다:" + "조합 특성을 모델에 추가하고 모델을 다시 훈련합니다:" ] }, { @@ -585,7 +585,7 @@ "id": "rwfdZj7ImLwb" }, "source": [ - "이제 정확도 77.6%에 도달했습니다. 기본 특징만 이용한 학습보다는 약간 더 좋았습니다. 더 많은 특징과 변환을 사용해서 더 잘할 수 있다는 것을 보여주세요!" + "이제 정확도 77.6%에 도달했습니다. 기본 특성만 이용한 학습보다는 약간 더 좋았습니다. 더 많은 특성과 변환을 사용해서 더 잘할 수 있다는 것을 보여주세요!" ] }, { From 98c15c9ffe80b9317db7d4686a981532042a50e1 Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Thu, 13 Jun 2019 19:08:15 +0900 Subject: [PATCH 07/12] Fixed link --- site/ko/beta/tutorials/estimators/linear.ipynb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index dc3c717967d..5623d3b8dd5 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -48,10 +48,10 @@ " TensorFlow.org에서 보기\n", " \n", " \n", - " 구글 코랩(Colab)에서 실행하기\n", + " 구글 코랩(Colab)에서 실행하기\n", " \n", " \n", - " 깃허브(GitHub) 소스 보기\n", + " 깃허브(GitHub) 소스 보기\n", " \n", "" ] From c415313a437c332f766a1ed7e6a3877a4397895f Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Sat, 15 Jun 2019 10:54:39 +0900 Subject: [PATCH 08/12] 'Download notebook' add --- site/ko/beta/tutorials/estimators/linear.ipynb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index 5623d3b8dd5..68abec9c6fa 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -53,6 +53,9 @@ " \n", " 깃허브(GitHub) 소스 보기\n", " \n", + " \n", + " 노트북 다운로드\n", + " \n", "" ] }, From 05d0ac65210a73f1f65c84d087357241f0790861 Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Mon, 17 Jun 2019 15:17:49 +0900 Subject: [PATCH 09/12] fix version number --- site/ko/beta/tutorials/estimators/linear.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index 68abec9c6fa..6307e9523ca 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -147,7 +147,7 @@ }, "outputs": [], "source": [ - "!pip install tensorflow==2.0.0-beta0\n", + "!pip install tensorflow==2.0.0-beta1\n", "import tensorflow.compat.v2.feature_column as fc\n", "\n", "import tensorflow as tf" From a9e535d3b85cc15b799db31c2c230ca0e631641a Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Wed, 19 Jun 2019 17:34:27 +0900 Subject: [PATCH 10/12] remove download notebook button --- site/ko/beta/tutorials/estimators/linear.ipynb | 3 --- 1 file changed, 3 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index 6307e9523ca..6036850606b 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -53,9 +53,6 @@ " \n", " 깃허브(GitHub) 소스 보기\n", " \n", - " \n", - " 노트북 다운로드\n", - " \n", "" ] }, From 529ae3b5426585316e62655575cb413838895a5d Mon Sep 17 00:00:00 2001 From: Sung Il Kim Date: Thu, 20 Jun 2019 18:38:15 +0900 Subject: [PATCH 11/12] apply reviewer's comment --- site/ko/beta/tutorials/estimators/linear.ipynb | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index 6036850606b..c30cfa25f69 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -220,7 +220,7 @@ "id": "8JSa_duD4tFZ" }, "source": [ - "훈련셋은 627개의 사례로 평가셋은 264개의 사례로 구성되어 있습니다." + "훈련셋은 627개의 샘플로 평가셋은 264개의 샘플로 구성되어 있습니다." ] }, { @@ -312,7 +312,7 @@ "id": "FXJhGGL85TLp" }, "source": [ - "여자는 남자보다 살아남을 확률이 훨씬 높습니다. 이는 모델에서 명확하게 예측가능한 특성입니다." + "여자는 남자보다 살아남을 확률이 훨씬 높습니다. 이는 명확하게 모델에 유용한 특성입니다." ] }, { @@ -338,9 +338,9 @@ "## 모델을 위한 특성 공학(feature engineering)\n", "추정기는 [특성 열(feature columns)](https://www.tensorflow.org/guide/feature_columns)이라는 시스템을 사용하여 모델이 각각의 입력 특성을 어떻게 해석할지 설명합니다. 추정기가 숫자 입력 벡터를 요구하면, *특성 열*은 모델이 어떻게 각 특성을 변환해야하는지 설명합니다.\n", "\n", - "효과적인 모델 학습에서는 적절한 특성 열을 고르고 다듬는 것이 키포인트 입니다. 하나의 특성 열이 원래의 특성 `dict` (*기준 특성 열*)의 원래 입력 중 하나가 되거나 하나 또는 여러 기준열 (*얻어진 특성 열*) 에 정의된 변환을 이용하여 생성된 새로운 열이 될 수 있습니다.\n", + "효과적인 모델 학습에서는 적절한 특성 열을 고르고 다듬는 것이 키포인트 입니다. 하나의 특성 열은 특성 딕셔너리(dict)의 원본 입력으로 만들어진 열(*기본 특성 열*)이거나 하나 이상의 기본 열(*얻어진 특성 열*)에 정의된 변환을 이용하여 새로 생성된 열입니다.\n", "\n", - "선형 추정기는 수치형, 범주형 특성을 모두 사용할 수 있습니다. 특성 열은 모든 텐서플로 추정기와 함께 작동하고 목적은 모델링에 사용되는 특성들을 정의하는 것입니다. 또한 원핫인코딩(one-hot-encoding), 정규화(normalization), 버킷화(bucketization)와 같은 특성 공학 방법을 지원합니다." + "선형 추정기는 수치형, 범주형 특성을 모두 사용할 수 있습니다. 특성 열은 모든 텐서플로 추정기와 함께 작동하고 목적은 모델링에 사용되는 특성들을 정의하는 것입니다. 또한 원-핫-인코딩(one-hot-encoding), 정규화(normalization), 버킷화(bucketization)와 같은 특성 공학 방법을 지원합니다." ] }, { @@ -350,7 +350,7 @@ "id": "puZFOhTDkblt" }, "source": [ - "### 기준 특성 열" + "### 기본 특성 열" ] }, { @@ -469,7 +469,7 @@ "id": "f4zrAdCIjr3s" }, "source": [ - "`DenseFeatures`는 조밀한(dense) 텐서만 허용합니다. 우선 범주 열을 지시 열로 변환해야 합니다:" + "`DenseFeatures`는 조밀한(dense) 텐서만 허용합니다. 범주형 데이터를 점검하려면 우선 범주형 열에 indicator_column 함수를 적용해야 합니다:" ] }, { @@ -493,7 +493,7 @@ "id": "MEp59g5UkHYY" }, "source": [ - "모든 기본 특성을 모델에 추가한 다음에 모델을 훈련해 봅시다. 모델을 훈련하려면 `tf.estimator` API를 이용한 커맨드 하나면 충분합니다:" + "모든 기본 특성을 모델에 추가한 다음에 모델을 훈련해 봅시다. 모델을 훈련하려면 `tf.estimator` API를 이용한 메서드 호출 한번이면 충분합니다:" ] }, { @@ -595,7 +595,7 @@ "id": "8_eyb9d-ncjH" }, "source": [ - "이제 훈련 모델을 이용해서 평가셋에서 승객에 대해 예측을 할 수 있습니다. 텐서플로 모델은 한번에 사례의 한 배치 또는 콜렉션에 대한 예측을 하도록 최적화되어있습니다. 이전에, `eval_input_fn`은 모든 평가셋을 사용하도록 정의되어 있었습니다." + "이제 훈련 모델을 이용해서 평가셋에서 승객에 대해 예측을 할 수 있습니다. 텐서플로 모델은 한번에 샘플의 배치 또는 일부에 대한 예측을 하도록 최적화되어있습니다. 앞서, `eval_input_fn`은 모든 평가셋을 사용하도록 정의되어 있었습니다." ] }, { From 661854739a621aed3659789d2d0b9aa64f0184ec Mon Sep 17 00:00:00 2001 From: Billy Lamberta Date: Thu, 20 Jun 2019 10:34:24 -0700 Subject: [PATCH 12/12] Fix button. Colab formatting --- .../ko/beta/tutorials/estimators/linear.ipynb | 1356 ++++++++--------- 1 file changed, 678 insertions(+), 678 deletions(-) diff --git a/site/ko/beta/tutorials/estimators/linear.ipynb b/site/ko/beta/tutorials/estimators/linear.ipynb index c30cfa25f69..8b80147a182 100644 --- a/site/ko/beta/tutorials/estimators/linear.ipynb +++ b/site/ko/beta/tutorials/estimators/linear.ipynb @@ -1,679 +1,679 @@ { - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "OoasdhSAp0zJ" - }, - "source": [ - "##### Copyright 2019 The TensorFlow Authors." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "cellView": "form", - "colab": {}, - "colab_type": "code", - "id": "cIrwotvGqsYh" - }, - "outputs": [], - "source": [ - "#@title 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.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "C81KT2D_j-xR" - }, - "source": [ - "# 추정기(Estimator)로 선형 모델 만들기\n", - "\n", - "\n", - " \n", - " \n", - " \n", - "
\n", - " TensorFlow.org에서 보기\n", - " \n", - " 구글 코랩(Colab)에서 실행하기\n", - " \n", - " 깃허브(GitHub) 소스 보기\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "tUP8LMdYtWPz" - }, - "source": [ - "Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상 정확한 번역과 최신 내용을 반영하기 위해 노력함에도 불구하고 [공식 영문 문서](https://github.com/tensorflow/docs/blob/master/site/en/r2/guide/using_gpu.ipynb)의 내용과 일치하지 않을 수 있습니다. 이 번역에 개선할 부분이 있다면 [tensorflow/docs](https://github.com/tensorflow/docs) 깃헙 저장소로 풀 리퀘스트를 보내주시기 바랍니다. 문서 번역이나 리뷰에 참여하려면 [docs-ko@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ko)로 메일을 보내주시기 바랍니다." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "tUP8LMdYtWPz" - }, - "source": [ - "## 개요\n", - "\n", - "이 문서에서는 `tf.estimator` API를 사용하여 로지스틱 회귀 모델(logistic regression model)을 훈련합니다. 이 모델은 다른 더 복잡한 알고리즘의 기초로 사용할 수 있습니다.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "vkC_j6VpqrDw" - }, - "source": [ - "## 설정" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "rutbJGmpqvm3" - }, - "outputs": [], - "source": [ - "!pip install sklearn" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "54mb4J9PqqDh" - }, - "outputs": [], - "source": [ - "from __future__ import absolute_import, division, print_function, unicode_literals\n", - "\n", - "import os\n", - "import sys\n", - "\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from IPython.display import clear_output\n", - "from six.moves import urllib" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "fsjkwfsGOBMT" - }, - "source": [ - "## 타이타닉 데이터셋을 불러오기\n", - "타이타닉 데이터셋을 사용할 것입니다. 성별, 나이, 클래스, 기타 등 주어진 정보를 활용하여 승객이 살아남을 것인지 예측하는 것을 목표로 합니다." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "bNiwh-APcRVD" - }, - "outputs": [], - "source": [ - "!pip install tensorflow==2.0.0-beta1\n", - "import tensorflow.compat.v2.feature_column as fc\n", - "\n", - "import tensorflow as tf" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "DSeMKcx03d5R" - }, - "outputs": [], - "source": [ - "# 데이터셋 불러오기.\n", - "dftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')\n", - "dfeval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv')\n", - "y_train = dftrain.pop('survived')\n", - "y_eval = dfeval.pop('survived')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "jjm4Qj0u7_cp" - }, - "source": [ - "## 데이터 탐험하기" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "UrQzxKKh4d6u" - }, - "source": [ - "데이터셋은 다음의 특성을 가집니다" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "rTjugo3n308g" - }, - "outputs": [], - "source": [ - "dftrain.head()" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "y86q1fj44lZs" - }, - "outputs": [], - "source": [ - "dftrain.describe()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "8JSa_duD4tFZ" - }, - "source": [ - "훈련셋은 627개의 샘플로 평가셋은 264개의 샘플로 구성되어 있습니다." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "Fs3Nu5pV4v5J" - }, - "outputs": [], - "source": [ - "dftrain.shape[0], dfeval.shape[0]" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "RxCA4Nr45AfF" - }, - "source": [ - "대부분의 승객은 20대와 30대 입니다." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "RYeCMm7K40ZN" - }, - "outputs": [], - "source": [ - "dftrain.age.hist(bins=20)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "DItSwJ_B5B0f" - }, - "source": [ - "남자 승객이 여자 승객보다 대략 2배 많습니다." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "b03dVV9q5Dv2" - }, - "outputs": [], - "source": [ - "dftrain.sex.value_counts().plot(kind='barh')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "rK6WQ29q5Jf5" - }, - "source": [ - "대부분의 승객은 \"삼등석\" 입니다." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "dgpJVeCq5Fgd" - }, - "outputs": [], - "source": [ - "dftrain['class'].value_counts().plot(kind='barh')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "FXJhGGL85TLp" - }, - "source": [ - "여자는 남자보다 살아남을 확률이 훨씬 높습니다. 이는 명확하게 모델에 유용한 특성입니다." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "lSZYa7c45Ttt" - }, - "outputs": [], - "source": [ - "pd.concat([dftrain, y_train], axis=1).groupby('sex').survived.mean().plot(kind='barh').set_xlabel('% survive')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "VqDKQLZn8L-B" - }, - "source": [ - "## 모델을 위한 특성 공학(feature engineering)\n", - "추정기는 [특성 열(feature columns)](https://www.tensorflow.org/guide/feature_columns)이라는 시스템을 사용하여 모델이 각각의 입력 특성을 어떻게 해석할지 설명합니다. 추정기가 숫자 입력 벡터를 요구하면, *특성 열*은 모델이 어떻게 각 특성을 변환해야하는지 설명합니다.\n", - "\n", - "효과적인 모델 학습에서는 적절한 특성 열을 고르고 다듬는 것이 키포인트 입니다. 하나의 특성 열은 특성 딕셔너리(dict)의 원본 입력으로 만들어진 열(*기본 특성 열*)이거나 하나 이상의 기본 열(*얻어진 특성 열*)에 정의된 변환을 이용하여 새로 생성된 열입니다.\n", - "\n", - "선형 추정기는 수치형, 범주형 특성을 모두 사용할 수 있습니다. 특성 열은 모든 텐서플로 추정기와 함께 작동하고 목적은 모델링에 사용되는 특성들을 정의하는 것입니다. 또한 원-핫-인코딩(one-hot-encoding), 정규화(normalization), 버킷화(bucketization)와 같은 특성 공학 방법을 지원합니다." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "puZFOhTDkblt" - }, - "source": [ - "### 기본 특성 열" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "GpveXYSsADS6" - }, - "outputs": [], - "source": [ - "CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck',\n", - " 'embark_town', 'alone']\n", - "NUMERIC_COLUMNS = ['age', 'fare']\n", - "\n", - "feature_columns = []\n", - "for feature_name in CATEGORICAL_COLUMNS:\n", - " vocabulary = dftrain[feature_name].unique()\n", - " feature_columns.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocabulary))\n", - "\n", - "for feature_name in NUMERIC_COLUMNS:\n", - " feature_columns.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32))" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "Gt8HMtwOh9lJ" - }, - "source": [ - "`input_function`은 입력 파이프라인을 스트리밍으로 공급하는 `tf.data.Dataset`으로 데이터를 변환하는 방법을 명시합니다. `tf.data.Dataset`은 데이터 프레임, CSV 형식 파일 등과 같은 여러 소스를 사용합니다." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "qVtrIHFnAe7w" - }, - "outputs": [], - "source": [ - "def make_input_fn(data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):\n", - " def input_function():\n", - " ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df))\n", - " if shuffle:\n", - " ds = ds.shuffle(1000)\n", - " ds = ds.batch(batch_size).repeat(num_epochs)\n", - " return ds\n", - " return input_function\n", - "\n", - "train_input_fn = make_input_fn(dftrain, y_train)\n", - "eval_input_fn = make_input_fn(dfeval, y_eval, num_epochs=1, shuffle=False)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "P7UMVkQnkrgb" - }, - "source": [ - "다음과 같이 데이터셋을 점검할 수 있습니다:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "8ZcG_3KiCb1M" - }, - "outputs": [], - "source": [ - "ds = make_input_fn(dftrain, y_train, batch_size=10)()\n", - "for feature_batch, label_batch in ds.take(1):\n", - " print('특성 키:', list(feature_batch.keys()))\n", - " print()\n", - " print('클래스 배치:', feature_batch['class'].numpy())\n", - " print()\n", - " print('레이블 배치:', label_batch.numpy())" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "lMNBMyodjlW3" - }, - "source": [ - "또한 `tf.keras.layers.DenseFeatures` 층을 사용하여 특정한 특성 열의 결과를 점검할 수 있습니다:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "IMjlmbPlDmkB" - }, - "outputs": [], - "source": [ - "age_column = feature_columns[7]\n", - "tf.keras.layers.DenseFeatures([age_column])(feature_batch).numpy()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "f4zrAdCIjr3s" - }, - "source": [ - "`DenseFeatures`는 조밀한(dense) 텐서만 허용합니다. 범주형 데이터를 점검하려면 우선 범주형 열에 indicator_column 함수를 적용해야 합니다:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "1VXmXFTSFEvv" - }, - "outputs": [], - "source": [ - "gender_column = feature_columns[0]\n", - "tf.keras.layers.DenseFeatures([tf.feature_column.indicator_column(gender_column)])(feature_batch).numpy()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "MEp59g5UkHYY" - }, - "source": [ - "모든 기본 특성을 모델에 추가한 다음에 모델을 훈련해 봅시다. 모델을 훈련하려면 `tf.estimator` API를 이용한 메서드 호출 한번이면 충분합니다:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "aGXjdnqqdgIs" - }, - "outputs": [], - "source": [ - "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns)\n", - "linear_est.train(train_input_fn)\n", - "result = linear_est.evaluate(eval_input_fn)\n", - "\n", - "clear_output()\n", - "print(result)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "3tOan4hDsG6d" - }, - "source": [ - "### 도출된 특성 열" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "NOG2FSTHlAMu" - }, - "source": [ - "이제 정확도 75%에 도달했습니다. 별도로 각 기본 특성 열을 사용하면 데이터를 설명하기에는 충분치 않을 수 있습니다. 예를 들면, 성별과 레이블간의 상관관계는 성별에 따라 다를 수 있습니다. 따라서 `gender=\"Male\"`과 'gender=\"Female\"`의 단일 모델가중치만 배우면 모든 나이-성별 조합(이를테면 `gender=\"Male\" 그리고 'age=\"30\"` 그리고 `gender=\"Male\"` 그리고 `age=\"40\"`을 구별하는 것)을 포함시킬 수 없습니다.\n", - "\n", - "서로 다른 특성 조합들 간의 차이를 학습하기 위해서 모델에 *교차 특성 열*을 추가할 수 있습니다(또한 교차 열 이전에 나이 열을 버킷화할 수 있습니다):" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "AM-RsDzNfGlu" - }, - "outputs": [], - "source": [ - "age_x_gender = tf.feature_column.crossed_column(['age', 'sex'], hash_bucket_size=100)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "DqDFyPKQmGTN" - }, - "source": [ - "조합 특성을 모델에 추가하고 모델을 다시 훈련합니다:" - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "s8FV9oPQfS-g" - }, - "outputs": [], - "source": [ - "derived_feature_columns = [age_x_gender]\n", - "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns+derived_feature_columns)\n", - "linear_est.train(train_input_fn)\n", - "result = linear_est.evaluate(eval_input_fn)\n", - "\n", - "clear_output()\n", - "print(result)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "rwfdZj7ImLwb" - }, - "source": [ - "이제 정확도 77.6%에 도달했습니다. 기본 특성만 이용한 학습보다는 약간 더 좋았습니다. 더 많은 특성과 변환을 사용해서 더 잘할 수 있다는 것을 보여주세요!" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "8_eyb9d-ncjH" - }, - "source": [ - "이제 훈련 모델을 이용해서 평가셋에서 승객에 대해 예측을 할 수 있습니다. 텐서플로 모델은 한번에 샘플의 배치 또는 일부에 대한 예측을 하도록 최적화되어있습니다. 앞서, `eval_input_fn`은 모든 평가셋을 사용하도록 정의되어 있었습니다." - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "wiScyBcef6Dq" - }, - "outputs": [], - "source": [ - "pred_dicts = list(linear_est.predict(eval_input_fn))\n", - "probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])\n", - "\n", - "probs.plot(kind='hist', bins=20, title='예측 확률')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "colab_type": "text", - "id": "UEHRCd4sqrLs" - }, - "source": [ - "마지막으로, 수신자 조작 특성(receiver operating characteristic, ROC)을 살펴보면 정탐률(true positive rate)과 오탐률(false positive rate)의 상충관계에 대해 더 잘 이해할 수 있습니다. " - ] - }, - { - "cell_type": "code", - "execution_count": 0, - "metadata": { - "colab": {}, - "colab_type": "code", - "id": "kqEjsezIokIe" - }, - "outputs": [], - "source": [ - "from sklearn.metrics import roc_curve\n", - "from matplotlib import pyplot as plt\n", - "\n", - "fpr, tpr, _ = roc_curve(y_eval, probs)\n", - "plt.plot(fpr, tpr)\n", - "plt.title('ROC curve')\n", - "plt.xlabel('오탐률(false positive rate)')\n", - "plt.ylabel('정탐률(true positive rate)')\n", - "plt.xlim(0,)\n", - "plt.ylim(0,)" - ] - } - ], - "metadata": { - "colab": { - "collapsed_sections": [], - "name": "linear.ipynb", - "private_outputs": true, - "provenance": [], - "toc_visible": true, - "version": "0.3.2" - }, - "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.7.1" - } - }, - "nbformat": 4, - "nbformat_minor": 1 -} + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "name": "linear.ipynb", + "version": "0.3.2", + "provenance": [], + "private_outputs": true, + "collapsed_sections": [], + "toc_visible": true + }, + "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.7.1" + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "OoasdhSAp0zJ" + }, + "source": [ + "##### Copyright 2019 The TensorFlow Authors." + ] + }, + { + "cell_type": "code", + "metadata": { + "cellView": "form", + "colab_type": "code", + "id": "cIrwotvGqsYh", + "colab": {} + }, + "source": [ + "#@title 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.\n" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "C81KT2D_j-xR" + }, + "source": [ + "# 추정기(Estimator)로 선형 모델 만들기\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "
\n", + " TensorFlow.org에서 보기\n", + " \n", + " 구글 코랩(Colab)에서 실행하기\n", + " \n", + " 깃허브(GitHub) 소스 보기\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "tUP8LMdYtWPz" + }, + "source": [ + "Note: 이 문서는 텐서플로 커뮤니티에서 번역했습니다. 커뮤니티 번역 활동의 특성상 정확한 번역과 최신 내용을 반영하기 위해 노력함에도 불구하고 [공식 영문 문서](https://github.com/tensorflow/docs/blob/master/site/en/r2/guide/using_gpu.ipynb)의 내용과 일치하지 않을 수 있습니다. 이 번역에 개선할 부분이 있다면 [tensorflow/docs](https://github.com/tensorflow/docs) 깃헙 저장소로 풀 리퀘스트를 보내주시기 바랍니다. 문서 번역이나 리뷰에 참여하려면 [docs-ko@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ko)로 메일을 보내주시기 바랍니다." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "nNgxmCgx8aAM" + }, + "source": [ + "## 개요\n", + "\n", + "이 문서에서는 `tf.estimator` API를 사용하여 로지스틱 회귀 모델(logistic regression model)을 훈련합니다. 이 모델은 다른 더 복잡한 알고리즘의 기초로 사용할 수 있습니다.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "vkC_j6VpqrDw" + }, + "source": [ + "## 설정" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "rutbJGmpqvm3", + "colab": {} + }, + "source": [ + "!pip install sklearn" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "54mb4J9PqqDh", + "colab": {} + }, + "source": [ + "from __future__ import absolute_import, division, print_function, unicode_literals\n", + "\n", + "import os\n", + "import sys\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from IPython.display import clear_output\n", + "from six.moves import urllib" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "fsjkwfsGOBMT" + }, + "source": [ + "## 타이타닉 데이터셋을 불러오기\n", + "타이타닉 데이터셋을 사용할 것입니다. 성별, 나이, 클래스, 기타 등 주어진 정보를 활용하여 승객이 살아남을 것인지 예측하는 것을 목표로 합니다." + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "bNiwh-APcRVD", + "colab": {} + }, + "source": [ + "!pip install tensorflow==2.0.0-beta1\n", + "import tensorflow.compat.v2.feature_column as fc\n", + "\n", + "import tensorflow as tf" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "DSeMKcx03d5R", + "colab": {} + }, + "source": [ + "# 데이터셋 불러오기.\n", + "dftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')\n", + "dfeval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv')\n", + "y_train = dftrain.pop('survived')\n", + "y_eval = dfeval.pop('survived')" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "jjm4Qj0u7_cp" + }, + "source": [ + "## 데이터 탐험하기" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "UrQzxKKh4d6u" + }, + "source": [ + "데이터셋은 다음의 특성을 가집니다" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "rTjugo3n308g", + "colab": {} + }, + "source": [ + "dftrain.head()" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "y86q1fj44lZs", + "colab": {} + }, + "source": [ + "dftrain.describe()" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "8JSa_duD4tFZ" + }, + "source": [ + "훈련셋은 627개의 샘플로 평가셋은 264개의 샘플로 구성되어 있습니다." + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "Fs3Nu5pV4v5J", + "colab": {} + }, + "source": [ + "dftrain.shape[0], dfeval.shape[0]" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "RxCA4Nr45AfF" + }, + "source": [ + "대부분의 승객은 20대와 30대 입니다." + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "RYeCMm7K40ZN", + "colab": {} + }, + "source": [ + "dftrain.age.hist(bins=20)" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "DItSwJ_B5B0f" + }, + "source": [ + "남자 승객이 여자 승객보다 대략 2배 많습니다." + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "b03dVV9q5Dv2", + "colab": {} + }, + "source": [ + "dftrain.sex.value_counts().plot(kind='barh')" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rK6WQ29q5Jf5" + }, + "source": [ + "대부분의 승객은 \"삼등석\" 입니다." + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "dgpJVeCq5Fgd", + "colab": {} + }, + "source": [ + "dftrain['class'].value_counts().plot(kind='barh')" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "FXJhGGL85TLp" + }, + "source": [ + "여자는 남자보다 살아남을 확률이 훨씬 높습니다. 이는 명확하게 모델에 유용한 특성입니다." + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "lSZYa7c45Ttt", + "colab": {} + }, + "source": [ + "pd.concat([dftrain, y_train], axis=1).groupby('sex').survived.mean().plot(kind='barh').set_xlabel('% survive')" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "VqDKQLZn8L-B" + }, + "source": [ + "## 모델을 위한 특성 공학(feature engineering)\n", + "추정기는 [특성 열(feature columns)](https://www.tensorflow.org/guide/feature_columns)이라는 시스템을 사용하여 모델이 각각의 입력 특성을 어떻게 해석할지 설명합니다. 추정기가 숫자 입력 벡터를 요구하면, *특성 열*은 모델이 어떻게 각 특성을 변환해야하는지 설명합니다.\n", + "\n", + "효과적인 모델 학습에서는 적절한 특성 열을 고르고 다듬는 것이 키포인트 입니다. 하나의 특성 열은 특성 딕셔너리(dict)의 원본 입력으로 만들어진 열(*기본 특성 열*)이거나 하나 이상의 기본 열(*얻어진 특성 열*)에 정의된 변환을 이용하여 새로 생성된 열입니다.\n", + "\n", + "선형 추정기는 수치형, 범주형 특성을 모두 사용할 수 있습니다. 특성 열은 모든 텐서플로 추정기와 함께 작동하고 목적은 모델링에 사용되는 특성들을 정의하는 것입니다. 또한 원-핫-인코딩(one-hot-encoding), 정규화(normalization), 버킷화(bucketization)와 같은 특성 공학 방법을 지원합니다." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "puZFOhTDkblt" + }, + "source": [ + "### 기본 특성 열" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "GpveXYSsADS6", + "colab": {} + }, + "source": [ + "CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck',\n", + " 'embark_town', 'alone']\n", + "NUMERIC_COLUMNS = ['age', 'fare']\n", + "\n", + "feature_columns = []\n", + "for feature_name in CATEGORICAL_COLUMNS:\n", + " vocabulary = dftrain[feature_name].unique()\n", + " feature_columns.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocabulary))\n", + "\n", + "for feature_name in NUMERIC_COLUMNS:\n", + " feature_columns.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32))" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Gt8HMtwOh9lJ" + }, + "source": [ + "`input_function`은 입력 파이프라인을 스트리밍으로 공급하는 `tf.data.Dataset`으로 데이터를 변환하는 방법을 명시합니다. `tf.data.Dataset`은 데이터 프레임, CSV 형식 파일 등과 같은 여러 소스를 사용합니다." + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "qVtrIHFnAe7w", + "colab": {} + }, + "source": [ + "def make_input_fn(data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):\n", + " def input_function():\n", + " ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df))\n", + " if shuffle:\n", + " ds = ds.shuffle(1000)\n", + " ds = ds.batch(batch_size).repeat(num_epochs)\n", + " return ds\n", + " return input_function\n", + "\n", + "train_input_fn = make_input_fn(dftrain, y_train)\n", + "eval_input_fn = make_input_fn(dfeval, y_eval, num_epochs=1, shuffle=False)" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "P7UMVkQnkrgb" + }, + "source": [ + "다음과 같이 데이터셋을 점검할 수 있습니다:" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "8ZcG_3KiCb1M", + "colab": {} + }, + "source": [ + "ds = make_input_fn(dftrain, y_train, batch_size=10)()\n", + "for feature_batch, label_batch in ds.take(1):\n", + " print('특성 키:', list(feature_batch.keys()))\n", + " print()\n", + " print('클래스 배치:', feature_batch['class'].numpy())\n", + " print()\n", + " print('레이블 배치:', label_batch.numpy())" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "lMNBMyodjlW3" + }, + "source": [ + "또한 `tf.keras.layers.DenseFeatures` 층을 사용하여 특정한 특성 열의 결과를 점검할 수 있습니다:" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "IMjlmbPlDmkB", + "colab": {} + }, + "source": [ + "age_column = feature_columns[7]\n", + "tf.keras.layers.DenseFeatures([age_column])(feature_batch).numpy()" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "f4zrAdCIjr3s" + }, + "source": [ + "`DenseFeatures`는 조밀한(dense) 텐서만 허용합니다. 범주형 데이터를 점검하려면 우선 범주형 열에 indicator_column 함수를 적용해야 합니다:" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "1VXmXFTSFEvv", + "colab": {} + }, + "source": [ + "gender_column = feature_columns[0]\n", + "tf.keras.layers.DenseFeatures([tf.feature_column.indicator_column(gender_column)])(feature_batch).numpy()" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "MEp59g5UkHYY" + }, + "source": [ + "모든 기본 특성을 모델에 추가한 다음에 모델을 훈련해 봅시다. 모델을 훈련하려면 `tf.estimator` API를 이용한 메서드 호출 한번이면 충분합니다:" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "aGXjdnqqdgIs", + "colab": {} + }, + "source": [ + "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns)\n", + "linear_est.train(train_input_fn)\n", + "result = linear_est.evaluate(eval_input_fn)\n", + "\n", + "clear_output()\n", + "print(result)" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "3tOan4hDsG6d" + }, + "source": [ + "### 도출된 특성 열" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "NOG2FSTHlAMu" + }, + "source": [ + "이제 정확도 75%에 도달했습니다. 별도로 각 기본 특성 열을 사용하면 데이터를 설명하기에는 충분치 않을 수 있습니다. 예를 들면, 성별과 레이블간의 상관관계는 성별에 따라 다를 수 있습니다. 따라서 `gender=\"Male\"`과 'gender=\"Female\"`의 단일 모델가중치만 배우면 모든 나이-성별 조합(이를테면 `gender=\"Male\" 그리고 'age=\"30\"` 그리고 `gender=\"Male\"` 그리고 `age=\"40\"`을 구별하는 것)을 포함시킬 수 없습니다.\n", + "\n", + "서로 다른 특성 조합들 간의 차이를 학습하기 위해서 모델에 *교차 특성 열*을 추가할 수 있습니다(또한 교차 열 이전에 나이 열을 버킷화할 수 있습니다):" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "AM-RsDzNfGlu", + "colab": {} + }, + "source": [ + "age_x_gender = tf.feature_column.crossed_column(['age', 'sex'], hash_bucket_size=100)" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "DqDFyPKQmGTN" + }, + "source": [ + "조합 특성을 모델에 추가하고 모델을 다시 훈련합니다:" + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "s8FV9oPQfS-g", + "colab": {} + }, + "source": [ + "derived_feature_columns = [age_x_gender]\n", + "linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns+derived_feature_columns)\n", + "linear_est.train(train_input_fn)\n", + "result = linear_est.evaluate(eval_input_fn)\n", + "\n", + "clear_output()\n", + "print(result)" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rwfdZj7ImLwb" + }, + "source": [ + "이제 정확도 77.6%에 도달했습니다. 기본 특성만 이용한 학습보다는 약간 더 좋았습니다. 더 많은 특성과 변환을 사용해서 더 잘할 수 있다는 것을 보여주세요!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "8_eyb9d-ncjH" + }, + "source": [ + "이제 훈련 모델을 이용해서 평가셋에서 승객에 대해 예측을 할 수 있습니다. 텐서플로 모델은 한번에 샘플의 배치 또는 일부에 대한 예측을 하도록 최적화되어있습니다. 앞서, `eval_input_fn`은 모든 평가셋을 사용하도록 정의되어 있었습니다." + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "wiScyBcef6Dq", + "colab": {} + }, + "source": [ + "pred_dicts = list(linear_est.predict(eval_input_fn))\n", + "probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])\n", + "\n", + "probs.plot(kind='hist', bins=20, title='예측 확률')" + ], + "execution_count": 0, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "UEHRCd4sqrLs" + }, + "source": [ + "마지막으로, 수신자 조작 특성(receiver operating characteristic, ROC)을 살펴보면 정탐률(true positive rate)과 오탐률(false positive rate)의 상충관계에 대해 더 잘 이해할 수 있습니다. " + ] + }, + { + "cell_type": "code", + "metadata": { + "colab_type": "code", + "id": "kqEjsezIokIe", + "colab": {} + }, + "source": [ + "from sklearn.metrics import roc_curve\n", + "from matplotlib import pyplot as plt\n", + "\n", + "fpr, tpr, _ = roc_curve(y_eval, probs)\n", + "plt.plot(fpr, tpr)\n", + "plt.title('ROC curve')\n", + "plt.xlabel('오탐률(false positive rate)')\n", + "plt.ylabel('정탐률(true positive rate)')\n", + "plt.xlim(0,)\n", + "plt.ylim(0,)" + ], + "execution_count": 0, + "outputs": [] + } + ] +} \ No newline at end of file