The Internet of Things (IoT) has become more prevalent in recent years, generating a huge amount of data from several interconnected devices. These datasets frequently experience severe class imbalance, where certain classes are significantly underrepresented compared to others, resulting in biased machine learning (ML) models. Addressing the class imbalance in IoT datasets is critical for achieving accurate and reliable predictions. In this paper, we propose a novel approach for handling imbalanced IoT datasets using Optimized Generative Adversarial Networks (OGAN). The proposed approach relies on the powerful capabilities of GANs to generate synthetic data for minority classes and balance the dataset, resulting in enhanced model performance. The approach involves using a GAN to generate synthetic data for the minority class, thereby balancing the dataset. This balanced dataset is then used to test the performance of four different machine learning models. The entire process is optimized using Optuna, which maximizes performance by testing various hyperparameters of the GAN. This approach ensures that the models are trained on a more representative dataset, potentially improving their accuracy and robustness. We demonstrate the efficacy of our method by performing extensive experiments on real-world IoT datasets and comparing them with existing methods for imbalanced data handling. The results reveal that our optimized GAN-based approach outperforms previous methods with an accuracy of 99% for all models and effectively handles the class imbalance problem in IoT datasets.