15 Lines of Code to Teach AI to Turn Lights On and Off: A Smart Energy-Saving Butler with Neural Networks
No rules, no if-else, just “trial and error + reward” — let AI learn to intelligently control lighting. This is the magic of Reinforcement Learning!
Problem: When Should the Light Be On?
Is your home light still manually operated? Or using a simple “someone’s there, turn on; no one’s there, turn off” logic?
Reality is more complex:
- Daytime, someone’s present, but plenty of sunlight → no need for lights, save power!
- Late night, someone’s present, room is dark → must turn on lights, prioritize experience!
- No one around → lights on is wasteful!
Can the system learn to make optimal decisions in various situations?
The answer is yes! Using reinforcement learning + neural networks.
Our Goal: Train a “Smart Lighting AI”
It needs to understand three pieces of information (State):
- Whether someone is present (infrared sensor)
- Current light level (photoresistor)
- What time it is (system clock)
Then decide on an Action:
- Turn light on (1)
- Turn light off (0)
Its “teacher” uses only one number — Reward — to tell it: “You did well, +1 point!” or “Wasted electricity, -0.3 points!”
Over time, the AI learns a strategy that’s both energy-efficient and considerate.
Core Idea: Neural Networks Instead of Hand-coded Rules
Traditional approach: write lots of if-else
RL approach: Let the neural network learn the “thresholds” and “logic” itself!
Input state → Neural network → Output each action’s “expected value” (Q-value) → Choose the highest-value action
This is the essence of Deep Q-Network (DQN).
Minimal Code Demo (20 Core Lines)
No labels, no supervision, only reward signals for self-evolution!
What the AI Learned After Training
Test scenarios:
| Scenario | AI Decision |
|———-|————-|
| Late night (3 AM), someone present, dark room | ✅ Turn on |
| Noon (12 PM), someone present, plenty of sun | ✅ Turn off (saves power!) |
| Night (10 PM), no one present | ✅ Turn off |
| Evening (6 PM), someone present, dim light | ✅ Turn on |
Comments