{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "rX8mhOLljYeM" }, "source": [ "##### Copyright 2019 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "cellView": "form", "execution": { "iopub.execute_input": "2022-12-14T22:35:49.525805Z", "iopub.status.busy": "2022-12-14T22:35:49.525560Z", "iopub.status.idle": "2022-12-14T22:35:49.529806Z", "shell.execute_reply": "2022-12-14T22:35:49.529236Z" }, "id": "BZSlp3DAjdYf" }, "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." ] }, { "cell_type": "markdown", "metadata": { "id": "3wF5wszaj97Y" }, "source": [ "# 전문가를 위한 TensorFlow 2 빠른 시작" ] }, { "cell_type": "markdown", "metadata": { "id": "DUNzJc4jTj6G" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
TensorFlow.org에서 보기Google Colab에서 실행GitHub에서 소스 보기노트북 다운로드
" ] }, { "cell_type": "markdown", "metadata": { "id": "hiH7AC-NTniF" }, "source": [ "이것은 [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb) 노트북 파일입니다. Python 프로그램은 브라우저에서 직접 실행되므로 TensorFlow를 배우고 사용하기에 좋습니다. 이 튜토리얼을 따르려면 이 페이지 상단에 있는 버튼을 클릭하여 Google Colab에서 노트북을 실행하세요.\n", "\n", "1. 파이썬 런타임(runtime)에 연결하세요: 메뉴 막대의 오른쪽 상단에서 *CONNECT*를 선택하세요.\n", "2. 노트북의 모든 코드 셀(cell)을 실행하세요: *Runtime* > *Run all*을 선택하세요." ] }, { "cell_type": "markdown", "metadata": { "id": "eOsVdx6GGHmU" }, "source": [ "TensorFlow 2를 다운로드하여 설치합니다. TensorFlow를 프로그램으로 가져옵니다.\n", "\n", "참고: TensorFlow 2 패키지를 설치하려면 `pip`를 업그레이드하세요. 자세한 내용은 [설치 가이드](https://www.tensorflow.org/install)를 참조하세요." ] }, { "cell_type": "markdown", "metadata": { "id": "QS7DDTiZGRTo" }, "source": [ "TensorFlow를 프로그램으로 가져옵니다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:49.533621Z", "iopub.status.busy": "2022-12-14T22:35:49.533093Z", "iopub.status.idle": "2022-12-14T22:35:51.573292Z", "shell.execute_reply": "2022-12-14T22:35:51.572576Z" }, "id": "0trJmd6DjqBZ" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2022-12-14 22:35:50.530976: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory\n", "2022-12-14 22:35:50.531082: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory\n", "2022-12-14 22:35:50.531092: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "TensorFlow version: 2.11.0\n" ] } ], "source": [ "import tensorflow as tf\n", "print(\"TensorFlow version:\", tf.__version__)\n", "\n", "from tensorflow.keras.layers import Dense, Flatten, Conv2D\n", "from tensorflow.keras import Model" ] }, { "cell_type": "markdown", "metadata": { "id": "7NAbSZiaoJ4z" }, "source": [ "[MNIST 데이터셋](http://yann.lecun.com/exdb/mnist/)을 로드하여 준비합니다." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:51.577000Z", "iopub.status.busy": "2022-12-14T22:35:51.576544Z", "iopub.status.idle": "2022-12-14T22:35:52.130223Z", "shell.execute_reply": "2022-12-14T22:35:52.129420Z" }, "id": "JqFRS6K07jJs" }, "outputs": [], "source": [ "mnist = tf.keras.datasets.mnist\n", "\n", "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n", "x_train, x_test = x_train / 255.0, x_test / 255.0\n", "\n", "# Add a channels dimension\n", "x_train = x_train[..., tf.newaxis].astype(\"float32\")\n", "x_test = x_test[..., tf.newaxis].astype(\"float32\")" ] }, { "cell_type": "markdown", "metadata": { "id": "k1Evqx0S22r_" }, "source": [ "tf.data를 사용하여 데이터셋을 섞고 배치를 만듭니다:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:52.134766Z", "iopub.status.busy": "2022-12-14T22:35:52.133975Z", "iopub.status.idle": "2022-12-14T22:35:56.251418Z", "shell.execute_reply": "2022-12-14T22:35:56.250647Z" }, "id": "8Iu_quO024c2" }, "outputs": [], "source": [ "train_ds = tf.data.Dataset.from_tensor_slices(\n", " (x_train, y_train)).shuffle(10000).batch(32)\n", "\n", "test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)" ] }, { "cell_type": "markdown", "metadata": { "id": "BPZ68wASog_I" }, "source": [ "케라스(Keras)의 [모델 서브클래싱(subclassing) API](https://www.tensorflow.org/guide/keras#model_subclassing)를 사용하여 `tf.keras` 모델을 만듭니다:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:56.255947Z", "iopub.status.busy": "2022-12-14T22:35:56.255374Z", "iopub.status.idle": "2022-12-14T22:35:56.273387Z", "shell.execute_reply": "2022-12-14T22:35:56.272786Z" }, "id": "h3IKyzTCDNGo" }, "outputs": [], "source": [ "class MyModel(Model):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", " self.conv1 = Conv2D(32, 3, activation='relu')\n", " self.flatten = Flatten()\n", " self.d1 = Dense(128, activation='relu')\n", " self.d2 = Dense(10)\n", "\n", " def call(self, x):\n", " x = self.conv1(x)\n", " x = self.flatten(x)\n", " x = self.d1(x)\n", " return self.d2(x)\n", "\n", "# Create an instance of the model\n", "model = MyModel()" ] }, { "cell_type": "markdown", "metadata": { "id": "uGih-c2LgbJu" }, "source": [ "훈련에 필요한 옵티마이저(optimizer)와 손실 함수를 선택합니다: " ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:56.277316Z", "iopub.status.busy": "2022-12-14T22:35:56.276643Z", "iopub.status.idle": "2022-12-14T22:35:56.283196Z", "shell.execute_reply": "2022-12-14T22:35:56.282546Z" }, "id": "u48C9WQ774n4" }, "outputs": [], "source": [ "loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n", "\n", "optimizer = tf.keras.optimizers.Adam()" ] }, { "cell_type": "markdown", "metadata": { "id": "JB6A1vcigsIe" }, "source": [ "모델의 손실과 성능을 측정할 지표를 선택합니다. 에포크가 진행되는 동안 수집된 측정 지표를 바탕으로 최종 결과를 출력합니다." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:56.286855Z", "iopub.status.busy": "2022-12-14T22:35:56.286285Z", "iopub.status.idle": "2022-12-14T22:35:56.302890Z", "shell.execute_reply": "2022-12-14T22:35:56.302238Z" }, "id": "N0MqHFb4F_qn" }, "outputs": [], "source": [ "train_loss = tf.keras.metrics.Mean(name='train_loss')\n", "train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n", "\n", "test_loss = tf.keras.metrics.Mean(name='test_loss')\n", "test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')" ] }, { "cell_type": "markdown", "metadata": { "id": "ix4mEL65on-w" }, "source": [ "`tf.GradientTape`를 사용하여 모델을 훈련합니다:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:56.306932Z", "iopub.status.busy": "2022-12-14T22:35:56.306345Z", "iopub.status.idle": "2022-12-14T22:35:56.311032Z", "shell.execute_reply": "2022-12-14T22:35:56.310417Z" }, "id": "OZACiVqA8KQV" }, "outputs": [], "source": [ "@tf.function\n", "def train_step(images, labels):\n", " with tf.GradientTape() as tape:\n", " # training=True is only needed if there are layers with different\n", " # behavior during training versus inference (e.g. Dropout).\n", " predictions = model(images, training=True)\n", " loss = loss_object(labels, predictions)\n", " gradients = tape.gradient(loss, model.trainable_variables)\n", " optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n", "\n", " train_loss(loss)\n", " train_accuracy(labels, predictions)" ] }, { "cell_type": "markdown", "metadata": { "id": "Z8YT7UmFgpjV" }, "source": [ "이제 모델을 테스트합니다:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:56.314581Z", "iopub.status.busy": "2022-12-14T22:35:56.314003Z", "iopub.status.idle": "2022-12-14T22:35:56.318115Z", "shell.execute_reply": "2022-12-14T22:35:56.317457Z" }, "id": "xIKdEzHAJGt7" }, "outputs": [], "source": [ "@tf.function\n", "def test_step(images, labels):\n", " # training=False is only needed if there are layers with different\n", " # behavior during training versus inference (e.g. Dropout).\n", " predictions = model(images, training=False)\n", " t_loss = loss_object(labels, predictions)\n", "\n", " test_loss(t_loss)\n", " test_accuracy(labels, predictions)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:35:56.321305Z", "iopub.status.busy": "2022-12-14T22:35:56.320811Z", "iopub.status.idle": "2022-12-14T22:36:19.095219Z", "shell.execute_reply": "2022-12-14T22:36:19.094428Z" }, "id": "i-2pkctU_Ci7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1, Loss: 0.13726592063903809, Accuracy: 95.95333099365234, Test Loss: 0.065406933426857, Test Accuracy: 97.79999542236328\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 2, Loss: 0.04497866705060005, Accuracy: 98.60166931152344, Test Loss: 0.05809991806745529, Test Accuracy: 98.22000122070312\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 3, Loss: 0.02388325147330761, Accuracy: 99.24166870117188, Test Loss: 0.05342353880405426, Test Accuracy: 98.30999755859375\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 4, Loss: 0.013876602053642273, Accuracy: 99.5433349609375, Test Loss: 0.06588396430015564, Test Accuracy: 98.23999786376953\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Epoch 5, Loss: 0.009471668861806393, Accuracy: 99.68499755859375, Test Loss: 0.06574567407369614, Test Accuracy: 98.25999450683594\n" ] } ], "source": [ "EPOCHS = 5\n", "\n", "for epoch in range(EPOCHS):\n", " # Reset the metrics at the start of the next epoch\n", " train_loss.reset_states()\n", " train_accuracy.reset_states()\n", " test_loss.reset_states()\n", " test_accuracy.reset_states()\n", "\n", " for images, labels in train_ds:\n", " train_step(images, labels)\n", "\n", " for test_images, test_labels in test_ds:\n", " test_step(test_images, test_labels)\n", "\n", " print(\n", " f'Epoch {epoch + 1}, '\n", " f'Loss: {train_loss.result()}, '\n", " f'Accuracy: {train_accuracy.result() * 100}, '\n", " f'Test Loss: {test_loss.result()}, '\n", " f'Test Accuracy: {test_accuracy.result() * 100}'\n", " )" ] }, { "cell_type": "markdown", "metadata": { "id": "T4JfEh7kvx6m" }, "source": [ "훈련된 이미지 분류기는 이 데이터셋에서 약 98%의 정확도를 달성합니다. 더 자세한 내용은 [TensorFlow 튜토리얼](https://www.tensorflow.org/tutorials/)을 참고하세요." ] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [], "name": "advanced.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.16" } }, "nbformat": 4, "nbformat_minor": 0 }