추천) Latent Matrix Factorization - 기본 컨셉 이해

2021. 7. 18. 12:38관심있는 주제/Recommendation

728x90

목차

     

    참고: 추천 시스템의 기본 개념, 추천 시스템의 유형, 경사로 강하, 선형 회귀, 매트릭스 인수화 등과 같은 ML의 기본 개념에 익숙하다고 가정합니다.

     

    2009년 9월 21일, Netflix Competition은 사용자나 영화에 대한 다른 정보 없이 이전 등급을 기준으로 영화에 대한 사용자의 등급을 예측하는 최고의 협업 필터링 알고리즘을 찾기 위해 조직되었습니다.

    Bell Kor의 Practical Chaos가 이 대회에서 우승하여 백만 달러를 받았다.

    그들이 생각해낸 접근법은 잠재 매트릭스 인수분해법(Latent Matrix Factorization)이었습니다.

     

    본 글에서는 Latent Matrix Factorzation에 대한 개념을 이해해보고자 합니다.

     

    Latent Matrix Factorization

    Matrix factorization algorithm works by decomposing the user-item interaction matrix into the product of two lower dimensionality rectangular matrices.

    즉) user-item matrix를 2개의 저차원 메트릭스로 분해하는 방식으로 작동합니다.

     

    USER-ITEM interaction Matrix란?

    User-item interaction matrix란 n(users) by m(items)으로 이루어진 메트릭스이며, 유저들의 아이템에 대한 점수를 등록해 놓은 것이라고 볼 수 있습니다. 

    (i,j)의 의미는 "user i 의 item j에 대한 rating" 입니다.

    Latent Factor란 무엇인지?

     

    Latent factors는 기본적으로 item과 user의 hidden feature입니다.

     

    5점 척도에서 Benjamin은 Action과 Comedy를 동등하게 좋아하는 경향이 있으므로 각각 3과 3입니다.(왼쪽 그림)

    반면 Richard는 Action보다 Comedy를 더 좋아하는 경향이 있으므로 Action은 3개, Comedy는 4개입니다.

     

    그래서 각 객체에 관한 이러한 특징 측정한 것을 잠재 요인(latent factor)라고 부릅니다.

     

    이 알고리즘은 Latent Factor를 사람이 알아야 하는 것이 아니라 기계가 알아내게 하려고 합니다.

    기계는 기본적으로 잠재 요인의 크기를 확인하여, USER와 ITEM을 모두 암시하고 일부 값을 임의로 지정합니다.

    그리고 데이터를 학습하여 USER 및 ITEM에 대한 잠재 인자를 얻습니다.

    예측된 등급(RATING)이 미리 정의된 등급에 근접할 수 있도록 기계가 이를 수행해야 합니다.

     

    How does Latent Matrix Factorization work?

    User-Item interaction matrix(R)이 X 및 Y 행렬로 분해됩니다. 'Matrix X'는 총 사용자 수와 동일한 행을 포함하지만, 열의 크기는 프로그래머에 의해 결정되며 열은 잠재 요인를 참조한다.

    반면에 행렬 Y에서 열의 수는 ITEM 수와 같고 행의 수는 잠재 요인의 크기와 같습니다.

     

    초기에는 USER(X)와 ITEM(Y)에 임의의 값을 할당하고 훈련을 시킵니다.

    잠재 인자는 User-Matrix(X) 및 Item-Matrix(Y)의 제품이 User-Item Interaction Matrix와 동등한 자극을 제공하도록 결정해야 한다.

     

    우리의 문제는 Latent Factor를 잘 만들어서 기존 user matrix를 잘 매칠 할 수 있게 학습시켜야 합니다.

     

     

    What optimization technique does Latent Matrix factorization use?

    여기서 사용하는 최적화 기술인 Gradient Descent입니다. 

    Gradient descent is an optimization algorithm used to minimize some function by iteratively moving in the direction of steepest descent as defined by the negative of the gradient. In machine learning, we use gradient descent to update the parameters of our model.

     

    Pytorch Implementation 

    class MatrixFactorization(torch.nn.Module):
        def __init__(self, n_users, n_items, n_factors=20):
            super().__init__()
            self.user_factors = torch.nn.Embedding(n_users, n_factors, sparse=True)
            self.item_factors = torch.nn.Embedding(n_items, n_factors, sparse=True)
    
        def forward(self, user, item):
            return (self.user_factors(user) * self.item_factors(item)).sum(1)
            
    model = MatrixFactorization(n_users, n_items, n_factors=20)
    loss_func = torch.nn.MSELoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=1e-6)
    
    # Sort our data
    rows, cols = ratings.nonzero()
    p = np.random.permutation(len(rows))
    rows, cols = rows[p], cols[p]
    
    for row, col in zip(*(rows, cols)):
        # Set gradients to zero
        optimizer.zero_grad()
        
        # Turn data into tensors
        rating = torch.FloatTensor([ratings[row, col]])
        row = torch.LongTensor([row])
        col = torch.LongTensor([col])
    
        # Predict and calculate loss
        prediction = model(row, col)
        loss = loss_func(prediction, rating)
    
        # Backpropagate
        loss.backward()
    
        # Update the parameters
        optimizer.step()

     

    참고

    content link
    concept https://medium.com/swlh/latent-matrix-factorization-6fa1cd0b2e5f
      https://towardsdatascience.com/introduction-to-latent-matrix-factorization-recommender-systems-8dfc63b94875
    한국어 자료 https://bluehorn07.github.io/computer_science/2021/04/08/latent-matrix-factorization.html
    Probabalistic Matrix Factorization(2년전) https://www.kaggle.com/robottums/probabalistic-matrix-factorization-with-suprise
    Movie Recommendation System(실습코드) https://developers.google.com/machine-learning/recommendation/labs/movie-rec-programming-exercise
    google collaborative 설명 https://developers.google.com/machine-learning/recommendation/collaborative/summary
    728x90