Utilities & Notebook Helpers
Provides some utilities widely used by other modules
- remove_all(item, seq)[source]
Return a copy of seq (or string) with all occurrences of item removed.
- identity(x)
- argmin_random_tie(seq, key=<function <lambda>>)[source]
Return a minimum element of seq; break ties at random.
- argmax_random_tie(seq, key=<function <lambda>>)[source]
Return an element with highest fn(seq[i]) score; break ties at random.
- histogram(values, mode=0, bin_function=None)[source]
Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first.
- matrix_multiplication(x, *y)[source]
Return a matrix as a matrix-multiplication of x and arbitrary number of matrices *y.
- weighted_sample_with_replacement(n, seq, weights)[source]
Pick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding weight.
- weighted_sampler(seq, weights)[source]
Return a random-sample function that picks from seq weighted by weights.
- num_or_str(x: str) int | float | str[source]
The argument is a string; convert to a number if possible, or strip it.
- cross_entropy_loss(x, y) float[source]
Return the mean binary cross-entropy loss between targets x and predictions y.
- mean_squared_error_loss(x, y) float[source]
Return the mean squared error loss between vectors x and y.
- mean_error(x, y) float[source]
Return the mean of the absolute differences between vectors x and y.
- mean_boolean_error(x, y) float[source]
Return the fraction of positions at which vectors x and y differ.
- random_weights(min_value: float, max_value: float, num_weights: int) list[source]
Return a list of num_weights random floats drawn uniformly from [min_value, max_value].
- sigmoid_derivative(value)[source]
Return the derivative of the sigmoid, given its already-computed output value.
- elu(x: float, alpha: float = 0.01) float[source]
Return the Exponential Linear Unit activation of x.
- elu_derivative(value: float, alpha: float = 0.01) float[source]
Return the derivative of the ELU activation, given its output value.
- tanh_derivative(value)[source]
Return the derivative of tanh, given its already-computed output value.
- leaky_relu(x: float, alpha: float = 0.01) float[source]
Return the Leaky ReLU activation of x (slope alpha for negative inputs).
- leaky_relu_derivative(value: float, alpha: float = 0.01) float[source]
Return the derivative of the Leaky ReLU activation, given its output value.
- relu_derivative(value: float) int[source]
Return the derivative of the ReLU activation, given its output value.
- gaussian(mean: float, st_dev: float, x: float) float[source]
Given the mean and standard deviation of a distribution, it returns the probability of x.
- linear_kernel(x, y=None)[source]
Return the linear kernel (dot product) between x and y; defaults y to x.
- polynomial_kernel(x, y=None, degree=2.0)[source]
Return the polynomial kernel (1 + x.y)**degree between x and y; defaults y to x.
- rbf_kernel(x, y=None, gamma=None)[source]
Radial-basis function kernel (aka squared-exponential kernel).
- turn_heading(heading, inc, headings=[(1, 0), (0, 1), (-1, 0), (0, -1)])[source]
Return the heading reached by turning inc steps around the list of headings.
- turn_left(heading)[source]
Return the heading obtained by turning left (counter-clockwise) from heading.
- class injection(**kwds)[source]
Bases:
objectDependency injection of temporary values for global functions/classes/etc. E.g., with injection(DataBase=MockDataBase): …
- memoize(fn, slot=None, maxsize=32)[source]
Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, use lru_cache for caching the values.
- print_table(table, header=None, sep=' ', numfmt='{}')[source]
Print a list of lists as a table, so that columns line up nicely. header, if specified, will be printed as the first row. numfmt is the format for all numbers; you might want e.g. ‘{:.2f}’. (If you want different formats in different columns, don’t use print_table.) sep is the separator between columns.
- open_data(name, mode='r')[source]
Open and return the file named name from the aima-data directory.
- failure_test(algorithm, tests)[source]
Grades the given algorithm based on how many tests it passes. Most algorithms have arbitrary output on correct execution, which is difficult to check for correctness. On the other hand, a lot of algorithms output something particular on fail (for example, False, or None). tests is a list with each element in the form: (values, failure_output).
- class Expr(op, *args)[source]
Bases:
objectA mathematical expression with an operator and 0 or more arguments. op is a str like ‘+’ or ‘sin’; args are Expressions. Expr(‘x’) or Symbol(‘x’) creates a symbol (a nullary Expr). Expr(‘-’, x) creates a unary; Expr(‘+’, x, 1) creates a binary.
- class PartialExpr(op, lhs)[source]
Bases:
objectGiven ‘P |’==>’| Q, first form PartialExpr(‘==>’, P), then combine with Q.
- expr(x)[source]
Shortcut to create an Expression. x is a str in which: - identifiers are automatically defined as Symbols. - ==> is treated as an infix |’==>’|, as are <== and <=>. If x is already an Expression, it is returned unchanged.
- class defaultkeydict[source]
Bases:
defaultdictLike defaultdict, but the default_factory is a function of the key.
- class hashabledict[source]
Bases:
dictAllows hashing by representing a dictionary as tuple of key:value pairs. May cause problems as the hash value may change during runtime.
- class PriorityQueue(order='min', f=<function PriorityQueue.<lambda>>)[source]
Bases:
objectA Queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is ‘min’, the item with minimum f(x) is returned first; if order is ‘max’, then it is the item with maximum f(x). Also supports dict-like lookup.
- class Bool[source]
Bases:
intJust like bool, except values display as ‘T’ and ‘F’ instead of ‘True’ and ‘False’.
- gaussian_kernel(size=3)[source]
Return a length-size 1D Gaussian kernel centred at the middle (fixed st_dev 0.1).
- gaussian_kernel_1D(size=3, sigma=0.5)[source]
Return a length-size 1D Gaussian kernel centred at the middle with st_dev sigma.
- gaussian_kernel_2D(size=3, sigma=0.5)[source]
Return a size x size 2D Gaussian kernel with st_dev sigma, normalized to sum to 1.
- class MCT_Node(parent=None, state=None, U=0, N=0)[source]
Bases:
objectNode in the Monte Carlo search tree, keeps track of the children states.
- ucb(n, C=1.4)[source]
Return the UCB1 score of node n (exploitation plus C-weighted exploration term).
Unvisited nodes (n.N == 0) score infinity so they are selected first; used to guide selection in Monte Carlo tree search.
- show_iris(i=0, j=1, k=2)[source]
Plots the iris dataset in a 3D plot. The three axes are given by i, j and k, which correspond to three of the four iris features.
- load_MNIST(path='aima-data/MNIST/Digits', fashion=False)[source]
Load the MNIST (or Fashion-MNIST when
fashionis True) dataset from its IDX files underpath. Returns(train_img, train_lbl, test_img, test_lbl)as numpy arrays, with images flattened to one row per sample.
- show_MNIST(labels, images, samples=8, fashion=False)[source]
Display a grid of
samplesrandom example images for each class of the (Fashion-)MNIST dataset.
- show_ave_MNIST(labels, images, fashion=False)[source]
Display the average image of every class in the (Fashion-)MNIST dataset and print how many images each class contains.
- make_plot_grid_step_function(columns, rows, U_over_time)[source]
ipywidgets interactive function supports single parameter as input. This function creates and return such a function by taking as input other parameters.
- make_visualize(slider)[source]
Takes an input a sliderand returns callback function for timer and animation.
- class Canvas(varname, width=800, height=600, cid=None)[source]
Bases:
objectInherit from this class to manage the HTML canvas element in jupyter notebooks. To create an object of this class any_name_xyz = Canvas(“any_name_xyz”) The first argument given must be the name of the object being created. IPython must be able to reference the variable name that is being passed.
- execute(exec_str)[source]
Stores the command to be executed to a list which is used later during update()
- rect(x, y, w, h)[source]
Draw a rectangle with ‘w’ width, ‘h’ height and (x, y) as the top-left corner
- rect_n(xn, yn, wn, hn)[source]
Similar to rect(), but the dimensions are normalized to fall between 0 and 1
- line_n(x1n, y1n, x2n, y2n)[source]
Similar to line(), but the dimensions are normalized to fall between 0 and 1
- arc(x, y, r, start, stop)[source]
Draw an arc with (x, y) as centre, ‘r’ as radius from angles ‘start’ to ‘stop’
- class Canvas_TicTacToe(varname, player_1='human', player_2='random', width=300, height=350, cid=None)[source]
Bases:
CanvasPlay a 3x3 TicTacToe game on HTML canvas
- mouse_click(x, y)[source]
Handle a click at pixel (x, y): make the move for the current human or AI player, or restart the game when it is over, then redraw the board.
- class Canvas_min_max(varname, util_list, width=800, height=600, cid=None)[source]
Bases:
CanvasMinMax for Fig52Extended on HTML canvas
- min_max(node)[source]
Run minimax from the given node, recording the sequence of canvas changes (visited nodes, explored utilities, thick edges) for step-by-step animation. Returns the node’s minimax value.
- stack_manager_gen()[source]
Generator that replays the recorded change list, updating the node stack, explored set and thick lines, and yielding once per animation step.
- class Canvas_alpha_beta(varname, util_list, width=800, height=600, cid=None)[source]
Bases:
CanvasAlpha-beta pruning for Fig52Extended on HTML canvas
- alpha_beta_search(node)[source]
Run alpha-beta pruning from the given node, recording the sequence of canvas changes (visited nodes, alpha/beta bounds, pruned nodes, thick edges) for step-by-step animation. Returns the node’s value.
- stack_manager_gen()[source]
Generator that replays the recorded change list, updating the node stack, alpha/beta bounds, explored and pruned sets and thick lines, yielding once per animation step.
- class Canvas_fol_bc_ask(varname, kb, query, width=800, height=600, cid=None)[source]
Bases:
Canvasfol_bc_ask() on HTML canvas
- fol_bc_ask()[source]
Run first-order backward chaining for the stored query against the knowledge base, yielding proof trees together with their substitutions.
- make_table(graph)[source]
Lay out the proof tree as a table of node positions and edges (stored on the instance) ready for rendering on the canvas.
- show_map(graph_data, node_colors=None)[source]
Draw a networkx graph of the given map data with coloured nodes, edge weight labels and a legend describing the search-state colours.
- final_path_colors(initial_node_colors, problem, solution)[source]
Return a node_colors dict of the final path provided the problem and solution.
- display_visual(graph_data, user_input, algorithm=None, problem=None)[source]
Build interactive ipywidgets controls to animate a search algorithm on the map. When
user_inputis True, also let the user choose the algorithm and the start and goal cities; otherwise animate the suppliedalgorithm.
- plot_NQueens(solution)[source]
Draw an N-Queens chessboard with queen images for the given solution, which may be a dict (from NQueensCSP) or a list (from NQueensProblem).
- heatmap(grid, cmap='binary', interpolation='nearest')[source]
Display the given 2D grid as a heatmap.
- plot_pomdp_utility(utility)[source]
Plot the piecewise-linear utility functions of a POMDP’s actions and mark the belief thresholds between the optimal actions.
- plot_model_boundary(dataset, attr1, attr2, model=None)[source]
Plot the decision boundary of a classifier over two attributes of a dataset. Builds a mesh over the
attr1/attr2plane, colours each cell by themodel’s prediction, and overlays the training examples.
- grid_search_steps(problem, strategy='astar')[source]
Run a search on a
GridProblem, recording how it explores.Returns
(explored, path):exploredis the list of cells in the order they are expanded (popped from the frontier), andpathis the list of cells from start to goal (Noneif the goal is unreachable).strategyselects the evaluation function –'astar'(g + h),'ucs'(g),'bfs'(depth) or'greedy'(h) – which is what makes the different exploration patterns.
- plot_grid_search(problem, explored, path=None, ax=None, title=None)[source]
Visualise a grid search: obstacles, the cells expanded (shaded by when they were expanded), the solution path, and the start/goal.
exploredandpathare as returned bygrid_search_steps(). Returns the matplotlib Axes.
- class ContinuousWorldView(world, fill='#AAA')[source]
Bases:
objectView for continuousworld Implementation in agents.py
- object_name()[source]
Return the variable name this view is bound to in the main namespace, matched by its creation timestamp, so the JavaScript canvas can address it.
- handle_add_obstacle(vertices)[source]
Vertices must be a nestedtuple. This method is called from kernel.execute on completion of a polygon.
- handle_remove_obstacle()[source]
Hook for removing an obstacle from the world; not yet implemented.
- class GridWorldView(world, block_size=30, default_fill='white')[source]
Bases:
objectView for grid world. Uses XYEnviornment in agents.py as model. world: an instance of XYEnviornment. block_size: size of individual blocks in pixels. default_fill: color of blocks. A hex value or name should be passed.
- object_name()[source]
Return the variable name this view is bound to in the main namespace, matched by its creation timestamp, so the JavaScript canvas can address it.
- set_label(coordinates, label)[source]
Add labels to a particular block of grid. coordinates: a tuple of (row, column). rows and columns are 0 indexed.
- set_representation(thing, repr_type, source)[source]
Set the representation of different things in the environment. thing: a thing object. repr_type : type of representation can be either “color” or “img” source: Hex value in case of color. Image path in case of image.
- handle_click(coordinates)[source]
This method needs to be overridden. Make sure to include a self.show() call at the end.