728x90
728x90
728x90

참고자료가 너무나 잘 정리되어있다.

 

핵심은

document2word방식(이를 forward index)의 index를 뒤집어서 word2document(Inverted index)로 저장한다는 것

document를 database에 추가할 때 추가 cost가 들더라도, full text search때 fast하게 하겠다는 것이 목적

inverted file은 word마다 document만 mapping

inverted list은 word마다 document + position정보까지 mapping, 따라서 document를 insert할 때 더 cost가 들긴 하지만 강력한 검색엔진이 됨

 

참고자료:

cloudingdata.tistory.com/45

 

Inverted Index 이해하기

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

cloudingdata.tistory.com

en.wikipedia.org/wiki/Inverted_index

 

Inverted index - Wikipedia

In computer science, an inverted index (also referred to as a postings file or inverted file) is a database index storing a mapping from content, such as words or numbers, to its locations in a table, or in a document or a set of documents (named in contra

en.wikipedia.org

 

728x90
728x90

RMSE(Root Mean Squared Error)로 Rating prediction 성능을 평가하는 것은

실제로 추천 시스템의 역량을 평가하는 것인지 다시 한번 생각해볼 필요가 있다.

 

우리는 Top-N recommendation을 통해 좀 더 user-focused metric을 가질 필요가 있다.

내가 사용자로서 추천 시스템이 내가 어떤 영화를 rating을 얼마나 줄 지 알아맞춰주기 보다는

내가 필요로 하는 상품이 상단에 나와주면 되는 것이다.

 

따라서 다양한 평가 지표 중에 RMSE에 너무 집중하지 말자.

특히, paper에서는 RMSE가지고 성능이 좋아졌니 마니 하는데, 이것에 너무 집중하지 말자는 것이다.

 

실제로 DB에 추천 결과를 적재할 때, 모든 유저에 모든 상품의 predicted rating을 적재하려고 하지 말자.

굉장히 비효율적일 뿐더러, 유저는 그러한 rating맞추기엔 관심없을 테니 말이다.

 

728x90
728x90

Candidate Generation -> Scoring(Hybrid) -> Ranking -> Filtering

 

Candidate Generation,

여기에서는 개별 모델들을 학습한다.

 

Scoring,

여기에서는 개별 모델을 취합하는 Hybrid Recommendation을 설계한다.

 

Ranking,

단순히 item을 score에 따라 sorting하기 보다는, ranking을 다시 매기는 작업을 한다.

예를 들면, 자주 등장, 인기 상품, 평점 높은 상품 등을 상단에 배치하는 로직을 적용한다.

 

Filtering,

기 구매한 상품을 제거, 유해한 상품을 제거, score가 낮은 상품은 제거 등의 Filtering을 거친다.

Filtering을 거치고 나서야 Top-"N" recommendation을 얻는다.

728x90
728x90

Missing data에도 분류가 있다.

 

MCAR(Missing Completely At Random), 특정 column(c_k)의 결측 여부가 완전히 random으로 발생하는 경우, 즉 c_k가 다른 c_1, c_2, ...와는 관련이 없을 때를 가리킴

 

MAR(Missing At Random), 특정 c_k의 결측 여부가 다른 c_1, c_2, ... 중 몇몇과 관련이 있는 경우

예를 들면, 소득수준(=c_1)에 따라 학업성취도(=c_k)의 결측 여부가 관련이 있을 경우

 

MNAR(Missing Not At Random, non ignorable), 특정 c_k의 결측 여부가 c_k의 값과 관련이 있는 경우

예를 들면, 학업성취도가 낮은 학생들이 학업성취도에 응답하지 않는 경우

 

 

 

 

Missing data 처리 테크닉

(1) Listwise deletion

변수에 적어도 하나의 결측치라도 존재하면 해당 instance를 제거하는 방식

MCAR일 때만 가능함

sample의 개수가 줄어든다는 단점이 존재

 

(2) Pairwise deletion

특정 분석에서 사용되는 변수에만 결측치가 존재하는 instance를 제거하는 방식

MCAR일 때만 가능함

sample의 개수가 줄긴하지만 listwise보단 덜 줄어듦

 

(3) Mean imputation

전체점수의 평균값으로 결측치를 대체해버리는 방식

MAR일 때 baised된 값이 나오게 됨

 

728x90
728x90

확률변수 X가 discrete일 때

the likelihood function given the outcome x of the random variable X는 P_theta(X=x)

 

확률변수 X가 continuous일 때

the likelihood function given the outcome x of the random variable X는 f_theta(x), where f is the pdf of X

 

설명:

(1) 

Discrete variable에 대해서는 probability를 가리킨다.

Continuous variable에 대해서는 pdf를 가리킨다.

 

(2)

Parameter가 주어졌을 때 evidence가 일어날 확률을 likelihood라 한다. 즉, P(E|H)

이 때 parameter를 변수로 취급하면 특별히 이 확률을 likelihood function이라 한다.

 

(3)

MLE(Maximum Likelihood Estimation)이란,

P(E|H)가 최대가 되게하는 parameter H_0을 택하는 방식이다.

즉, theta_0 = argmax over theta P(E|theta)

 

(4) 

MAP(Maximum A Posterior)란,

parameter의 prior distribution(g(theta))가 존재하여

P(E|theta)*g(theta)가 최대가 되게하는 parameter H_0을 택하는 방식이다.

즉, theta_0 = argmax over theta P(E|theta)*g(theta)

 

728x90
728x90

상황:

a:numpy.ndarray, 2-dimensional, 

a의 각 row마다 k개의 top values뽑기

 

ex)

a=np.random.randint(0,10,(4,5))  # 0에서 9까지 values중 random integers뽑아서 shape이 (4,5)인 것

k=3

res = a[np.arange(len(a))[:, None], np.argsort(a)[:, -k:]][:, ::-1]

 

설명:

(1)

np.argsort는 ascending order로 indices를 뽑아냄

 

(2)

the smallest top k를 구하려면 np.argsort(a)[:, :k], 그리고 뒤에 [:, ::-1] 없어야함

 

(3) 

만약 the top k largest/smallest values 를 ordering없이 뽑으려면

np.argsort보다 np.partition이 낫다. 왜냐하면 np.argsort는 sorting(O(n*log(n))을 하지만 후자는 sorting하지 않음(O(n))

즉, 

res = np.partition(a, -k)[:, -k:] 하면은 top k values(not ordered)를 얻을 수 있다.

 

(4)

the top k largest/smallest values의 indices를 ordering없이 뽑으려면

np.partition말고 np.argpartition을 활용하면 된다.

즉,

res = np.argparition(a, -k)[:, -k:]

 

(5)

a에 negation붙여서 하진 말 것, 그러면 new object를 만들어서 하기 때문에 memory 더 쓰게 됨

 

참고자료:

kanoki.org/2020/01/14/find-k-smallest-and-largest-values-and-its-indices-in-a-numpy-array/

 

Find K smallest and largest values and its indices in a numpy array

To find the maximum and minimum value in an array you can use numpy argmax and argmin function

kanoki.org

 

728x90
728x90

상황:

a = np.arange(20).reshape(4,5)

b = np.array([[0,1],[1,2],[2,3],[3,4]])

a의 first row에서는 [0,1]에 해당하는 entries를

a의 second row에서는 [1,2]에 해당하는 entries를

a의 third row에서는 [2,3]에 해당하는 entries를

a의 fourth row에서는 [3,4]에 해당하는 entries를 

가져오고 싶다.

 

res = a[np.arange(4)[:, None], b]

 

설명 

(1)

numpy.ndarray에 [:, None]을 하면 길이가 1인 axis를 하나 더 생성한다.

예를 들면

q = np.arange(10)  # shape은 (10,)

w = q[:, None]  # shape은 (10,1)

e = q[:, None]  # shape은 (10, 1, 1)

 

reshape(-1,1)과 비슷해보이지만

w = q.reshape(-1,1)  # (10,1)

e = w.reshape(-1,1)  # (10,1), 즉 w와 shape이 같음

 

(2)

a의 third row 빼고 가져오고 싶다면

ind = np.array([0,1,3])

res = a[ind[:,None], b[ind]]

 

(3)

a의 first, third빼고 모두 가져오고 싶다면

ind = np.array([x for x in range(len(a)) if x not in [0,2]])

res = a[ind[:,None], b[ind]]

 

728x90
728x90

상황:

arr는 2d numpy.ndarray

dict_는 dictionary, arr의 각 원소를 변환시킬 mapping

 

1.

res = np.vectorize(dict_.__getitem__)(arr)

np.vectorize는 내부적으로는 결국 python loop방식으로 돌기 때문에 numpy의 C base speedup 이점을 얻기 힘들다.

 

2.

u, inv = np.unique(arr, return_inverse=True)

res = np.array([dict_[x] for x in u])[inv].reshape(a.shape)

이는 [inv]와 reshape에서 numpy의 speedup이점을 얻을 수가 있다.

 

3. 만약 dict_의 key에 arr에 특정 원소만 존재한다면?

 

(1) arr의 일부 원소는 변환하고, 일부는 default값으로 바꿔 넣고 싶다면

u, inv = np.unique(arr, return_inverse=True)

res = np.array([dict_.get(x, "DEFAULT") for x in u])[inv].reshape(a.shape)

이렇게 dict_의 get method로 변환하고, missing key에 대해선 default 입력 가능

 

(2) arr의 일부 원소는 변환하고, 일부는 원래 그대로 두고 싶다면

u, inv = np.unique(arr, return_inverse=True)

res = np.array([dict_.get(x, x) for x in u])[inv].reshape(a.shape)

이렇게 dict_의 get method로 변환하고, missing key에 대해선 원본 그대로 입력 가능

728x90
728x90

dataframe에서 특정 column에 duplicates가 존재하면 지우는 것은 drop_duplicates를 활용한다.

 

중복인 것만 살리고 싶다면?

즉, 특정 column에서 한번만 등장한 것을 지우고, 다중 등장인 row만 살리고 싶다면

 

df = df[df."COLUMN".duplicated(keep=False)]

or

df = df[df.duplicated(['COLUMN'], keep=False)

를 사용하자. (후자는 multiple columns에도 활용 가능)

 

중복 여부 확인은 duplicated()

중복값 처리는 drop_duplicated()

 

keep에 'first', 'last', False가 가능

'first'는 중복이 있으면 첫 등장하는 것은 True, 이후는 False

'last'는 중복이 있으면 마지막 등장하는 것은 True, 이전은 False

False는 중복이 있으면 처음이든 끝이든 모두 True

728x90
728x90

itertuples가 iterrows보다 빠르다

 

itertuples에 들어갈 수 있는 argument로는

-index, default는 True이고 True이면 first element에 index가 포함된다. False면 index가 포함되지 않는다.

-name, default는 Pandas이며 반출하는 namedtuple의 이름을 가리킨다. 만약 name=None을 사용하면 namedtuple이 아니라 tuple을 반출한다.

-column의 개수가 255 이상이면 무조건 tuple을 반출한다. 따라서 itertuples를 활용한 함수를 정의시, 입력받은 dataframe의 column개수가 255이상인지 아닌지에 따라 구분해서 작성이 필요하다.

728x90

+ Recent posts