Python

Python - Lambda and List Comprehension

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

I. 개요

Python을 활용한 데이터전처리를 수행할 때, Lambda and List Comprehension 활용하면 매우 handy한 경험을 할 수 있다. 특히, 코드 수행 시, for-loop가 많을 때 유용하다.

II. Lambda Expression

우선 Lambda의 표현 방법은 아래와 같다.

lambda 인자 : 표현식

어떻게 사용할 수 있을까요? 우선, temp_sum이라는 함수를 만들어 본다.

Python Basic Syntax - list(1)

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

본 포스트에서는 짧게 list를 만드는 법과, 값을 추가하는 것에 대해 작성합니다.

I. list 개요

list는 순서는 순서가 있는 집합이며, [] 형태를 가집니다. list는 (integer, float, string, etc) 등으로 구성되는데, 서로 다른 데이터 값이 들어올 수도 있다. 아래 코드를 보자.

# empty list
my_list = []

# 숫자형 list
num_list = [1, 2, 3]

# 문자형 list
chr_list = ['A', 'B', 'C']

리스트는 또다른 리스트를 포함할 수 도 있다. 이것을 A nested list라고 부른다.

Tensorflow 2.0 Tutorial ch9.5 - 이미지 분할

공지

  • 본 Tutorial은 교재 시작하세요 텐서플로 2.0 프로그래밍의 강사에게 국비교육 강의를 듣는 사람들에게 자료 제공을 목적으로 제작하였습니다.

  • 강사의 주관적인 판단으로 압축해서 자료를 정리하였기 때문에, 자세하게 공부를 하고 싶으신 분은 반드시 교재를 구매하실 것을 권해드립니다.

  • 본 교재 외에 강사가 추가한 내용에 대한 Reference를 확인하셔서, 추가적으로 학습하시는 것을 권유드립니다.

Tutorial

이전 강의가 궁금하신 분들은 아래에서 선택하여 추가 학습 하시기를 바랍니다.

I. 개요

  • 이미지에서 단순히 경계선을 추출하는 작업은 전통적인 알고리즘의 필터나 한 층의 컨볼루션 레이어로도 가능하지만, 의미 있는 부분과 그렇지 않은 부분으로 분할하기 위해서는 학습이 필요합니다.
  • 앞 절에서 정의한 REDNet을 조금만 수정하면 이미지 분할(Segmentation)에서 사용할 수 있습니다.
  • 이미지의 경계선과 내용, 그리고 외곽의 3가지로 분류하는 Oxford-IIIT Pet 데이터세트로 이미지 분할 문제를 학습합니다.
  • 교재에 있는 코드에서 몇몇 에러가 발생하였습니다. 내용상 텐서플로 홈페이지와 유사하여 텐서플로 공식 홈페이지에 있는 소스코드를 참고하였습니다.
  • 먼저 필수 파일들을 pip 도구를 활용하여 설치합니다.
!pip install git+https://github.com/tensorflow/examples.git
!pip install -U tfds-nightly
Collecting git+https://github.com/tensorflow/examples.git
  Cloning https://github.com/tensorflow/examples.git to /tmp/pip-req-build-36g0gu68
  Running command git clone -q https://github.com/tensorflow/examples.git /tmp/pip-req-build-36g0gu68
Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from tensorflow-examples===63ee35adcc3e3dd2d228bc3283e27f6a1e2158ab-) (0.9.0)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from tensorflow-examples===63ee35adcc3e3dd2d228bc3283e27f6a1e2158ab-) (1.12.0)
Building wheels for collected packages: tensorflow-examples
  Building wheel for tensorflow-examples (setup.py) ... [?25l[?25hdone
  Created wheel for tensorflow-examples: filename=tensorflow_examples-63ee35adcc3e3dd2d228bc3283e27f6a1e2158ab_-cp36-none-any.whl size=125226 sha256=f2f0d0a9e57edde6593979e55a26983574dba25b3f7008be261173181109f5b8
  Stored in directory: /tmp/pip-ephem-wheel-cache-f32yqfdy/wheels/83/64/b3/4cfa02dc6f9d16bf7257892c6a7ec602cd7e0ff6ec4d7d714d
Successfully built tensorflow-examples
Installing collected packages: tensorflow-examples
Successfully installed tensorflow-examples-63ee35adcc3e3dd2d228bc3283e27f6a1e2158ab-
Collecting tfds-nightly
[?25l  Downloading https://files.pythonhosted.org/packages/8c/42/df5f05f2124f9d1b6e16b88c518f04a7d282d77daf3113ba548baadc4ce5/tfds_nightly-3.1.0.dev202005100106-py3-none-any.whl (3.3MB)
     |████████████████████████████████| 3.3MB 11.6MB/s 
[?25hRequirement already satisfied, skipping upgrade: wrapt in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (1.12.1)
Requirement already satisfied, skipping upgrade: requests>=2.19.0 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (2.23.0)
Requirement already satisfied, skipping upgrade: tqdm in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (4.41.1)
Requirement already satisfied, skipping upgrade: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (19.3.0)
Requirement already satisfied, skipping upgrade: future in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (0.16.0)
Requirement already satisfied, skipping upgrade: absl-py in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (0.9.0)
Requirement already satisfied, skipping upgrade: dill in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied, skipping upgrade: promise in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (2.3)
Collecting tensorflow-metadata<0.16,>=0.15
  Downloading https://files.pythonhosted.org/packages/3b/0c/afb81ea6998f6e26521671585d1cd9d3f7945a8b9834764e91757453dc25/tensorflow_metadata-0.15.2-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied, skipping upgrade: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (3.10.0)
Requirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (1.18.4)
Requirement already satisfied, skipping upgrade: termcolor in /usr/local/lib/python3.6/dist-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied, skipping upgrade: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly) (2020.4.5.1)
Requirement already satisfied, skipping upgrade: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly) (2.9)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly) (1.24.3)
Requirement already satisfied, skipping upgrade: googleapis-common-protos in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata<0.16,>=0.15->tfds-nightly) (1.51.0)
Requirement already satisfied, skipping upgrade: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tfds-nightly) (46.1.3)
Installing collected packages: tensorflow-metadata, tfds-nightly
  Found existing installation: tensorflow-metadata 0.21.2
    Uninstalling tensorflow-metadata-0.21.2:
      Successfully uninstalled tensorflow-metadata-0.21.2
Successfully installed tensorflow-metadata-0.15.2 tfds-nightly-3.1.0.dev202005100106

II. REDNet[^1]

  • REDNetResidual Encoder-Decoder Network의 약자이며, ResidualResNet등에서 사용하는 건너뛴 연결(skip-connection)입니다.
  • 다수의 레이어가 중첩되는 구조에서 앞쪽의 정보를 잃어버리기 않기 위해 뒤쪽에 정보를 그대로 전달해줄 때 건너뛴 연결이 사용됩니다.
import tensorflow as tf
from tensorflow_examples.models.pix2pix import pix2pix

import tensorflow_datasets as tfds
tfds.disable_progress_bar()

from IPython.display import clear_output
import matplotlib.pyplot as plt

III. 데이터 불러오기

  • tf.keras.utils.get_file() 데이터를 불러옵니다.
  • 교재에서는 oxford_iiit_pet:3.0.0으로 되어 있었는데, 버전을 3.*.*으로 수정하여 다운로드를 하기를 바랍니다.
dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True)
Downloading and preparing dataset oxford_iiit_pet/3.2.0 (download: 773.52 MiB, generated: 774.69 MiB, total: 1.51 GiB) to /root/tensorflow_datasets/oxford_iiit_pet/3.2.0...
Shuffling and writing examples to /root/tensorflow_datasets/oxford_iiit_pet/3.2.0.incompleteONHCBY/oxford_iiit_pet-train.tfrecord
Shuffling and writing examples to /root/tensorflow_datasets/oxford_iiit_pet/3.2.0.incompleteONHCBY/oxford_iiit_pet-test.tfrecord
Dataset oxford_iiit_pet downloaded and prepared to /root/tensorflow_datasets/oxford_iiit_pet/3.2.0. Subsequent calls will reuse this data.
info
tfds.core.DatasetInfo(
    name='oxford_iiit_pet',
    version=3.2.0,
    description='The Oxford-IIIT pet dataset is a 37 category pet image dataset with roughly 200
images for each class. The images have large variations in scale, pose and
lighting. All images have an associated ground truth annotation of breed.',
    homepage='http://www.robots.ox.ac.uk/~vgg/data/pets/',
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=37),
        'segmentation_mask': Image(shape=(None, None, 1), dtype=tf.uint8),
        'species': ClassLabel(shape=(), dtype=tf.int64, num_classes=2),
    }),
    total_num_examples=7349,
    splits={
        'test': 3669,
        'train': 3680,
    },
    supervised_keys=('image', 'label'),
    citation="""@InProceedings{parkhi12a,
      author       = "Parkhi, O. M. and Vedaldi, A. and Zisserman, A. and Jawahar, C.~V.",
      title        = "Cats and Dogs",
      booktitle    = "IEEE Conference on Computer Vision and Pattern Recognition",
      year         = "2012",
    }""",
    redistribution_info=,
)

Dataset의 주요 정보를 구성하고 있는 부분은 features입니다. 여기에는 image, label, segmentation_mask가 보입니다.

matplotlib 07 Polar Chart

강의 홍보

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

I. Matplotlib & Seaborn

(1) 기본 개요

Matplotlib는 파이썬 표준 시각화 도구라고 불리워지며 파이썬 그래프의 기본 토대가 된다고 해도 무방하다. 객체지향 프로그래밍을 지원하므로 세세하게 꾸밀 수 있다.

Ch13 Inner Join

I. 구글 클라우드 설정

본격적인 빅쿼리 실습에 앞서서, Python과 연동하는 예제를 준비하였다. 빅쿼리 시작에 앞서서 선행적으로 클라우드 사용을 해야 한다.

  1. 만약 GCP 프로젝트가 없다면, 계정을 연동한다. Go to Cloud Resource Manager
  2. 그리고, 비용결제를 위한 카드를 등록한다. Enable billing
  3. 마지막으로 BigQuery API를 사용해야 하기 때문에 빅쿼리 API 사용허가를 내준다.Enable BigQuery

위 API를 이용하지 않으면 Python 또는 R과 연동해서 사용할 수는 없다. 자주 쓰는것이 아니라면 비용은 거의 발생하지 않으니 염려하지 않아도 된다. 비용관리에 대한 자세한 내용은 BigQuery 권장사항: 비용 관리에서 확인하기를 바란다.

Automate Excel Reporting With Pandas

강의 홍보

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

  • 데이터는 코로나 데이터를 활용했다.

I. Overview

일부의 사람들이 RPython을 사용하지만, 대부분의 사람들은 엑셀을 사용한다. 피벗테이블은 모든 직장인이 알아야 하는 필수 용어로, 전체 데이터를 빠르게 요약해주는 일종의 skill이다.

Ch12 Join Explained

1. 구글 클라우드 설정

본격적인 빅쿼리 실습에 앞서서, Python과 연동하는 예제를 준비하였다. 빅쿼리 시작에 앞서서 선행적으로 클라우드 사용을 해야 한다.

  1. 만약 GCP 프로젝트가 없다면, 계정을 연동한다. Go to Cloud Resource Manager
  2. 그리고, 비용결제를 위한 카드를 등록한다. Enable billing
  3. 마지막으로 BigQuery API를 사용해야 하기 때문에 빅쿼리 API 사용허가를 내준다.Enable BigQuery

위 API를 이용하지 않으면 Python 또는 R과 연동해서 사용할 수는 없다. 자주 쓰는것이 아니라면 비용은 거의 발생하지 않으니 염려하지 않아도 된다. 비용관리에 대한 자세한 내용은 BigQuery 권장사항: 비용 관리에서 확인하기를 바란다.

Tensorflow 2.0 Tutorial ch9.4 - 초해상도

공지

  • 본 Tutorial은 교재 시작하세요 텐서플로 2.0 프로그래밍의 강사에게 국비교육 강의를 듣는 사람들에게 자료 제공을 목적으로 제작하였습니다.

  • 강사의 주관적인 판단으로 압축해서 자료를 정리하였기 때문에, 자세하게 공부를 하고 싶으신 분은 반드시 교재를 구매하실 것을 권해드립니다.

  • 본 교재 외에 강사가 추가한 내용에 대한 Reference를 확인하셔서, 추가적으로 학습하시는 것을 권유드립니다.

Tutorial

이전 강의가 궁금하신 분들은 아래에서 선택하여 추가 학습 하시기를 바랍니다.

I. 개요

  • 저해상도에서 고해상도의 이미지로 변환하는 것은 어려운 연산입니다.
  • 픽셀로 구성된 이미지는 고해상도로 변환(확대)하면 이미지에서 사각형이 두드러져 보이는 것이 바로 초해상도(Super Resolution) 작업입니다.
  • 전통적으로는 interpolation(보간) 등의 기법이 있지만, 선명함을 잃고 흐릿해지는 단점이 있습니다.
  • 오토인코더로 초해상도 작업을 하는 과정을 진행합니다.
  • 이 때, REDNet이라는 네트워크를 사용합니다.

II. REDNet1

  • REDNetResidual Encoder-Decoder Network의 약자이며, ResidualResNet등에서 사용하는 건너뛴 연결(skip-connection)입니다.
  • 다수의 레이어가 중첩되는 구조에서 앞쪽의 정보를 잃어버리기 않기 위해 뒤쪽에 정보를 그대로 전달해줄 때 건너뛴 연결이 사용됩니다.
  • 논문에서 사용한 이미지는 BSD (Berkeley Segmentation Dataset) 이며, 책에서도 동일하게 사용합니다.
# 텐서플로 2 버전 선택
try:
    # %tensorflow_version only exists in Colab.
    %tensorflow_version 2.x
except Exception:
    pass
import tensorflow as tf
import numpy as np
import pandas as pd
import tensorflow_hub as hub
import matplotlib.pyplot as plt
import cv2

III. 데이터 불러오기

  • tf.keras.utils.get_file() 데이터를 불러옵니다.
tf.keras.utils.get_file('/content/bsd_images.zip', 'http://bit.ly/35pHZlC', extract=True)
Downloading data from http://bit.ly/35pHZlC
37527552/37520292 [==============================] - 0s 0us/step





'/content/bsd_images.zip'
!unzip /content/bsd_images.zip
Archive:  /content/bsd_images.zip
   creating: images/
   creating: images/test/
  inflating: images/test/100007.jpg  
  inflating: images/test/100039.jpg  
  .
  .
  .
  .
  inflating: images/val/97033.jpg    
  inflating: images/val/Thumbs.db    
  • 이미지 경로 저장 및 확인을 합니다.
import pathlib
image_root = pathlib.Path('/content/images')
all_images_paths=list(image_root.glob('*/*'))
print(all_images_paths[:10])
[PosixPath('/content/images/val/62096.jpg'), PosixPath('/content/images/val/361010.jpg'), PosixPath('/content/images/val/Thumbs.db'), PosixPath('/content/images/val/54082.jpg'), PosixPath('/content/images/val/87046.jpg'), PosixPath('/content/images/val/38082.jpg'), PosixPath('/content/images/val/156065.jpg'), PosixPath('/content/images/val/33039.jpg'), PosixPath('/content/images/val/14037.jpg'), PosixPath('/content/images/val/159008.jpg')]
  • 각 이미지의 경로는 root 디렉터리에서 glob() 함수를 사용해 하단의 모든 파일을 불러올 수 있습니다.
  • 각 파일의 경로는 PosixPath라는 객체가 되는데, 이 객체에서 경로를 가져오기 위해서는 문자열로 변환하는 str()함수를 사용합니다.

(1) 이미지 시각화

  • matplotlib.pyplot으로 확인합니다.
import PIL.Image as Image
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 12))
for c in range(9):
  plt.subplot(3,3,c+1)
  plt.imshow(plt.imread(all_images_paths[c]))
  plt.title(all_images_paths[c])
  plt.axis('off')
plt.show()

/img/programming/2020/05/ch9_4_super_resolution/output_7_1.png png

pandas pivot table

강의 홍보

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

  • 데이터는 코로나 데이터를 활용했다.

I. Overview

일부의 사람들이 RPython을 사용하지만, 대부분의 사람들은 엑셀을 사용한다. 피벗테이블은 모든 직장인이 알아야 하는 필수 용어로, 전체 데이터를 빠르게 요약해주는 일종의 skill이다.

Tensorflow 2.0 Tutorial ch9.3 - 클러스터링

공지

  • 본 Tutorial은 교재 시작하세요 텐서플로 2.0 프로그래밍의 강사에게 국비교육 강의를 듣는 사람들에게 자료 제공을 목적으로 제작하였습니다.

  • 강사의 주관적인 판단으로 압축해서 자료를 정리하였기 때문에, 자세하게 공부를 하고 싶으신 분은 반드시 교재를 구매하실 것을 권해드립니다.

  • 본 교재 외에 강사가 추가한 내용에 대한 Reference를 확인하셔서, 추가적으로 학습하시는 것을 권유드립니다.

Tutorial

이전 강의가 궁금하신 분들은 아래에서 선택하여 추가 학습 하시기를 바랍니다.

I. 개요

  • 오토인코더(AutoEncoder)는 입력에 대한 출력을 학습해야 한다는 점은 기존 지도학습 네트워크와 동일합니다.
  • 그러나 그 출력이 입력과 동일하다는 점이 조금 다릅니다.
  • 오토인코더는 자기 자신을 재생성하는 네트워크입니다.