As a ubiquitous aspect of modern information technology, data compression has a wide range of applications. Therefore, a quantum autoencoder which can compress quantum information into a low-dimensional space is fundamentally important to achieve automatic data compression in the field of quantum information. Such a quantum autoencoder can be implemented through training the parameters of a quantum device using classical optimization algorithms. In this article, we analyze the condition of achieving a perfect quantum autoencoder and theoretically prove that a quantum autoencoder can losslessly compress high-dimensional quantum information into a low-dimensional space (also called latent space) if the number of maximum linearly independent vectors from input states is no more than the dimension of the latent space. Also, we experimentally realize a universal two-qubit unitary gate and design a quantum autoencoder device by applying machine learning method. Experimental results demonstrate that our quantum autoencoder is able to compress two two-qubit states into two one-qubit states. Besides compressing quantum information, the quantum autoencoder is used to experimentally discriminate two groups of nonorthogonal states.