Home > Articles > Programming > Java

Building a Light-Seeking Robot with Q-Learning

Q-Learning is a well-known algorithm that allows machines to learn while unsupervised. The Lego Mindstorms kit, along with leJOS, contains everything needed to implement this fascinating algorithm. This article demonstrates how to build a robot that will learn to seek out a bright light.
Like this article? We recommend

One of the most powerful aspects of Lego Mindstorms is that it can be programmed to do whatever we want it to do. This can be interesting, but often these types of projects are very predictable. Rather than doing what we tell it to do, an even more fascinating robot would have the ability to learn on its own. The field of AI has produced numerous algorithms for learning. There are essentially two large subdivisions of learning (which apply to animals as well as robots): supervised learning and unsupervised learning.

Supervised learning is often accomplished using neural networks. In a supervised learning situation, a robot is given input/output pairs and, after many examples, it develops its own function that can decide what to do with a given input. For example, a computer hooked up to a camera could be shown a series of satellite photographs of a forest. Some of the pictures could contain tanks hiding in the trees, and others could be regular unoccupied forest. One photo after another, the robot is shown a picture and told whether or not tanks are present in the scene. Once the teaching process is done, a new picture is shown to the robot and it tries to identify whether or not a tank is present. This type of problem is ideal for neural networks. The robot in this situation is learning passively; that is, after each photograph is shown, it doesn't take an action or make any statements. It just sits back and learns.

Even more interesting than supervised learning is unsupervised learning. This type of robot receives feedback from each action it performs, which allows it to judge how effective the action was. The feedback is extracted from the environment, either through sensors or internal states such as counting. This feedback is then classified as a reward (or reinforcement). An algorithm decides the value of the reward, which can be either positive or negative. These built-in rewards are very similar to the instincts and feelings that guide humans and other animals. A small sampling of reinforcements that guide your typical day are hunger, pain, enjoyment of food, and sensing cold temperatures.

There are three main advantages of reinforcement learning:

  • Very little programming is required because the robot figures out the algorithm itself.

  • If the environment changes, it doesn't need to be reprogrammed. Even if the robot design is altered, it will relearn the optimal algorithm.

  • If the learning algorithm is properly designed, the robot is guaranteed to find the most efficient policy.

Reinforcement learning shines when given a complex problem. Any problem with many different states and actions—so many that it is complicated for humans to fathom—is ideal for reinforcement learning. In robotics, if you want to program a six-legged walking robot, you need to understand which direction each of the motors turns, you need to pay attention to the sensors that indicate leg position relative to the others, and you need to pay attention to a myriad of physical conditions such as balance. This can be downright complex because a simple pair of wires that are reversed could throw everything off. With reinforcement learning, the robot can sit there experimenting with different walking gaits, measure how far a gait has caused it to move, and the best gait will reveal itself with enough reinforcement. The user could then change the length of the robot legs, change motor sizes, and reverse wires; and the robot will readapt to the new hardware. If the walking-algorithm were manually programmed everything would need to be reprogrammed.

There are two types of unsupervised reinforcement learning. The first requires a model of the world so it can make proper decisions. For example, a self-learning chess program would need to know the position of all the pieces and all the available moves to both players in order to make an informed decision. This can be complex because it needs to keep many statistics. The second type uses an action-value model, which creates a function to deal with different states. This is known as Q-Learning.

The rest of this article will reveal more about Q-Learning, including the algorithm and the parts that make up that algorithm. This includes building and programming a real Lego Mindstorms robot with Java. The result will be a light-seeking robot that uses Q-Learning to produce a light-seeking algorithm.

The Q-Learning Algorithm

A Q-Learning robot can determine the value of an action right after the action is performed, and doesn't need to know about the larger world model. It just needs to know the available actions for each step. Because it requires no model, it is much simpler to program than other learning algorithms.

Q-Learning values are built on a reward scheme. We need to design a reward algorithm that will motivate our robot to perform a goal-oriented behavior. For this project, we'll create a goal-based robot that is rewarded for finding brighter areas of light. This turns out to be very easy to do, using the following criteria:

  1. Goal: Approach Light. The value of the current light reading minus the last light reading determines the reward (greater increase = greater reward). So if the current light reading is 56 and the previous light reading was 53, it receives a reward of +3.

  2. Goal: Avoid Obstacles. If one of the bumpers is pressed, the reward is -2.

  3. Goal: Avoid Staying Still. If the light reading hasn't changed in the last five steps, it receives a negative reward of -2. Presumably, if the robot is receiving identical light readings for five or more steps in a row, it is hung up or not moving.

So how are the actual Q-Values calculated? Basically we just need an equation that increases the Q-Value when a reward is positive, decreases the value when it is negative, and holds the value at equilibrium when the Q-Values are optimal. The equation is as follows:

Q(a,i)fl Q(a,i) + ß(R(i) + Q(a1,j) - Q(a,i))

where the following is true:

Q—a table of Q-values
a—previous action
i—previous state
j—the new state that resulted from the previous action
a1—the action that will produce the maximum Q value
ß-—the learning rate (between 0 and 1)
R—the reward function

NOTE

This calculation must occur after an action has taken place, so the robot can determine how successful the action was (hence, why previous action and previous state are used).

In order to implement this algorithm, all movement by the robot must be segregated into steps. Each step consists of reading the percepts, choosing an action, and evaluating how well the action performed. All Q-values will presumably be equal to zero for the first step, but during the next step (when the algorithm is invoked), it will set a Q-Value for Q(a,i) that will be a product of the reward it received for the last action. So as the robot moves along, the Q-values are calculated repeatedly, gradually becoming more refined (and more accurate).

In order to better understand the overall flow of the program, it would be useful to examine this in abstract. The abstract algorithm would look something like this:

repeat(forever): 
input = getInputs() 
action = chooseAction(inputs, qvalues) 
apply(action) 
qvalues=updateQvalues(qvalues, getFeedback() ) 

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020