Semi-Lexical Languages -- A Formal Basis for Unifying Machine Learning andSymbolic Reasoning in Computer Vision

Human vision is able to compensate imperfections in sensory inputs from the real world by reasoning based on prior knowledge about the world. Machine learning has had a significant impact on computer vision due to its inherent ability in handling imprecision, but the absence of a reasoning framework based on domain knowledge limits its ability to interpret complex scenarios. We propose semi-lexical languages as a formal basis for dealing with imperfect tokens provided by the real world. The power of machine learning is used to map the imperfect tokens into the alphabet of the language and symbolic reasoning is used to determine the membership of input in the language. Semi-lexical languages also have bindings that prevent the variations in which a semi-lexical token is interpreted in different parts of the input, thereby leaning on deduction to enhance the quality of recognition of individual tokens. We present case studies that demonstrate the advantage of using such a framework over pure machine learning and pure symbolic methods.


Introduction
Symbolic reasoning is a fundamental component of Artificial Intelligence (AI) which enables any rule-based system to generalize from known facts and domain specific rules to new facts. A necessary first step for all such systems is the modeling of the domain specific rules and facts in an underlying formal language or logic. Such systems also require the input to be encoded in the alphabet of the language.
One of the primary limitations of symbolic reasoning is in handling imperfections or noise in the system [Hupkes et al., 2019]. The real world often presents itself imperfectly, and we require the additional ability to interpret the input from the real world and reduce it to the tokens in the alphabet. The imperfections in the input from the real world can be quite varied and may have individual biases, and therefore real world systems do not easily lend themselves succinctly to symbolic capture. Machine learning, on the other hand, is designed to handle noise in the input and thereby recognize the components of a system under various forms of imperfections.
In this paper, we propose the notion of semi-lexical languages as the basis for solving several types of computer vision problems involving a combination of machine learning and symbolic reasoning. We accommodate imperfections in the inputs by allowing the alphabet of the language to support semi-lexical tokens, that is, each member of the alphabet may have many different variations and these variations are not defined symbolically, but learned from examples. For example, hand-written letters of the English alphabet are semi-lexical tokens. We may have many different ways in which people write the letter, u, including ways in which it may be confused with the letter, v, but we do not attempt to symbolically define all variations formally using more detailed features (such as the ones used by a forensic expert). This has the following consequences: 1. Given an input in terms of semi-lexical tokens, we need a mapping from the tokens to the alphabet of the language. By the very nature of semi-lexical languages, such a map is not defined symbolically, but learned from examples (for example, using machine learning techniques). 2. Depending on the level of imperfection in the semilexical tokens, the mapping indicated above may not be unique. For example, a given hand-written u, may be interpreted by some mapping as u and by some other mapping as v. We introduce bindings between interpretations of semi-lexical tokens to ensure that the same token is not interpreted in two different ways if it appears multiple times in the same input. For example, an individual writes the letter u in a certain way, and therefore, in the same sentence the hand-written letter, u, should not be interpreted in two different ways in two different portions of the text. 3. Since the mapping from semi-lexical tokens to the alphabet is not explicit and formal, testing whether a given input is a member of the language is not formally guaranteed. In spite of the limitation indicated in the third point above, we believe that semi-lexical languages are useful in representing and solving a large class of problems. The primary reasons are the following: • Since the inputs from the real world often have noise and imperfections, a purely symbolic form of reasoning is not possible in practice. Attempting to model the input variations symbolically will typically lead to overfitting, and such models will not generalize to other inputs. For example, different people have different ways of writing the same letters and modeling the system with respect to one person's handwriting will make it a poor model for another person's handwriting.
• Using pure machine learning is not suitable for learning complex and recursively defined systems, especially when an underlying rule-based structure is known and can be reduced to practice.
As an example, consider the problem of training a neural network to learn the less than relation among digits by training it with hand-written digits. Machine learning is good at learning to recognize the hand-written digits [Baldominos et al., 2019], but in the absence of the knowledge of the number system, the neural network will have to be explicitly trained for each pair of digits. It will not be able to generalize, for example, to deduce 3 < 7 even when it has been trained with 3 < 5 and 5 < 7 [Evans and Grefenstette, 2018]. A semilexical approach, as proposed in this paper, will use machine learning to learn the hand-written digits and use a back-end algebraic rule-based system to decide whether a given input, such as 9 < 3, is correct. In this paper we consider two interesting case studies combining computer vision and symbolic reasoning to demonstrate the use of semi-lexical languages.
• The first case study examines a hand-written solution of a Sudoku puzzle where some of the digits are ambiguous. The task is to decide whether the solution is valid. We use this case study as a running example.
• The second case study develops a framework for recognizing bicycles in images. Machine learning is used to learn the components and symbolic spatial constraints are used to decide whether the components add up to a bicycle. We demonstrate the advantage of this approach over methods which train a neural network to recognize bicycles as a whole.
It is important to separate our work from previous structured component-based approaches such as stochastic AND/OR graphs, and from the proponents of using machine learning as a front-end of GOFAI 1 , though the notion of semi-lexical languages subsumes such approaches. This paper includes a section on related work for this purpose. The paper is organized as follows. Section 2 formalizes the notion of semi-lexical languages, sections 3 and 4 elaborate the case studies. Section 5 presents an overview of the related work. Section 6 provides concluding remarks.

Semi-Lexical Languages
Formally, a semi-lexical language, L ⊆ Σ * , is defined using the following: • The alphabet, Σ, of the language • A set of rules (or constraints), R, which defines the membership of a word ω ∈ Σ * in the language, L.

GOFAI stands for Good Old Fashioned AI
• Semi-lexical domain knowledge in the form of a set T of tagged semi-lexical tokens. Each semi-lexical token, t, is tagged with a single tag, Tag(t), where Tag(t) ∈ Σ. We refer to T as the training set. • A set, C, of semi-lexical integrity constraints.
In order to elucidate our proposal of semi-lexical languages, we shall use a running case study for the game of Sudoku, a Japanese combinatorial number-placement puzzle. The objective of the game is to fill a 9 × 9 grid with digits so that each column, each row, and each of the nine 3 × 3 subgrids that compose the grid contain all of the digits from 1 to 9.
Let C ij denote the entry in the i th row and j th column of the Sudoku table. Formally, the language, L, defining the valid solutions of Sudoku is as follows: • The alphabet, Σ = {1, . . . , 9} • We consider words of the form: ω = R 1 . . . R 9 , where R i represents a row of the Sudoku, that is: . A given word ω belongs to L only if it satisfies the following set R of constraints for all i, j: The second constraint enforces that no two elements in a row or column are equal, and the third constraint enforces that no two elements in each of the 3 × 3 subgrids are equal.  , 2010] show that some digits like 9 and 4 are extremely close to each other in their latent representation exhibiting semi lexical behaviour. Each image is tagged with a member of Σ, that is, a digit from 1, . . . , 9. • A set, C, of semi-lexical integrity constraints, which is elaborated later .
Let us now consider the problem of determining whether a string of semi-lexical tokens is recognized as a word of the language. In the Sodoku example, our input is a 9 × 9 table containing handwritten digits. The inherent connotation of semi-lexical languages allows the tokens present in the input to be outside the training set T as well. As opposed to formal languages, the set of semi-lexical tokens is potentially infinite. For example, there may be infinite variations in the way people write a given letter. Let SLT denote the (potentially infinite) set of semilexical tokens from the real world. Obviously T ⊆ SLT . To determine whether a word ω ∈ SLT * belongs to L, we require a mapping: A naive way to look at semi-lexical languages would be to use machine learning (such as a convolutional neural network) to learn the mapping F from the tagged training set, T and then Figure 1: a) Some semi-lexical tokens from MNIST dataset along with global support for top 2 classes b) t-SNE plot of 1000 random MNIST digits shows some digits are extremely close to others in their 2D latent representation c) Sudoku board with highlighted semi lexical tokens. d) Mapping of selected tokens from the board in Figure 1c to Σ, the edges are marked with global support, C2,3 is both globally and locally consistent where as C7,6 is locally inconsistent.
use that mapping on SLT . Such an approach would have the following pitfalls, specifically when deciding tokens which are ambiguous (similar to more than one member of Σ). We use the Sudoku example to explain.
1. Inconsistent Penalties. In Figure 1c, C 1,2 is interpreted by F as the digit 5, whereas interpreting it as the digit 3 would have yielded a valid solution.
2. Inconsistent Rewards. In Figure 1c, C 7,6 is interpreted by F as the digit 6 and the solution is found to be valid. However in C 2,3 the digit 6 is written in a completely different way, and the same person is unlikely to write the digit 6 in these two different ways.
In human cognition, the systems of vision and reasoning support each other. We see some parts of an object, deduce other parts of it from domain knowledge, and this deduction is used as additional evidence in recognizing the other parts of the object which may not be visible with the same clarity. Our aim is to develop such methods with semi-lexical languages as the basis. The pitfalls indicated above can be addressed by adding integrity constraints on the mapping F from semi-lexical tokens to the alphabet Σ, and making the mapping a part of the underlying reasoning system. In other words, the support for mapping a semi-lexical token to a member of the alphabet comes from two sources, namely support from the learning based on the training set T , and support from the evidence provided by the reasoning system which tests membership of the entire word in the language. Broadly we categorize the integrity constraints, C, into two types: 1. Reasoning Assisted Similarity Constraints. The main idea here is that the rules in R can be used in conjunction with semi-lexical tokens of low ambiguity to hypothesize the interpretation of the ambiguous tokens. The hypothesis acts as increased support for interpreting the ambiguous tokens in a certain way.

2.
Reasoning Assisted Dissimilarity Constraints. The main idea here is that two semi-lexical tokens which are very different should not be allowed to be mapped to the same member of the alphabet if they appear in the same word. As of now, we refrain from formalizing the definition of an integrity constraint any further, because we realize that the nature of such constraints will be very domain-specific and susceptible to the level of noise in the training data and input. We shall demonstrate the use of such types of constraints through our case studies.

Handwritten Sudoku
The broad steps of our semi-lexical approach towards validating a handwritten Sudoku board is outlined in Algorithm 1. The given image is segmented to extract the images of the digits in each position of the board. These are then mapped to the digits 1 to 9 using the CNN and the board is validated using the rules of Sudoku. The semi-lexical analysis becomes apparent when some of the images are ambiguous, which is reflected by low support from the CNN, and justifies the need for our semi-lexical approach for reasoning about such images. We elaborate on this aspect in the following text.
1. We use a CNN with only two convolution layers followed by max-pooling, fully connected and softmax activation layers to learn handwritten digits using the MNIST dataset. T ag(C ij ) denotes the digit recognized by the CNN at position C ij . 2. In order to formalise integrity constraints for handwritten digits we use two distance based metrics with respect to the training data T and local handwritten digits present on the board.
f gs (T t ) = top k ( (g l−1 (T t ), g l−1 (T ) ) (1) The function g l−1 computes representations from the penultimate layer of the neural network in order to capture translation invariance provided by the maxpool layer. For each instance T t ∈ R 784 , g l−1 gives a representation T t ∈ R 128 (our architecture has 128 neurons). Token T t is globally consistent if the confidence for the correct class in the top k neighbours calculated using L2 norm from g l−1 (T ) (using Equation 1) is greater than a lower confidence bound c l , that is, f gs (T t ) ≥ c l .
To calculate local consistency we check the average feature distance (f dist) over m common features calculated via scale-invariant feature transform (SIFT) [Lowe, 2004] over all n similar tokens S on the board (using Equation 2). Token T t is locally consistent if f ls (T t ) ≤ .
3. The cells C ij with f gs (T ag(C ij )) ≥ c h are assigned the predicted T ag(C ij ), otherwise the location is treated as blank. In our experiments we used a c h of 80%. The valid(Board) function checks whether the board satisfies the Sudoku constraints, R. If not then the blank positions are solved using backtracking using R and the reasoning assisted constraints as outlined below.
4. The function, GlobalSupport(), in Algorithm 1 uses function f gs to compute the k nearest member neighbours of the token in C ij . It then generates a support map defining confidence for each alphabet that the token image shows membership in. For example the image in C 4,4 in Figure 1c has 430 members of class 4 and 460 members of class 9 having similar last layer activations. Therefore support map(C 4,4 ) = {9 : 46%, 4 : 43%}. In our experiments we used k = 1000.

The blank positions representing the ambiguous digits in
the board may be completed using reasoning, but only without violating the reasoning assisted similarity / dissimilarity constraints. The constraints are represented as a bipartite graph The edges E ⊆ V X × V Y are determined using f gs . An edge C i,j , m exists in G iff support map(C i,j ) for digit m is more than the lower confidence bound c l . In our experiments, we used a c l of 10%. Figure 1d shows the graph G for the board of Figure 1c. The edges in the graph enable reasoning assisted similarity by virtue of multiple edges incident on a vertex of V X . The objective is to ≤ .This is achieved by the bipartite graph.
6. The function Solve(board, support map) is used to choose an edge incident on each C ij of the bipartite graph G. Reasoning assisted dissimilarity constraints are used while making this choice. For example, C 7,6 has membership in both 6 and 8 (that is, C 7,6 , 6 ∈ E and C 7,6 , 8 ∈ E). In the absence of reasoning assisted dissimilarity, C 7,6 , 6 may be chosen. However, the average SIFT feature distance over all 8 cells containing 6 in the board is LocalSupport(C 7,6 ) = 11.59, whereas LocalSupport(C 2,3 ) = 5.49, = 10 in our experiment. This implies that the cell C 7,6 does not match with other return Corrected Board else return Not Solvable end end tokens on the board having similar tag and it should not be allowed to map to the same vertex of V Y as C 2,3 . The function Solve returns a valid board iff it is able to map each vertex of V X without violating any of the reasoning assisted dissimilarity constraints.
We highlight the fact that 7 written in cell C 6,6 has membership in both 7 and 1, and can therefore be interpreted as 1. Training the learning system to fit these variations would lead to overfitting. Reasoning assisted correction overcomes this shortcoming of assuming pure learning-based predictions to be correct.

Uni/Bi/Tri-Cycle Identification Problem
Many real world vision problems have more abstract constraints than the Sudoku example. In this section we consider one of the more popular problems, namely that of identifying different types of cycles. We define the alphabet as Σ = {wheel, seat, f rame, handlebar}. The following rule R defines a bi-cycle.
These constraints express that a bi-cycle must have two distinct wheels w 1 and w 2 (constraint C1), and a single frame, f , which is spatially within the range of both the wheels (constraint C2). The rules for defining uni-cycles and tri-cycles are similarly encoded. Figure 2: a) Detected components wheels and frame for different object classes b) Loss curves comparing networks with 9, 8, 7 and 6 convolutional layers, the network with 7 layers is chosen. c) Wheel of motorcycle detected to be that of bicycle however, it is flagged to be inconsistent following integrity constraints d) A decision diagram illustrating rules for identifying an object as bicycle The predicates, wheel(), f rame(), and inrange() will have semi-lexical connotations, For example, the association of a wheel to uni/bi/tri-cycle can be ambiguous if the prediction is made only in terms of features. In the proposed semi-lexical framework the membership will therefore be resolved based on rules. As opposed to studies on stochastic AND-OR graphs, and other shape grammars, the rules will be used to enhance the interpretation of the vision by using the reasoning assisted knowledge to resolve ambiguities.
The symbolic rules can be used to enforce a decision chain, as shown in Figure 2d. In our setup, the YOLOv2 network [Redmon and Farhadi, 2016], known for real time object detection and localisation, is used to learn the semi-lexical tokens. The training set is prepared with images from Cal-tech256 [Griffin et al., 2007], VOC [Everingham and Winn, 2011], and consists of only 100 images of bicycles.
The semi-lexical tokens in a given image containing any of the three objects are identified using the same network and tagged as T ag(T t ) = (name, pos), where name refers to the name of the component and pos refers to the bounding box containing the component. An example of identified components is shown in Figure 2a, where we consider only semi-lexical tokens for wheel and frame. The tagged components decide the truth of the predicates wheel and frame, for example if the network identifies one wheel w 1 and a bicycle frame f the predicates wheel(w 1 ) and f rame(f ) are set to true. The inrange predicate is set to true if the euclidean distance between the identified components lie within permitted range, the range check also ensures that the identified components are unique. For bicycles, range = [min distance , max distance ] between two components is calculated over the training dataset T . Distance between component c 1 and c 2 of the i th instance distance i = {(c 1x − c 2x )/w} 2 + {(c 1y − c 2y )/h} 2 where w and h are the width and height of image i .
If the network is unable to identify all the components required for logical deduction in the first pass (for example, if only one wheel of a bicycle was identified), then we mask the identified components and reduce the threshold by = 0.1 and continue searching for the required parts until the component is found or threshold ≥ 0.2. Drawing parallel from the semi lexical integrity constraints formalised for handwritten digits in Section 3 the reduced threshold search enforces reasoning assisted similarity constraint, trying to look for other components of an object in the pictures if some supporting component for the object is found. After the object is identified to belong to a particular class, we check for similarity between two similar types of components using Equation 2 to enforce reasoning assisted dissimilarity constraint. If the two components are not similar, they are tagged to be inconsistent. For example, in Figure 2c, one of the wheels belong to a motorcycle. Even though the rules are satisfied, this wheel will not be tagged as a part of the bicycle.
A semi-lexical analysis reduces the burden on pure machine learning. For example, the traditional YOLOv2 network used for detecting complete objects uses 9 convolutional layers. In our setup, we need to identify the components rather than objects, and therefore we use a smaller network with substantially less training data. Based on the performance of different plots in Figure 2b we chose a network with 7 layers. The proposed bicycle detection methodology is tested with clear bicycle images from Caltech256 and WSID-100 [Yao et al., 2019] data sets. The algorithms are tested with unicycle and tricycle images as well, which do not require any extra learning because the components are the same. The results obtained are shown in Table 1. Table 1 illustrates that semi-lexical deduction outperforms standard CNN based identification techniques in terms of F1 score, that is, our model maintains good precision recall balance in all cases when tested on different bicycle data-sets.  Though the VGG16 network with only classifier retrained layer has better accuracy, its feature extraction layers are trained on Imagenet dataset [Deng et al., 2009] and the network miss classifies objects like tennis racket, cannon, etc. as bicycle lacking in precision. Our method has the added advantage of low data requirement (trained on only 100 bicycles), explainability in terms of choice of tokens that trigger the final classification outcome and detecting classes of objects sharing similar components without training.

Related Work
CNN's have shown exceptional performance in computer vision tasks like image recognition, object localization, segmentation, etc. [He et al., 2016;Girshick et al., 2014;Redmon and Farhadi, 2016]. Unfortunately, CNN's lack interpretability, which is necessary for learning complex scenarios in a transparent way, and are known to fail in simple logical tasks such as learning a transitive relation [Saxton et al., 2019]. These networks are also susceptible to adversarial attacks [Szegedy et al., 2013;Goodfellow et al., 2014] and are bad at retaining spatial information [Hinton et al., 2018]. Such weaknesses occur as the network latches onto certain high dimensional components for pattern matching [Jetley et al., 2018]. Another major drawback that deep learning faces is the requirement of huge amounts of annotated data. Hence, a lot of current research advocates merging the power of both connection based and symbol-based AI [Garnelo and Shanahan, 2019;Yang et al., 2017;Evans and Grefenstette, 2018;Wang et al., 2019]. These works aim at solving problems using a SAT optimization formulation. However, the methods are limited by their memory requirements. Other advances, like neuro-symbolic concept learner, proposes hybrid neuro-symbolic systems that use both AI systems and Neural Networks to solve visual question answering problems [Mao et al., 2019], have the advantage of exploiting structured language prior.
For computer vision tasks symbolic formulation of image grammar has been explored using stochastic AND-OR graphs that are probabilistic graphical models that aim to learn the hierarchical knowledge semantics hidden inside an image [Zhu and Mumford, 2006]. The parse graph generated from a learnt attribute graph grammar is traversed in a top-down/bottom-up manner to generate inferences while maximizing a Bayesian posterior probability. This method requires a large number of training examples to learn the probability distribution. Also, the graph can have exponentially large number of different topologies. Methods that use pure symbolic reasoning for identification, like ellipse and triangle detection for bicycle identification [Lin and Young, 2016], do not generalize well. Works by [Lake et al., 2015] learn concepts in terms of simple probabilistic programs which are built compositionally from simpler primitives. These programs use hierarchical priors that are modified with experience and are used as generative models rather than identification. Also, [Chaofan Chen, 2019] uses special prototypical layers at the end of the model that learns small parts called prototypes from the training image. The test image is then broken into parts and checked for similarity against the learnt prototype parts and prediction is made based on a weighted combination of the similarity scores. In general, the methods discussed do not account for ambiguous tokens that can exhibit overlapping membership in multiple classes.

Conclusions
The real world often presents itself in wide diversity, and capturing such diversity purely in symbolic form is not practical. Therefore, inherent in our ability to interpret the real world is a mapping from the non-lexical artifacts that we see and the lexical artifacts that we use in our reasoning. Semi-lexical languages, as we propose in this paper, provides the formal basis for such reasoning. For implementing this notion on real world problems in computer vision, we use machine learning (ML) to learn the association between the non-lexical real world and the alphabet of the formal language used in the underlying reasoning system. An important difference with related work is that the ML-based interpretation of the real world is assisted by the reasoning system through the similarity / dissimilarity consistency constraints.