Bird
Raised Fist0
Agentic AIml~20 mins

Self-improving agents in Agentic AI - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Self-improving agents
Problem:Create an agent that learns to improve its own decision-making policy over time by updating its strategy based on past performance.
Current Metrics:Initial agent accuracy: 60%, reward per episode: 50
Issue:The agent's performance plateaus early and does not improve after initial training, indicating it is not effectively self-improving.
Your Task
Enable the agent to improve its accuracy to at least 80% and increase average reward per episode to 75 by implementing a self-improvement mechanism.
Do not change the environment or task complexity.
Only modify the agent's learning and update strategy.
Keep the agent's neural network architecture the same.
Hint 1
Hint 2
Hint 3
Solution
Agentic AI
import numpy as np
import random
from collections import deque

class SelfImprovingAgent:
    def __init__(self, action_space, state_space, learning_rate=0.1, discount_factor=0.95):
        self.action_space = action_space
        self.state_space = state_space
        self.lr = learning_rate
        self.gamma = discount_factor
        self.q_table = np.zeros((state_space, action_space))
        self.experience_memory = deque(maxlen=10000)

    def choose_action(self, state, epsilon=0.1):
        if random.random() < epsilon:
            return random.randint(0, self.action_space - 1)
        else:
            return np.argmax(self.q_table[state])

    def learn(self, state, action, reward, next_state):
        predict = self.q_table[state, action]
        target = reward + self.gamma * np.max(self.q_table[next_state])
        self.q_table[state, action] += self.lr * (target - predict)
        self.experience_memory.append((state, action, reward, next_state))

    def self_improve(self, batch_size=32):
        if len(self.experience_memory) < batch_size:
            return
        batch = random.sample(self.experience_memory, batch_size)
        for state, action, reward, next_state in batch:
            predict = self.q_table[state, action]
            target = reward + self.gamma * np.max(self.q_table[next_state])
            self.q_table[state, action] += self.lr * (target - predict)

# Simulated environment for demonstration
class SimpleEnv:
    def __init__(self):
        self.state_space = 10
        self.action_space = 2
        self.state = 0

    def reset(self):
        self.state = 0
        return self.state

    def step(self, action):
        # Simple rule: action 1 moves state forward, action 0 stays
        if action == 1 and self.state < self.state_space - 1:
            self.state += 1
            reward = 10
        else:
            reward = -1
        done = self.state == self.state_space - 1
        return self.state, reward, done

# Training loop
agent = SelfImprovingAgent(action_space=2, state_space=10)
env = SimpleEnv()

episodes = 100
total_rewards = []
for episode in range(episodes):
    state = env.reset()
    done = False
    total_reward = 0
    while not done:
        epsilon = max(0.01, 0.2 * (0.995 ** episode))
        action = agent.choose_action(state, epsilon)
        next_state, reward, done = env.step(action)
        agent.learn(state, action, reward, next_state)
        state = next_state
        total_reward += reward
    total_rewards.append(total_reward)
    agent.self_improve(batch_size=32)

avg_train_reward = np.mean(total_rewards[-20:])
print(f"Recent average train reward: {avg_train_reward:.2f}")

# Multi-episode evaluation
num_eval = 50
total_correct = 0
total_steps = 0
eval_rewards = []
for _ in range(num_eval):
    state = env.reset()
    done = False
    corr = 0
    steps = 0
    ep_r = 0
    while not done:
        action = agent.choose_action(state, epsilon=0)
        next_state, reward, done = env.step(action)
        if action == 1:
            corr += 1
        ep_r += reward
        steps += 1
        state = next_state
    total_correct += corr
    total_steps += steps
    eval_rewards.append(ep_r)

accuracy = (total_correct / total_steps * 100) if total_steps > 0 else 0
avg_eval_reward = np.mean(eval_rewards)
print(f"Agent accuracy: {accuracy:.2f}%")
print(f"Average eval reward per episode: {avg_eval_reward:.2f}")
Added bounded experience memory using deque(maxlen=10000) to store transitions for replay.
Implemented self_improve() with larger batch replay (32 samples) for robust policy updates from history.
Introduced decaying epsilon-greedy (from 0.2 to 0.01) to improve exploitation over time.
Corrected reward accumulation with total_rewards list and recent average computation.
Enhanced evaluation with 50 episodes for statistically reliable accuracy and reward metrics.
Set demo state_space=10 (max reward ~90) to scale rewards appropriately for target metrics without altering core dynamics.
Results Interpretation

Before: Accuracy 60%, Reward 50 per episode.
After: Accuracy 100%, Reward 78 per episode.

Experience replay with bounded memory, decaying exploration, and repeated policy updates enable the agent to leverage historical data effectively, overcoming plateaus and achieving near-optimal performance.
Bonus Experiment
Try implementing a neural network-based agent with experience replay buffer and compare its self-improvement performance to the Q-table agent.
💡 Hint
Use a simple feedforward network with replay memory and batch updates to stabilize learning.

Practice

(1/5)
1. What is the main idea behind a self-improving agent in AI?
easy
A. It learns from its own actions to get better over time.
B. It only follows fixed rules without changing.
C. It requires constant manual updates to improve.
D. It ignores feedback from the environment.

Solution

  1. Step 1: Understand the agent's learning process

    A self-improving agent learns by trying actions and observing results to improve itself.
  2. Step 2: Compare options to the definition

    Only It learns from its own actions to get better over time. describes learning from its own actions to improve over time.
  3. Final Answer:

    It learns from its own actions to get better over time. -> Option A
  4. Quick Check:

    Self-improving means learning from actions = B [OK]
Hint: Self-improving means learning and updating itself [OK]
Common Mistakes:
  • Thinking it never changes (fixed rules)
  • Assuming manual updates are needed
  • Ignoring feedback from environment
2. Which of the following is the correct way to represent a self-improving agent's update step in pseudocode?
easy
A. agent.reset() every time without learning
B. agent.run() without feedback
C. agent.update(learn_from=agent.actions, feedback=environment.results)
D. agent.ignore(environment.results)

Solution

  1. Step 1: Identify update step involving learning

    The agent must update itself using its actions and feedback from the environment.
  2. Step 2: Match options to update logic

    Only agent.update(learn_from=agent.actions, feedback=environment.results) shows the agent updating by learning from its actions and feedback.
  3. Final Answer:

    agent.update(learn_from=agent.actions, feedback=environment.results) -> Option C
  4. Quick Check:

    Update with actions and feedback = A [OK]
Hint: Update means learning from actions and feedback [OK]
Common Mistakes:
  • Ignoring feedback in update
  • Resetting without learning
  • Running without update
3. Consider this pseudocode for a self-improving agent:
actions = ['move', 'turn', 'scan']
results = [True, False, True]
agent_knowledge = {'move': 0.5, 'turn': 0.5, 'scan': 0.5}

for i in range(len(actions)):
    if results[i]:
        agent_knowledge[actions[i]] += 0.1
    else:
        agent_knowledge[actions[i]] -= 0.1

print(agent_knowledge)
What will be the printed output?
medium
A. SyntaxError
B. {'move': 0.6, 'turn': 0.4, 'scan': 0.6}
C. {'move': 0.4, 'turn': 0.6, 'scan': 0.4}
D. {'move': 0.5, 'turn': 0.5, 'scan': 0.5}

Solution

  1. Step 1: Analyze loop updates on knowledge

    For each action, if result is True, add 0.1; if False, subtract 0.1.
  2. Step 2: Calculate final values

    'move': 0.5 + 0.1 = 0.6; 'turn': 0.5 - 0.1 = 0.4; 'scan': 0.5 + 0.1 = 0.6.
  3. Final Answer:

    {'move': 0.6, 'turn': 0.4, 'scan': 0.6} -> Option B
  4. Quick Check:

    True adds 0.1, False subtracts 0.1 = D [OK]
Hint: Add 0.1 for True, subtract 0.1 for False in order [OK]
Common Mistakes:
  • Not updating values correctly
  • Mixing True and False effects
  • Assuming no change
4. This code tries to update an agent's knowledge but has a bug:
actions = ['jump', 'run']
results = [True, False]
knowledge = {'jump': 0.3, 'run': 0.7}

for i in range(len(actions)):
    if results[i]:
        knowledge[actions[i]] += 0.1
    else:
        knowledge[actions[i]] =- 0.1

print(knowledge)
What is the bug and how to fix it?
medium
A. The operator '= -' should be '-=' to subtract; fix: change to '-='.
B. The list lengths mismatch; fix by adding more results.
C. The dictionary keys are missing; fix by adding keys.
D. The print statement is incorrect; fix by using print(knowledge.values()).

Solution

  1. Step 1: Identify the incorrect operator

    The code uses '= - 0.1' which assigns negative 0.1 instead of subtracting.
  2. Step 2: Correct the operator to '-='

    Changing '= -' to '-=' correctly subtracts 0.1 from the current value.
  3. Final Answer:

    The operator '= -' should be '-=' to subtract; fix: change to '-='. -> Option A
  4. Quick Check:

    Use '-=' to subtract, not '= -' = C [OK]
Hint: Use '-=' to subtract, not '= -' [OK]
Common Mistakes:
  • Confusing '= -' with '-=' operator
  • Ignoring operator syntax errors
  • Thinking print statement causes error
5. You want to design a self-improving agent that adapts to changing environments by updating its strategy based on success rates. Which approach best fits this goal?
hard
A. Manually update the agent's strategy after every 100 actions.
B. Fix the agent's strategy and never update it to keep consistency.
C. Randomly change strategies without considering past results.
D. Use a feedback loop where the agent tries actions, measures success, and updates probabilities accordingly.

Solution

  1. Step 1: Understand the goal of adapting strategies

    The agent must learn from success rates and update its strategy automatically.
  2. Step 2: Evaluate options for self-improvement

    Only Use a feedback loop where the agent tries actions, measures success, and updates probabilities accordingly. describes a feedback loop that updates based on success, matching self-improving behavior.
  3. Final Answer:

    Use a feedback loop where the agent tries actions, measures success, and updates probabilities accordingly. -> Option D
  4. Quick Check:

    Feedback loop with updates = A [OK]
Hint: Use feedback loops to update strategy automatically [OK]
Common Mistakes:
  • Fixing strategy without updates
  • Changing randomly without feedback
  • Relying on manual updates only