【问题标题】:PyTorch loss function referencing model parametersPyTorch 损失函数引用模型参数
【发布时间】:2020-01-29 20:49:39
【问题描述】:

对于一个作业,我需要创建一个使用提供的损失函数的电影推荐系统:

sum(????i=1,M) ????sum(j=1,M) indicator[i̸=j](viT vj − Xi,j )**2

这意味着,两个电影嵌入之间的点积 Vi 和 Vj 应该非常接近 Xi,j。其中 Xi,j 是同时喜欢电影 i 和电影 j 的用户的总和。指标函数省略了 i == j 的条目,(设置为 0。)

分配可交付成果是来自隐藏层的权重矩阵。它的尺寸应该是 9724x300,其中有 9724 个唯一的电影 ID,以及 300 个神经元。 300 是任意选择,受 Google 的 word2vec 中使用 300 个神经元的影响。

我有什么:

  • source_data:行是用户,列是电影。给定单元格中的 1 表示相应的用户喜欢相应的电影(不喜欢 = 0。)
  • preprocessed_data:source_data 自身转置的矩阵乘法。 (即每个单元格都是喜欢电影 i 和 j 的用户的总和。对角线条目对我没有用,因为它们只是喜欢一部电影的用户的总和。)

我被困在哪里:

  • 不知道如何根据 i 和 j 定义我自己的损失函数,它可以将 preprocessed_data 中喜欢电影 i 和 j 的用户的总和与隐藏层权重张量中的行 i 和 j 进行比较。
  • 不确定如何将我的数据组织成 X 和 y 张量,以使数据适合损失函数。

【问题讨论】:

    标签: pytorch loss-function recommender-systems


    【解决方案1】:

    在您进一步阅读之前,请注意,在您的作业中从 StackOverflow 寻求和接受直接帮助可能违反您学校的规则,并会给您作为学生带来后果!

    话虽如此,我对这个问题的建模方式如下:

    import torch
    
    U = 300 # number of users
    M = 30  # number of movies
    D = 4   # dimension of embedding vectors
    
    source = torch.randint(0, 2, (U, M)) # users' ratings
    X = source.transpose(0, 1) @ source  # your `preprocessed_data`
    
    # initial values for your embedding. This is what your algorithm needs to learn
    v = torch.randn(M, D, requires_grad=True)
    X = X.to(torch.float32) # necessary to be in line with `v`
    
    # this is the `(viT vj − Xi,j )**2` part
    loss_elementwise = (v @ v.transpose(0, 1) - X).pow(2)
    
    # now we need to get rid of the diagonal. Notice that we can equally
    # well get rid of the diagonal and the whole upper triangular part,
    # as well, since both V @ V.T and source.T @ source are symmetric, so
    # the upper triangular part contains just
    # a mirror reflection of the lower triangular part.
    # This means that we actually implement a bit different summation:
    # sum(i=1,M) sum(j=1,i-1) stuff(i, j)
    # instead of
    # sum(i=1,M) sum(j=1,M) indicator[i̸=j] stuff(i, j)
    # and get exactly half the original value
    masked = torch.tril(loss_elementwise, -1)
    
    # finally we sum it up, multiplying by 2 to make up
    # for the "lost" upper triangular part
    loss = 2 * masked.sum()
    

    现在留给您实现的是优化循环,它将使用loss 的梯度来优化v 的值。

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 2022-01-15
      • 2019-07-12
      • 2019-05-27
      • 2021-10-05
      • 2021-07-30
      • 2021-11-13
      • 2019-03-12
      • 2021-02-20
      相关资源
      最近更新 更多