Showing posts with label Reward function. Show all posts
Showing posts with label Reward function. Show all posts

February 23, 2022

3d1 Pipeline for robot programming

< 3d The bottleneck in robot programming

The following simple pipeline allows to create fully autonomous robots for all domains:
1. Create a simulation with object oriented programming
2. control the robot in the simulation with teleoperation
3. Extract features like distance to goal and angle of the robot
4. convert the features into a cost function
A cost function in a simulation allows to solve the concrete domain. If such a cost function is available the domain was grounded.
 

February 20, 2022

3a1e Improved production line robot

 < 3a1d Programming an assembly line robot



In addition to the previous simulation game, the GUI was improved a lot. The robot has to sort the tokens but this time the task is more complicated. Also the performance evaluation was improved, so the robot needs to adjust it's movements.
One thing remains the same. The robot isn't controlled by an AI, but the game is played by human intervention. That means the operator has to press the arrow keys and this will trigger the actions of the robot. The AI is located in the referee, that means, the box with the performance information on the left lower side is generated by software on the fly.
For example, if the robot worker has placed the token into the wrong bin, his reward is reduced by -4. Also if the robot keeps on walking even the energy level is low, a negative reward is the result. Why this performance evaluation is needed is because of grounding reasons. The task of navigating a robot in a factory is translated into a score. That means it is not important what exactly the robot is doing but the only thing who cares is the measured reward.
At the end of the game it is pretty easy to judge what the robot has done. For example he has executed 16 picks, has reached an overall score of 11 and it took a time of 92 seconds. All the quality criteria are available as numerical integer values, that means, they can be stored in a computer program very well. In contrast, the original domain which has to do with sorting tokens by color and place them to the correct position are hard or even not possible to understand by a computer. So we can say, that the shown game is an example for a grounded Artificial Intelligence.
 
Let us take a look into the game itself. The incoming line on the left side delivers new tokens in random order. The task for the robot work is to sort them by putting them on the outgoing lines on the right side. So it is some sort of pick&place task.
The interesting situation is, that the robot worker isn't controlled by a sophisticated Artificial Intelligence but it is working in the teloperated mode. That means, the shown simulation is a normal computer game. After pressing the keys the robot is doing something. The new and advanced element is, that the virtual referee determines very precisely if the action is making sense or not. That means, every action of the robot is tracked, monitored and translated into a reward score. The robot worker is under total surveillance and has to explain itself for everything. So it is a highly accurate scoring system to determine the performance of the robot.
On the first look such a game doesn't look very pleasant, because human workers doesn't like the idea to be monitored. But from the perspective of Artificial Intelligence it makes a lot of sense. Because such a domain is a great testbed for an optimal control algorithm. The domain has possible actions (up,down, left, right), and the domain provides a feedback stored in the total reward. The feedback is a numerical value and the task for the model predictive control algorithm is pretty easy. The goal is to maximize the reward. This is equal to win the game.
Here the pipeline in short:
Teleoperation -> simulation -> features -> cost function
 
Playing the game with an algorithm
How humans are playing such games is easy. They are looking at the monitor and decide which actions should be done next. With a bit of training a human operator will reach a better performance and for sure he will make some minor mistakes after repeating the actions over and over again.
The more interesting question is how will an optimal control algorithm play the game. The algorithm doesn't have any sort of human intelligence so he has to focus on the information box on the left lower side. The box contains the variables: elapsed time, energy, picks, totalward reward.
From a computer perspective these variables are stored in an integer array which contains of 4 elements. In addition the computer will need another variable to store possible actions for the robot (0=left, 1=up, and so on). The interesting thing is, that with this minimalist information a computer is able to play the game. There are many existing algorithm available to determine the optimal action sequence. Most of them are working with graph search which is improved by the reward information.
 
The inner working of the AI
In the concrete example it is possible to explain who the AI is working. The normal conception is that the robot is doing something and the robot should be determine by it's own intelligence which action is the best one. So the question is how exactly does the AI know, that the the robot has to go the charging station or place the token to the correct place?
The surprising answer is, that the robot doesn't know the answer. What is available instead is a virtual referee. The referee determines the score during the game. He determines if the action was good or not. Such a referee is used in most video games to determine the collision of a player with walls. Here in the production line simulation the referee is more advanced and determines many other details. The interesting situation is that the referee can judge about human players and AI Controlled robots itself. So the new understanding is, that the robot doesn't need an onboard AI, but the game needs a virtual referee.
This referee allows to ground a game. Grounding means to convert the pixel map which is 320x200 into a small list of variables shown on the lower left. These small amount of variables are used by a solver to play this game automatically.



February 19, 2022

3a1d Programming an assembly line robot

< 3a1c Game design with petri nets



The picture shows an assembly line simulation game. The user can control a robot in the middle and the task is to sort incoming tokens. The robot has a battery level and all the actions are scored. If the robot puts the wrong token on the outgoing conveyor a certain amount of error costs are created. So the overall objective of the game is to reduce the costs.
Sounds not very complicated, right? The AI is located in the game engine. The game engine determines the score, and simulates pick&place actions in the game. The shown game can be played by a human player very well.
The interesting situation is that such a grounded domain can be automated easily. All what is needed is to solve the given optimization problem. The goal is, to minimize the costs for the robot and the costs are calculated by the game.
 
Let us try to elaborate the situation a bit. In bottom up robotics the idea is to program the robot in a certain way, that he is solving a task. Such a program is not needed here and it wasn't implemented. The idea of top down robotics is, that the AI is equal to the virtual referee. The virtual referee monitors a game and determines the score for a player.
The example simulation allows the robot to do certain actions. It can pick a token, it can place a token, it can walk around and it can charge the battery at the lower position. All these actions have consequences. For example if the battery level is below a certain threshold, the costs for the robot are growing fast. So it is a classical video game, except a strong emphasizes was put on the scoring function.
The interesting situation is that after starting the game in the command line the robot won't do anything. the reason is, that it wasn't the objective to program the robot. Instead the idea is that core element is the scoring function which is located inside the physics engine. What this scoring function is able to do is to judge about the actions. It converts possible behaviors in the game into a score. This score is shown on top left of the screen. It is a numerical feedback about the meaning of actions. Only actions which are generating low costs are sense making.
The principle has to do with social roles. There is an actor which is the robot. In theory, the robot can do anything which includes to put the token on the wrong conveyor. In the game, such actions are producing a higher costs. This virtual referee is sometimes called a critic because he judges about the robot.

February 13, 2022

3a1 Reward function

< 3a 

As an entry level task, a robot can be realized by defining a reward function. A reward function isn't about programming the robot itself, but it defines the game. Or to be more specific, it's a scoring algorithm to evaluate the actions of the players within the game. The player's role can be fulfilled by humans and robots as well. For example, in the famous pong game, the scoring mechanism decides, that player1 gets a +1 score if the opponent player wasn't able to block the ball.
A good scoring mechanism provides a continuous reward. The game can be paused at any moment and the algorithm determines, who has won the game with a floating point number precision level. Visualizing a reward function or a cost function as well, is usually done with a potential field which is heat map.

August 23, 2021

OpenAI gym with a reward function

The OpenAI gym library is the perhaps most important reinforcement learning project available. It provides an out-of-the-box environment for simulating control problems and it gives advice how to solve them with algorithms like q-learning and neural networks. The only problem available is, that no documentation is available how to control the example domains like the inverted pendulum problem.
Let us start with the basics because many newbies doesn't know how to run the simulation in general. After installing the openai library in a Linux or Windows operating system the programmer can utilize the library in Python. A simple example is given in the following sourcecode.

 

import gym
import time, random

class Plaincartpole:
  def __init__(self):
    self.env = gym.make('CartPole-v0')
    observation=self.env.reset()
    for framestep in range(100):
      self.env.render()
      action=random.randint(0,1)
      observation,  reward,  done,  info  =  self.env.step(action)
      print("observation",observation, "reward",reward)
      time.sleep(0.5)
    
if __name__ == '__main__':
  p=Plaincartpole()

 

Apart from the “gym” library itself, two extra Python libraries are imported for generating random actions and for slowing down the simulation. After executing the python script the user should see an inverted pendulum on the screen which is doing something.
On the terminal, the status is shown which contains of the measured features itself and a reward information. This first python script is nothing new or special but most openai Gym tutorials are working with this example. In the for loop of the script, the frame counter is increased and each time step is send to the graphical screen.
After this trivial example is running, the more complicated question is how to control the pendulum. From a technical perspective, the user send the actions (0=left, 1=right) to the pendulum. This will affect the system and the pendulum will swing into a certain direction. It is important to know that the reward will change from 1.0 to 0.0 if the pendulum has reached an angle of greater than 45 degree. That means the game has stopped and the control problem wasn't solved.
For generating a sequence of actions which can stabilize the pendulum the first thing to know is, that the reward provided by openai gym is the bottleneck. The built in reward function isn't providing useful feedback but it is simply a check if the angle is larger than 45 degree or smaller than -45 degree. A second problem with the reward function is, that it can become only 0 or 1 but no value inbetween. This problem can be fixed easily with a self created reward function.

 

import gym
import time, random

class Plaincartpole:
  def __init__(self):
    self.env = gym.make('CartPole-v0')
    observation=self.env.reset()
    for framestep in range(100):
      self.env.render()
      action=random.randint(0,1)
      observation,  reward,  done,  info  =  self.env.step(action)
      # handcrafted reward function
      reward=1-abs(observation[2])
      if reward<0: reward=0
      print("observation",observation, "reward",reward)
      time.sleep(0.5)
    
if __name__ == '__main__':
  p=Plaincartpole()

 

The new reward function measures also the angle of the pole but it provides a more elaborated information. If the pendulum is in the upward position the reward is 1.0 and if it is a bit rotated then the reward is 0.8 and so on. The idea is that the original reward function from the open AI gym environment is overwritten by a self-created function.
This handcrafted reward function can be modified according to the needs of the programmer. The example shows only a very basic version. It is possible to improve it for example by checking if the cart is outside of the visible playfield.
The idea is that random actions are send to the system and then a reward is determined. Before it can be determined what the optimal control action, it should be defined what the goal is. The goal is formalized in the reward function.
Let me give an example. Suppose the goal is to bring the cart into the middle of the playfield. The reward function would be:
      reward=1-abs(observation[0])
      if reward<0: reward=0

 

That means, the feature in the observation variable is converted into a numercial value. This value is 1 if the cart is in the middle, it will decrease to 0.5 if the cart has left the middle and it will be 0 if the cart is outside of the allowed range. In between values are also provided, so it is a continuous reward function.
Or let me give a more advanced example. If the pole should be upwards and the cart should be in the middle the combined reward function is:

 

rewarda=1-abs(observation[2])
if rewarda<0: rewarda=0
rewardb=1-abs(observation[0])
if rewardb<0: rewardb=0
reward=(rewarda+rewardb)/2

 


 

Example

Suppose a reward function was created which determines the position of the cart and ignores the angle of the pole. If the cart is outside of the playfield the reward become zero. The idea is that is cart is moving left or right and while the cart is doing so the reward is shown on the screen. It some sort of score like in a videogame.
That means all the other features which are stored in the observation variable are no longer interesting but only the reward value is monitored. Winning the game means to maximize the reward. And different reward functions will result into different games. A controller which maximizes the cart position reward will produce actions in which the cart is always in the middle and it will never leave the playfield. So the reward function is some sort of constraint which defines what the problem is about.
The interesting point is, that after changing the reward function the game engine remeains the same, that means, the pendulum will fall with the same speed like before. The only new thing is that the reward score is determined different.
Suppose there is a universal policy available which maximizes the reward function. The actions generated by this policy will depend on the reward function. that means, after adjusting the reward function a new behavior is shown on the screen. Or let me explain it the other way around. The forward model of the gym environment aka the simulation remains the same, and the policy which converts a reward signal into actions is also the same. The only variable is the reward function which is handcrafted by a human programmer.





August 21, 2021

Reward function

 

The topic seems to be relevant for robot control. In short the idea is to map measured feature values to a numerical reward value, and then use this value for controlling the robot towards the highest reward. So it is some sort of layer between the robot and the game it is playing.
What the paper doesn't answers is how to create reward functions. There are two opposite approaches available, first idea is to create reward functions with algorithm mainly neural networks, q tables and reward automaton. And the second approach is to handle reward design as a collaborative social activity. This is realized with examples from previous projects and a code repository which holds concrete reward functions. The deepracer project from Amazon goes into this direction.
The interesting point around reward functions is, that it answers the question how to control a robot. Robot control is nothing else than navigating the robot on the reward map. The reward map is an artificial created mathematical model. The advantage is, that the details for games likes tetris, car driving or biped robot simulators can be ignored. That means, the robot doesn't know which game he is playing because the robot sees only the reward map.

February 11, 2020

Extending learning from demonstration into Reward learning from demonstration

The vanilla learning from demonstration idea is about recording the human's demonstration and replay the trajectory on the robot. For example, the human operator is executing a trajectory (100,10),(150,30),(150,80) and this waypoints are used for control the robot's arm.

The disadvantage is, that the connection between demonstration and replay is very static. One option to avoid the cons is to use the demonstration as an indirect pathway. In the literature the concept is called reward learning and the idea is to create a heatmap. The heatmap allows to find many different trajectories which are all bring the robot into the goal state.

A heatmap aka costmap is a visual representation of a learned cost function. The idea is that colors from green to red are shown as overlay picture over the normal map. The information which pixel becomes which color is given by the demonstration of the human operator. Bascially spoken, the human demonstration creates a path in the map, and the path is extended to a colored heatmap. A trajectory planner like RRT is used to find in this map a path.

Clicker training with dogs

In animal training there is a powerful technique available called clicker training. For the newbie the technique is hard to understand. The human trainer is using a noise making device, and feeds the dog with some cookies. After a while the dog is able to do lots of tricks. But how does it work from a technical perspective?

Teaching skills can be done in two forms: direct and indirect. Suppose the idea is to explain who to move from start to goal. This can be done in giving the direct command. At first, the dog has to walk 10 meter ahead, and then he has to go left for 5 meters. The problem with this method is, that the explanation can't be adapted to new situations. For example, if the pathway is blocked, it makes no sense to walk 10 meter ahead. So the question is how to give a tutorial which is more flexible?

Clicker training is working with a cost map. What the human trainer is doing with the noise making device is produce a cost map for the dog. He sets reward points on the map. A reward is a situation in which the dog gets a cookie. The dog labels the point on the map with the positive reward. In the replay mode, the dog is approaching all the +1 rewards on it's reward map and this will make the human trainer happy.

In case of spatial maps, it's not very complicated to imagine such a map. In abstract situation the map looks more complicated. For example, if the goal is not to reach a point in space, but to walk in a circle, it's an abstract behavior. If the dog is smart he can create the cost map for such abstract tasks as well.