本篇內容介紹了“怎么使用Python實現自動駕駛系統(tǒng)”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
南江網站建設公司創(chuàng)新互聯公司,南江網站設計制作,有大型網站制作公司豐富經驗。已為南江近千家提供企業(yè)網站建設服務。企業(yè)網站搭建\外貿網站建設要多少錢,請找那個售后服務好的南江做網站的公司定做!
gym是用于開發(fā)和比較強化學習算法的工具包,在python中安裝gym庫和其中子場景都較為簡便。
安裝gym:
pip install gym
安裝自動駕駛模塊,這里使用 Edouard Leurent 發(fā)布在 github 上的包 highway-env:
pip install --user git+https://github.com/eleurent/highway-env
其中包含6個場景:
高速公路——“highway-v0”
匯入——“merge-v0”
環(huán)島——“roundabout-v0”
泊車——“parking-v0”
十字路口——“intersection-v0”
賽車道——“racetrack-v0”
安裝好后即可在代碼中進行實驗(以高速公路場景為例):
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)state
highway-env包中沒有定義傳感器,車輛所有的state (observations) 都從底層代碼讀取,節(jié)省了許多前期的工作量。根據文檔介紹,state (ovservations) 有三種輸出方式:Kinematics,Grayscale Image和Occupancy grid。
Kinematics
輸出V*F的矩陣,V代表需要觀測的車輛數量(包括ego vehicle本身),F代表需要統(tǒng)計的特征數量。例:
數據生成時會默認歸一化,取值范圍:[100, 100, 20, 20],也可以設置ego vehicle以外的車輛屬性是地圖的絕對坐標還是對ego vehicle的相對坐標。
在定義環(huán)境時需要對特征的參數進行設定:
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) action
highway-env包中的action分為連續(xù)和離散兩種。連續(xù)型action可以直接定義throttle和steering angle的值,離散型包含5個meta actions:
ACTIONS_ALL = {
0: 'LANE_LEFT',
1: 'IDLE',
2: 'LANE_RIGHT',
3: 'FASTER',
4: 'SLOWER'
}(3) reward
highway-env包中除了泊車場景外都采用同一個reward function:

這個function只能在其源碼中更改,在外層只能調整權重。
(泊車場景的reward function原文檔里有)
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'))各個部分都完成之后就可以組合在一起訓練模型了,流程和用CARLA差不多,就不細說了。
初始化環(huán)境(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次統(tǒng)計一次平均值。
平均碰撞發(fā)生率:

epoch平均時長(s):

平均reward:

可以看出平均碰撞發(fā)生率會隨訓練次數增多逐漸降低,每個epoch持續(xù)的時間會逐漸延長(如果發(fā)生碰撞epoch會立刻結束)
“怎么使用Python實現自動駕駛系統(tǒng)”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識可以關注創(chuàng)新互聯網站,小編將為大家輸出更多高質量的實用文章!
網站題目:怎么使用Python實現自動駕駛系統(tǒng)
文章出自:http://www.chinadenli.net/article14/pesige.html
成都網站建設公司_創(chuàng)新互聯,為您提供網站設計、網站營銷、服務器托管、網站策劃、網站維護、網站導航
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯