### SAT Plan Example 1 Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Example of using SAT_plan with a given transition dictionary and start/end states. ```python transition = {'A': {'Left': 'A', 'Right': 'B'}, 'B': {'Left': 'A', 'Right': 'C'}, 'C': {'Left': 'B', 'Right': 'C'}} print(SAT_plan('A', transition, 'C', 2)) print(SAT_plan('A', transition, 'B', 3)) print(SAT_plan('C', transition, 'A', 3)) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/aimacode/aima-python/blob/master/README.md Navigate to the project directory and install the required Python packages using pip and the requirements.txt file. ```bash cd aima-python pip install -r requirements.txt ``` -------------------------------- ### Install Pytest for Running Tests Source: https://github.com/aimacode/aima-python/blob/master/README.md Install the pytest framework, which is used to run the project's test suite. ```bash pip install pytest ``` -------------------------------- ### Initialize CSP and Run AC3 (Example 2) Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Sets up a CSP with modified constraints and runs the AC3 algorithm. This example demonstrates a scenario where AC3 returns True, indicating a consistent solution was found. ```python constraints = lambda X, x, Y, y: (x % 2) == 0 and (x + y) == 4 removals = [] csp = CSP(variables=None, domains=domains, neighbors=neighbors, constraints=constraints) ``` ```python AC3(csp,removals=removals) ``` -------------------------------- ### Initialize CSP and Run AC3 (Example 1) Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Sets up a CSP with specific neighbors, domains, and constraints, then runs the AC3 algorithm. This example demonstrates a scenario where AC3 returns False, indicating no consistent solution. ```python neighbors = parse_neighbors('A: B; B: ') domains = {'A': [0, 1, 2, 3, 4], 'B': [0, 1, 2, 3, 4]} constraints = lambda X, x, Y, y: x % 2 == 0 and (x + y) == 4 and y % 2 != 0 removals = [] ``` ```python csp = CSP(variables=None, domains=domains, neighbors=neighbors, constraints=constraints) ``` ```python AC3(csp, removals=removals) ``` -------------------------------- ### SAT Plan Example 2 Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Another example of using SAT_plan with a different transition dictionary, including tuple states. ```python transition = {(0, 0): {'Right': (0, 1), 'Down': (1, 0)}, (0, 1): {'Left': (1, 0), 'Down': (1, 1)}, (1, 0): {'Right': (1, 0), 'Up': (1, 0), 'Left': (1, 0), 'Down': (1, 0)}, (1, 1): {'Left': (1, 0), 'Up': (0, 1)}} print(SAT_plan((0, 0), transition, (1, 1), 4)) ``` -------------------------------- ### Setting up the Planning Problem and Angelic Descriptions Source: https://github.com/aimacode/aima-python/blob/master/planning_angelic_search.ipynb This snippet defines a specific planning problem with its initial state and goal, and creates optimistic and pessimistic descriptions for an Angelic High-Level Action (HLA). This setup is crucial for guiding the Angelic Search. ```python shuttle_SFO = HLA('Shuttle(SFOLongTermParking, SFO)', 'Have(Cash) & At(SFOLongTermParking)', 'At(SFO)') prob_3 = Problem('At(SFOLongTermParking) & Have(Cash)', 'At(SFO) & Have(Cash)', [shuttle_SFO]) # optimistic/pessimistic descriptions angelic_opt_description = Angelic_HLA('Shuttle(SFOLongTermParking, SFO)', precond = 'At(SFOLongTermParking)', effect ='$+At(SFO) & $-At(SFOLongTermParking)' ) angelic_pes_description = Angelic_HLA('Shuttle(SFOLongTermParking, SFO)', precond = 'At(SFOLongTermParking)', effect ='$+At(SFO) & ~At(SFOLongTermParking)' ) # initial Plan initialPlan_3 = [Angelic_Node(prob.init, None, [angelic_opt_description], [angelic_pes_description])] ``` -------------------------------- ### OutputLayer with Softmax Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter19/Loss Functions and Layers.ipynb Demonstrates creating an OutputLayer and feeding an example through it. The output can be treated as normalized probabilities. ```python layer = OutputLayer(size=4) example = [1,2,3,4] print(layer.forward(example)) ``` -------------------------------- ### Run the Test Suite Source: https://github.com/aimacode/aima-python/blob/master/README.md Execute the project's test suite using pytest to verify the installation and setup. ```bash py.test ``` -------------------------------- ### Alpha-Beta Visualization Setup Source: https://github.com/aimacode/aima-python/blob/master/games.ipynb Initializes the Canvas_alphabeta visualization for the alpha-beta algorithm with a list of 27 random integers. ```python from notebook import Canvas_alphabeta from random import randint alphabeta_viz = Canvas_alphabeta('alphabeta_viz', [randint(1, 50) for i in range(27)]) ``` -------------------------------- ### Simulation Setup and Run 1 Source: https://github.com/aimacode/aima-python/blob/master/agents.ipynb Initializes the Park environment, BlindDog agent, food, and water. Runs the simulation for 5 steps to observe initial behavior. ```python park = Park() dog = BlindDog(program) dogfood = Food() water = Water() park.add_thing(dog, 1) park.add_thing(dogfood, 5) park.add_thing(water, 7) park.run(5) ``` -------------------------------- ### Setup for Utility Estimation Plotting Source: https://github.com/aimacode/aima-python/blob/master/reinforcement_learning.ipynb Enables matplotlib inline backend and defines a function to collect utility estimates over iterations for plotting. Requires matplotlib and agent program setup. ```python %matplotlib inline import matplotlib.pyplot as plt def graph_utility_estimates(agent_program, mdp, no_of_iterations, states_to_graph): graphs = {state:[] for state in states_to_graph} for iteration in range(1,no_of_iterations+1): run_single_trial(agent_program, mdp) for state in states_to_graph: graphs[state].append((iteration, agent_program.U[state])) for state, value in graphs.items(): state_x, state_y = zip(*value) plt.plot(state_x, state_y, label=str(state)) plt.ylim([0,1.2]) plt.legend(loc='lower right') plt.xlabel('Iterations') plt.ylabel('U') ``` -------------------------------- ### Import and Inspect Iris Dataset Source: https://github.com/aimacode/aima-python/blob/master/learning.ipynb Demonstrates how to import the 'iris' dataset using the `DataSet` class and inspect its first example and input features. This is a common starting point for working with tabular data. ```python iris = DataSet(name="iris") print(iris.examples[0]) print(iris.inputs) ``` -------------------------------- ### Socks and Shoes Planning with PartialOrderPlanner Source: https://github.com/aimacode/aima-python/blob/master/planning_partial_order_planner.ipynb Initializes and executes the PartialOrderPlanner for the Socks and Shoes problem. This example shows a plan with more flexibility, where actions can be reordered as long as dependencies are met. ```python ss = socks_and_shoes() pop = PartialOrderPlanner(ss) pop.execute() ``` -------------------------------- ### Instantiate PeakFindingProblem Source: https://github.com/aimacode/aima-python/blob/master/search.ipynb Initializes a PeakFindingProblem with a starting state, a grid representing the search space, and defined movement directions. ```python problem = PeakFindingProblem(initial, grid, directions8) ``` -------------------------------- ### Restaurant Example Data Structure Function Source: https://github.com/aimacode/aima-python/blob/master/knowledge_current_best.ipynb Defines a helper function `r_example` to construct dictionary representations of restaurant examples. This function is used to create the dataset for the learning algorithm. ```python def r_example(Alt, Bar, Fri, Hun, Pat, Price, Rain, Res, Type, Est, GOAL): return {'Alt': Alt, 'Bar': Bar, 'Fri': Fri, 'Hun': Hun, 'Pat': Pat, 'Price': Price, 'Rain': Rain, 'Res': Res, 'Type': Type, 'Est': Est, 'GOAL': GOAL} ``` -------------------------------- ### Weighted Sample Generation Example Source: https://github.com/aimacode/aima-python/blob/master/probability.ipynb An example of generating a weighted sample from the 'sprinkler' Bayesian Network with evidence 'Rain=True'. Returns the sampled event and its associated weight. ```python weighted_sample(sprinkler, dict(Rain=True)) ``` -------------------------------- ### Restaurant Dataset Initialization Source: https://github.com/aimacode/aima-python/blob/master/knowledge_current_best.ipynb Initializes the 'restaurant' dataset using the `r_example` function. This dataset contains various attributes and a 'WillWait' goal for each example, used to train the learning algorithm. ```python restaurant = [ r_example('Yes', 'No', 'No', 'Yes', 'Some', '$$$', 'No', 'Yes', 'French', '0-10', True), r_example('Yes', 'No', 'No', 'Yes', 'Full', '$', 'No', 'No', 'Thai', '30-60', False), r_example('No', 'Yes', 'No', 'No', 'Some', '$', 'No', 'No', 'Burger', '0-10', True), r_example('Yes', 'No', 'Yes', 'Yes', 'Full', '$', 'Yes', 'No', 'Thai', '10-30', True), r_example('Yes', 'No', 'Yes', 'No', 'Full', '$$$', 'No', 'Yes', 'French', '>60', False), r_example('No', 'Yes', 'No', 'Yes', 'Some', '$$', 'Yes', 'Yes', 'Italian', '0-10', True), r_example('No', 'Yes', 'No', 'No', 'None', '$', 'Yes', 'No', 'Burger', '0-10', False), r_example('No', 'No', 'No', 'Yes', 'Some', '$$', 'Yes', 'Yes', 'Thai', '0-10', True), r_example('No', 'Yes', 'Yes', 'No', 'Full', '$', 'Yes', 'No', 'Burger', '>60', False), r_example('Yes', 'Yes', 'Yes', 'Yes', 'Full', '$$$', 'No', 'Yes', 'Italian', '10-30', False), r_example('No', 'No', 'No', 'No', 'None', '$', 'No', 'No', 'Thai', '0-10', False), r_example('Yes', 'Yes', 'Yes', 'Yes', 'Full', '$', 'No', 'No', 'Burger', '30-60', True) ] ``` -------------------------------- ### Define POMDP Parameters for Voicemail Example Source: https://github.com/aimacode/aima-python/blob/master/mdp.ipynb Sets up transition probabilities, evidence function, rewards, discount factor, actions, and states for a voicemail POMDP. ```python # transition function P(s'|s,a) t_prob = [[[0.65, 0.35], [0.65, 0.35]], [[0.65, 0.35], [0.65, 0.35]], [[1.0, 0.0], [0.0, 1.0]]] # evidence function P(e|s) e_prob = [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.8, 0.2], [0.3, 0.7]]] # reward function rewards = [[5, -10], [-20, 5], [-1, -1]] gamma = 0.95 actions = ('0', '1', '2') states = ('0', '1') ``` -------------------------------- ### Define Animals and Umbrellas Example Dataset Source: https://github.com/aimacode/aima-python/blob/master/knowledge_current_best.ipynb Defines a list of dictionaries representing examples for the 'animals taking umbrellas' scenario. Each dictionary includes attributes like 'Species', 'Rain', 'Coat', and the 'GOAL' outcome. ```python animals_umbrellas = [ {'Species': 'Cat', 'Rain': 'Yes', 'Coat': 'No', 'GOAL': True}, {'Species': 'Cat', 'Rain': 'Yes', 'Coat': 'Yes', 'GOAL': True}, {'Species': 'Dog', 'Rain': 'Yes', 'Coat': 'Yes', 'GOAL': True}, {'Species': 'Dog', 'Rain': 'Yes', 'Coat': 'No', 'GOAL': False}, {'Species': 'Dog', 'Rain': 'No', 'Coat': 'No', 'GOAL': False}, {'Species': 'Cat', 'Rain': 'No', 'Coat': 'No', 'GOAL': False}, {'Species': 'Cat', 'Rain': 'No', 'Coat': 'Yes', 'GOAL': True} ] ``` -------------------------------- ### Extend Knowledge Base with Map Logic and Starting Location Source: https://github.com/aimacode/aima-python/blob/master/planning.ipynb Adds logical rules for connection symmetry and transitivity, and sets the initial 'At' proposition for the starting city. This completes the map's logical representation. ```python knowledge_base.extend([ expr("Connected(x,y) ==> Connected(y,x)"), expr("Connected(x,y) & Connected(y,z) ==> Connected(x,z)"), expr("At(Sibiu)") ]) ``` -------------------------------- ### Minimax Game Visualization Setup Source: https://github.com/aimacode/aima-python/blob/master/games.ipynb Imports necessary modules and initializes the Canvas_minimax for visualizing the game. It generates a list of 27 random integers to define the game's state. ```python from notebook import Canvas_minimax from random import randint ``` ```python minimax_viz = Canvas_minimax('minimax_viz', [randint(1, 50) for i in range(27)]) ``` -------------------------------- ### Print First Three Iris Examples Source: https://github.com/aimacode/aima-python/blob/master/learning.ipynb Displays the first three entries in the Iris dataset, showing feature values and their corresponding class labels. ```python print(iris.examples[:3]) ``` -------------------------------- ### Set Initial State for a Custom MDP Source: https://github.com/aimacode/aima-python/blob/master/mdp_apps.ipynb Sets the starting state for the custom MDP. This defines where the agent begins its decision-making process. ```python init = 'class1' ``` -------------------------------- ### Initialize Zebra CSP Source: https://github.com/aimacode/aima-python/blob/master/improving_sat_algorithms.ipynb Initializes the Zebra constraint satisfaction problem. This is the starting point for solving the puzzle using CSP techniques. ```python zebra_csp = Zebra() ``` -------------------------------- ### Initialize and Test Socks and Shoes Problem Source: https://github.com/aimacode/aima-python/blob/master/planning.ipynb Initializes the socks and shoes problem and checks the initial goal state. This helps in understanding the starting conditions before applying actions. ```python socksShoes = socks_and_shoes() socksShoes.goal_test() ``` -------------------------------- ### Define Grammar and Words for Parsing Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter22/Parsing.ipynb Sets up the grammar and the list of words for the 'the wumpus is dead' example. This is a prerequisite for calling the `astar_search_parsing` function. ```python grammar = E0 words = ['the', 'wumpus', 'is', 'dead'] ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Imports the required libraries for graph manipulation, plotting, and visualization. This setup is essential for the subsequent code examples. ```python %matplotlib inline import networkx as nx import matplotlib.pyplot as plt import matplotlib import time ``` -------------------------------- ### Alpha-Beta Search Example Source: https://github.com/aimacode/aima-python/blob/master/games.ipynb Demonstrates finding the best move for player MAX at state A using the alpha-beta search algorithm on the Fig52 game. ```python print(alphabeta_search('A', fig52)) ``` -------------------------------- ### Define OnlineSearchProblem Instance Source: https://github.com/aimacode/aima-python/blob/master/search.ipynb Creates an instance of OnlineSearchProblem to define the search space, start state, and goal state for the LRTA* agent. This setup is crucial for initializing the agent. ```python LRTA_problem = OnlineSearchProblem('State_3', 'State_5', one_dim_state_space) ``` -------------------------------- ### Demonstrate subst Helper Function Usage Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Shows an example of using the `subst` helper function to substitute variables within a First-Order Logic expression. ```python subst({x: expr('Nono'), y: expr('M1')}, expr('Owns(x, y)')) ``` -------------------------------- ### Define Sample Pages and Initialize NLP Variables Source: https://github.com/aimacode/aima-python/blob/master/nlp.ipynb Sets up the Page objects with in-links and out-links, and initializes global NLP variables like pageDict, pages_index, and pages_content for the HITS algorithm. ```python testHTML = """Like most other male mammals, a man inherits an X from his mom and a Y from his dad.""" testHTML2 = "a mom and a dad" pA = Page('A', ['B', 'C', 'E'], ['D']) pB = Page('B', ['E'], ['A', 'C', 'D']) pC = Page('C', ['B', 'E'], ['A', 'D']) pD = Page('D', ['A', 'B', 'C', 'E'], []) pE = Page('E', [], ['A', 'B', 'C', 'D', 'F']) pF = Page('F', ['E'], []) nlp.pageDict = {pA.address: pA, pB.address: pB, pC.address: pC, pD.address: pD, pE.address: pE, pF.address: pF} nlp.pages_index = nlp.pageDict nlp.pages_content ={pA.address: testHTML, pB.address: testHTML2, pC.address: testHTML, pD.address: testHTML2, pE.address: testHTML, pF.address: testHTML2} ``` -------------------------------- ### Sanitize Example by Hiding Class Source: https://github.com/aimacode/aima-python/blob/master/learning.ipynb Demonstrates the `sanitize` function, which replaces non-input values (like the class label) with `None` in a copy of the example. The original example remains unchanged. ```python print("Sanitized:",iris.sanitize(iris.examples[0])) print("Original:",iris.examples[0]) ``` -------------------------------- ### Populate PropDefiniteKB with clauses Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Initializes a `PropDefiniteKB` instance and populates it with the defined clauses. The `tell` method is used to assert each clause into the knowledge base. ```python definite_clauses_KB = PropDefiniteKB() for clause in clauses: definite_clauses_KB.tell(expr(clause)) ``` -------------------------------- ### Load and Prepare MNIST Dataset for Training Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter19/Learners.ipynb Loads the MNIST dataset and prepares training and testing examples, appending labels to image data. Prints the lengths of the training and test datasets. ```Python train_img, train_lbl, test_img, test_lbl = load_MNIST(path="../../aima-data/MNIST/Digits") import numpy as np import matplotlib.pyplot as plt train_examples = [np.append(train_img[i], train_lbl[i]) for i in range(len(train_img))] test_examples = [np.append(test_img[i], test_lbl[i]) for i in range(len(test_img))] print("length of training dataset:", len(train_examples)) print("length of test dataset:", len(test_examples)) ``` -------------------------------- ### Initialize GridMDP with R(s) = 4 Source: https://github.com/aimacode/aima-python/blob/master/mdp.ipynb Configures a GridMDP with positive rewards for all non-terminal states. This setup explores agent behavior in a desirable environment where exits are avoided. ```python sequential_decision_environment = GridMDP([[4, 4, 4, +1], [4, None, 4, -1], [4, 4, 4, 4]], terminals=[(3, 2), (3, 1)]) ``` -------------------------------- ### Initialize Planning Graph Search Source: https://github.com/aimacode/aima-python/blob/master/classical_planning_approaches.ipynb Initializes the planning graph and solution storage. ```python def __init__(self, planning_problem): self.graph = Graph(planning_problem) self.no_goods = [] self.solution = [] ``` -------------------------------- ### Setup Visualization Callback and Controls Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Creates a callback function for visualization and sets up interactive controls like a toggle button for visualization and toggle buttons for selecting extra delay time. These are used to control the playback and speed of the N-Queens solution visualization. ```python visualize_callback = make_visualize(iteration_slider) visualize_button = widgets.ToggleButton(description = "Visualize", value = False) time_select = widgets.ToggleButtons(description='Extra Delay:',options=['0', '0.1', '0.2', '0.5', '0.7', '1.0']) a = widgets.interactive(visualize_callback, Visualize = visualize_button, time_step=time_select) display(a) ``` -------------------------------- ### Getting Object Description with '?' Source: https://github.com/aimacode/aima-python/blob/master/intro.ipynb Append a question mark to a variable or function name to get an abbreviated description of the object in IPython. ```python WalkSAT? ``` -------------------------------- ### Wumpus Environment Setup and Drawing Function Source: https://github.com/aimacode/aima-python/blob/master/agents.ipynb Sets up a Wumpus environment with a specified program and dimensions, and initializes a BlockGrid for visualization. Includes a `draw_grid` function to update the grid's appearance based on the world state and a `step` function to advance the environment and redraw the grid. ```python from ipythonblocks import BlockGrid from agents import * color = {"Breeze": (225, 225, 225), "Pit": (0,0,0), "Gold": (253, 208, 23), "Glitter": (253, 208, 23), "Wumpus": (43, 27, 23), "Stench": (128, 128, 128), "Explorer": (0, 0, 255), "Wall": (44, 53, 57) } def program(percepts): '''Returns an action based on it's percepts''' print(percepts) return input() w = WumpusEnvironment(program, 7, 7) grid = BlockGrid(w.width, w.height, fill=(123, 234, 123)) def draw_grid(world): global grid grid[:] = (123, 234, 123) for x in range(0, len(world)): for y in range(0, len(world[x])): if len(world[x][y]): grid[y, x] = color[world[x][y][-1].__class__.__name__] def step(): global grid, w draw_grid(w.get_world()) grid.show() w.step() ``` -------------------------------- ### Run Beam Search Parsing on Negative Example Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter22/Parsing.ipynb Executes the beam search parsing algorithm on a negative example represented by 'words_swaped' and a given 'grammar'. This demonstrates a failed parse. ```python beam_search_parsing(words_swaped, grammar) ``` -------------------------------- ### Park2D Initialization and Test Run Source: https://github.com/aimacode/aima-python/blob/master/agents.ipynb Initializes a Park2D environment with specified dimensions and colors, adds an agent, food, and water items, and then runs the simulation for a set number of steps. This demonstrates the agent's ability to find and consume resources within the environment. ```python park = Park2D(5,5, color={'EnergeticBlindDog': (200,0,0), 'Water': (0, 200, 200), 'Food': (230, 115, 40)}) dog = EnergeticBlindDog(program) dogfood = Food() water = Water() park.add_thing(dog, [0,0]) park.add_thing(dogfood, [1,2]) park.add_thing(water, [0,1]) morewater = Water() morefood = Food() park.add_thing(morewater, [2,4]) park.add_thing(morefood, [4,3]) print("dog started at [0,0], facing down. Let's see if he found any food or water!") park.run(20) ``` -------------------------------- ### Run Beam Search Parsing on Positive Example Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter22/Parsing.ipynb Executes the beam search parsing algorithm on a positive example represented by 'words' and a given 'grammar'. This demonstrates a successful parse. ```python beam_search_parsing(words, grammar) ``` -------------------------------- ### Perform Version Space Learning and Predict Outcomes Source: https://github.com/aimacode/aima-python/blob/master/knowledge_version_space.ipynb Applies version space learning to the 'party' dataset and iterates through the examples to make predictions. It prints the predicted outcome for each example. ```python V = version_space_learning(party) for e in party: guess = False for h in V: if guess_value(e, h): guess = True break print(guess) ``` -------------------------------- ### Initialize Wumpus World KB Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Initializes an empty `PropKB` instance to store Wumpus World knowledge. ```python wumpus_kb = PropKB() ``` -------------------------------- ### Instantiate QLearningAgent Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter21/Active Reinforcement Learning.ipynb Creates an instance of the QLearningAgent with a specified environment, exploration parameters (Ne, Rplus), and a learning rate (alpha) function. ```python q_agent = QLearningAgent(sequential_decision_environment, Ne=5, Rplus=2, alpha=lambda n: 60./(59+n)) ``` -------------------------------- ### Initialize and Update Git Submodules for Datasets Source: https://github.com/aimacode/aima-python/blob/master/README.md Fetch the necessary datasets by initializing and updating the git submodules. This step may take some time. ```bash git submodule init git submodule update ``` -------------------------------- ### Initialize and Run a 2D Park Simulation Source: https://github.com/aimacode/aima-python/blob/master/agents.ipynb Instantiate a Park2D environment, define colors for elements, add agent and items (Food, Water), and run the simulation for a specified number of steps. ```Python park = Park2D(5,20, color={'BlindDog': (200,0,0), 'Water': (0, 200, 200), 'Food': (230, 115, 40)}) # park width is set to 5, and height to 20 dog = BlindDog(program) dogfood = Food() water = Water() park.add_thing(dog, [0,1]) park.add_thing(dogfood, [0,5]) park.add_thing(water, [0,7]) morewater = Water() park.add_thing(morewater, [0,15]) print("BlindDog starts at (1,1) facing downwards, lets see if he can find any food!") park.run(20) ``` -------------------------------- ### Get Actions for a State Source: https://github.com/aimacode/aima-python/blob/master/games.ipynb Retrieves the list of possible moves from a given state in the Fig52 game. ```python print(fig52.actions('B')) ``` -------------------------------- ### Initialize and Solve N-Queens with Min-Conflicts Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Sets up a 12-Queens CSP instance and solves it using the min-conflicts algorithm, storing the assignment history for visualization. ```python conflicts_instru_queen = make_instru(twelve_queens_csp) result = min_conflicts(conflicts_instru_queen) ``` -------------------------------- ### Load Iris Dataset Source: https://github.com/aimacode/aima-python/blob/master/learning.ipynb Loads the iris dataset for use in algorithm evaluation. This is a prerequisite for all subsequent examples. ```python iris = DataSet(name="iris") ``` -------------------------------- ### Initialize and Query UnixConsultant Source: https://github.com/aimacode/aima-python/blob/master/text.ipynb Initializes a UnixConsultant instance and performs a query to find information on removing a file. Shows how to access the top score and document URL. ```python uc = UnixConsultant() q = uc.query("how do I remove a file") top_score, top_doc = q[0][0], q[0][1] print(top_score, uc.documents[top_doc].url) ``` -------------------------------- ### Initialize Interactive Visualization Widgets Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Sets up and displays interactive widgets, including a slider for iteration control and buttons for visualization and delay settings. This allows users to interact with the graph coloring process. ```python import ipywidgets as widgets from IPython.display import display iteration_slider = widgets.IntSlider(min=0, max=len(coloring_problem1.assignment_history)-1, step=1, value=0) w=widgets.interactive(step_func,iteration=iteration_slider) display(w) visualize_callback = make_visualize(iteration_slider) visualize_button = widgets.ToggleButton(description = "Visualize", value = False) time_select = widgets.ToggleButtons(description='Extra Delay:',options=['0', '0.1', '0.2', '0.5', '0.7', '1.0']) a = widgets.interactive(visualize_callback, Visualize = visualize_button, time_step=time_select) display(a) ``` -------------------------------- ### Get Resulting State from Move Source: https://github.com/aimacode/aima-python/blob/master/games.ipynb Determines the next state after a specific move is made from a current state. ```python print(fig52.result('A', 'a1')) ``` -------------------------------- ### Sigmoid Activation Function Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter19/Loss Functions and Layers.ipynb Illustrates how to get the value and derivative of the sigmoid activation function at a specific point. ```python s = sigmoid() print("Sigmoid at 0:", s.f(0)) print("Deriavation of sigmoid at 0:", s.derivative(0)) ``` -------------------------------- ### Instantiate Planning Problem Source: https://github.com/aimacode/aima-python/blob/master/planning.ipynb Creates an instance of the 'PlanningProblem' class, combining the knowledge base, the defined goals, and the list of all possible actions (flights and drives). ```python prob = PlanningProblem(knowledge_base, goals, [fly_s_b, fly_b_s, fly_s_c, fly_c_s, fly_b_c, fly_c_b, drive]) ``` -------------------------------- ### Get Probability Distribution of a Variable Source: https://github.com/aimacode/aima-python/blob/master/probability4e.ipynb Retrieves the probability distribution for a defined variable. This shows the probabilities of all possible outcomes. ```Python from probability import Variable Earthquake = Variable('Earthquake', 0.002) # The probability distribution for Earthquake P(Earthquake) ``` -------------------------------- ### Initialize and Run SARSA Agent Source: https://github.com/aimacode/aima-python/blob/master/sarsa.ipynb Initializes a SARSA agent with specified environment and learning parameters. It then runs multiple trials to learn utilities and prints the learned utilities for each state. ```python sarsa = SARSALearningAgent(env, Ne=5, Rplus=2, alpha=lambda n: 60. / (59 + n)) for _ in range(200): run_single_trial(sarsa, env) print('Learned SARSA utilities U(s) = max_a Q(s, a):') U = {} for (state, action), q in sarsa.Q.items(): if action is not None: U[state] = max(U.get(state, -float('inf')), q) for state in sorted(U): print(' ', state, '->', round(U[state], 3)) ``` -------------------------------- ### Initialize and Solve N-Queens with Backtracking Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Sets up a 12-Queens CSP instance and solves it using the backtracking search algorithm, storing the assignment history for visualization. ```python twelve_queens_csp = NQueensCSP(12) backtracking_instru_queen = make_instru(twelve_queens_csp) result = backtracking_search(backtracking_instru_queen) ``` -------------------------------- ### Initialize Neural Network Layers Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter19/Learners.ipynb Demonstrates the initialization of layers for a dense neural network, including input, hidden, and output layers. ```Python # initialize the network raw_net = [InputLayer(input_size)] # add hidden layers hidden_input_size = input_size for h_size in hidden_layer_sizes: raw_net.append(DenseLayer(hidden_input_size, h_size)) hidden_input_size = h_size raw_net.append(DenseLayer(hidden_input_size, output_size)) ``` -------------------------------- ### Importing Symbols from a Module Source: https://github.com/aimacode/aima-python/blob/master/intro.ipynb This is a common starting point for aima-python notebooks to import all necessary symbols from a specific module. ```python from logic import * ``` -------------------------------- ### Get Sensor Distribution Source: https://github.com/aimacode/aima-python/blob/master/probability.ipynb Retrieves the conditional probabilities of the sensor model for a given observation. Use `ev=True` for a positive observation. ```python hmm.sensor_dist(ev=True) ``` -------------------------------- ### Get Negative Watched Literal Source: https://github.com/aimacode/aima-python/blob/master/improving_sat_algorithms.ipynb Retrieves the negative watched literal from the internal watch list based on a given index. ```python def get_neg_watched(self, l): return self.__watch_list[l][1] ``` -------------------------------- ### Initialize FolKB with Empty Clauses Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Demonstrates initializing an empty list to store First-Order Logic clauses. ```python clauses = [] ``` -------------------------------- ### Get Positive Watched Literal Source: https://github.com/aimacode/aima-python/blob/master/improving_sat_algorithms.ipynb Retrieves the positive watched literal from the internal watch list based on a given index. ```python def get_pos_watched(self, l): return self.__watch_list[l][0] ``` -------------------------------- ### Basic WalkSAT usage with a simple clause list Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Demonstrates a basic usage of the WalkSAT algorithm with a list of clauses and a probability for random flips. This example shows the algorithm converging to a satisfying assignment. ```python WalkSAT([A, B, ~C, D], 0.5, 100) ``` -------------------------------- ### Initialize Population and Run Genetic Algorithm Source: https://github.com/aimacode/aima-python/blob/master/search.ipynb Creates an initial population and then runs the stepwise genetic algorithm with specified parameters. ```python population = init_population(max_population, gene_pool, len(target)) solution, generations = genetic_algorithm_stepwise(population, fitness_fn, gene_pool, f_thres, ngen, mutation_rate) ``` -------------------------------- ### Initialize LRTAStarAgent Source: https://github.com/aimacode/aima-python/blob/master/search.ipynb Initializes the LRTAStarAgent with the defined problem instance. This prepares the agent to start learning and searching within the environment. ```python lrta_agent = LRTAStarAgent(LRTA_problem) ``` -------------------------------- ### Define Three Block Tower Problem Source: https://github.com/aimacode/aima-python/blob/master/planning.ipynb Instantiates the three_block_tower planning problem. This is the starting point for solving the Sussman anomaly. ```python threeBlockTower = three_block_tower() ``` -------------------------------- ### Initialize Planning Graph Builder Source: https://github.com/aimacode/aima-python/blob/master/classical_planning_approaches.ipynb Initializes the planning graph builder with empty mutex list. ```python self.mutex = [] ``` -------------------------------- ### Print Values for the First Feature Source: https://github.com/aimacode/aima-python/blob/master/learning.ipynb Shows all possible values for the first feature (index 0) across all examples in the Iris dataset. ```python print(iris.values[0]) ``` -------------------------------- ### Instantiating Canvas_fol_bc_ask Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Shows the instantiation of the Canvas_fol_bc_ask object, which likely involves setting up a canvas for visualization or interaction based on a given expression and knowledge base. ```python from notebook import Canvas_fol_bc_ask canvas_bc_ask = Canvas_fol_bc_ask('canvas_bc_ask', crime_kb, expr('Criminal(x)')) ``` -------------------------------- ### Obtain Step Function for Plotting Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Calls the `make_update_step_function` to get a function that will be used to plot the graph at different stages of the coloring process. ```python step_func = make_update_step_function(neighbors, coloring_problem1) ``` -------------------------------- ### Custom MDP Initialization Parameters Source: https://github.com/aimacode/aima-python/blob/master/mdp.ipynb Sets the initial state, terminal states, and rewards for the custom MDP. ```python init = "A" terminals = ["End"] rewards = { "A": 5, "B": -10, "End": 100 } ``` -------------------------------- ### Get Utility of a Terminal State Source: https://github.com/aimacode/aima-python/blob/master/games.ipynb Returns the utility value of a terminal state for 'MAX' and 'MIN' players. For 'MIN', the value is negated. ```python print(fig52.utility('B1', 'MAX')) print(fig52.utility('B1', 'MIN')) ``` -------------------------------- ### Delete Table-Driven Agent Source: https://github.com/aimacode/aima-python/blob/master/vacuum_world.ipynb Removes a previously added table-driven agent from the environment. This is a setup step before introducing the simple reflex agent. ```python # Delete the previously added table-driven agent trivial_vacuum_env.delete_thing(table_driven_agent) ``` -------------------------------- ### Import SARSA and Q-Learning Agents Source: https://github.com/aimacode/aima-python/blob/master/sarsa.ipynb Imports the necessary classes for SARSA and Q-learning agents, along with a utility function to run trials and the sequential decision environment. ```python from reinforcement_learning import SARSALearningAgent, QLearningAgent, run_single_trial from mdp import sequential_decision_environment as env ``` -------------------------------- ### Import CSP Module Source: https://github.com/aimacode/aima-python/blob/master/arc_consistency_heuristics.ipynb Imports the necessary Constraint Satisfaction Problem (CSP) module. This is a common starting point for CSP-related tasks. ```python from csp import * ``` -------------------------------- ### Visualize Greedy Best-First Search Source: https://github.com/aimacode/aima-python/blob/master/search.ipynb Sets up and visualizes the greedy best-first search algorithm. This requires the 'romania_map', 'GraphProblem', and 'display_visual' to be available. ```python all_node_colors = [] romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) display_visual(romania_graph_data, user_input=False, algorithm=greedy_best_first_search, problem=romania_problem) ``` -------------------------------- ### Unify two expressions with the same predicate and a variable Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb This example demonstrates unifying two expressions with the same predicate but different arguments, where one argument is a variable. ```python unify(expr('A(x)'), expr('A(B)')) ``` -------------------------------- ### Initialize UniversalDict for Variable Domain Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Demonstrates initializing a UniversalDict with a list of possible values (colors) for variables. This dict provides the same value for any key accessed. ```python s = UniversalDict(['R','G','B']) s[5] ``` -------------------------------- ### WalkSAT usage with conjunctive clauses Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Applies the WalkSAT algorithm to a set of conjunctive clauses. This example illustrates how the algorithm handles conjunctions in the input. ```python WalkSAT([A & B, A & C], 0.5, 100) ``` -------------------------------- ### Instantiate Custom MDP Source: https://github.com/aimacode/aima-python/blob/master/mdp.ipynb Creates an instance of the CustomMDP class with the defined parameters, including the transition matrix, initial state, terminals, rewards, and discount factor. ```python our_mdp = CustomMDP(init, terminals, t, rewards, gamma=.9) ``` -------------------------------- ### Access Sequential Decision Environment Instance Source: https://github.com/aimacode/aima-python/blob/master/mdp.ipynb Retrieves the instance of the sequential decision environment, which is created using the GridMDP class with the same configuration as the example. ```python sequential_decision_environment ``` -------------------------------- ### Execute Partial Order Planner for Spare Tire Problem Source: https://github.com/aimacode/aima-python/blob/master/planning_partial_order_planner.ipynb Instantiates and executes the PartialOrderPlanner for the spare tire problem, printing the resulting causal links, constraints, and the partial order plan. ```python st = spare_tire() pop = PartialOrderPlanner(st) pop.execute() ``` -------------------------------- ### Create Selective Search Segmentation Object Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter24/Objects in Images.ipynb Initializes the Selective Search segmentation object from the opencv-python package. Ensure 'opencv-contrib-python' is also installed. ```python ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() ``` -------------------------------- ### Find and Visualize a Different 8-Queens Solution Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Re-initializes the 8-Queens CSP and solves it again using min_conflicts to find a potentially different valid solution, then visualizes it. ```python eight_queens = NQueensCSP(8) solution = min_conflicts(eight_queens) plot_NQueens(solution) ``` -------------------------------- ### Import MDP and Notebook Utilities Source: https://github.com/aimacode/aima-python/blob/master/mdp.ipynb Imports all necessary functions from the mdp module and utility functions from the notebook module for visualization and pseudocode display. ```python from mdp import * from notebook import psource, pseudocode, plot_pomdp_utility ``` -------------------------------- ### Get Hill Climbing Solution for Peak Finding (8 Directions) Source: https://github.com/aimacode/aima-python/blob/master/search.ipynb Executes hill_climbing once on the 8-direction PeakFindingProblem and retrieves the value of the found solution. ```python solution = problem.value(hill_climbing(problem)) solution ``` -------------------------------- ### Get Probability Distribution of a Bayes Net Variable Source: https://github.com/aimacode/aima-python/blob/master/probability4e.ipynb Retrieves the marginal probability distribution for a variable within the Alarm Bayes Net, such as 'Burglary'. ```Python from probability import BayesNet, Variable, T, F alarm_net = (BayesNet() .add('Burglary', [], 0.001) .add('Earthquake', [], 0.002) .add('Alarm', ['Burglary', 'Earthquake'], {(T, T): 0.95, (T, F): 0.94, (F, T): 0.29, (F, F): 0.001}) .add('JohnCalls', ['Alarm'], {T: 0.90, F: 0.05}) .add('MaryCalls', ['Alarm'], {T: 0.70, F: 0.01})) globalize(alarm_net.lookup) # Probability distribution of a Burglary P(Burglary) ``` -------------------------------- ### Define POMDP Parameters Source: https://github.com/aimacode/aima-python/blob/master/mdp_apps.ipynb Sets up the actions, states, and discount factor (gamma) for the POMDP. Actions are represented by strings '0', '1', '2' and states by '0', '1'. ```python # 0: open-left, 1: open-right, 2: listen actions = ('0', '1', '2') # 0: left, 1: right states = ('0', '1') gamma = 0.95 ``` -------------------------------- ### Initialize and Visualize Grid Source: https://github.com/aimacode/aima-python/blob/master/probability.ipynb Initializes a grid representing the environment and visualizes the initial probability distribution of the robot's position using a heatmap. This is useful for understanding the starting state of the localization process. ```python grid = [[0]*17 for _ in range(11)] for x, y, _ in S: if 0 <= x < 11 and 0 <= y < 17: grid[x][y] += 1 print("GRID:") print_table(grid) heatmap(grid, cmap='Oranges') ``` -------------------------------- ### Get Probability of a Specific Outcome Source: https://github.com/aimacode/aima-python/blob/master/probability4e.ipynb Accesses the probability of a specific outcome (e.g., 'T' for True) from a variable's probability distribution by subscripting. ```Python from probability import Variable Earthquake = Variable('Earthquake', 0.002) # Get the probability of a specific outcome by subscripting the probability distribution P(Earthquake)[T] ``` -------------------------------- ### Initialize Distances and Cities Source: https://github.com/aimacode/aima-python/blob/master/search.ipynb Initializes a dictionary to store distances between cities and a list of all city names. This setup is required before calculating distances for the TSP. ```python distances = {} all_cities = [] for city in romania_map.locations.keys(): distances[city] = {} all_cities.append(city) all_cities.sort() print(all_cities) ``` -------------------------------- ### Create FolKB Instance Source: https://github.com/aimacode/aima-python/blob/master/logic.ipynb Initializes a First-Order Logic Knowledge Base (FolKB) instance using the collected list of clauses. ```python crime_kb = FolKB(clauses) ``` -------------------------------- ### Print Best Policy Source: https://github.com/aimacode/aima-python/blob/master/mdp_apps.ipynb Displays the optimal policy derived for the MDP, showing the recommended action for each state. ```python print(pi) ``` -------------------------------- ### Example: Probability of Alarm Given Earthquake and Mary Calls Source: https://github.com/aimacode/aima-python/blob/master/probability4e.ipynb Illustrates `enumeration_ask` for calculating the probability of an Alarm, given evidence of an Earthquake and that Mary calls. ```python # The probability of an Alarm, given that there is an Earthquake and Mary calls: enumeration_ask(Alarm, {MaryCalls: T, Earthquake: T}, alarm_net) ``` -------------------------------- ### Initialize and Test Have Cake and Eat Cake Too Problem Source: https://github.com/aimacode/aima-python/blob/master/planning.ipynb Initializes the 'Have Cake and Eat Cake Too' problem and checks the initial goal state. This sets up the scenario for demonstrating the planning actions. ```python cakeProblem = have_cake_and_eat_cake_too() print(cakeProblem.goal_test()) ``` -------------------------------- ### CSP Formulation for Planning Source: https://github.com/aimacode/aima-python/blob/master/classical_planning_approaches.ipynb Sets up the CSP for a planning problem by expanding actions and fluents, and defining domains and initial state constraints for a given solution length. This is a core step in solving planning problems using CSPs. ```python expanded_actions = planning_problem.expand_actions() fluent_values = planning_problem.expand_fluents() for horizon in range(solution_length): act_vars = [str('action', stage) for stage in range(horizon + 1)] domains = {av: list(map(lambda action: expr(str(action)), expanded_actions)) for av in act_vars} domains.update({ str(var, stage): { True, False } for var in fluent_values for stage in range(horizon + 2) }) # initial state constraints constraints = [ Constraint((str(var, 0),), is_(val)) for fluent, val in planning_problem.initial.items() if fluent.op[:3] != 'Not' else False ] constraints += [ Constraint((str(var, 0),), is_(False)) ] ``` -------------------------------- ### Create an 8-Queens CSP Instance Source: https://github.com/aimacode/aima-python/blob/master/csp.ipynb Instantiates the NQueensCSP class for an 8x8 chessboard. This sets up the problem for solving. ```python eight_queens = NQueensCSP(8) ``` -------------------------------- ### RNN Training Output Source: https://github.com/aimacode/aima-python/blob/master/notebooks/chapter19/RNN.ipynb Example output during the training of the RNN model, showing epoch progress, loss, and accuracy metrics for both training and validation sets. ```text WARNING: Logging before flag parsing goes to stderr. W1018 22:51:23.614058 140557804885824 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/nn_impl.py:180: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where W1018 22:51:24.267649 140557804885824 deprecation_wrapper.py:119] From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:422: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. Train on 24990 samples, validate on 25000 samples Epoch 1/10 - 59s - loss: 0.6540 - accuracy: 0.5959 - val_loss: 0.6234 - val_accuracy: 0.6488 Epoch 2/10 - 61s - loss: 0.5977 - accuracy: 0.6766 - val_loss: 0.6202 - val_accuracy: 0.6326 Epoch 3/10 - 61s - loss: 0.5269 - accuracy: 0.7356 - val_loss: 0.4803 - val_accuracy: 0.7789 Epoch 4/10 - 61s - loss: 0.4159 - accuracy: 0.8130 - val_loss: 0.5640 - val_accuracy: 0.7046 Epoch 5/10 - 61s - loss: 0.3931 - accuracy: 0.8294 - val_loss: 0.4707 - val_accuracy: 0.8090 Epoch 6/10 - 61s - loss: 0.3357 - accuracy: 0.8637 - val_loss: 0.4177 - val_accuracy: 0.8122 Epoch 7/10 - 61s - loss: 0.3552 - accuracy: 0.8594 - val_loss: 0.4652 - val_accuracy: 0.7889 Epoch 8/10 - 61s - loss: 0.3286 - accuracy: 0.8686 - val_loss: 0.4708 - val_accuracy: 0.7785 Epoch 9/10 - 61s - loss: 0.3428 - accuracy: 0.8635 - val_loss: 0.4332 - val_accuracy: 0.8137 Epoch 10/10 - 61s - loss: 0.3650 - accuracy: 0.8471 - val_loss: 0.4673 - val_accuracy: 0.7914 ```