gym是用來開發和比較強化學習演算法的工具包,在python中安裝gym函式庫和其中子場景都較為簡單。
安裝gym:
pip install gym
安裝自動駕駛模組,這裡使用Edouard Leurent 發佈在github 上的套件highway-env:
pip install --user git+https://github.com/eleurent/highway-env
其中包含6個場景:
#https://www.php.cn/link/c0fda89ebd645bd7cea60fcbb5960309
#設定環境安裝好後即可在程式碼中進行實驗(以高速公路場景為例):import gym import highway_env %matplotlib inline env = gym.make('highway-v0') env.reset() for _ in range(3): action = env.action_type.actions_indexes["IDLE"] obs, reward, done, info = env.step(action) env.render()運行後會在模擬器中產生以下場景: env類別有很多參數可以配置,具體可以參考原文檔。 訓練模型1、資料處理(1)statehighway-env套件中沒有定義感測器,車輛所有的state (observations)都從底層程式碼讀取,節省了許多前期的工作量。根據文件介紹,state (ovservations) 有三種輸出方式:Kinematics,Grayscale Image和Occupancy grid。 Kinematics輸出V*F的矩陣,V代表需要觀測的車輛數量(包括ego vehicle本身),F代表需要統計的特徵數量。例:資料產生時會預設歸一化,取值範圍:[100, 100, 20, 20],也可以設定ego vehicle以外的車輛屬性是地圖的絕對座標還是ego vehicle的相對座標。 在定義環境時需要對特徵的參數進行設定:
config = { "observation": { "type": "Kinematics", #选取5辆车进行观察(包括ego vehicle) "vehicles_count": 5, #共7个特征 "features": ["presence", "x", "y", "vx", "vy", "cos_h", "sin_h"], "features_range": { "x": [-100, 100], "y": [-100, 100], "vx": [-20, 20], "vy": [-20, 20] }, "absolute": False, "order": "sorted" }, "simulation_frequency": 8,# [Hz] "policy_frequency": 2,# [Hz] }Grayscale Image產生一張W*H的灰階影像,W代表影像寬度, H代表影像高度Occupancy grid產生一個WHF的三維矩陣,用W*H的表格表示ego vehicle周圍的車輛狀況,每個格子包含F個特徵。 (2) actionhighway-env套件中的action分為連續和離散兩種。連續型action可以直接定義throttle和steering angle的值,離散型包含5個meta actions:
ACTIONS_ALL = { 0: 'LANE_LEFT', 1: 'IDLE', 2: 'LANE_RIGHT', 3: 'FASTER', 4: 'SLOWER' }(3) rewardhighway-env包中除了泊車場景外都採用同一個reward function: 這個function只能在其原始碼中更改,在外層只能調整權重。 (泊車場景的reward function原始文檔裡有)2、搭建模型DQN網絡,我採用第一種state表示方式-Kinematics進行示範。由於state資料量較小(5輛車*7個特徵),可以不考慮使用CNN,直接把二維資料的size[5,7]轉成[1,35]即可,模型的輸入就是35,輸出是離散action數量,共5個。
import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as T from torch import FloatTensor, LongTensor, ByteTensor from collections import namedtuple import random Tensor = FloatTensor EPSILON = 0# epsilon used for epsilon greedy approach GAMMA = 0.9 TARGET_NETWORK_REPLACE_FREQ = 40 # How frequently target netowrk updates MEMORY_CAPACITY = 100 BATCH_SIZE = 80 LR = 0.01 # learning rate class DQNNet(nn.Module): def __init__(self): super(DQNNet,self).__init__() self.linear1 = nn.Linear(35,35) self.linear2 = nn.Linear(35,5) def forward(self,s): s=torch.FloatTensor(s) s = s.view(s.size(0),1,35) s = self.linear1(s) s = self.linear2(s) return s class DQN(object): def __init__(self): self.net,self.target_net = DQNNet(),DQNNet() self.learn_step_counter = 0 self.memory = [] self.position = 0 self.capacity = MEMORY_CAPACITY self.optimizer = torch.optim.Adam(self.net.parameters(), lr=LR) self.loss_func = nn.MSELoss() def choose_action(self,s,e): x=np.expand_dims(s, axis=0) if np.random.uniform() < 1-e: actions_value = self.net.forward(x) action = torch.max(actions_value,-1)[1].data.numpy() action = action.max() else: action = np.random.randint(0, 5) return action def push_memory(self, s, a, r, s_): if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = Transition(torch.unsqueeze(torch.FloatTensor(s), 0),torch.unsqueeze(torch.FloatTensor(s_), 0), torch.from_numpy(np.array([a])),torch.from_numpy(np.array([r],dtype='float32')))# self.position = (self.position + 1) % self.capacity def get_sample(self,batch_size): sample = random.sample(self.memory,batch_size) return sample def learn(self): if self.learn_step_counter % TARGET_NETWORK_REPLACE_FREQ == 0: self.target_net.load_state_dict(self.net.state_dict()) self.learn_step_counter += 1 transitions = self.get_sample(BATCH_SIZE) batch = Transition(*zip(*transitions)) b_s = Variable(torch.cat(batch.state)) b_s_ = Variable(torch.cat(batch.next_state)) b_a = Variable(torch.cat(batch.action)) b_r = Variable(torch.cat(batch.reward)) q_eval = self.net.forward(b_s).squeeze(1).gather(1,b_a.unsqueeze(1).to(torch.int64)) q_next = self.target_net.forward(b_s_).detach() # q_target = b_r + GAMMA * q_next.squeeze(1).max(1)[0].view(BATCH_SIZE, 1).t() loss = self.loss_func(q_eval, q_target.t()) self.optimizer.zero_grad() # reset the gradient to zero loss.backward() self.optimizer.step() # execute back propagation for one step return loss Transition = namedtuple('Transition',('state', 'next_state','action', 'reward'))3、運行結果各個部分都完成之後就可以組合在一起訓練模型了,流程和用CARLA差不多,就不細說了。 初始化環境(DQN的類別加進去就行了):
import gym import highway_env from matplotlib import pyplot as plt import numpy as np import time config = { "observation": { "type": "Kinematics", "vehicles_count": 5, "features": ["presence", "x", "y", "vx", "vy", "cos_h", "sin_h"], "features_range": { "x": [-100, 100], "y": [-100, 100], "vx": [-20, 20], "vy": [-20, 20] }, "absolute": False, "order": "sorted" }, "simulation_frequency": 8,# [Hz] "policy_frequency": 2,# [Hz] } env = gym.make("highway-v0") env.configure(config)訓練模型:
dqn=DQN() count=0 reward=[] avg_reward=0 all_reward=[] time_=[] all_time=[] collision_his=[] all_collision=[] while True: done = False start_time=time.time() s = env.reset() while not done: e = np.exp(-count/300)#随机选择action的概率,随着训练次数增多逐渐降低 a = dqn.choose_action(s,e) s_, r, done, info = env.step(a) env.render() dqn.push_memory(s, a, r, s_) if ((dqn.position !=0)&(dqn.position % 99==0)): loss_=dqn.learn() count+=1 print('trained times:',count) if (count%40==0): avg_reward=np.mean(reward) avg_time=np.mean(time_) collision_rate=np.mean(collision_his) all_reward.append(avg_reward) all_time.append(avg_time) all_collision.append(collision_rate) plt.plot(all_reward) plt.show() plt.plot(all_time) plt.show() plt.plot(all_collision) plt.show() reward=[] time_=[] collision_his=[] s = s_ reward.append(r) end_time=time.time() episode_time=end_time-start_time time_.append(episode_time) is_collision=1 if info['crashed']==True else 0 collision_his.append(is_collision)我在程式碼中加入了一些畫圖的函數,在運行過程中就可以掌握一些關鍵的指標,每訓練40次統計一次平均值。 平均碰撞發生率: epoch平均長度(s): 平均reward : 可以看出平均碰撞發生率會隨訓練次數增加逐漸降低,每個epoch持續的時間會逐漸延長(如果發生碰撞epoch會立刻結束)總結相比於模擬器CARLA,highway-env環境包明顯更加抽象化,用類似遊戲的表示方式,使得演算法可以在一個理想的虛擬環境中得到訓練,而不用考慮資料取得方式、感測器精確度、運算時長等現實問題。對於端到端的演算法設計和測試非常友好,但從自動控制的角度來看,可以入手的方面較少,研究起來不太靈活。
以上是學習Python實現自動駕駛系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!