728x90
728x90
728x90

배경:

우리가 어떤 class의 object를 만들 때면, 각 object마다 dictionary가 할당되는데, 이는 object의 attribute를 저장해두기 위함이다. 이는 dictionary다 보니까 메모리를 꽤나 차지한다. 다수의 object를 만들 때면 이러한 메모리들이 쌓여 태산이 된다.

 

사용할 상황:

class에 attibutes가 제한되어 있다면(즉 향후에 dynamic하게 attributes를 추가하거나 하는 작업이 없다면)

__slots__로 attribute를 제한하고 시작하고, 이렇게 되면 dictionary를 사용하지 않아 메모리를 절약함과 동시에

attribute 접근 속도도 빨라진다.

 

사용법:

class attribute로 __slots__ = ['att1', 'att2'] 형태로, 사용할 attributes를 선언하면,

이 class의 object는 __dict__를 갖지 않는다.

 

장점:

-object의 attribute 접근 속도 향상

-메모리 절약

 

단점:

-dynamic attribute 할당은 불가

 

 

참고자료:

www.geeksforgeeks.org/python-use-of-__slots__/

 

Python | Use of __slots__ - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

728x90
728x90

헷갈리는 Iterator, Iterable 개념의 공통점과 차이를 보아 확실히 이해해보자.

명확한 정의를 알아보자. 단순히 특징을 알아보는게 아니다.

즉, Iterable은 for-loop을 돌 수 있는 것, 따위 형태로 알아보자는 것이 아니라, 

정확한 정의를 통해 성질을 알아보는 형태로 작성한다.

 

Iterable->Iterator->Generator 순으로 알아보자.

 

Iterable이란

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-equence types like dict, file objects, and objects of any classes you define with an __iter__() method or with a __getitem__() method that implements Sequence semantics.

 

Iterator란

Iterators are required to have both __iter__() method that returns the iterator object itself so every iterator is also iterable and __next__() method.

 

Generator란, 아래 2개 중 하나를 가리킬 때 쓰는데, 여기서는 후자를 가리킨다. 

-generator function란

function which returns a generator iterator. It looks like a normal function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function.

-generator iterator란

An object created by a generator function.

비고:

generator iterator는 생성하면 반드시 __iter__() method와 __next__() method를 갖는다.

따라서 generator는 반드시 iterator이다.

iteration을 돌 때 순차적인 값을 얻는 것에만 관심있다면 generator만으로 족하다.

하지만, 현재 current state를 조회한다는 등의 추가적인 method가 필요하다면 iterator를 직접 정의하여 사용하자.

 

따라서 다음 포함관계가 성립한다.

generator ⊂ iterator ⊂ iterable

 

위 3개의 개념을 헷갈리게 만드는 주범으로는

from collections.abc import Iterable

isinstance([object], Iterable)

-> 위에서 정의한 Iterable을 판단하기에 완벽하지 않다. 

object가 만약 __getitem__() method만 갖는 object면 False를 반환한다.

그렇다면 정확한 Iterable 객체임을 판단하는 방법은 무엇인가?

iter([object])을 씌웠을 때 error가 안뜨면 object는 iterable 객체이다.

 

Iterable 객체가 loop을 돌 때 작동하는 방식은

-iter을 씌운 다음에

-next해서 원소들을 반환함

 

Iterable, Iterator, Generator를 각각 언제 쓸 것인가?

 

순환하고 값 조회를 더이상 할 필요가 없다면 iterator/generator를 사용

이 때, 순차적인 1회성 조회할 iterator를 만들 것이면 generator를 사용

순환하면서도 current state같은 것을 조회하려면 (custom) iterator를 사용

 

iter() function은 무엇인가?

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

즉 sentinel(=보초병, 감시병)값이 argument로 넣냐 안넣냐에 따라 달라진다.

안넣으면 object의 __iter__()을 실행시켜 iterator를 반환한다.

넣으면 first argument는 반드시 callable이어야하고 sentinel값이 나올 때 까지 next가 가능한 iterator를 반환한다.

후자는 callable_iterator type이 반환된다.

전자든 후자든 isinstance([object], Iterator)로 iterator 확인 가능

즉 iter(iterable) or iter(callable object, sentinel) 형태로 사용

 

참고자료의 마지막을 꼭 보자.(Iterator을 만드는 다양한 방법을 제시한다.)

__iter__()를 활용하여 iterable을 정의하고 __next__()을 추가하여 iterator을 만드는 예제

__getitem__()을 활용한 iterable을 정의하고 iterator을 만들어서 동작하는 예제

callable object(class with __call__() or function)와 sentinel을 활용한 iterator 생성하는 예제

 

 

 

참고자료:

docs.python.org/3/glossary.html

 

Glossary — Python 3.9.0 documentation

The implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type. For example, int(3.15) converts the floating point number to the integer 3, but in 3+4.5, each argument is of a different type

docs.python.org

stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators

 

Difference between Python's Generators and Iterators

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.

stackoverflow.com

twiserandom.com/python/python-iterable-and-iterator-a-tutorial/#implement_the_getitem_methods

 

Python iterable and iterator a tutorial | Twise Random

what is an iterable ? In python , objects are abstraction of data , they have methods that work with data , and help us to manipulate it . If we take a look at a list , and see all of its methods >>> import json >>> _list = [] # an empty list >>> json_list

twiserandom.com

 

728x90
728x90

NAVER의 추천 시스템과 연관된 내용들을 특별한 분류없이 마구잡이로 정리해보자.

Termiology를 정리할 수도 있겠고

부족한 이론을 채울 수도 있겠고

단순 정보를 정리할 수도 있겠다.

해당 기업의 블로그와 개발자 컨퍼런스 블로그 등을 참고하여 작성

 

POI:Point Of Interest, a specific point location that someone may find useful or interesting.

 

CONOMI:네이버 플레이스의 POI Management 기술과 AI를 활용하여 사용자가 좋은 리뷰를 편리하게 작성할 수 있도록 하고, 이를 기반으로 다양한 식당과 음식을 찾도록 도와주는 프로그램

 

UGC:User-generated content, 사용자가 제작한 콘텐츠

 

RIYO:Rank It YOurself, 사용자가 선택하는 옵션 단계에 따라 가중치를 가감하여 급상승 검색어를 재정렬하는 기능

 

AiRS:AI Recommender System, 공기(AIR)와 같이 항상 이용자 곁에서 유용한 콘텐츠를 추천한다는 뜻으로 붙임, 

블로그에는 CF(Collaborative Filtering, 활동내역->클러스터링->클러스터링 내 유저들의 활동내역으로 추천)과 RNN을 사용한다고 하나, 2017년 2월 아티클이므로 기술 수준이 달라졌을 듯

 

SRE:Site Reliability Engineering, 매우 큰 규모의 데이터 처리, 높은 트래픽 환경에서 안정적으로 처리하기 위한 엔지니어링, 운영 자동화 등 서비스에 필연적으로 따르는 운영을 합리적으로 다루는 일

(Metric 정의 & Monitoring, Capacity Planning(서비스에 필요한 용량 계산, 용량 확보 방안, 소프트웨어 최적화), Change Management(배포/업데이트 관리), Emergency Response(장애 처리) 등으로 업무가 분류됨)

 

on-call:비상 대기 인력으로 근무 시에 사용(그냥 근무할 때는 on duty라고 사용)

 

pain-point:불편사항, 고충

 

CIC:Company-in-company, 사내독립기업이란 의미로 창업가형 리더를 길러내고 각 사업단위를 독자적으로 잘 키워 독립할 수 있도록 하는게 목표로, 일정 비즈니스 모델로 정착이 되면 분사

(약어 CIC를 사용하는 CLOVA Interface Connect는 협력사가 클로바 기술을 쉽게 접목시키게 만든 인터페이스)

 

cross-domain recommendation:타 도메인의 활동이력을 활용하여 해당 도메인의 상품을 추천하는, 추천 시스템 내의 한 분야

 

장소추천에 있어서

일본에서는 유저간의 follower-following관계, 메뉴 단위의 리뷰와 평점 데이터, 이미지 중심의 데이터 활용

한국에서는 지도 데이터, 블로그 데이터와 이를 클릭하는 유저들의 데이터를 활용

이는 두 국가의 문화적 차이보다는 서비스에서 오는 데이터의 차이 때문

하지만, 두 국가간의 활용 데이터 차이는 좁혀져 가고 있으며

두 국가모두 모든 데이터를 활용할 수 있을 거라 예상

 

 

slideshare내용 마저 정리하기

d2에서 클로바 모델 2.0정리하기 등

 

 

 

참고자료:

www.slideshare.net/deview/airs-80886207

 

인공지능추천시스템 airs개발기_모델링과

인공지능추천시스템 airs개발기_모델링과시스템

www.slideshare.net

blog.naver.com/naver_diary

 

네이버 다이어리 : 네이버 블로그

사람과 사람, 오늘과 내일, Network와 Network가 연결되는- 더 큰 세상을 만들어 가는 NAVER의 공식블로그입니다

blog.naver.com

d2.naver.com/home

 

728x90
728x90

throughput?

concurrency?...

 

운영체제 공부하며 봤던 것들 정리 필요

봐도봐도 헷갈리니까 예제 하나씩 끼워넣기

 

728x90
728x90

dictionary의 값을 한번 조회하고 그 이후에 필요없다면 pop method를 사용하자.

(자꾸 get이나 dict[key]만 사용하려고함)

 

 

 

element가 sequence에 존재하는지를 자주 체크한다면

list보다는 set을 사용하자.

list는 O(n), set은 O(1)(open hashing 방식이므로)

 

 

 

메모리에 크게 들고 있지 않아도 된다면, generator를 쓸 생각을 하자.

이는 단순히 메모리 절약차원 뿐 아니라, 실제 속도도 더 높을 수가 있다.

순차적으로 sequence내 원소를 합하는 경우, 

단순 큰 list였다면 메모리에 builing하느라 시간을 잡아먹기때문

 

 

 

Global variable을 Local ones로 바꿀 수 있다면 바꿔라

이는 variable search 순서에서 오는 속도높이는 방법인데

local에서 variable을 search할 때, 

local->global->built-in namespace 순서로 찾기 때문이다.

 

 

 

Class property(예를 들면 self._value)를 자주 access한다면

마찬가지로 local variable(class내의 function에서 자주 접근한다면)로 바꿔라.

 

 

 

.function을 자주 쓸 것이면, function을 assign해서 쓰자.

즉, list.append()을 자주 쓸 것이면

appender = list.append라 두고 appender를 쓰자.

이는, function call할 때면 __getattribute__()나 __getattr__()을 호출하게되는데 이 time cost를 줄일 수 있다.

 

 

 

많은 string을 여러번 +연산을 할 때에는 join을 사용하자.

'a' + 'b'을 한다고하면 memory space 요청을 1번 하게 되고 그 때 a와 b를 copy하여 박는다.

'a' + 'b' + 'c'는 memory space요청을 2번하게 된다.

따라서 n개의 string을 +하면 n-1개의 요청을 하게된다.

이 때, join을 쓰면, 전체 필요 memory space를 계산하여 1번만 메모리 요청을 한다.

 

 

 

Multiple conditions에서 condition의 위치는

-if Condition1 and Condition2 에는 1과 2중 False가 자주 뜰 것을 Condition1에 할당

-if Condition1 or Condition2에는 1과 2중 True가 자주 뜰 것을 Condition1에 할당

(short-circuit evaluation, AND 혹은 OR 연산에 있어서 First condition에 의하여 return이 확정되면, 이후 condition은 연산을 실행조차 하지 않는 것을 가리킴)

 

 

 

While문보다는 Foor문을 쓰자.

이는 While문에서 i

 

 

참고자료:

towardsdatascience.com/10-techniques-to-speed-up-python-runtime-95e213e925dc

 

10 Techniques to Speed Up Python Runtime

Compare good writing style and bad writing style with the code runtime

towardsdatascience.com

 

 

728x90
728x90

list comprehension에서 if else를 쓰고 싶다면

res = [x if x >3 else 2 for x in iter_]

즉 for 뒤에 optional if condition이 아니라 실제 값을 받는 부분에 if else ternary operator를 쓰자.

 

 

 

참고자료:

medium.com/techtofreedom/8-levels-of-using-list-comprehension-in-python-efc3c339a1f0

 

8 Levels of Using List Comprehension in Python

A Complete Guidance From Elementary to Profound

medium.com

 

728x90
728x90

가장 기본적인 clustering algorithm, unsupervised.

 

k는 cluster의 개수를 나타낸다.(hyperparameter)

최적의 k개의 centroids를 찾는 것이 알고리즘의 목표

 

알고리즘:

Assignment-step과 Update-step으로 나뉘어져있다.

각 data마다 가장 가까운 centroid을 갖는 cluster로 assign

위의 loop를 다 돌면 centroid를 해당 cluster내의 point average를 통해 update

위 2과정을 반복 후 converge하면 알고리즘 종료

 

특징:

Optimum으로 convergence가 보장되어 있지 않다.

L2 distance가 아닌 distance는 더 converge가 보장 안된다.

->data의 scatter가 Sphere모양이 아닌 경우에는 clustering이 잘 되지 않는다. 

->이 때는 DBSCAN을 사용하자.(DBSCAN은 다음에 알아보자.)

NP-hard for any k >= 2

복잡도가 O(n^(dk+1)), where n:데이터 개수, d:데이터 차원, k:cluster개수

->따라서 변형인 Lloyd's algorithm을 대개 사용한다. (이는 다음에 알아보자.)

 

metric:

clustering이 얼마나 잘됐나 평가하는 데에 있어 

각 클러스터 내의 data가 해당 centroid까지의 distance,

그리고 이를 전체 data에 대해 평균내린 값을 metric으로 잡아 사용(낮을 수록 좋은)

이러한 metric을 average diameter라 한다.

 

최적의 k찾기:

average diameter가 k가 클수록 낮아지는 경향이 있다. 이 때 낮아지는 "폭이" 줄어들 때의 k를 최적의 k로 택한다.

 

 

참고자료:

en.wikipedia.org/wiki/K-means_clustering

 

k-means clustering - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Vector quantization algorithm minimizing the sum of squared deviations k-means clustering is a method of vector quantization, originally from signal processing, that aims to partition

en.wikipedia.org

www.secmem.org/blog/2019/05/17/clustering/

 

클러스터링(군집화) 개요

클러스터링(군집화) 클러스터링(군집화)은 개체들이 주어졌을 때, 개체들을 몇 개의 클러스터(부분 그룹)으로 나누는 과정을 의미합니다. 이렇게 개체들을 그룹으로 나누는 과정을 통해서, 클러

www.secmem.org

 

728x90
728x90

Faiss란,

Faiss is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also contains supporting code for evaluation and parameter tuning. Faiss is written in C++ with complete wrappers for Python/numpy. Some of the most useful algorithms are implemented on the GPU. It is developed by Facebook AI Research.

 

Faiss의 특징

즉, dense vector databases에서 query vector와 가장 유사한 vector를 뽑는 효율적인 알고리즘이다.

CPU, GPU 기반으로 작동하게 할 수 있으며,

IVF(InVerted File index)를 활용

L2 distance, Dot product(L2 normalization하면 cosine similarity도 가능)가 가능

binary vectors and compact quantization vectors(PCA, Product Quantization사용)를 활용

따라서 original vectors를 keep하지 않아 낮은 RAM으로도 billions vector database에 적용 가능

Multi-GPU 사용도 제공

Batch processing 제공

L2, inner product, L1, Linf 등의 distance 제공

query vector의 radius 내의 모든 vectors in DB를 return할 수도 있음

index(=DB)를 RAM이 아니라 DISK에 store

 

Faiss 설치

pypi.org/project/faiss-gpu/#files

에서 환경에 맞는 whl파일을 받아(file.whl)

pip3 install file.whl을 치면 된다.

 

Faiss의 tutorial을 보며 각 용어들을 정리하자.

 

Tutorial(Getting started, IndexFlatL2 사용)

 

Tutorial(Faster search, IndexIVFFlat 사용)

IndexIVFFlat이란

"Index":index객체를 만들것인데

"IVF":각 vector(word)마다 voronoi cell(document)가 무엇인지 mapping하는 quantiser를 활용할 것이고

"Flat":product quantization으로 vector를 compress하지 않고 raw vector를 활용하는

Index객체를 만들 것이다.

 

Tutorial(Faster search, PCA사용)

 

Tutorial(Faster search, Product Quantization사용)

 

 

 

실제 사용에서는 Batch + GPU 등으로 돌리니, github->wiki에서 더 많은 tutorial, basics 등을 참고하자.

 

 

참고자료:

github.com/facebookresearch/faiss

 

facebookresearch/faiss

A library for efficient similarity search and clustering of dense vectors. - facebookresearch/faiss

github.com

pypi.org/project/faiss-gpu/#files

 

faiss-gpu

A library for efficient similarity search and clustering of dense vectors.

pypi.org

github.com/facebookresearch/faiss/tree/master/tutorial/python

 

facebookresearch/faiss

A library for efficient similarity search and clustering of dense vectors. - facebookresearch/faiss

github.com

github.com/facebookresearch/faiss/wiki/Getting-started

 

facebookresearch/faiss

A library for efficient similarity search and clustering of dense vectors. - facebookresearch/faiss

github.com

github.com/facebookresearch/faiss/wiki/Faster-search

 

facebookresearch/faiss

A library for efficient similarity search and clustering of dense vectors. - facebookresearch/faiss

github.com

medium.com/dotstar/understanding-faiss-part-2-79d90b1e5388

 

Understanding FAISS : Part 2

Compression Techniques and Product Quantization on FAISS

medium.com

github.com/facebookresearch/faiss/wiki/Faiss-building-blocks:-clustering,-PCA,-quantization

 

facebookresearch/faiss

A library for efficient similarity search and clustering of dense vectors. - facebookresearch/faiss

github.com

 

728x90
728x90

set/dictionary는

hash table

hash collision을 막는 방법으로는 closed hashing(open addressing, 같은 의미인데 하나는 closed, 하나는 open...)

 

따라서, 특정 element가 set/dictionary에 존재하냐는

element의 hash값을 구하고 그 위치만 따지면 되므로 O(1)

 

참고자료:

stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented

 

How are Python's Built In Dictionaries Implemented?

Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.

stackoverflow.com

jinyes-tistory.tistory.com/10

 

[python] 자료구조 - 해시 테이블(Hash Table)

해시 테이블(Hash Table) 해쉬 테이블은 키와 밸류를 기반으로 데이터를 저장한다. 파이썬에서는 딕셔너리가 있어서 굳이 만들 필요는 없는데, 아무래도 파이썬으로 코드를 짜면 간단해서 파악하

jinyes-tistory.tistory.com

jinyes-tistory.tistory.com/11

 

[python] 자료구조 - 오픈 해싱(Open Hashing)

오픈 해싱(Open Hashing) 오픈 해싱은 해시 테이블의 충돌 문제를 해결하는 대표적인 방법중 하나로 체이닝(Separate Chaining) 기법이라고도 한다. 만약 해시 값이 중복되는 경우, 먼저 저장된 데이터에

jinyes-tistory.tistory.com

jinyes-tistory.tistory.com/12

 

[python] 자료구조 - 클로즈 해싱(Close hashing) / Open Addressing

클로즈 해싱(Close Hashing) 클로즈 해싱은 해시 테이블의 충돌 문제를 해결하는 방법 중 하나로 Linear Probing, Open Addressing 이라고 부르기도 한다. 구조는 간단하다. 위 이미지에서 John Smith와 Sandra D..

jinyes-tistory.tistory.com

 

728x90

'CS' 카테고리의 다른 글

[Python]List comprehension에서 if else 쓰기  (0) 2020.10.30
(미완)Faiss, Facebook AI Similarity Search  (0) 2020.10.29
(미완)[Elasticsearch]특징  (0) 2020.10.29
Inverted index 이해하기  (0) 2020.10.29
(미완)[Docker] option 정리  (0) 2020.10.21
728x90

-Full text search가 가능

->이 말은 토큰 analyer같은게 내장디ㅗ어 있다는 것, document사이 relevancy를 측정할 measure가 있다는 것

->inverted index 사용

구체적으로는 참고자료 inverted index이해하기 참고

요약하면,

row는 field1(term11,term12,...)field2(term21,term22,...),...

column은 document로 document에 대해

term(in each field)의

doc freq(term을 포함하는 document개수),

position(term이 doc내에서 몇번째 token인지)

term freq(term이 각 doc마다 몇번 나타나는가),

offset(term이 doc내에서 몇번째 위치에서 시작하고 끝나는지)

정보를 분석하여 저장해둔다는 것이 핵심

이에 ES는 Standard Analyzer라는 Tokenization기능이 내장되어 있다.

->따라서 NRT(Near Real Time)검색이 가능

 

-Platform-indenpendent

->RESTful API를 사용하기 때문에

 

-같은 field명이면 다룬 index에 속하는 document도 한번에 조회가 가능하다.

->검색 특화

 

다중 Shard의 존재로 병렬처리가 가능

->Scalibility가 존재

 

단점으로는

-롤백, 트랜잭션 기능이 제공되지 않음(트랜잭션 기능이란게 뭐지?)

-Real Time은 불가능, NRT만 가능, 이는 indexed data는 내부적인 commit/flush같은 과정을 거치기 때문(commit/flush가 뭐지?)

 

참고자료:

medium.com/@AIMDekTech/what-is-elasticsearch-why-elasticsearch-advantages-of-elasticsearch-47b81b549f4d

 

What is ElasticSearch? Why ElasticSearch? Advantages of ElasticSearch!

What is Elasticsearch?

medium.com

cloudingdata.tistory.com/45

 

Inverted Index 이해하기

들어가며 Elasticsearch를 사용하는데에 있어서 가장 핵심이 되는 개념인 Inverted Index를 정리해본다. 또한, Inverted Index를 알아야 Elasticsearch를 용도에 맞게 사용할 수 있다고 생각한다. 따라서, Inverte..

cloudingdata.tistory.com

deviscreen.tistory.com/17

 

Elasitcsearch 기본

유사도 검색 텍스트 분석의 기초 텍스트 데이터 분석으 숫자, 날짜, 시간과 같은 다른 타입의 데이터 분석과는 다르다. 문자열 타입으로 지정하거나 종종 해당 필드에 정확히 일치하는 쿼리를

deviscreen.tistory.com

velog.io/@jakeseo_me/%EC%97%98%EB%9D%BC%EC%8A%A4%ED%8B%B1%EC%84%9C%EC%B9%98-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0-2-DB%EB%A7%8C-%EC%9E%88%EC%9C%BC%EB%A9%B4-%EB%90%98%EB%8A%94%EB%8D%B0-%EC%99%9C-%EA%B5%B3%EC%9D%B4-%EA%B2%80%EC%83%89%EC%97%94%EC%A7%84

 

[엘라스틱서치 알아보기 #2] DB만 있으면 되는데, 왜 굳이 검색엔진?

엘라스틱서치 알아보기 프로젝트는 엘라스틱서치 실무가이드의 목차와 내용을 참조하였습니다. 이 포스트를 읽는 분들이라면 엘라스틱서치 실무가이드 책을 한권 반드시 구매하는 것을 권장

velog.io

 

728x90

+ Recent posts