pythonでのサンプルコード 強化学習

2024年6月10日

以下に、Pythonでの強化学習のサンプルコードを示します。この例では、OpenAI GymのCartPole環境を使用して、Q学習エージェントを実装します。

python
import gym
import numpy as np

# Q学習エージェントの定義
class QLearningAgent:
    def __init__(self, env, learning_rate=0.1, discount_factor=0.99, epsilon=0.1):
        self.env = env
        self.learning_rate = learning_rate
        self.discount_factor = discount_factor
        self.epsilon = epsilon
        self.q_table = np.zeros((env.observation_space.n, env.action_space.n))

    def choose_action(self, state):
        if np.random.uniform(0, 1) < self.epsilon:
            return self.env.action_space.sample()  # ε-greedy方策
        else:
            return np.argmax(self.q_table[state, :])  # 最適な行動を選択

    def update_q_table(self, state, action, reward, next_state):
        # Q値の更新
        next_max = np.max(self.q_table[next_state, :])
        self.q_table[state, action] += self.learning_rate * (
                reward + self.discount_factor * next_max - self.q_table[state, action])

# CartPole環境の読み込み
env = gym.make('CartPole-v1')

# Q学習エージェントの初期化
agent = QLearningAgent(env)

# エピソードの実行
num_episodes = 1000
for episode in range(num_episodes):
    state = env.reset()
    total_reward = 0
    done = False
    while not done:
        action = agent.choose_action(state)
        next_state, reward, done, _ = env.step(action)
        agent.update_q_table(state, action, reward, next_state)
        state = next_state
        total_reward += reward
    print(f"Episode {episode + 1}: Total Reward = {total_reward}")

# 学習したQ値を表示
print("Learned Q-table:")
print(agent.q_table)

このコードでは、Q学習エージェントがCartPole環境でエピソードを実行し、Q値を更新します。エージェントはε-greedy方策を使用して行動を選択し、その結果、安定した挙動を学習することが期待されます。

未分類

Posted by ぼっち