2019-05-01-机器人传感器

python

Posted by berlinfog on May 1, 2019

机器人传感器

机器人通过摄像头和其他传感器来感知世界,但这些传感器并是不完全准确的。在这段视频中,你看到的示例是一个由彩色网格单元格组成的一维世界中的机器人。所有单元格都是绿色或红色的。机器人可以感觉到自己在一个红色网格单元中。

这个读数准确的概率,我们称之为传感器达到目标pHd,这个概率是0.6,但这是个读数不准确的概率(传感器已经错过了它的目标),机器人实际上在一个绿色网格单元中,且pMiss等于0.2。

在这个notebook中,我们会一步一步地了解它的工作原理。

均匀分布

该机器人会从一个长度为5个单元格的地图中开始运动。由于它最初不知道自己在哪里,所以在任何一个空间的概率是相同的,这就是均匀分布!

# importing resources
import matplotlib.pyplot as plt
import numpy as np
# ex. initialize_robot(5) = [0.2, 0.2, 0.2, 0.2, 0.2]
def initialize_robot(grid_length):
    ''' Takes in a grid length and returns 
       a uniform distribution of location probabilities'''
    
    p = []
    
    # create a list that has the value of 1/grid_length for each cell
    for i in range(grid_length):
        p.append(1.0/grid_length)
        
    return p

还要用到一个辅助函数,用于可视化此分布。下面的函数display_map将会输出一个条形图,显示机器人在每个网格空间中的概率。至于概率范围,y轴的范围是0到1。对于均匀分布来说,这看起来像一条扁平线。如果想要将它们分开,可以选择每个条的宽度<= 1。

def display_map(grid, bar_width=1):
    if(len(grid) > 0):
        x_labels = range(len(grid))
        plt.bar(x_labels, height=grid, width=bar_width, color='b')
        plt.xlabel('Grid Cell')
        plt.ylabel('Probability')
        plt.ylim(0, 1) # range of 0-1 for probability values 
        plt.title('Probability of the robot being at each cell in the grid')
        plt.xticks(np.arange(min(x_labels), max(x_labels)+1, 1))
        plt.show()
    else:
        print('Grid is empty')

# initialize a 5 cell, 1D world
p = initialize_robot(5)
display_map(p)

感知后的概率

然后,这个机器人会感知到它处于一个红色网格单元中,并更新其概率。根据我们的例子:

  • 机器人对颜色感知正确的概率是pHit = 0.6
  • 机器人对颜色感知不正确的概率是pMiss = 0.2,在这个示例中:它看到了红色,但实际上它在绿色单元格中。

<img src=’images/robot_sensing.png’ width=50% height=50% />

接下来,我们编写一段代码,使每个条目在适当的位置乘以pHit或pMiss后输出一个新的网格p

请记住,红色单元格(单元格1和单元格2)代表“感知正确”,而其他绿色单元格代表“感知不正确”。

请注意,由于机器人在表示浮点方面并不是无可挑剔的,因此,你看到的值可能会不准确。

# given initial variables
p = initialize_robot(5)
pHit  = 0.6
pMiss = 0.2

# Creates a new grid, with modified probabilities, after sensing
# All values are calculated by a product of 1. the sensing probability for a color (pHit for red)
# and 2. the current probability of a robot being in that location p[i]; all equal to 0.2 at first.
p[0] = p[0]*pMiss
p[1] = p[1]*pHit
p[2] = p[2]*pHit
p[3] = p[3]*pMiss
p[4] = p[4]*pMiss

print(p)
display_map(p)

你应该看到红色网格单元格(1和2)的概率高于绿色单元格。但奇怪的是,这些概率条竟然那么低,同时,你可能已经注意到,这些不能准确地表示概率分布,因为这个列表中的分量总和不是1!

练习:计算所有概率的总和。

这些值加起来是多少?你认为我们如何将其转化为一个其分量总和为1的概率分布,?

在下一个代码单元格中,编写一段代码,计算一个新空间中的概率值p 的总和。

# What is the sum of all the values in p?

## TODO: add up all the values in the list of location probabilities to determine the answer