Saturday, August 26, 2017

Artificial Intelligence A3, planning

Note: Due to time constraint, I have to pause AIND at the planning section. If I have time in the future, I may restore my study in the following:
  1. pac-man lab
  2. simulated annealing lab
  3. airport transportation planning project.

Peter Norvig: AI is all about figuring out what to do when you don’t know what to do. Regular programming is writing instructions to make the computer do what you want when you do know what to do. In AI, it’s for when you don’t know. search is one of key areas where we can figure out what to do by planning a sequence of steps, even when we have no idea what the first step should be until we solve the search problem.
  • breadth first search (shortest)
  • uniform cost search (cheapest)
  • depth first search (least storage space, fastest computing time)
Also called best estimated total path cost first
only expanse the minimum value. f = g+h
g(path) = path cost so far
h(path) = h(s) = estimated distance to goal = straigh line distance
g is to keep the path short, h is to keep us focus on the goal.
A search finds the lowest cost path if *h(s) < true cost. h is optimistic.
A problem solver that uses a heuristic function given to it really is not intelligent at all.
crossing out parts of the rules is called generating a relaxed problem.
searching is one of the most fundamental methods of solving problems in AI.
Peter: To me, AI is programming a computer to do the right thing when you don’t know for sure the right thing is.
The book was successful because of a fortuitous accident of timing. we happened to come along just as AI was making this transition from Boolean logic to probability and from handcarfted knowledge to machine learning.

lab: pac man

simulated annealing

do the stupid thing first, and only add intelligence when necessary.
global optimum: an element of randomness is what you need
  • random restart
  • genetic algorithms
  • simulated annealing
taboo search: it is taboo if somewhere you have already been.
stage algorithm: keep a list of all local maximum and try to get the general shape of the problem,try to predict where a new maximum might be, given the areas I haven’t explored yet.
local beam search/ stochastic beam search: keep track of k particles. At each time frame, we randomly generate neighbors of these particles and keep the best ones for the next iteration. There are messages sharing between these particles.
genetic algorithm is a fancy version of beam search that happens to make a nice analogy to biology. some people call it the 2nd best solution to any problem.
We’ll see these ideas repeatedly in aI, in techniques like particle filters, pattern recognition with hidden Markov models, and Monte Carlo Markov chains. Sometimes let them go and embrace randomness is the key to the solution.

lab

Follow the instructions to implement Simulated Annealing from AIMA

constraint satisfaction

techniques:
  • backtracking
  • forward checking
  • minimum remaining values
  • least constraining value
problems with preference constraints are called constraint optimization problems and are with solving linear programming.
Examples:
  • car assembly
  • job scheduling in factories
  • class scheduling
  • spreadsheets
  • transportation scheduling
  • floor planning
Constraint Satisfaction Problems by solving the N-queens problem using symbolic constraints and backtracking search: https://github.com/udacity/AIND-Constraint_Satisfaction
complete the constraints for the N-Queens CSP and implement Backtracking-Search from AIMA (chapter 6)

logic

AI started in the 50s~70s with the idea that what we needed was better language and systems for writing down logical statements. Once we have done enough of them, we should be able to do anything of them. Some progress but 2 major issues:
  1. the world is uncertain. We didn’t get good algorithm to deal with probability until mid 1980s
  2. too laborious to try to write down everything by hand.
Today, logic is still useful in many domains where we can eliminate much of the uncertainty of real world and solve significant problems. Like FedEx planning all the deliveries of its packages.
Expert system.
future of planning algorithms:
  • Learning from examples would be an important area.
  • transfer learning across domain.
  • interactive planning
  • explainable, adaptable.
value iteration is a key concept for Markov decision processing.
  • first order logic: relation , object,function
  • propositional logic: facts
  • probability theory

planning

Blindfold Hiker Test: We can’t just plan ahead and come up with a whole plan. We need feedback from environment. We have to interweave planning and execution:
  • environment is stochastic.
  • multiagent
  • partial observability
  • unkown/imcomplete knowledge
  • hierarchical
When we start, we only have the high level parts of the plan, then during execution that we schedule the rest of low level parts of the plan.
sensorless planning in a deterministic world.
observation updates our believe state. Observation alone can’t create new states, but can partition them into pieces.

project

implement my_air_cargo_problems.py and test it by python run_search.py -p 1 -s 5 in which 5 is uniform cost search/ best_first_graph_search.
my_planning_graph.py
hierachy structure of code:
void main (vector<int> p, vector<int> s){
  void run_search(Problem p, Search_func(),para){
    void show_solution()
  }
}
FluentState(vector<Expr>,vector<Expr>)

string encode_state(FluentState fs,vector<Expr> fluent_map){}  // state 

AirCargoProblem(vector<string> cargos, vector<string> planes, vector<string> airports, FluentState init, vector<Expr> goal){
  vector<Action> get_action()
}

Action(Expr action,array<vector<Expr>,2> precond, array<vector<Expr>,2> effect)
-> represent return type, : represent input type.
expr('At(C1, SFO)') is an Expr object.
precondition is only very small part of the whole initial state.
what next?:
  • try single Action and Expr, see how it works
  • try understand various planning algorithms
submit requirement when udacity submit
  • my_air_cargo_problems.py
  • my_planning_graph.py
  • heuristic_analysis.pdf (if present)
  • research_review.pdf (one-page report on three of these developments, highlighting the relationships between the developments and their impact on the field of AI as a whole. Appropriate sources (such as books or magazine or journal articles) should be cited. There’s a lot of resources at the end of AIMA chapter 10 )

AIMA

codes: aima.cs.berkeley.edu

AIMA chapter 2, Intelligent Agents

In a sense, all areas of engineering can be seen as designing artifacts that interact with the world; AI operates at the most interesting end of the spectrum, where the artifacts have signficant computational resources and the task environment requires nontrivial decision making.
As a general rule, it is better to design performance measures according to what one actually wants in the environment, rather than according to how one thinks the agent should behave.
which is better— a reckless life of highs and lows, or a safe but humdrum existence?
rational agent: given percept sequence and built-in knowledge it has, select an action that is expected to maximize its performance measure.
Rationality maximizes expected performance, while perfection maximizes actual performance. The latter is impossible unless you have a crystall ball or time machine.
autonomous: an agent not only relies on its prior knowledeg of its designer; it can use its own percepts to learn and compensate for partial or incorrect prior knowledge.
Task environment: performance, environment, actuatoors, sensors.
“percept,action” table-driven approach is doomed to failture due to super large number of entries, say, 10^{250B} much larger than 10^{80} (number of atoms in the observable universe).
4 kinds of agent programs:
  1. Simple reflex agents: condition-action rule
  2. Model-based. handle partial observability: maintain internal state. The model of “how the world works”: how the world evolves independently of the agent, how the agent’s own actions affect the world. Uncertainty about the current state is unavoidable, but the agent still has to make a decision—best guess.
  3. Goal-based: external performance measure, crude binary distinction between happy and unhappy states.
  4. Utility-based: use an internal utility function to measure goals in greater details. If there are conflicting goals (e.g. speed and safety), the utility function specifies the appropriate tradeoff. when uncertainty, provides a way in which the likelihood of success can be weighted against the importance of the goals.
Any rational agent must behave as if it possesses a utility function whose expected value it tries to maximize.
learning agent:
  1. performance element: responsible for selecting external actions.
  2. learning element: responsible for making improvements
  3. critic: a fixed performance standard. It can be thought as outside the agent because the agent must not modify it to fit its own standard.
  4. probelm generator: suggest new exploratory actions to discover much better actions for the long run.
state representations:
  • atomic: inside is an identical black box. Algorithms: search, game-playing, hidden markov models, markov decision process
  • factored: splits up each state into a fixed set of key-value pairs. Algorithms: constraint satisfaction, propositional logic, planning, Bayesian networks, machine learning.
  • structured: having thins in it that are related to each other, like a class object. Algorithms: relational databases, first-order logic, first-order probablity models, knowledge-based learning, natural language processing.
More expressive representation is much more concise.

AIMA chapter 10, classical planning

fully observable, deterministic, static environments with single agents
factored representation.
a fluent is a condition that can change over time. In logical approaches to reasoning about actions, fluents can be represented in first-order logic by predicates having an argument that depends on time.
To describe the planning problem concisely, we use PDDL (Planning Domain Definition Language):
  • initial state: a conjunction of fluents that are ground, functionless atoms.
  • actions: a set of action schemas that consists of action name, a list of all the variables, a precondition and an effect.
  • result
  • goal test
​

Friday, August 25, 2017

Artificial Intelligence A4, Hidden Markov Model

Probabilities is the cornerstone of AI. Express uncertainty and the management of uncertainty is the key to many, many things in AI.
naive Bayes: incidences are independent to each other.
Need 3 parameters to determine joint probability: P(A), P(B/A), P(B/~A)
The caveat is that B is dependent on the not observable A.
reading: AIMA: Chapter 13.
1st order Markove models only depend on the state immediately preceding them and not a history of states. We don’t necessarily know which state matches which physical event. Instead, each state can yield one or more outputs. we observe the output over time and determine a sequence of states, based on how likely they were to produce the output.
Because the base frequency may change, we use delta frequency and euclidean distance to compare the 2 signals.
transition probability x output probability.
AIMA: Chapter 15.1-15.3
  • Please read Chapter 1 The Fundamentals of HTK (pages 3-13) in The HTK Book (version 3.4) [PDF | HTML].
AIMA: Chapter 15.4-15.6 (provides another viewpoint on HMMs with a natural extension to Kalman filters, particle filtering, and Dynamic Bayes Nets), Chapter 20.3 (hidden variables, EM algorithm)
Huang, Ariki, and Jack’s book Hidden Markov Models for Speech Recognition.
Yechiam Yemini’s slides on HMMs used in genetics (gene sequencing, decoding).
Sebastian Thrun and Peter Norvig’s AI course:
Resources for Segmentally Boosted HMMs
HMMs for Speech Synthesis
DeepMind’s WaveNet

project: build a sign language recognizer

In this project, you will build a system that can recognize words communicated using the American Sign Language (ASL). You will be provided a preprocessed dataset of tracked hand and nose positions extracted from video. Your goal would be to train a set of Hidden Markov Models (HMMs) using part of this dataset to try and identify individual words from test sequences.

learning notes

It is best to dig into the original asl_data.py to see how to data is wrangled.
asl.df is a dataframe with 15.746 k entries and 7 columns. The rows are from (98,0) to (125,56) . 6 columns are from hands_condensed.csv, 1 column is from speaker.csv
asl.build_training() gives a ssl_data.WordsData object. Each word in the training set has multiple examples from various videos.
feature selection: feature_ground, features_norm, features_polar, features_delta.
The base model is GaussianHMM: https://hmmlearn.readthedocs.io/
Each time the model is trained on a single word. We are mostly interested in the number of hidden states.
training = asl.build_training(features)  # worksdata object
X, lengths = training.get_word_Xlengths(word)
model = GaussianHMM(n_components=num_hidden_states, n_iter=1000).fit(X, lengths)
logL = model.score(X, lengths)
Note that the training set and test set are the same in the above example.

Submission

Once you have completed the project and met all the requirements set in the rubric (see below), please save the notebook as an HTML file. You can do this by going to the File menu in the notebook and choosing “Download as” > HTML. Submit the following files (and only these files) in a .zip archive:
  • asl_recognizer.ipynb
  • asl_recognizer.html
  • my_model_selectors.py
  • my_recognizer.py
the goal is to get 40% correct or 72 of 178.
features selector correct/178 time
ground SelectorConstant 59 24
ground SelectorCV 59 82
ground SelectorBIC 67 63
ground SelectorDIC 71 174
polar BIC 69 64
polar DIC 75 187
delta DIC 63 176
norm DIC 68 200
norm BIC 67 66
norm CV 67 81
norm-delta BIC 78 71
norm-delta DIC 78 201

number of free params

In this project, however, we are using the “diag” in the hmmlearn model and we are not specifying starting probabilities. Therefore, if we say that m = num_components and f = num_features…
The free parameters are a sum of:
the free transition probability parameters, which is the size of the transmat matrix less one row because they add up to 1 and therefore the final row is deterministic, so m*(m-1)
PLUS
the free starting probabilities, which is the size of startprob minus 1 because it adds to 1.0 and last one can be calculated so m-1
PLUS
number of means, which is m*f
number of covariances which is the size of the covars matrix, which for “diag” is m*f
WHICH EQUALS :
m^2 + 2*m*f - 1
​

Monday, August 7, 2017

global optimization


Global optimization is a set of problems. Most of them are NP-hard.
An algorithm is said to be of polynomial time if its running time is upper bounded by a polynomial expression in the size of the input, i.e. T(n) = O(n^k). Polynomial time is a synonym for tractable, feasible, efficient or fast.
Complexity class P: problems for which a deterministic polynomial time algorithm exists
NP: non-deterministic polynomial time. The answer is easy to verify, but may be difficult to compute.
e.g. given a set of integers, does some subset of them sum to 0? The algorithm to find such a subset takes exponential time: 2^n-n-1. Hence this problem is in NP (quickly checkable) but not necessarily in P (quickly solvable).
if P= NP, it means the problem can be solved in polynomial time and verified in polynomial time.
if P!=NP, it means there are problems in NP that are harder to compute than to verify.
A decision problem is NP-complete when it is both in NP and NP-hard. NP-complete problems are often addressed by using heuristic) methods and approximation algorithms
NP-hard: class of decision problems which are at least hard as the hardest problems in NP. NP-hard problem does not have to be elements of NP.

  • deterministic methods
  • stochastic methods
  • heuristics and metaheuristics: evolutionary algorithms

2 research groups

Ferenc Domes

Head of software development in DAGOPT at Austria, previous professor at Universtiy of Vienna

Zabinsky, Z.B.

She is a professor of Industrial Engineering at the University of Washington. Her expertise is in operation research, global optimization.
“Stochastic Adaptive Search for Global Optimization” in 2003
  • grid search
  • pure random search
  • simulated annealing
  • pure random search: samples from the domain independently
  • pure adaptive search: samples the next point from the subset of the domain with strictly superior objective function values. The expected number of iterations is linear in dimension.
The book focuses on stochastic methods for global optimization, the theoretical understanding of the performance. Consolidates a collection of papers on the analysis and development of stochastic adaptive search.
Ultimate goal (we are far from that!):
  • works for a large class of problems
  • finds the global optima with an absolute guarantee
  • uses very little computation
Typically the optimization technique is chosen to match the structure of the relevant problem. For example, a practitioner solving a linear program would select a different algorithm than if the problem was nonlinear and convex. He can take advantage of the linear structure of the problem. However, if the problem is nonlinear and multimodal, the practitioner would have difficulty selecting the best algorithms to use. Thus, for global optimization it is still an open research question as to the best choice of algorithm given a particular problem.
Global optimization algorithms are often classified as either deterministic or stochastic. Stochastic methods can be applied to global optimization problems with little-known structure, such as ‘black box‘ functions.
Random search methods have been shown to have a potential to solve large problems efficiently in a way that is not possible for deterministic algorithms. Estimating the volume of convex body takes an exponential number of function evaluations for any deterministic algorithm, but if one is willing to accept a weaker claim of being correct with an estimate that has a high probability of being correct, then a stochastic algorithm can provide such an estimate in polynomial time. Thus there is a trade-off between the amount of computation and the type of guarantee of optimality. This book relax the requirement of providing an absolute guarantee of the global optimum and instead are satisfied with a probablisitc estimate of the global optimum.
Another advantage to stochastic methods is that they are relatively was to implement on complex problems. Methods like simulated annealing, genetic algorithms and tabu search are widely used. They only rely on function evaluations, rather than gradient and Hessian information, so they can be coded and run quickly. But a disadvantage of these methods is that they are currently customized to each specific problem largely through trial and error, and there is little theory to support the quality of the solution.
The basic measure of performance is the number of iterations until first sampling within \epsilon of the global optimum.
pure adaptive search and hesitant adaptive search use an underlying sampling distribution that is restricted to sampling from improving sets, annealing adaptive search always samples from the original feasible region but modifies the sampling distribution so that the probalility of sampling in the improving level set is high.

2 papers

2015

R. H. Abiyev and M. Tunay, “Optimization of High-Dimensional Functions through Hypercube Evaluation,” Computational Intelligence and Neuroscience, vol. 2015, p. 11, 2015.
Hypercube optimization, including initialization and evaluation process, displacement-shrink process, and searching space process.
derivative based vs derivative free learning algorithms:
  • local minima
  • computationally expensive
HO is an evolutionary algorithm, like the dove flies up, chooses the previously marked areas, changes and shrinks the size of the search area.
  • hypercube is used to describe the search area, represented by center and size(radii)
  • evaluate of a set of points randomly distributed in an -m-dimenional hypercube.
  • the point shifts and contracts
  • intense stochastic search
  • initial sampling has to be sufficiently dense so as to probe all the possible zones of higher and lower values;

1997

R. Storn and K. Price, “Differential Evolution – A Simple and Efficient Heuristic for global Optimization over Continuous Spaces,” Journal of Global Optimization, vol. 11, pp. 341-359, 1997/12/01 1997.
objective function is more accurately called a cost function.
central to every direct search method is a stategy that generates variations of the parameter vectors.
Most standard direct search methods use the greedy criterion: a new parameter vector is accepted if and only if it reduces the value of cost function. It converges fairly fast but has the risk of becoming trapped in a local minimum.
parallel search techniques like genetic algorithms and evolution strategies can help escape local minima.
Annealing algorithms relax the greedy criterion by occasionally permitting an uphill move, which could help a potential parameter vector to climb out of a local minimum. The uphill probability also decreases as the iteration increases. This lead to greedy criterion in the long run.
Differential Evolution (DE) is a parallel direct search method. It has 3 steps:
  1. mutation
  2. trial vector
  3. selection
​