Learning to act
In Week 1, an engineer wrote the rule of the thermostat. Reinforcement learning lets an agent find the rule itself. At every step the agent observes a state, chooses an action and receives a reward and a new state; its goal is a policy that maximises the expected sum of discounted future rewards [1]. The formal model is a Markov decision process: The next state depends only on the current state and action. The discount factor gamma, between 0 and 1, sets how far the agent looks ahead. Unlike supervised learning, nobody tells the agent the correct action; it must explore to find out which actions pay off, and exploit what it has learned to collect reward.
The value of taking action a in state s and acting well afterwards is Q(s, a). Q-learning improves an estimate of Q after every step with Q(s, a) = Q(s, a) + alpha (r + gamma max Q(s', a') - Q(s, a)), where alpha is a learning rate and the maximum runs over the actions in the next state; Watkins and Dayan proved that it converges to the optimal values under suitable conditions [2]. An epsilon-greedy policy explores with a random action with probability epsilon and exploits the best known action otherwise. Tables work for small discrete problems; for large or continuous state spaces, a neural network approximates Q, as in the deep Q-network that learned to play Atari games from pixels [3].
Animation: Q-learning on a cliff walk
The agent starts at the lower left and must reach the lower right without stepping into the cliff, which costs heavily. Each step costs a little. Watch the arrows of the greedy policy and the colours of the state values change as episodes accumulate. Raise epsilon to explore more.
Check your understanding. Q(s, a) = 2.0, the reward is -1, gamma = 0.9, the best Q-value in the next state is 3.0 and alpha = 0.5. What is the updated Q(s, a)?
Formulas: Returns, values and the Bellman equations
A Markov decision process consists of states , actions , transition probabilities of the next state , rewards and a discount factor with [1]. From the time on, the agent collects the rewards , and its return is their discounted sum:
The reward counts with the weight . A constant reward in every step is worth , the sum of a geometric series, so with a reward of 1 per step is worth 10, and acts as the horizon of the agent.
A policy chooses the actions. The value of a state is the expected return of an agent that starts there and follows , and the action value adds a first action :
The best possible values satisfy the Bellman optimality equations: The value of a state is the best action value, and an action value is the expected sum of the reward and the discounted value of the next state [1]:
Value iteration starts from and turns these equations into an update that is repeated for all states, one sweep after another:
Each sweep shrinks the largest error of the values at least by the factor , so the values converge, and the greedy policy, which picks an action with the largest action value, becomes optimal.
Q-learning learns action values from experience, without knowing the transition probabilities [2]. After each transition from with the action to with the reward , the estimate moves by the learning rate towards the target :
The difference is the temporal-difference error. An -greedy policy with actions chooses a random action with the probability , so the greedy action has the probability and every other action .
Worked example: The return of a maintenance history
A pump is inspected at the start of every week and is good (G), worn (W) or failed (F). The engineer can continue (c) or service (s). Continuing earns 10 units of production with a good pump, 6 with a worn pump and nothing with a failed one. Servicing costs 2, 4 or 20 units in the three states and returns the pump to G for the next week. A good pump wears within a week with the probability 0.3, and a worn pump fails with the probability 0.4.
In one history, the engineer continued three times and then serviced the worn pump, with the rewards 10, 10, 6 and −4. With the weights are , , and :
The service at the end lowers the return of this history, but it restores the production of later weeks, which a return of four weeks does not see. The values of the next example weigh all future weeks.
Worked example: Value iteration for pump maintenance
Step 1. The first sweep. With in every state, every action value equals its reward, and the larger one is the new value:
Step 2. The second sweep. The action values weigh the values of the possible next states with their probabilities:
Servicing and continuing with a failed pump lead to a single next state, and the value of a state is its larger action value:
| State | Continue, | Service, | , the larger |
|---|---|---|---|
| G | 17.92 | 17.92 | |
| W | 9.24 | 9.24 | |
| F | 0 |
Step 3. The third sweep. With the values :
Servicing and continuing with a failed pump lead to a single next state, and the value of a state is its larger action value:
| State | Continue, | Service, | , the larger |
|---|---|---|---|
| G | 23.7844 | 23.7844 | |
| W | 10.9896 | 12.128 | |
| F | 0 |
Servicing a worn pump now beats continuing, because the value of a good pump, which a service restores, has grown faster than the value of continuing with a worn one.
Step 4. The exact values. Further sweeps change the values less and less, and from the fourth sweep on the greedy policy stays the same: Continue in G, service in W and service in F. The values of this policy solve its three Bellman equations, which have no maximum because the actions are fixed:
With and , inserting the second equation into the first gives
Step 5. The check. The policy is optimal because no other action does better with these values. Continuing with a worn pump, continuing with a failed pump and servicing a good pump give
which are all smaller than , and . The high cost of a failure makes preventive service of a worn pump worthwhile, the logic of condition-based maintenance. Part A of the interactive lab runs the sweeps for any rewards, probabilities and discount factors.
Worked example: Q-learning from five transitions
An agent that does not know the probabilities of the pump starts with for every state and action, uses and , and observes five transitions.
Update 1. In state G, the action continue gave the reward 10 and the next state G, whose larger estimate is :
Update 2. In state G, the action continue gave the reward 10 and the next state W, whose larger estimate is :
Update 3. In state W, the action continue gave the reward 6 and the next state F, whose larger estimate is :
Update 4. In state F, the action service gave the reward −20 and the next state G, whose larger estimate is :
Update 5. In state G, the action continue gave the reward 10 and the next state G, whose larger estimate is :
After five transitions, the estimate is still far below its value 70.2362 from the previous example, and is lower than , so a greedy agent would leave a failed pump idle. Exploration corrects such early errors: With and two actions, the greedy action is taken with the probability and the other action with , so the agent keeps trying repairs. Part B of the lab runs Q-learning on the pump for thousands of weeks.
Reinforcement learning in engineering
Control problems were among the first testbeds of reinforcement learning: The cart-pole balancing task goes back to adaptive elements studied in the early 1980s [4], and Gymnasium now provides it with a standard interface for experiments [5]. Robotics has used reinforcement learning for manipulation and locomotion [6], and deep reinforcement learning has controlled the magnetic coils of a tokamak in a fusion experiment [7]. These successes share a feature: The agent learned mostly in simulation. Exploration on a real plant can damage equipment or endanger people, the reward may be satisfied in unintended ways, and a policy trained under one set of conditions may fail under others; Amodei and colleagues list safe exploration, reward hacking and distributional shift among the concrete problems of AI safety [8]. Simulators, constraints on actions, human oversight and gradual deployment are therefore part of any engineering use.
Check your understanding. Why do most engineering applications of reinforcement learning train the agent in simulation first?
Formulas: Rewards and the cross-entropy method
The reward is the specification of the task: The agent maximises exactly what it is rewarded for, and a missing or badly weighted term invites behaviour that the engineer did not intend [8]. The heating agent of the notebook receives, after it has chosen the heater command and the room has reached the temperature , the reward
where is 1 if the command differs from the previous one and 0 otherwise. The first term rewards comfort, the second penalises switching, which wears the relay, and the third penalises energy; the notebook uses and .
Policy search methods adjust the parameters of a policy directly. The cross-entropy method draws parameter vectors from a normal distribution with the mean and the standard deviation , runs an episode with each, keeps the vectors with the highest returns, the elite, and fits the distribution to the elite:
For vectors, these formulas apply to every component. The distribution narrows around good parameters within a few iterations; a small constant added to , 0.05 in the notebook, keeps it from collapsing too early. The method needs no gradients, like the population methods of Weeks 5 and 6, which suits simulators that are treated as black boxes.
Worked example: How the reward weights choose a behaviour
Two heater trajectories of four steps start from a heater that was off. Every reward splits into the comfort and energy part, which does not depend on , and the switching penalty , and the discount factor is . Trajectory A switches in every step and stays close to 21 °C:
| Step | Weight | (°C) | Switch | Comfort and energy | |
|---|---|---|---|---|---|
| 1 | 1 | 21.2 | 1 | 1 | |
| 2 | 0.9 | 20.9 | 0 | 1 | |
| 3 | 0.81 | 21.1 | 1 | 1 | |
| 4 | 0.729 | 20.8 | 0 | 1 |
Trajectory B switches twice and drifts further from 21 °C:
| Step | Weight | (°C) | Switch | Comfort and energy | |
|---|---|---|---|---|---|
| 1 | 1 | 21.4 | 1 | 1 | |
| 2 | 0.9 | 21.8 | 1 | 0 | |
| 3 | 0.81 | 21.3 | 0 | 1 | |
| 4 | 0.729 | 20.9 | 0 | 0 |
Step 1. Discounted sums. The comfort and energy parts and the switches, each weighted by , add up to
so the returns are and .
Step 2. A light penalty. With :
Trajectory A has the higher return, so a learning agent is drawn towards frequent switching.
Step 3. A heavier penalty. With :
Now trajectory B wins. The two returns are equal where , that is at
The weight is an engineering decision about relay wear against comfort, and the agent only carries it out. Part C of the interactive lab compares the two trajectories for any weights, and Part D lets a Q-learning thermostat learn with this reward and an adjustable penalty per switching.
Worked example: One iteration of the cross-entropy method
A controller gain is tuned on a simulator whose return, unknown to the method, is . Ten draws from the normal distribution with and give
| Draw | |||
|---|---|---|---|
| −2.1 | −4.1 | 16.81 | −6.81 |
| 0.4 | −1.6 | 2.56 | 7.44 |
| 1.8 | −0.2 | 0.04 | 9.96 |
| −0.7 | −2.7 | 7.29 | 2.71 |
| 3.2 | 1.2 | 1.44 | 8.56 |
| 2.5 | 0.5 | 0.25 | 9.75 |
| −1.5 | −3.5 | 12.25 | −2.25 |
| 0.9 | −1.1 | 1.21 | 8.79 |
| 4.4 | 2.4 | 5.76 | 4.24 |
| 1.1 | −0.9 | 0.81 | 9.19 |
Step 1. The elite. The best fifth of ten draws are the two draws with the highest returns, with 9.96 and with 9.75.
Step 2. The new distribution.
One iteration moved the mean from 0 to 2.15, close to the best gain 2, and narrowed the spread from 2 to 0.35, or 0.4 with the constant 0.05 of the notebook. Part E of the lab runs further iterations.
Physics-informed learning
Engineering rarely starts from zero knowledge. Conservation laws, constitutive equations and boundary conditions are known even when parameters or source terms are not. Physics-informed neural networks add the residual of the governing differential equation, evaluated at many collocation points, to the loss of a network whose input is space or time [9]. Automatic differentiation provides the derivatives of the network output exactly. The network then fits the data where they exist and obeys the physics everywhere else, which makes it far more reliable outside the measured range than a data-only network. The same framework solves inverse problems, estimating unknown coefficients of the equation from data. Karniadakis and colleagues review the broader field of physics-informed machine learning [10]; related methods discover governing equations from data by sparse regression [11, 12]. Physics-informed networks can be hard to train for stiff or multiscale problems, and classical numerical solvers remain the reference where they apply.

Check your understanding. What does the physics term in the loss of a physics-informed network contain?
Formulas: The damped oscillator and the physics-informed loss
A mass on a spring of stiffness with a damper of coefficient obeys , where and are the first and second derivatives of the displacement with respect to time. Divided by , the equation takes the standard form
with the natural angular frequency and the damping ratio . Inserting gives the characteristic equation . For its roots are , with the imaginary unit and the damped angular frequency . They yield the real solutions and , oscillations that decay with the envelope , and every combination of them solves the equation. Released from at rest, , the mass follows
A physics-informed network is trained on the sum of a data loss over the measurements and a physics loss over collocation points , at which no measurement is needed [9]:
The bracket of the second sum is the residual of the equation, which is zero for every exact solution. Automatic differentiation gives the derivatives of the network output exactly, the weight balances the two terms, and the initial conditions can enter as further terms of the same kind, as in the notebook [10].
Worked example: Residuals of two candidate solutions
The oscillator of the notebook obeys with and , and two measurements are and .
Step 1. Frequency and damping. Comparing with the standard form gives , so , and , so and . Then
Step 2. The exact solution at the measurement times. With :
The exact solution combines solutions of the equation, so its residual is 0 at every point and its physics loss is 0.
Step 3. An undamped candidate. The candidate starts at 1 at rest, like the true motion, but ignores the damper. Its derivatives are and , so its residual is
At four collocation points:
| 0.5 | −0.673177 | 0.453167 | |
| 1 | −0.727438 | 0.529166 | |
| 1.5 | −0.112896 | 0.012746 | |
| 2 | 0.605442 | 0.36656 |
Step 4. Data and total losses. At the measurement times, and . The data losses are
With , the total loss of the undamped candidate is , while that of the exact solution is 0.000008. The data alone separate the candidates only weakly, since both stay within 0.03 of the measurements, while the physics term exposes the undamped candidate at once; a network trained on the data alone has no reason to prefer the damped motion beyond the measured range. Part F of the interactive lab evaluates these losses for other candidates, data and weights.
Digital twins
Grieves and Vickers described a digital twin as a virtual representation of a physical product that is linked to it by data throughout its life, so that behaviour can be predicted and problems anticipated [13]. Tao and colleagues surveyed its industrial use in design, production and maintenance [14]. A twin combines a model of the asset, a data connection that keeps the model's state and parameters current, and services such as monitoring, forecasting, what-if analysis and controller testing. System identification, estimating model parameters from measured inputs and outputs, is its simplest learning component; the notebook identifies the thermal parameters of the room of Week 1 from noisy data and uses the resulting model to forecast and to test a controller. The methods of the whole course appear in twins: rules and fuzzy logic for decisions, optimisation for calibration, machine learning for components without physical models, anomaly detection for monitoring and reinforcement learning for control.
Formulas: Identifying a model by least squares
The room of Week 1 changes in a time step by heat loss to the outside and by the heater:
where is the time constant of the room, the heating rate in °C per minute and is 1 while the heater is on. With the change and the inputs and , the model is linear in the unknown parameters, , where collects noise and model error. Least squares chooses and that minimise [12]. Setting the derivatives of this sum with respect to and to zero gives the normal equations
with the sums , , , and . Cramer's rule solves this system of two equations:
The physical parameters follow as and . With the heater on and a constant outside temperature, the room settles where the loss balances the heating, , at . The identified model is the core of a simple twin: It forecasts the room from its current state, the differences between forecasts and measurements reveal faults, and controllers can be tested on it before they touch the building [13, 14].
Worked example: Identifying the room from six measurements
A room was logged every minutes at the outside temperature °C:
| (°C) | ||||
|---|---|---|---|---|
| 0 | 18.00 | 1 | ||
| 1 | 18.37 | 1 | ||
| 2 | 18.66 | 0 | ||
| 3 | 18.01 | 1 | ||
| 4 | 18.33 | 0 | ||
| 5 | 17.70 |
Step 1. The sums. The squares and products of each step are
| 0 | ||
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |
The heater was on in steps 0, 1 and 3, so the sums with collect only these steps:
Step 2. The parameters. The common denominator is
and the two numerators give
Step 3. Physical parameters. The time constant is minutes and the heating rate °C per minute. The data were simulated with minutes and °C per minute and carry sensor errors of about 0.02 °C, so six noisy measurements recover both parameters with errors of about 5%.
Step 4. Using the twin. With the heater on in the next step, the twin forecasts
and with the heater on for good, the room would settle at the temperature
in °C, close to the 25 °C of the simulated room. A measurement far from the forecast would point to an open window, a failed heater or a faulty sensor. Part G of the interactive lab repeats the identification with more data and noise and shows how the estimates improve.
Responsible engineering of AI systems
Engineering codes of ethics require practitioners to hold public safety paramount, and they apply to systems that include learned components. Earlier work on machine ethics and AI safety argued that safety must be designed in rather than added after deployment [15]. Regulation now makes parts of this explicit. The European Union's Artificial Intelligence Act, Regulation (EU) 2024/1689, follows a risk-based approach: A few practices are prohibited, such as social scoring and the inference of emotions in the workplace and in education except for medical or safety reasons; high-risk systems, which include safety components in the management of critical infrastructure such as water, gas, heating and electricity supply, and systems used in employment and education, must meet requirements on risk management, data governance, documentation, human oversight, accuracy and robustness; and systems such as chatbots and generators of synthetic content carry transparency obligations [16].
Frameworks turn principles into practice. The NIST AI Risk Management Framework organises activities into four functions: Govern establishes policies, roles and accountability; Map establishes the context and identifies risks; Measure analyses and tracks risks with appropriate metrics; and Manage prioritises and acts on them [17]. ISO/IEC 42001 specifies a management system for organisations that develop or use AI, in the style of other management system standards [18]. Türkiye's national strategy places trustworthy and responsible AI among its priorities [19]. The energy and resource costs of training and running models are part of the same responsibility [20].
Check your understanding. Under the EU AI Act, which category most likely applies to an AI system that acts as a safety component in the management of a city's water supply network?
Formulas: How many tests support a failure rate
The Measure function of the NIST framework asks for metrics whose uncertainty is known [17]. A frequent question is how many tests without failure support a claimed failure rate of a system, for example of a vision inspection that must miss fewer than 1% of the defects. If every test fails with the probability , independently of the others, all tests pass with the probability
The claim that is below is supported with the confidence if a system whose rate is exactly would pass all tests with a probability of at most :
Dividing by , which is negative, reverses the inequality. After tests without failure, the same reasoning gives the upper confidence bound of the failure rate. For small rates, is close to , and with , is close to , which gives the rule of three: About tests are needed, and passed tests bound the rate at about . The tests must represent the conditions of use, since a shift between test and operating conditions breaks the argument [8].
Worked example: Demonstrating a miss rate below 1%
Step 1. The number of tests. With and :
so 299 defective parts must all be detected, close to the of the rule of three.
Step 2. A test campaign of 500 parts. If the inspection detects all 500 defective parts, the upper bound of its miss rate is
about 0.6%, again close to .
Step 3. What the campaign rules out. A system that misses 1% of the defects would pass all 500 tests with the probability
so such a system would almost never pass the campaign. The bound covers only the defects and conditions that the 500 parts represent: Parts from a new supplier or a different lighting need tests of their own. Part H of the interactive lab places eight engineering AI systems into the risk categories of the EU AI Act, Part I matches project activities to the four functions of the NIST AI Risk Management Framework, and Part J plans the tests that support a failure rate.
The course in retrospect
The fourteen weeks form one toolbox. Search plans routes and sequences; rules encode standards; fuzzy logic turns words into control; evolutionary and swarm algorithms optimise designs; machine learning predicts, classifies and detects anomalies; deep learning perceives images and sequences; language models work with text and code; and reinforcement learning, physics-informed learning and digital twins bring learning into operation. The engineering skill lies in choosing the simplest tool that meets the requirement, validating it honestly, and knowing its limits. The final project, described in the exams folder of the repository, asks for exactly this on a problem of the student's own field.
Python step 14: Environments, learning and organised code
The Python step of this week is part of the Colab notebook, where every explanation stands next to a cell that runs it and the step closes with a quick check and exercises with immediate feedback. The printable lecture notes contain the same step together with the outputs of its code. The Colab button below opens the notebook at the step. Run the setup cell just above the step first, since the exercises use its check function.
Review cards
Select a card to turn it over.
Continue the week
The week continues with the simulation and the self-assessment of the interactive lab and with the Python step and the hands-on work of the Colab notebook. The week overview lists the discipline challenges, the weekly task and the research assignment.
Interactive lab Colab notebook Self-assessment Week overview and tasks
References
[1] Sutton, R. S., & Barto, A. G. (2018). Reinforcement Learning: An Introduction (2nd ed.). MIT Press.
[2] Watkins, C. J. C. H., & Dayan, P. (1992). Q-learning. Machine Learning, 8(3-4), 279-292. https://doi.org/10.1007/BF00992698
[3] Mnih, V., Kavukcuoglu, K., Silver, D., et al. (2015). Human-level control through deep reinforcement learning. Nature, 518(7540), 529-533. https://doi.org/10.1038/nature14236
[4] Barto, A. G., Sutton, R. S., & Anderson, C. W. (1983). Neuronlike adaptive elements that can solve difficult learning control problems. IEEE Transactions on Systems, Man, and Cybernetics, SMC-13(5), 834-846. https://doi.org/10.1109/TSMC.1983.6313077
[5] Towers, M., Kwiatkowski, A., Terry, J., et al. (2024). Gymnasium: A standard interface for reinforcement learning environments. arXiv preprint arXiv:2407.17032. https://arxiv.org/abs/2407.17032
[6] Kober, J., Bagnell, J. A., & Peters, J. (2013). Reinforcement learning in robotics: A survey. The International Journal of Robotics Research, 32(11), 1238-1274. https://doi.org/10.1177/0278364913495721
[7] Degrave, J., Felici, F., Buchli, J., et al. (2022). Magnetic control of tokamak plasmas through deep reinforcement learning. Nature, 602(7897), 414-419. https://doi.org/10.1038/s41586-021-04301-9
[8] Amodei, D., Olah, C., Steinhardt, J., Christiano, P., Schulman, J., & Mané, D. (2016). Concrete problems in AI safety. arXiv preprint arXiv:1606.06565. https://arxiv.org/abs/1606.06565
[9] Raissi, M., Perdikaris, P., & Karniadakis, G. E. (2019). Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations. Journal of Computational Physics, 378, 686-707. https://doi.org/10.1016/j.jcp.2018.10.045
[10] Karniadakis, G. E., Kevrekidis, I. G., Lu, L., Perdikaris, P., Wang, S., & Yang, L. (2021). Physics-informed machine learning. Nature Reviews Physics, 3(6), 422-440. https://doi.org/10.1038/s42254-021-00314-5
[11] Brunton, S. L., Proctor, J. L., & Kutz, J. N. (2016). Discovering governing equations from data by sparse identification of nonlinear dynamical systems. Proceedings of the National Academy of Sciences, 113(15), 3932-3937. https://doi.org/10.1073/pnas.1517384113
[12] Brunton, S. L., & Kutz, J. N. (2022). Data-Driven Science and Engineering: Machine Learning, Dynamical Systems, and Control (2nd ed.). Cambridge University Press. https://doi.org/10.1017/9781009089517
[13] Grieves, M., & Vickers, J. (2017). Digital twin: Mitigating unpredictable, undesirable emergent behavior in complex systems. In Transdisciplinary Perspectives on Complex Systems (F.-J. Kahlen, S. Flumerfelt, & A. Alves, Eds.) (pp. 85-113). Springer. https://doi.org/10.1007/978-3-319-38756-7_4
[14] Tao, F., Zhang, H., Liu, A., & Nee, A. Y. C. (2019). Digital twin in industry: State-of-the-art. IEEE Transactions on Industrial Informatics, 15(4), 2405-2415. https://doi.org/10.1109/TII.2018.2873186
[15] Kose, U. (2018). Are we safe enough in the future of artificial intelligence? A discussion on machine ethics and artificial intelligence safety. BRAIN. Broad Research in Artificial Intelligence and Neuroscience, 9(2), 184-197.
[16] European Parliament and Council of the European Union (2024). Regulation (EU) 2024/1689 laying down harmonised rules on artificial intelligence (Artificial Intelligence Act). Official Journal of the European Union, L series, 12 July 2024. https://eur-lex.europa.eu/eli/reg/2024/1689/oj
[17] National Institute of Standards and Technology (2023). Artificial Intelligence Risk Management Framework (AI RMF 1.0), NIST AI 100-1. NIST. https://doi.org/10.6028/NIST.AI.100-1
[18] International Organization for Standardization (2023). ISO/IEC 42001:2023 Information technology, Artificial intelligence, Management system. ISO.
[19] Presidency of the Republic of Türkiye Digital Transformation Office, & Ministry of Industry and Technology (2021). National Artificial Intelligence Strategy 2021-2025 (Ulusal Yapay Zekâ Stratejisi 2021-2025). Ankara. Action plan updated for 2024-2025. https://www.cbddo.gov.tr/UYZS
[20] Strubell, E., Ganesh, A., & McCallum, A. (2019). Energy and policy considerations for deep learning in NLP. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (pp. 3645-3650). https://doi.org/10.18653/v1/P19-1355