파이썬 객체 지향 프로그래밍 - Attributes & Methods

1줄 요약

  • Attributes & Methods의 차이점에 대해 이해한다.

개요

  • Object = State + Behavior
    • 예) Email, Phone Number, 배송상태
  • Class는 일종의 가이드라인을 의미
  • 파이썬 내의 모든 객체는 일종으 클래스임
ObjectClass
7int
“Hello”str
pd.DataFrame()DataFrame
  • 해당 클래스를 찾기 위해 type( )를 사용함.
import numpy as np
temp = np.array([1, 2, 3])
print(type(temp))
<class 'numpy.ndarray'>

State + Behavior

  • 그렇다면, State를 지칭하는 파이썬 문법은 무엇인가?
    • 파이썬에서는 이를 Attributes라고 부른다.
  • 또한, Behavior를 지칭하는 파이썬 문법은 무엇인가?
    • 파이썬에서는 이를 Methods라고 부른다.
  • 먼저 Attributes 문법을 확인해본다.
# shape attribute
temp.shape
(3,)
  • 이번에는 Methods 문법을 확인해본다.
# reshpae method
temp.reshape(3, 1)
array([[1],
       [2],
       [3]])

소결

  • Object = Attributes + Methods
    • attribute <-> variables <-> obj.my_attribute,
    • attribute <-> function() <-> obj.my_method().
  • dir() 해당 객체의 모든 attributes, methods를 보여줌
dir(temp)
['T',
 '__abs__',
 '__add__',
 '__and__',
 '__array__',
 '__array_finalize__',
 '__array_function__',
 '__array_interface__',
 '__array_prepare__',
 '__array_priority__',
 '__array_struct__',
 '__array_ufunc__',
 '__array_wrap__',
 '__bool__',
 '__class__',
 '__complex__',
 '__contains__',
 '__copy__',
 '__deepcopy__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__iand__',
 '__ifloordiv__',
 '__ilshift__',
 '__imatmul__',
 '__imod__',
 '__imul__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__invert__',
 '__ior__',
 '__ipow__',
 '__irshift__',
 '__isub__',
 '__iter__',
 '__itruediv__',
 '__ixor__',
 '__le__',
 '__len__',
 '__lshift__',
 '__lt__',
 '__matmul__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmatmul__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__setitem__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__xor__',
 'all',
 'any',
 'argmax',
 'argmin',
 'argpartition',
 'argsort',
 'astype',
 'base',
 'byteswap',
 'choose',
 'clip',
 'compress',
 'conj',
 'conjugate',
 'copy',
 'ctypes',
 'cumprod',
 'cumsum',
 'data',
 'diagonal',
 'dot',
 'dtype',
 'dump',
 'dumps',
 'fill',
 'flags',
 'flat',
 'flatten',
 'getfield',
 'imag',
 'item',
 'itemset',
 'itemsize',
 'max',
 'mean',
 'min',
 'nbytes',
 'ndim',
 'newbyteorder',
 'nonzero',
 'partition',
 'prod',
 'ptp',
 'put',
 'ravel',
 'real',
 'repeat',
 'reshape',
 'resize',
 'round',
 'searchsorted',
 'setfield',
 'setflags',
 'shape',
 'size',
 'sort',
 'squeeze',
 'std',
 'strides',
 'sum',
 'swapaxes',
 'take',
 'tobytes',
 'tofile',
 'tolist',
 'tostring',
 'trace',
 'transpose',
 'var',
 'view']

References

GCP Kubernetes Engine을 통한 배포(2)

인프런 강의

1줄 요약

  • (GCP) GKE를 활용하여 nginx를 실행해보자.

Step 1. GCP Shell 활성화

  • You can list the active account name with this command:
(your_project_id)$ gcloud auth list
           Credentialed Accounts
ACTIVE  ACCOUNT
*       student-04-e46af1f1cd7b@qwiklabs.net

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
  • You can list the project ID with this command:
(your_project_id)$ gcloud config list project
[core]
project = qwiklabs-gcp-04-79efc1e4ae0f

Your active configuration is: [cloudshell-24251]

Step 2. Create Deployment manifests

  • Task 1. Create deployment manifests and deploy to the cluster

(1) Connect to the lab GKE cluster

  • In Cloud Shell, type the following command to set the environment variable for the zone and cluster name.
(your_project_id)$ export my_zone=us-central1-a
(your_project_id)$ export my_cluster=standard-cluster-1
  • Configure kubectl tab completion in Cloud Shell.
(your_project_id)$ source <(kubectl completion bash)
  • In Cloud Shell, configure access to your cluster for the kubectl command-line tool, using the following command:
$ gcloud container clusters get-credentials $my_cluster --zone $my_zone
Fetching cluster endpoint and auth data.
kubeconfig entry generated for standard-cluster-1.
  • In Cloud Shell enter the following command to clone the repository to the lab Cloud Shell.
(your_project_id)$ git clone https://github.com/GoogleCloudPlatform/training-data-analyst
  • Create a soft link as a shortcut to the working directory.
(your_project_id)$ ln -s ~/training-data-analyst/courses/ak8s/v1.1 ~/ak8s
  • Change to the directory that contains the sample files for this lab.
(your_project_id)$ cd ~/ak8s/Deployments/
your_id@cloudshell:~/ak8s/Deployments (your_project_id)$

(2) Create a deployment manifest

  • You will create a deployment using a sample deployment manifest called nginx-deployment.yaml that has been provided for you. This deployment is configured to run three Pod replicas with a single nginx container in each Pod listening on TCP port 80.
    • Let’s create nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
  • To deploy your manifest, execute the following command:
~/ak8s/Deployments (your_project_id)$ kubectl apply -f ./nginx-deployment.yaml
  • To view a list of deployments, execute the following command:
~/ak8s/Deployments (your_project_id)$ kubectl get deployments
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3/3     3            3           24s

Step 3.Manually scale up and down the number of Pods in deployments

Sometimes, you want to shut down a Pod instance. Other times, you want ten Pods running. In Kubernetes, you can scale a specific Pod to the desired number of instances. To shut them down, you scale to zero. In this task, you scale Pods up and down in the Google Cloud Console and Cloud Shell.

[Python] Open API를 활용한 Air Quality 데이터 수집 예제

강의 홍보

1줄 요약

  • 오픈 데이터로 활용하여 시계열 데이터를 확보해보자.

동기 부여

  • Pandas 공식 홈페이지가 살짝 바뀐 듯 하였다.
  • 시계열 데이터를 다루는 페이지를 확인하던 중 open air quality data API가 있는 것을 확인하였다.

라이브러리 설치

  • 라이브러리 설치는 비교적 간단하다.
$ pip install py-openaq
Collecting py-openaq
  Downloading py-openaq-1.1.0.tar.gz (7.9 kB)
Building wheels for collected packages: py-openaq
  Building wheel for py-openaq (setup.py) ... done
  Created wheel for py-openaq: filename=py_openaq-1.1.0-py3-none-any.whl size=9036 sha256=1d5011bd3ef180c93d275081f6f5ad20d569c9f7ce2982eabaaeee7307070b75
  Stored in directory: /Users/evan/Library/Caches/pip/wheels/01/1d/be/6b6a0ee792bbc9138aeb645707cdad8da741bb2d789beb04d9
Successfully built py-openaq
Installing collected packages: py-openaq
Successfully installed py-openaq-1.1.0

데이터 불러오기

  • 데이터를 불러오면 다음과 같다.
import openaq
api = openaq.OpenAQ()

location = "FR04014"
date_from = "2019-05-07T01:00:00" 
date_to = "2019-06-21T00:00:00" 
parameter = "no2"

FR04014_results = api.measurements(location=location, 
                                   parameter=parameter, 
                                   date_from=date_from, 
                                   date_to=date_to, 
                                   limit=10000,
                                   df=True, 
                                   index='local')
print(FR04014_results.shape)
FR04014_results.head()
(1002, 9)
locationparametervalueunitcountrycitydate.utccoordinates.latitudecoordinates.longitude
date.local
2019-06-21 02:00:00FR04014no220.0b'\xc2\xb5g/m\xc2\xb3'FRParis2019-06-21 00:00:00+00:0048.8372432.393902
2019-06-21 01:00:00FR04014no221.8b'\xc2\xb5g/m\xc2\xb3'FRParis2019-06-20 23:00:00+00:0048.8372432.393902
2019-06-21 00:00:00FR04014no226.5b'\xc2\xb5g/m\xc2\xb3'FRParis2019-06-20 22:00:00+00:0048.8372432.393902
2019-06-20 23:00:00FR04014no224.9b'\xc2\xb5g/m\xc2\xb3'FRParis2019-06-20 21:00:00+00:0048.8372432.393902
2019-06-20 22:00:00FR04014no221.4b'\xc2\xb5g/m\xc2\xb3'FRParis2019-06-20 20:00:00+00:0048.8372432.393902
  • 정상적으로 데이터가 불러오진 것을 확인할 수 있다.
  • 다음은 3개의 데이터셋을 만들어서 합친 후, 시계열 데이터 핸들링을 연습해보독 한다.

Reference

HP-Nunes.(2020). An Introduction to Data Collection: REST APIs with Python & Pizzas, Medium, Retrieved from https://medium.com/@geocuriosity/an-introduction-to-data-collection-rest-apis-with-python-pizzas-7b682cef676c

GCP Kubernetes Engine을 통한 배포(1)

인프런 강의

1줄 요약

  • (GCP) GKE를 활용하여 nginx를 실행해보자.

Step 1. GKE Cluster Setup

  • 네비게이션 메뉴에서 Kubernetes Engine > Clusters를 클릭합니다.

  • 위 화면에서 Create를 클릭합니다.

  • 그 이후에, Cluster 이름은 standard-cluster-1으로 바꾸고, Zone은 us-central1-a로 바꿉니다.

  • 나머지는 모두 Default로 그냥 놔둡니다.

Docker Started using Cloud Build

인프런 강의

1줄 요약

  • (GCP) Cloud Build를 활용하여 Docker를 활용해보자.

Step 1. API Enabled

  • 클라우드 네비게이션 메뉴에서 APIs & Services를 클릭한다.
  • Enable APIs and Services를 클릭한다.
  • Search for APIs & Services에서 Cloud Build를 입력한다.
  • Cloud Build API를 클릭한 후, Enable 버튼을 클릭한다.
  • 뒤로가기 버튼을 클릭한 후, Google Container Registry API 버튼을 클릭한다.

Step 2. Docker File 작성

  • 아래 그림처럼 Activate Cloud Shell를 클릭한다.

Google Colab에서 Kaggle API 쉽게 사용하는 방법

한줄 요약

  • 귀찮지만 한 2개의 Cell은 입력후 실행하자.

개요

  • Google Colab에서 Kaggle을 사용하려면 보통 다음과 같은 과정을 거칩니다.
  • 패키지 설치는 필수입니다.
!pip install kaggle
Requirement already satisfied: kaggle in /usr/local/lib/python3.7/dist-packages (1.5.10)
Requirement already satisfied: python-dateutil in /usr/local/lib/python3.7/dist-packages (from kaggle) (2.8.1)
Requirement already satisfied: six>=1.10 in /usr/local/lib/python3.7/dist-packages (from kaggle) (1.15.0)
Requirement already satisfied: urllib3 in /usr/local/lib/python3.7/dist-packages (from kaggle) (1.24.3)
Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from kaggle) (2.23.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from kaggle) (4.41.1)
Requirement already satisfied: certifi in /usr/local/lib/python3.7/dist-packages (from kaggle) (2020.12.5)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.7/dist-packages (from kaggle) (4.0.1)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->kaggle) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->kaggle) (2.10)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.7/dist-packages (from python-slugify->kaggle) (1.3)

문제점

  • 아래 코드를 봅시다.
from google.colab import files

uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))
  
# Then move kaggle.json into the folder where the API expects to find it.
!mkdir -p ~/.kaggle/ && mv kaggle.json ~/.kaggle/ && chmod 600 ~/.kaggle/kaggle.json
  • 문제는 kaggle.json 파일을 매번 업로드 해줘야 하는데, 매우 번거롭습니다. 간혹 파일이 삭제되기도 합니다.

해결방법

  • 이럴 때 간편한 방법은 위 방법 대신에 아래와 같이 입력을 하는 것입니다.
  • key값은 kaggle.json 파일에 있습니다. 메모장 같은 텍스트 에디터나 파이참 같은 통합개발환경툴을 사용하면 바로 확인이 가능합니다.
!mkdir ~/.kaggle
!echo '{"username":"your_name","key":"your_key"}' > ~/.kaggle/kaggle.json
!chmod 600 ~/.kaggle/kaggle.json
mkdir: cannot create directory ‘/root/.kaggle’: File exists
  • 실제 잘 되는지 확인해 봅니다.
!kaggle competitions list
Warning: Looks like you're using an outdated API Version, please consider updating (server 1.5.12 / client 1.5.4)
ref                                            deadline             category            reward  teamCount  userHasEntered  
---------------------------------------------  -------------------  ---------------  ---------  ---------  --------------  
contradictory-my-dear-watson                   2030-07-01 23:59:00  Getting Started     Prizes        102           False  
gan-getting-started                            2030-07-01 23:59:00  Getting Started     Prizes        209           False  
tpu-getting-started                            2030-06-03 23:59:00  Getting Started  Knowledge        493           False  
digit-recognizer                               2030-01-01 00:00:00  Getting Started  Knowledge       3394           False  
titanic                                        2030-01-01 00:00:00  Getting Started  Knowledge      27213            True  
house-prices-advanced-regression-techniques    2030-01-01 00:00:00  Getting Started  Knowledge       6963            True  
connectx                                       2030-01-01 00:00:00  Getting Started  Knowledge        595           False  
nlp-getting-started                            2030-01-01 00:00:00  Getting Started  Knowledge       1723            True  
competitive-data-science-predict-future-sales  2022-12-31 23:59:00  Playground           Kudos      10797            True  
jane-street-market-prediction                  2021-08-23 23:59:00  Featured          $100,000       4245            True  
hungry-geese                                   2021-07-26 23:59:00  Playground          Prizes        423           False  
coleridgeinitiative-show-us-the-data           2021-06-22 23:59:00  Featured           $90,000        188           False  
bms-molecular-translation                      2021-06-02 23:59:00  Featured           $50,000        350           False  
iwildcam2021-fgvc8                             2021-05-26 23:59:00  Research         Knowledge         11           False  
herbarium-2021-fgvc8                           2021-05-26 23:59:00  Research         Knowledge         30           False  
plant-pathology-2021-fgvc8                     2021-05-26 23:59:00  Research         Knowledge        121           False  
hotel-id-2021-fgvc8                            2021-05-26 23:59:00  Research         Knowledge         26           False  
hashcode-2021-oqr-extension                    2021-05-25 23:59:00  Playground       Knowledge        101           False  
indoor-location-navigation                     2021-05-17 23:59:00  Research           $10,000        734           False  
hpa-single-cell-image-classification           2021-05-11 23:59:00  Featured           $25,000        432           False  
  • 만약, kaggle json 파일을 새로 받았다면? 당연한 말이지만, 위 key값도 새로 입력해줘야 합니다.
  • 아래 코드를 확인해본다.

귀찮지만, 두개의 Cell은 실행합시다. 작은 도움이 되기를 바랍니다. Happy to Code

왜 Git 그래프가 채워지지 않는가?

1줄 요약

  • 이메일을 확인하자.

개요

  • 필자는 강의를 위해 깃헙 계정이 여러개가 존재함
  • 강사용 PC에서 지속적으로 Commit을 진행했으나 Github 그래프가 출력이 되지 않는 오류 발생을 해결하는 과정에서 확인

Github 질의

왜? 공통 이유 중의 하나는 이메일

  • 이 때, 가장 중요한 것은 이메일입니다.
    • 사실, 해당 내용에도 나오지만, 가장 흔한 이유 중의 하나라고 합니다.

Your local Git commit email isn’t connected to your account Commits must be made with an email address that is connected to your account on GitHub, or the GitHub-provided noreply email address provided to you in your email settings, in order to appear on your contributions graph. For more information about noreply email addresses, see “Setting your commit email address.”

Introduction to MLOps

인프런 강의

1줄 요약

  • MLOps를 소개해본다.

What is MLOps?

  • 최근 기술 트렌드 중의 Hot한 주제는 DevOps이다.

    • DevDevelopment의 약어이며, OpsOperation의 약자이다.
    • 과거에는 개발팀과 운영팀 두개로 존재하는 것이 상식이었지만, 가장 큰 문제는 Communication 문제! 이러한 문제점을 해결하기 위해 나온 방법론이 DevOps이다.
  • 이러한 부분은 머신러닝과 딥러닝도 동일함. 즉, 개발자를 위한 배포와 운영이 DevOps라면, 머신러닝 엔지니어를 위해 나온 기술은 MLOps로 볼 수 있다. 자세한 것은 유투브 영상을 통해서 기본적인 개념을 배웠으면 한다.

Windows 10 KoNLP 설치

한줄 요약

  • KoNLP는 여기에서 무조건 해결한다.

KoNLP 이슈

  • R에서 텍스트 마이닝을 진행할 때에는 반드시 한번쯤은 패키지 설치로 인해 어려움을 겪는다. - R 입문자 분들이 초반에 호기롭게 시작하였다가 대부분 포기하려고 하는 지점이기도 하다.
  • 사실, 조금 더 간편한 방법이 나오기를 기대한다.

1단계 Java 설치 및 환경 변수 설정

  • 주의: 윈도우 10 64비트

  • 여러 좋은 자료들이 많아서 같이 참고하기를 바란다.

트위터 데이터 수집 with R

1줄 요약

  • R을 활용하여 트위터 데이터를 수집하는 방법 및 절차에 대해 배우도록 한다.

트위터 API 인증

  • https://apps.twitter.com에 접속한다.

    • 회원가입을 진행한다.
  • create an app 버튼을 클릭한다.

  • 필자는 Hobbysit-Exploring the API를 선택했다.

    • 그 후에 개인 정보 등을 입력해야 한다.
    • 휴대폰, 이메일 인증 등
  • 인증 메일이 오기전까지는 조금 시일이 걸린다.

rtweet 패키지

  • 별도의 인증 절차 없이 사용 가능한 패키지

  • 우선 설치 후, 사용해보도록 한다.

    • 본 코드는 Github 예제로 있는 코드를 가져온 것임
# install.packages("rtweet")
library(rtweet)
library(dplyr)
library(ggplot2)

Search Tweets

  • search_tweets() 함수를 활용하면 매우 쉽게 데이터를 가져올 수 있다.
rstats <- search_tweets("#테슬라", n = 1000, include_rts = FALSE) %>% 
  select(name, location, description)
  • 앱 인증 절차만 진행이 되면 데이터를 가져올 수 있다.
glimpse(rstats)
## Rows: 132
## Columns: 3
## $ name        <chr> "얼리어답터", "얼리어답터", "허프포스트코리아", "뉴스핌", "뉴스핌", "disclosure", ~
## $ location    <chr> "", "", "SEOUL", "Korea", "Korea", "", "", "", "", "", "",~
## $ description <chr> "2001년부터 전세계의 테크 트랜드를 한국에 소개했던 얼리어답터가 완전히 새롭게 다시 시작합니다. 더 ~
  • 텍스트 데이터를 수집할 수 있었다.

그 외 패키지와의 비교

  • Github에는 rtweet 패키지가 어떤 Task를 수행하는 비교하는 표가 있다.