Certainly! The Mountain Car problem is a classic reinforcement learning problem where an underpowered car must drive up a steep hill. Due to the gravity, the car cannot simply accelerate up the hill, and must build up momentum by driving back and forth.
Here's a simple implementation using PyTorch to solve the Mountain Car problem with a Deep Q-Network (DQN). This example uses the gym library to create the Mountain Car environment.
First, make sure you have the necessary libraries installed:
bash
pip install gym pytorch numpy
Now, here's the code:
python
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
# Hyperparameters
learning_rate = 0.001
gamma = 0.99
epsilon_start = 1.0
epsilon_end = 0.01
epsilon_decay = 0.995
batch_size = 64
memory_size = 10000
# Environment
env = gym.make('MountainCar-v0')
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
# Neural Network for Q-function approximation
class DQN(nn.Module):
def __init__(self):
super(DQN, self).__init__()
self.fc1 = nn.Linear(state_size, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, action_size)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Replay Memory
class ReplayMemory:
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
self.position = 0
def push(self, transition):
if len(self.memory) < self.capacity:
self.memory.append(None)
self.memory[self.position] = transition
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size):
return random.sample(self.memory, batch_size)
def __len__(self):
return len(self.memory)
# Training
def select_action(state, policy_net, epsilon):
if np.random.rand() <= epsilon:
return torch.tensor([[np.random.choice(action_size)]], dtype=torch.long)
with torch.no_grad():
return policy_net(state).max(1)[1].view(1, 1)
def optimize_model(policy_net, target_net, memory, optimizer):
if len(memory) < batch_size:
return
transitions = memory.sample(batch_size)
batch = Transition(*zip(*transitions))
non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), dtype=torch.bool)
non_final_next_states = torch.cat([s for s in batch.next_state if s is not None])
state_batch = torch.cat(batch.state)
action_batch = torch.cat(batch.action)
reward_batch = torch.cat(batch.reward)
state_action_values = policy_net(state_batch).gather(1, action_batch)
next_state_values = torch.zeros(batch_size)
next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()
expected_state_action_values = (next_state_values * gamma) + reward_batch
loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))
optimizer.zero_grad()
loss.backward()
for param in policy_net.parameters():
param.grad.data.clamp_(-1, 1)
optimizer.step()
# Main loop
policy_net = DQN()
target_net = DQN()
target_net.load_state_dict(policy_net.state_dict())
target_net.eval()
optimizer = optim.Adam(policy_net.parameters(), lr=learning_rate)
memory = ReplayMemory(memory_size)
epsilon = epsilon_start
num_episodes = 500
for i_episode in range(num_episodes):
state = env.reset()
state = torch.tensor([state], dtype=torch.float32)
total_reward = 0
for t in range(1000):
action = select_action(state, policy_net, epsilon)
epsilon = max(epsilon_end, epsilon * epsilon_decay)
next_state, reward, done, _ = env.step(action.item())
reward = torch.tensor([reward], dtype=torch.float32)
if done:
next_state = None
else:
next_state = torch.tensor([next_state], dtype=torch.float32)
memory.push((state, action, next_state, reward))
state = next_state
total_reward += reward.item()
optimize_model(policy_net, target_net, memory, optimizer)
if done:
print(f"Episode {i_episode + 1}, Total Reward: {total_reward}")
break
if i_episode % 10 == 0:
target_net.load_state_dict(policy_net.state_dict())
env.close()
This code sets up a DQN to learn the Mountain Car problem. It includes a neural network for approximating the Q-function, a replay memory for storing transitions, and an optimization loop to train the network. The epsilon-greedy policy is used for exploration. The target network is updated periodically to stabilize training.
“can you create a simple executable code that use pytorch solve mountain car question.” Conversation with deepseek-v2-api-0628, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m851cdyn2pxr6ea89y376s16