A Generalized Loop Correction Method for Approximate Inference in Graphical Models