With the increasing number of end users using electricity in modern cities, smart grids have some critical problems for energy efficiency and managing renewable energy resources. Therefore, electricity load forecasting is an important strategy to avoid power disconnection and power communication damages in smart grids. On the other hand, the Internet of Things (IoT) devices can collect appropriate data from end users with smart metering. In addition, smart devices can check and gather critical data from power stations using smart sensors and actuators to provide the Quality of Service (QoS) factors and energy efficiency of electricity transmission in the smart girds. Due to the huge data transmission, machine learning is useful for evaluating electricity load forecasting and power stability in smart grids. For detecting electric load forecasting and energy consumption factors, this paper develops Bayesian Optimization for K-nearest neighbor (BOKNN) with the hyper-parameters function to detect the electricity load forecasting and estimated power consumption factors in smart grids. The proposed technique optimizes the performance of electricity load forecasting and enhances the structure of the machine learning efficiency with high model accuracy. Two real-data sets as our case studies for Short-Term Electricity Load Forecasting are applied to evaluate the proposed BOKNN as existing experimental testbeds. The simulation results illustrate that the proposed BOKNN provides optimized high accuracy with 88.33% and 98.13% correlation coefficient and minimum Mean Absolute Error (MAE) with 0.04% for existing datasets. The experimental results show that the suggested BOKNN model greatly outperforms the state-of-the-art prediction algorithms.