我想使用 PyTorch 实现非负矩阵分解。这是我最初的实现:
def nmf(X, k, lr, epochs):
# X: input matrix of size (m, n)
# k: number of latent factors
# lr: learning rate
# epochs: number of training epochs
m, n = X.shape
W = torch.rand(m, k, requires_grad=True) # initialize W randomly
H = torch.rand(k, n, requires_grad=True) # initialize H randomly
# training loop
for i in range(epochs):
# compute reconstruction error
loss = torch.norm(X - torch.matmul(W, H), p='fro')
# compute gradients
loss.backward()
# update parameters using …
Run Code Online (Sandbox Code Playgroud) matrix mathematical-optimization gradient-descent pytorch autograd