Learning Factor Graphs in Polynomial Time & Sample Complexity