Decoding astronomical spectra using machine learning