Communication in cyber-physical systems relies heavily on Wireless Sensor Networks (WSNs), which have numerous uses including ambient monitoring, object recognition, and data transmission. However, they are vulnerable to cyberattacks because they are connected to the IoT. In order to combat the difficulties associated with WSN intrusion detection, this research employs machine learning techniques, notably the Gaussian Nave Bayes (GNB) and Stochastic Gradient Descent (SGD) algorithms. The effectiveness of recommendation systems is improved with the introduction of context awareness. To lessen the burden on the computer, we first do a principal component analysis and singular value decomposition on the raw traffic data. The system was tested on two datasets, yielding extremely high accuracy results. This is evidence of the system's strength, even when the dataset is changed. On the WSN-DS dataset, the suggested SG-IDS model achieved a 96% accuracy rate, outperforming state-of-the-art algorithms with higher rates of 98% accuracy, 96% recall, and 97% F1-measurement. In an evaluation on an IoMT dataset, the SG-IDS performed admirably, with an accuracy of 0.87 and a precision of 1.00 in intrusion detection tasks.