The Wayback Machine - https://web.archive.org/web/20240824142806/https://www.geeksforgeeks.org/ml-monte-carlo-tree-search-mcts/
Open In App

ML | Monte Carlo Tree Search (MCTS)

Last Updated : 23 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Introduction :

Monte Carlo Tree Search (MCTS) is a heuristic search set of rules that has won big attention and reputation within the discipline of synthetic intelligence, specially in the area of choice-making and game playing. It is known for its ability to effectively handle complex and strategic video games with massive search areas, in which traditional algorithms may additionally struggle due to the full-size number of feasible actions or actions.

MCTS combines the standards of Monte Carlo strategies, which rely upon random sampling and statistical evaluation, with tree-primarily based search techniques. Unlike traditional search algorithms that rely upon exhaustive exploration of the entire seek area, MCTS specializes in sampling and exploring only promising areas of the hunt area.

The center idea in the back of MCTS is to build a seek tree incrementally by using simulating more than one random performs (regularly known as rollouts or playouts) from the current recreation nation. These simulations are carried out until a terminal state or a predefined intensity is reached. The results of these simulations are then backpropagated up the tree, updating the records of the nodes visited at some stage in the play, which includes the wide variety of visits and the win ratios.

As the search progresses, MCTS dynamically balances exploration and exploitation. It selects moves through considering both the exploitation of notably promising movements with high win ratios and the exploration of unexplored or less explored moves. This balancing is finished through the usage of an top confidence sure (UCB) components, which includes the Upper Confidence Bounds for Trees (UCT), to decide which moves or nodes to visit for the duration of the hunt.

MCTS has been efficiently implemented in numerous domains, including board games (e.G., Go, chess, and shogi), card video games (e.G., poker), and video games. It has done splendid overall performance in lots of challenging recreation-gambling scenarios, frequently surpassing human understanding. MCTS has also been prolonged and tailored to deal with different trouble domains, which include making plans, scheduling, and optimization.

One of the exquisite blessings of MCTS is its ability to handle video games with unknown or imperfect data, as it relies on statistical sampling as opposed to whole know-how of the game state. Additionally, MCTS is scalable and may be parallelized efficaciously, making it suitable for disbursed computing and multi-core architectures.

Monte Carlo Tree Search (MCTS) is a search technique in the field of Artificial Intelligence (AI). It is a probabilistic and heuristic driven search algorithm that combines the classic tree search implementations alongside machine learning principles of reinforcement learning.
In tree search, there’s always the possibility that the current best action is actually not the most optimal action. In such cases, MCTS algorithm becomes useful as it continues to evaluate other alternatives periodically during the learning phase by executing them, instead of the current perceived optimal strategy. This is known as the ” exploration-exploitation trade-off “. It exploits the actions and strategies that is found to be the best till now but also must continue to explore the local space of alternative decisions and find out if they could replace the current best.
Exploration helps in exploring and discovering the unexplored parts of the tree, which could result in finding a more optimal path. In other words, we can say that exploration expands the tree’s breadth more than its depth. Exploration can be useful to ensure that MCTS is not overlooking any potentially better paths. But it quickly becomes inefficient in situations with large number of steps or repetitions. In order to avoid that, it is balanced out by exploitation. Exploitation sticks to a single path that has the greatest estimated value. This is a greedy approach and this will extend the tree’s depth more than its breadth. In simple words, UCB formula applied to trees helps to balance the exploration-exploitation trade-off by periodically exploring relatively unexplored nodes of the tree and discovering potentially more optimal paths than the one it is currently exploiting. 
For this characteristic, MCTS becomes particularly useful in making optimal decisions in Artificial Intelligence (AI) problems. 

Why use Monte Carlo Tree Search (MCTS) ?

Here are some reasons why MCTS is commonly used:

  1. Handling Complex and Strategic Games: MCTS excels in games with large search spaces, complex dynamics, and strategic decision-making. It has been successfully applied to games like Go, chess, shogi, poker, and many others, achieving remarkable performance that often surpasses human expertise. MCTS can effectively explore and evaluate different moves or actions, leading to strong gameplay and decision-making in such games.
  2. Unknown or Imperfect Information: MCTS is suitable for games or scenarios with unknown or imperfect information. It relies on statistical sampling and does not require complete knowledge of the game state. This makes MCTS applicable to domains where uncertainty or incomplete information exists, such as card games or real-world scenarios with limited or unreliable data.
  3. Learning from Simulations: MCTS learns from simulations or rollouts to estimate the value of actions or states. Through repeated iterations, MCTS gradually refines its knowledge and improves decision-making. This learning aspect makes MCTS adaptive and capable of adapting to changing circumstances or evolving strategies.
  4. Optimizing Exploration and Exploitation: MCTS effectively balances exploration and exploitation during the search process. It intelligently explores unexplored areas of the search space while exploiting promising actions based on existing knowledge. This exploration-exploitation trade-off allows MCTS to find a balance between discovering new possibilities and exploiting known good actions.
  5. Scalability and Parallelization: MCTS is inherently scalable and can be parallelized efficiently. It can utilize distributed computing resources or multi-core architectures to speed up the search and handle larger search spaces. This scalability makes MCTS applicable to problems that require significant computational resources.
  6. Applicability Beyond Games: While MCTS gained prominence in game-playing domains, its principles and techniques are applicable to other problem domains as well. MCTS has been successfully applied to planning problems, scheduling, optimization, and decision-making in various real-world scenarios. Its ability to handle complex decision-making and uncertainty makes it valuable in a range of applications.
  7. Domain Independence: MCTS is relatively domain-independent. It does not require domain-specific knowledge or heuristics to operate. Although domain-specific enhancements can be made to improve performance, the basic MCTS algorithm can be applied to a wide range of problem domains without significant modifications.

  
Monte Carlo Tree Search (MCTS) algorithm: 
In MCTS, nodes are the building blocks of the search tree. These nodes are formed based on the outcome of a number of simulations. The process of Monte Carlo Tree Search can be broken down into four distinct steps, viz., selection, expansion, simulation and backpropagation. Each of these steps is explained in details below: 
 

  • Selection: In this process, the MCTS algorithm traverses the current tree from the root node using a specific strategy. The strategy uses an evaluation function to optimally select nodes with the highest estimated value. MCTS uses the Upper Confidence Bound (UCB) formula applied to trees as the strategy in the selection process to traverse the tree. It balances the exploration-exploitation trade-off. During tree traversal, a node is selected based on some parameters that return the maximum value. The parameters are characterized by the formula that is typically used for this purpose is given below. 
     

UCBf

  • where; 
    Si = value of a node i 
    xi = empirical mean of a node i 
    C = a constant 
    t = total number of simulations
    When traversing a tree during the selection process, the child node that returns the greatest value from the above equation will be one that will get selected. During traversal, once a child node is found which is also a leaf node, the MCTS jumps into the expansion step.
  • Expansion: In this process, a new child node is added to the tree to that node which was optimally reached during the selection process.
  • Simulation: In this process, a simulation is performed by choosing moves or strategies until a result or predefined state is achieved.
  • Backpropagation: After determining the value of the newly added node, the remaining tree must be updated. So, the backpropagation process is performed, where it backpropagates from the new node to the root node. During the process, the number of simulation stored in each node is incremented. Also, if the new node’s simulation results in a win, then the number of wins is also incremented.

The above steps can be visually understood by the diagram given below: 
 

mcts_vis

These types of algorithms are particularly useful in turn based games where there is no element of chance in the game mechanics, such as Tic Tac Toe, Connect 4, Checkers, Chess, Go, etc. This has recently been used by Artificial Intelligence Programs like AlphaGo, to play against the world’s top Go players. But, its application is not limited to games only. It can be used in any situation which is described by state-action pairs and simulations used to forecast outcomes.
Pseudo-code for Monte Carlo Tree search: 
 

Python3




# main function for the Monte Carlo Tree Search
def monte_carlo_tree_search(root):
     
    while resources_left(time, computational power):
        leaf = traverse(root)
        simulation_result = rollout(leaf)
        backpropagate(leaf, simulation_result)
         
    return best_child(root)
 
# function for node traversal
def traverse(node):
    while fully_expanded(node):
        node = best_uct(node)
         
    # in case no children are present / node is terminal
    return pick_unvisited(node.children) or node
 
# function for the result of the simulation
def rollout(node):
    while non_terminal(node):
        node = rollout_policy(node)
    return result(node)
 
# function for randomly selecting a child node
def rollout_policy(node):
    return pick_random(node.children)
 
# function for backpropagation
def backpropagate(node, result):
    if is_root(node) return
    node.stats = update_stats(node, result)
    backpropagate(node.parent)
 
# function for selecting the best child
# node with highest number of visits
def best_child(node):
    pick child with highest number of visits


As we can see, the MCTS algorithm reduces to a very few set of functions which we can use any choice of games or in any optimizing strategy.
Advantages of Monte Carlo Tree Search: 
 

  1. MCTS is a simple algorithm to implement.
  2. Monte Carlo Tree Search is a heuristic algorithm. MCTS can operate effectively without any knowledge in the particular domain, apart from the rules and end conditions, and  can find its own moves and learn from them by playing random playouts.
  3. The MCTS can be saved in any intermediate state and that state can be used in future use cases whenever required.
  4. MCTS supports asymmetric expansion of the search tree based on the circumstances in which it is operating.

Disadvantages of Monte Carlo Tree Search: 
 

  1. As the tree growth becomes rapid after a few iterations, it requires a huge amount of memory.
  2. There is a bit of a reliability issue with Monte Carlo Tree Search. In certain scenarios, there might be a single branch or path, that might lead to loss against the opposition when implemented for those turn-based games. This is mainly due to the vast amount of combinations and each of the nodes might not be visited enough number of times to understand its result or outcome in the long run.
  3. MCTS algorithm needs a huge number of iterations to be able to effectively decide the most efficient path. So, there is a bit of a speed issue there.

Issues in  Monte Carlo Tree Search: 
 

Here are some common issues associated with MCTS:

  1. Exploration-Exploitation Trade-off: MCTS faces the challenge of balancing exploration and exploitation during the search. It needs to explore different branches of the search tree to gather information about their potential, while also exploiting promising actions based on existing knowledge. Achieving the right balance is crucial for the algorithm’s effectiveness and performance.
  2. Sample Efficiency: MCTS can require a large number of simulations or rollouts to obtain accurate statistics and make informed decisions. This can be computationally expensive, especially in complex domains with a large search space. Improving the sample efficiency of MCTS is an ongoing research area.
  3. High Variance: The outcomes of individual rollouts in MCTS can be highly variable due to the random nature of the simulations. This can lead to inconsistent estimations of action values and introduce noise in the decision-making process. Techniques such as variance reduction and progressive widening are used to mitigate this issue.
  4. Heuristic Design: MCTS relies on heuristics to guide the search and prioritize actions or nodes. Designing effective and domain-specific heuristics can be challenging, and the quality of the heuristics directly affects the algorithm’s performance. Developing accurate heuristics that capture the characteristics of the problem domain is an important aspect of using MCTS.
  5. Computation and Memory Requirements: MCTS can be computationally intensive, especially in games with long horizons or complex dynamics. The algorithm’s performance depends on the available computational resources, and in resource-constrained environments, it may not be feasible to run MCTS with a sufficient number of simulations. Additionally, MCTS requires memory to store and update the search tree, which can become a limitation in memory-constrained scenarios.
  6. Overfitting: In certain cases, MCTS can overfit to specific patterns or biases present in the early simulations, which can lead to suboptimal decisions. To mitigate this issue, techniques such as exploration bonuses, progressive unpruning, and rapid action-value estimation have been proposed to encourage exploration and avoid premature convergence.
  7. Domain-specific Challenges: Different domains and problem types can introduce additional challenges and issues for MCTS. For example, games with hidden or imperfect information, large branching factors, or continuous action spaces require adaptations and extensions of the basic MCTS algorithm to handle these complexities effectively.
     


Previous Article
Next Article

Similar Reads

Monte Carlo Policy Evaluation
Monte Carlo policy evaluation is a technique within the field of reinforcement learning that estimates the effectiveness of a policy—a strategy for making decisions in an environment. It’s a bit like learning the rules of a game by playing it many times, rather than studying its manual. This approach doesn't require a pre-built model of the environ
7 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children.  Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w
2 min read
Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Difference between Best-First Search and A* Search?
Best-First Search: Best-First search is a searching algorithm used to find the shortest path which uses distance as a heuristic. The distance between the starting node and the goal node is taken as heuristics. It defines the evaluation function for each node n in the graph as f(n) = h(n) where h(n) is heuristics function. A*Search: A*search is a se
2 min read
Comparing Randomized Search and Grid Search for Hyperparameter Estimation in Scikit Learn
Hyperparameters are the parameters that determine the behavior and performance of a machine-learning model. These parameters are not learned during training but are instead set prior to training. The process of finding the optimal values for these hyperparameters is known as hyperparameter optimization, and it is an important step in the developmen
8 min read
CatBoost Grid search and random search
Finding the best model and setting it up for optimum performance may be difficult in the realm of machine learning. Thankfully, methods like Grid Search and Random Search may be used to help. We shall clarify these techniques in this article, focusing on CatBoost, a potential gradient-boosting library. Building precise and effective machine learnin
8 min read
Ball Tree and KD Tree Algorithms
Ball tree and KD-tree (K-Dimensional tree) are sophisticated data structures used in Python for efficiently organizing and searching multidimensional data. Imagine the ball tree algorithm as a way of grouping points into a tree structure by enclosing them within hyperspheres. This clever organization facilitates speedy searches for the nearest neig
14 min read
Search Algorithms in AI
Artificial Intelligence is the study of building agents that act rationally. Most of the time, these agents perform some kind of search algorithm in the background in order to achieve their tasks. A search problem consists of: A State Space. Set of all possible states where you can be.A Start State. The state from where the search begins.A Goal Sta
10 min read
Elasticsearch Search Engine | An introduction
Elasticsearch is a full-text search and analytics engine based on Apache Lucene. Elasticsearch makes it easier to perform data aggregation operations on data from multiple sources and to perform unstructured queries such as Fuzzy Searches on the stored data. It stores data in a document-like format, similar to how MongoDB does it. Data is serialize
5 min read
Selective Search for Object Detection | R-CNN
The problem of object localization is the most difficult part of object detection. One approach is that we use sliding window of different size to locate objects in the image. This approach is called Exhaustive search. This approach is computationally very expensive as we need to search for object in thousands of windows even for small image size.
6 min read
Difference between Informed and Uninformed Search in AI
What is an Informed Search in AI? algorithms have information on the goal state which helps in more efficient searching. This information is obtained by a function that estimates how close a state is to the goal state. Informed search in AI is a type of search algorithm that uses additional information to guide the search process, allowing for more
5 min read
Search Techniques in Cyber Forensics
Computer forensic examinations uses computer generated data as their vital source. The goal of any given computer forensic examination is to find facts, and through these facts they try to recreate truth of an event. These Automated Search Techniques are used to find out whether given type of object such as hacking tools or pictures of specific typ
4 min read
Google Search Techniques
The Google search engine is fantastic search engine, which is quite easy to use but by knowing some techniques you can have the best result of your search. Getting information is easy but having the best of them is not quite common. The first thing which is quite common is Google Search button, which is activated by enter or return key in the keybo
2 min read
Docker - Search Image in Dockerhub through CLI
There are tons of pre-built Docker Images that you can find on Docker's official repository called DockerHub. In fact, you can also push your own customized Image on DockerHub. These Images can then be pulled using the Docker pull command and can be used as Base Images. In this article, we will discuss how you can search a Docker Image on DockerHub
2 min read
Google Search Techniques | Set 2
Prerequisite - Google Search Techniques Google's results are quite boring, not getting the actual format of files that we want or not getting PDF of a particular content which we want. Here are some techniques that help you to get your desired results. Let us have some techniques to get out of such boring practices of searching for everything. Let
3 min read
Generate and Test Search
Introduction: Generate and Test Search is a heuristic search technique based on Depth First Search with Backtracking which guarantees to find a solution if done systematically and there exists a solution. In this technique, all the solutions are generated and tested for the best solution. It ensures that the best solution is checked against all pos
5 min read
Current Best Hypothesis Search
Introduction : Current Best Hypothesis Search (CBHS) is a machine learning algorithm that focuses on finding the best hypothesis (or solution) to a problem, given a set of observed data. CBHS is commonly used in situations where there is a large search space, and it is not possible to exhaustively search the entire space to find the optimal solutio
5 min read
Implement Phonetic Search in Python with Soundex Algorithm
In this article, we will cover word similarity matching using the Soundex algorithm in Python. What is Soundex Algorithm and how does it work? Soundex is a phonetic algorithm that can locate phrases with similar sounds. A Soundex search method takes a word as input, such as a person's name, and outputs a character string that identifies a group of
6 min read
Similarity Search for Time-Series Data
Time-series analysis is a statistical approach for analyzing data that has been structured through time. It entails analyzing past data to detect patterns, trends, and anomalies, then applying this knowledge to forecast future trends. Time-series analysis has several uses, including in finance, economics, engineering, and the healthcare industry. T
15+ min read
Difference Between Greedy Best First Search and Hill Climbing Algorithm
AI algorithms, or Artificial Intelligence algorithms, are computational procedures or methods designed to solve problems and perform tasks that would typically require human intelligence. These algorithms are fundamental components of artificial intelligence systems and play a crucial role in various applications across different domains. Pre-requi
4 min read
Introduction to Beam Search Algorithm
In artificial intelligence, finding the optimal solution to complex problems often involves navigating vast search spaces. Traditional search methods like depth-first and breadth-first searches have limitations, especially when it comes to efficiency and memory usage. This is where the Beam Search algorithm comes into play. Beam Search is a heurist
5 min read
Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
Given a rooted tree, and two nodes are in the tree, find the Lowest common ancestor of both the nodes. The LCA for two nodes u and v is defined as the farthest node from the root that is the ancestor to both u and v. Prerequisites: LCA | SET 1 Example for the above figure : Input : 4 5 Output : 2 Input : 4 7 Output : 1 Converting LCA to RMQ(Range M
15+ min read
Python | Decision Tree Regression using sklearn
Decision Tree is a decision-making tool that uses a flowchart-like tree structure or is a model of decisions and all of their possible results, including outcomes, input costs, and utility.Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables. The bra
4 min read
NLP | Creating Shallow Tree
Prerequisite: Flattening Deep Tree We have flattened a Deep Tree by only keeping the lowest level subtrees. But here we can keep the highest level subtrees instead. Code #1 : Lets' understand shallow_tree() from nltk.tree import Tree def shallow_tree(tree): children = [] for t in tree: if t.height() < 3: children.extend(t.pos()) else: children.a
2 min read
NLP | Flattening Deep Tree
Some of the corpora that we use are often deep trees of nested phrases. But working on such deep trees is a tedious job for training the chunker. As IOB tag parsing is not designed for nested chunks. So, in order to use these trees for chunker training, we must flatten them. Well, POS (part of Speech) are actually part of the tree structure instead
2 min read
NLP | Chunk Tree to Text and Chaining Chunk Transformation
We can convert a tree or subtree back to a sentence or chunk string. To understand how to do it - the code below uses the first tree of the treebank_chunk corpus. Code #1: Joining the words in a tree with space. C/C++ Code # Loading library from nltk.corpus import treebank_chunk # tree tree = treebank_chunk.chunked_sents()[0] print ("Tree
3 min read
ML | Logistic Regression v/s Decision Tree Classification
Logistic Regression and Decision Tree classification are two of the most popular and basic classification algorithms being used today. None of the algorithms is better than the other and one's superior performance is often credited to the nature of the data being worked upon. We can compare the two algorithms on different categories - CriteriaLogis
2 min read
ML | Extra Tree Classifier for Feature Selection
Prerequisites: Decision Tree Classifier Extremely Randomized Trees Classifier(Extra Trees Classifier) is a type of ensemble learning technique which aggregates the results of multiple de-correlated decision trees collected in a "forest" to output it's classification result. In concept, it is very similar to a Random Forest Classifier and only diffe
6 min read
Proto Van Emde Boas Tree | Set 3 | Insertion and isMember Query
Please see previous articles on Proto Van Emde Boas Tree to understand these properly. Procedure for Insert: Base Case: If the size of Proto-VEB is 2 then assign true to the bit array( Here we in code we assign Proto-VEB(1) due to recursive structure and so now it is not nullptr and it act as true ) at the position of key.Until we reach at the base
9 min read
Proto Van Emde Boas Tree | Set 5 | Queries: Minimum, Maximum
Please check previous sets of Proto Van Emde Boas Tree article first. It is highly recommended. Procedure for finding minimum: Base Case: If the size of Proto-VEB is 2 then we will return smallest key present in the cluster if no keys present then we will return -1 as the symbol that no keys are present.Recursion: We will start recursion over summa
12 min read