Web Programming

Tensorflow란?

안녕하세요 씨앤텍 시스템즈입니다.

이번 포스트는 딥러닝 프레임워크 중 가장 대중적이고 인기있는 Tensorflow에 대해 알아보겠습니다.

 


  Tensorflow는 머신러닝 구현을 위한 프로그래밍 인터페이스이며 딥러닝을 위한 인터페이스도 지원하고 있으며 안드로이드와 iOS같은 모바일 환경은 물론 리눅스, MacOS의 데스크탑이나 GPU환경 등 다양한 플랫폼을 지원하고 있습니다.  구글브레인팀에서 개발하여 2015년 11월 9일 Apache 2.0 오픈소스 라이선스로 공개되었습니다. 

 

  Tensorflow는 1.1.0 버전부터 keras와 같은 고수준의 API가 추가되기 시작했으며, Tensorflow 2.0으로 업데이트 되면서 keras가 최상위 파이썬 API로 채택되었습니다. 훨씬 빠르고 간편하게 모델을 만들고 테스트를 해볼수 있습니다.

 

* Tensorflow 공식 홈페이지

https://www.tensorflow.org/

 

TensorFlow

모두를 위한 엔드 투 엔드 오픈소스 머신러닝 플랫폼입니다. 도구, 라이브러리, 커뮤니티 리소스로 구성된 TensorFlow의 유연한 환경입니다.

www.tensorflow.org

  Tensorflow는 데이터 플로우 그래프를 사용하여 다차원 데이터 배열이 노드 사이를 이동하면서 수치 연산이 수행되는 유연한 아키텍처로 구성되어 있습니다.

 

  Tensorflow를 학습 할때는 다양하게 배포되어 있는 인터넷에서 검색하여도 문제 없지만, 공식 홈페이지에 있는 튜토리얼 또한 매우 잘 설명되어 있기 때문에 이를 보면서 학습하여도 전혀 문제 없습니다.

 

 또한, 브라우저에서 실행 가능한 TensorBoard라는 시각화 도구를 제공하여 Tensorflow에서 모델 학습시, 학습이 되는 과정의 정확도나 네트워크의 노드 연결 과정을 시각화하여 볼 수 있습니다.

https://www.tensorflow.org/tensorboard?hl=ko

 

* Tensorflow 설치

  • Tensorflow는 다양한 플랫폼을 지원합니다.
    • Python 3.5-3.7
    • Ubuntu 16.04 이상
    • Windows7 이상
    • macOS 10.12.6 이상
    • Raspbian 9.0 이상

  - Tensorflow 패키지 다운로드

# Requires the latest pip
pip install --upgrade pip

# Current stable release for CPU and GPU
pip install tensorflow

# Or try the preview build (unstable)
pip install tf-nightly

  # Tensorflow2 패키지는 pip 19.0 이상의 버전이 필요합니다.

 

- Tensorflow Docker 컨테이너 실행

 docker pull tensorflow/tensorflow:latest-py3  # Download latest stable image
 docker run -it -p 8888:8888 tensorflow/tensorflow:latest-py3-jupyter  # Start Jupyter server 

 

* Tensorflow 코드 (저수준 API)


import tensorflow.compat.v1 as tf

import numpy as np

tf.logging.set_verbosity(tf.logging.INFO)

def cnn_model_fn(features, labels, mode):
  """Model function for CNN."""
  # Input Layer
  input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2 and Pooling Layer #2
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Dense Layer
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

  # Logits Layer
  logits = tf.layers.dense(inputs=dropout, units=10)

  predictions = {
      # Generate predictions (for PREDICT and EVAL mode)
      "classes": tf.argmax(input=logits, axis=1),
      # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
      # `logging_hook`.
      "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
  }

  if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

  # Calculate Loss (for both TRAIN and EVAL modes)
  loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == tf.estimator.ModeKeys.TRAIN:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

  # Add evaluation metrics (for EVAL mode)
  eval_metric_ops = {
      "accuracy": tf.metrics.accuracy(
          labels=labels, predictions=predictions["classes"])
  }
  return tf.estimator.EstimatorSpec(
      mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

https://github.com/tensorflow/docs/tree/master/site/en/r1/tutorials

 

* Tensorflow 코드 (고수준 API)

from __future__ import absolute_import, division, print_function, unicode_literals

!pip install -q tensorflow-gpu==2.0.0-rc1
import tensorflow as tf

from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

# MNIST 데이터셋을 로드하여 준비합니다.
mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# 채널 차원을 추가합니다.
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]

# tf.data를 사용하여 데이터셋을 섞고 배치를 만듭니다:
train_ds = tf.data.Dataset.from_tensor_slices(
    (x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)

# 케라스(Keras)의 모델 서브클래싱(subclassing) API를 사용하여 tf.keras 모델을 만듭니다:
class MyModel(Model):
  def __init__(self):
    super(MyModel, self).__init__()
    self.conv1 = Conv2D(32, 3, activation='relu')
    self.flatten = Flatten()
    self.d1 = Dense(128, activation='relu')
    self.d2 = Dense(10, activation='softmax')

  def call(self, x):
    x = self.conv1(x)
    x = self.flatten(x)
    x = self.d1(x)
    return self.d2(x)

model = MyModel()

# 훈련에 필요한 옵티마이저(optimizer)와 손실 함수를 선택합니다:
loss_object = tf.keras.losses.SparseCategoricalCrossentropy()

optimizer = tf.keras.optimizers.Adam()

# 모델의 손실과 성능을 측정할 지표를 선택합니다. 에포크가 진행되는 동안 수집된 측정 지표를 바탕으로 최종 결과를 출력합니다.
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')

test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')

# tf.GradientTape를 사용하여 모델을 훈련합니다:
@tf.function
def train_step(images, labels):
  with tf.GradientTape() as tape:
    predictions = model(images)
    loss = loss_object(labels, predictions)
  gradients = tape.gradient(loss, model.trainable_variables)
  optimizer.apply_gradients(zip(gradients, model.trainable_variables))

  train_loss(loss)
  train_accuracy(labels, predictions)
  
# 이제 모델을 테스트합니다:
@tf.function
def test_step(images, labels):
  predictions = model(images)
  t_loss = loss_object(labels, predictions)

  test_loss(t_loss)
  test_accuracy(labels, predictions)
  
  EPOCHS = 5

for epoch in range(EPOCHS):
  for images, labels in train_ds:
    train_step(images, labels)

  for test_images, test_labels in test_ds:
    test_step(test_images, test_labels)

  template = '에포크: {}, 손실: {}, 정확도: {}, 테스트 손실: {}, 테스트 정확도: {}'
  print (template.format(epoch+1,
                         train_loss.result(),
                         train_accuracy.result()*100,
                         test_loss.result(),
                         test_accuracy.result()*100))
728x90