def grad_check_sparse(f, x, analytic_grad, num_checks):
    '''
    sample a few random elements and only return numerical
    in this dimensions.
    '''
    h = 1e-5

    x.shape
    for i in xrange(num_checks):
        ix = tuple([randrange(m) for m in x.shape])

        oldval = x[ix]
        x[ix] = oldval + h  # increment by h
        fxph = f(x)  # evaluate f(x + h)
        x[ix] = oldval - h  # increment by h
        fxmh = f(x)  # evaluate f(x - h)
        x[ix] = oldval  # reset

        grad_numerical = (fxph - fxmh) / (2 * h)
        grad_analytic = analytic_grad[ix]
        rel_error = abs(grad_numerical - grad_analytic) / \
            (abs(grad_numerical) + abs(grad_analytic))
        print 'numerical: %f analytic: %f, relative error: %e' % (grad_numerical, grad_analytic, rel_error)
dataset/ETHPy150Open dnlcrl/PyFunt/pyfunt/utils/gradient_check.py/grad_check_sparse/original