我试图在Python中实现Adagrad。出于学习目的,我使用矩阵分解作为示例。我正在使用Autograd来计算渐变。
我的主要问题是实施是否正常。
注意:我非常清楚基于ALS的实现非常适合。我仅将Adagrad用于学习目的
import autograd.numpy as np
import pandas as pd
A = np.array([[3, 4, 5, 2],
[4, 4, 3, 3],
[5, 5, 4, 3]], dtype=np.float32).T
A[0, 0] = np.NAN
def cost(W, H):
pred = np.dot(W, H)
mask = ~np.isnan(A)
return np.sqrt(((pred - A)[mask].flatten() ** 2).mean(axis=None))
rank = 2
learning_rate=0.01
n_steps = 10000
from autograd import grad, multigrad
grad_cost= multigrad(cost, argnums=[0,1])
shape = A.shape
# Initialising W and H
H = np.abs(np.random.randn(rank, shape[1]))
W = np.abs(np.random.randn(shape[0], rank))
# gt_w and gt_h contain accumulation of sum of gradients
gt_w = np.zeros_like(W)
gt_h = np.zeros_like(H)
# stability factor
eps = 1e-8
print "Iteration, Cost"
for i in range(n_steps):
if i%1000==0:
print "*"*20
print i,",", cost(W, H)
# computing grad. wrt W and H
del_W, del_H = grad_cost(W, H)
# Adding square of gradient
gt_w+= np.square(del_W)
gt_h+= np.square(del_H)
# modified learning rate
mod_learning_rate_W = np.divide(learning_rate, np.sqrt(gt_w+eps))
mod_learning_rate_H = np.divide(learning_rate, np.sqrt(gt_h+eps))
W = W-del_W*mod_learning_rate_W
H = H-del_H*mod_learning_rate_H
当问题收敛并且我得到一个合理的解决方案时,我想知道实现是否正确。具体来说,如果理解梯度之和然后计算自适应学习率是否正确?
答案 0 :(得分:3)
粗略地看一下,您的代码与https://github.com/benbo/adagrad/blob/master/adagrad.py
上的代码非常匹配del_W, del_H = grad_cost(W, H)
匹配
grad=f_grad(w,sd,*args)
gt_w+= np.square(del_W) gt_h+= np.square(del_H)
匹配
gti+=grad**2
mod_learning_rate_W = np.divide(learning_rate, np.sqrt(gt_w+eps)) mod_learning_rate_H = np.divide(learning_rate, np.sqrt(gt_h+eps))
匹配
adjusted_grad = grad / (fudge_factor + np.sqrt(gti))
W = W-del_W*mod_learning_rate_W H = H-del_H*mod_learning_rate_H
匹配
w = w - stepsize*adjusted_grad
因此,假设adagrad.py
正确并且翻译正确,则会使您的代码正确无误。 (共识并不能证明你的代码是正确的,但它可能是一个提示)