Machine learning and optimization-based approaches to duality in statistical physics