(Source code of this post is available here)

Propositional Logic

Propositional logic is the foundational study of logical statements. It helps us to analyze overall truth of statements, how statements are connected to form arguments and whether conclusion follows from premises in an argument etc. So, any declaration of statement with a truth value is a proposition in classical logic.

A statement yields either True or False. For example:

$$ P = \text{Earth has an atmosphere} $$

P is a valid statement since it yields True. Another example:

$$ Q = \text{Istanbul is the capital of Türkiye} $$

Q is also a valid statament since it yields False. (Despite the popular belief, Istanbul is not the capital of Türkiye, Ankara is.)

Check out the statement S:

$$ S = \text{How many integer divisors exist for 100?} $$

S is not a valid statement since there is not a simple True or False answer to it. However, consider statement R:

$$ R = \text{Is 10 is a positive integer divisor of 100?} $$

R, on the other hand, is a valid statement since it can yield either True or False.

Statement by themselves are not particularly useful. However, if we combine and build relations among the statements, we can get insteresting outcomes.

Logical Connectives

Logical connectives are helpful for building relation among proposotinal statements. Basically we have following connectives:

$$ \begin{array}{l|c|c} \text{Formal name} & \text{Symbol} & \text{Read as} \\ \hline \text{Negation (NOT)} & \neg X_1 & \text{not } X_1 \\ \text{Conjunction (AND)} & X_1 \land X_2 & X_1 \text{ and } X_2 \\ \text{Disjunction (OR)} & X_1 \lor X_2 & X_1 \text{ or } X_2 \\ \text{Implication (Conditional)} & X_1 \to X_2 & \text{If } X_1 \text{ then } X_2 \\ \text{Equivalence (Biconditional)} & X_1 \leftrightarrow X_2,\ X_1 \equiv X_2 & X_1 \text{ if and only if } X_2 \end{array} $$

In the previous post, I have implemented conjuction, disjuction and negation. But we also need the implementation of logical implication and equivalence as well.

(NOTE: traditionally $P$ and $Q$ symbols are more common in textbooks. However, I am used to working with multi-dimentional arrays. I believe the notation with $X_1, X_2, \dots$ will prove handy in the future.)

Logical Implication

Implication truth table is given below. We can see that implication is only Fase when $X_1$ is True and $X_2$ is False. This can be hard to grasp, so let’s break it down before advancing further.

$$ \begin{array}{c|c|c|c} X_1 & X_2 & X_1 \rightarrow X_2 & \neg X_1 \lor X_2 \\ \hline \text{T} & \text{T} & \text{T} & \text{T} \\ \text{T} & \text{F} & \text{F} & \text{F} \\ \text{F} & \text{T} & \text{T} & \text{T} \\ \text{F} & \text{F} & \text{T} & \text{T} \end{array} $$

Implication is in the form: If CONDITION STATEMENT, then OUTCOME STATEMENT. Consider the imaginatory example where I work in a research company:

  • $X_1$ (The condition): I publish an article in journal A.
  • $X_2$ (The outcome): Company will allocate more GPUs.
  • $X_1 \rightarrow X_2$: If I publish an article, then company will allocate more GPUs.

Scenerio 1 ($X_1$ is True, $X_2$ is True): This is a straightforward case where I and company both keep the word. Therefore, implication is True.

Scenerio 2 ($X_1$ is True, $X_2$ is False): This is a broken promise case where I keep my word in publishing in journal A. However, company lied and did not allocate more GPUs. Since it is broken, implication is False.

Scenerio 3 ($X_1$ is False, $X_2$ is True): I publish an article in journal B, not A. But company was kind enough to reward me anyway. This is the most confusing “vacuous truth” scenerio. Was the original condition broken? No, because the coniditon stated that article should be published in journal A, it did not say anything about journal B. Implication is still considered True.

Scenerio 4 ($X_1$ is False, $X_2$ is False): I did not publish an article and company did not allocate more GPUs. Nothing is broken, so the implication is True.

Differential Implementation of Implication

From the truth table you can see that logical implication $X_1 \rightarrow X_2$ is just $\neg X_1 \lor X_2$. Since we already implemented negation and disjunction with t-norms and t-conorms, implication will also be differentialable in range $[0.0, 1.0 ]$. JAX implementation with t-conorms is given below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import jax
import jax.numpy as jnp

from functools import partial

from logic_utils import print_binary, plot_norm_functions
from triangular_norms import diff_and, diff_or, diff_not


# x1: True, True, False, False
x1 = jnp.array((0.95, 0.88, 0.21, 0.16))
# x2: True, False, True, False
x2 = jnp.array((0.71, 0.02, 0.99, 0.10))

def diff_implies(x1, x2, name_tconorm):
    return diff_or(diff_not(x1), x2, name_tconorm)

diff_implies_maximum  = partial(diff_implies, name_tconorm='maximum')
diff_implies_prob_sum = partial(diff_implies, name_tconorm='probabilistic_sum')
diff_implies_bounded  = partial(diff_implies, name_tconorm='bounded')

For example, truth outpus for the probailisitic sum t-conorm realization of the implies given below:

1
2
x_imp = diff_implies_prob_sum(x1, x2)
print_binary(x_imp)
0.72 --> 1 (True)
0.14 --> 0 (False)
1.00 --> 1 (True)
0.86 --> 1 (True)

Plot for the all possible t-conorm realizations are given below. We can see from the plots that logical implication mostly True except for the case $X_1=\text{True}$ and $X_2=\text{False}$. Just like the previous post, probabilistic sum gives the smoothest truth outputs.

A plot showing logical implication realized by Maximum (Gödel) T-conorm function with axes ranging from 0 to 1 for approximated logic values
A plot showing logical implication realized by Probabilistic Sum function with axes ranging from 0 to 1 for approximated logic values
A plot showing logical implication realized by Bounded (Łukasiewicz) T-conorm function with axes ranging from 0 to 1 for approximated logic values

Logical Equivalence

Logical equivalence considers the scenerio if and only if. So both of propositions should be the True or False at the same time for equivalence to be True. Impilication is one directional, equivalence on the other hand, is bidirectional. You can see from the truth table below, $X_1 \leftrightarrow X_2$ is just conjuction of implication in both directions $(X_1 \rightarrow X_2) \land (X_2 \rightarrow X_1)$.

$$ \begin{array}{c|c|c|c} X_1 & X_2 & X_1 \leftrightarrow X_2 & (X_1 \rightarrow X_2) \land (X_2 \rightarrow X_1) \\ \hline \text{T} & \text{T} & \text{T} & \text{T} \\ \text{T} & \text{F} & \text{F} & \text{F} \\ \text{F} & \text{T} & \text{F} & \text{F} \\ \text{F} & \text{F} & \text{T} & \text{T} \end{array} $$

Differential Implementation of Equivalence

For 3 t-norm and 3 t-conorm realizations, we have total 9 possible equivalence realizations. It is hard to display 9 outputs, so I’ll just stick with product t-norm and probabilistic sum t-conorm for smoother truth outputs. JAX implementaion with t-norm and t-conorm is given below:

1
2
3
4
5
6
7
def diff_equivalence(x1, x2, name_tnorm, name_tconorm):
    return diff_and(diff_implies(x1, x2, name_tconorm), diff_implies(x2, x1, name_tconorm), name_tnorm)

diff_equivalence_product_prob_sum = partial(diff_equivalence, name_tnorm='product', name_tconorm='probabilistic_sum')

x_equiv = diff_equivalence_product_prob_sum(x1, x2)
print_binary(x_equiv)
0.70 --> 1 (True)
0.14 --> 0 (False)
0.22 --> 0 (False)
0.78 --> 1 (True)

Plot for the logical equivalence (with product t-norm and probabilistic sum t-conorm) is given below. We can see that most of the True outputs are concentrated when $X_{1,2}=\text{True}$ or $X_{1,2}=\text{False}$. Outputs are False when $X_1=\text{True}$, $X_2=\text{False}$ or vice versa. Interestingly, we have a transient region around the diagonal where outputs are close to True ($\geq 0.5$) but not fully True like the corners. This is unique to norm function realizations since they operate on approximated real values of truth in range $[0.0, 1.0]$.

A plot showing logical equivalence realized by Product t-norm and Probabilistic Sum functions with axes ranging from 0 to 1 for approximated logic values

Arguments and Deduction

An argument is a sequential combination of premises and conclusion, where each premise and conclusion is a statement. Our job is to see if premisses deductively entail a conclusion or not.

$$ \begin{array}{l} \hspace{1.3em} \text{If the weather is clear, then I will go outside} \\ \hspace{1.3em} \text{The weather is clear} \\ \hline \therefore \hspace{0.3em} \text{I will go outside} \end{array} $$

All the statements above the line are premises. The symbol $\therefore$ above mean “therefore” and statement given next to it is conclusion. Given all the statements, we can perform two types of reasoning here: deductive and inductive. In deductive reasoning, if all premises are True, the conclusion must be True. In inductive reasoning, premises make the conclusion probabily True (similar to statistical estimation). So deductive reasoning gives 100% guarantee whereas inductive does not.

In general, we can perform reasoning inference with such methods: modus ponens, modus tollens, hypothetical syllogism and disjunctive syllogism. Of course, these are not the only methods but the most prominent ones. We will focus on modus ponens and tollens for now.

Modus Ponens

Below is the deductive form of modus ponens. If we go back and see the truth table of logical implication, we can see that if $X_1 \rightarrow X_2$ is True and $X_1$ is True, then $X_2$ must be True. So we can deduce the result of $X_2$ from $(X_1 \rightarrow X_2) \land X_1$.

$$ \begin{array}{l} \hspace{1.3em} X_1 \rightarrow X_2 \\ \hspace{1.3em} X_1 \\ \hline \therefore \hspace{0.3em} X_2 \end{array} $$

Modus Tollens

Below is the deductive form of modus tollens. Similarly from the logical implication truth table, we see that if $X_1 \rightarrow X_2$ is True and $X_2$ is False ($\neg X_2$ is True), then $X_1$ must be False ($\neg X_1$ is True). Again we can deduce the result of $\neg X_1$ from $(X_1 \rightarrow X_2) \land \neg X_2$.

$$ \begin{array}{l} \hspace{1.3em} X_1 \rightarrow X_2 \\ \hspace{1.3em} \neg X_2 \\ \hline \therefore \hspace{0.3em} \neg X_1 \end{array} $$

Chain of Premises

In general, we can have more than one premise and we only we have a single conclusion. This builds a chain of reasoning that is for more complex logical deductions.

$$ \begin{array}{r} \hspace{1.3em} X_1 \\ \hspace{1.3em} X_2 \\ \vdots\phantom{_1} \\ \hspace{1.3em} X_n \\ \hline \therefore \hspace{0.3em} X_m \end{array} $$

(Note: There is no example of this chain structure in this post. However, it shall prove useful for the upcoming posts.)

First Order Logic

We investigated the propositional logic with simple statements. However, simple statement are often not sufficient enough represent deductions. First order logic extends propositional logic by introducing variables, quantifiers, and predicates. This gives more expressive power.

For example, consider the simple weather deduction example: if a variable temperature $Temp$ is above a variable condition $Cond$, then weather is sunny.

$$ \text{IF } (Temp > Cond) \text{, THEN weather is sunny.} $$

Notice that this is in fact a form of logical implication. So we can write the modus ponens and tollens forms of the deduction below:

$$ \begin{array}{l} \hspace{1.3em} (Temp > Cond) \rightarrow \text{The weather is sunny} \\ \hspace{1.3em} (Temp > Cond) \\ \hline \therefore \hspace{0.3em} \text{The weather is sunny} \end{array} $$

$$ \begin{array}{l} \hspace{1.3em} (Temp > Cond) \rightarrow \text{The weather is sunny} \\ \hspace{1.3em} \text{The weather is NOT sunny} \\ \hline \therefore \hspace{0.3em} \neg (Temp > Cond) \end{array} $$

Predicates

Predicates are useful for evaluating statements with variables into $\{\text{True}, \text{False}\}$ depending on the values assigned to those variables. Unlike simple propositions, predicates allow logic to build relations.

In the example above, we need to compute the truth value of $(Temp > Cond)$ where both $Temp\text{, } Cond \in \mathbb{R}$. Programatically we can get the result with a simple if/else block of code of course, but remember that we need a continuous truth value that is in $[0.0, 1.0]$. How can we compute a real valued $\mathcal{T}_{Cond}$ from $(Temp > Cond)$ that gives dynamic range of truth given the values of $Temp$ and $Cond$? Continuous relaxation methods can help with that.

Continuous Relaxations

Continuous relaxations are linear programming methods that converts a hard decision variable into a soft real valued variables (Bourguignon et al., 2016; Nowak, 2005). This enables us to convert a non-differentiable decision into a differentiable one. We can learn and optimize conditions for different datasets.

Logistic Sigmoid Function

Logistic sigmoid (or simply sigmoid) is a common and useful function for implementing relaxations that can squeeze any $x \in \R$ into the range $[0.0, 1.0]$. It is shown that sigmoid relaxations provide continuous truth values for inequalties (Dombi & Jónás, 2022; Semenov, 2025). But first, let’s define it below:

$$\sigma(x) = \frac{1}{1 + e^{-x}} \tag{1}$$

This is convinent for us but we also need to set a condition.

Greater-Than Relaxation

This function provides a differentiable approximation of a binary decision that outputs near 1.0 (evaluates to True) when $x > c$ and 0.0 otherwise (evaluates to False). This function takes three parameters: input value/array $x$, $c$ condition (referred as $Cond$ above) and steepnees $s$ which controls how hard or soft the decision is.

$$\sigma_{\text{gt}}(x, c, s) = \sigma(s(x - c)) = \frac{1}{1 + e^{-s(x - c)}} \tag{2}$$

Less-Than Relaxation

Similarly, differentiable approximation of $x < c$ that outputs near 1.0 (evaluates to True) and 0.0 otherwise (evaluates to False) with the given form below with the same input parameters.

$$\sigma_{\text{lt}}(x, c, s) = \sigma(s(c - x)) = \frac{1}{1 + e^{-s(c - x)}} \tag{3}$$

Implementation of Continuous Relaxations in JAX

Using JAX, implementations of equations 1, 2 and 3 are given below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
NUM_SAMPLES = 100
x1 = jnp.linspace(10.0, 50.0, NUM_SAMPLES)

def sigmoid(x):
    return 1.0 / (1.0 + jnp.power(jnp.e, -x))

def logistic_sigmoid_relaxation_gt(x, condition, steepness):
    """
    True for points satisfying: x > condition
    """
    return sigmoid(steepness*(x-condition))

def logistic_sigmoid_relaxation_lt(x, condition, steepness):
    """
    True for points satisfying x < condition
    """
    return sigmoid(steepness*(condition-x))

The two plots of $x_i > 40$ and $x_i < 40$ relaxations for $x_i$ values of range $[10.0, 50.0]$ are given below. As we can observe, output is 1.0 (True) for inputs where condition is met and 0.0 (False) for vice versa. There is also a transition area occurs just around the condition (in this case 40) due to the nature of sigmoid.

A plot showing continuous relaxation outputs of logistic sigmoid where x-axis is real valued input and y-axis ranging from 0 to 1 for approximated truth output for the greater-than condition value
A plot showing continuous relaxation outputs of logistic sigmoid where x-axis is real valued input and y-axis ranging from 0 to 1 for approximated truth output for the less-than condition value

Steepness is also another input that determines the “sharpness” of the transition area. If we are to increase the steepness, transition gets very sudden. Thus, decision is harder and stricter when steepness is higher. Two plots below demostrate this with condition is set to 20 with high steepness.

A plot showing continuous relaxation outputs of logistic sigmoid where x-axis is real valued input and y-axis ranging from 0 to 1 for approximated truth output for the greater-than condition value with higher steepness
A plot showing continuous relaxation outputs of logistic sigmoid where x-axis is real valued input and y-axis ranging from 0 to 1 for approximated truth output for the less-than condition value with higher steepness

Gradient Vanishing Problem

If you observe the plots above carefully, you will see that the most of the truth output of relaxation is flat for wide range of input values. This makes gradient based optimization of truth difficult since derivatives are zero for most of the input. Since we receive little or no learning feedback from relaxations, we can’t update our variables to improve the desired output.

We can compute and plot the gradients per input sample with the code below where JAX’s vmap is used to map each input x1 to grad_fn.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
CONDITION = 30.0
STEEPNESS = 1.0

x_res = logistic_sigmoid_relaxation_gt(x1, CONDITION, STEEPNESS)

grad_fn = jax.grad(logistic_sigmoid_relaxation_gt, argnums=(1,))
grad_fn_per_sample = jax.vmap(grad_fn, in_axes=(0, 0, 0))

c_vmap = jnp.full_like(x_res, fill_value=CONDITION)
s_vmap = jnp.full_like(x_res, fill_value=STEEPNESS)
grad_c_per_sample = grad_fn_per_sample(x1, c_vmap, s_vmap)[0]

plt.plot(x1, x_res, linewidth=3.0, label='Sigmoid', c='b')
plt.plot(x1, grad_c_per_sample, linewidth=3.0, label='Gradients', c='r')
plt.title(f'Gradients per Sample for {r"$x_i$"} > {CONDITION}')
plt.xlabel(r"$x_i$")
plt.ylabel('Truth/Grad Value')
plt.grid('on')
plt.legend()
plt.tight_layout()
plt.savefig(
    'grad_fn_per_sample.png',
    bbox_inches='tight', 
    dpi=300
)

From the two plots below we can clearly see that the gradients are only useful for a very small range that is in the transition area. Higher steepnesss is even worse, gradients only exist for a tiny range and also jumps suddenly from 0.0 to -1.0 which is unstable.

A plot showing gradient per sample input of continuous relaxation outputs of logistic sigmoid where x-axis is real valued input and y-axis ranging from 0 to 1 for approximated truth output for the greater-than condition value with higher steepness
A plot showing gradient per sample input of continuous relaxation outputs of logistic sigmoid where x-axis is real valued input and y-axis ranging from 0 to 1 for approximated truth output for the less-than condition value with higher steepness

Fortunately, we can apply feature scaling to input values such that only the non-flat transition area is present. For sigmoid, range of $[-4.0, 4.0]$ works best.

Differential Optimziation of Relaxations

So far so good, let’s train a relaxtion using synthetic toy data $x_{\text{data}}$. We initalize our initial condition $x_{\text{Cond}}$ as the mean of available data points and set a target condition of $Cond_{\text{target}} = 20$ arbitrarily.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
x_data = jnp.array([
    42.0, 7.0, 89.0, 13.0, 56.0, 3.0, 74.0, 91.0, 28.0, 65.0,
    17.0, 100.0, 34.0, 82.0, 5.0, 49.0, 76.0, 21.0, 68.0, 11.0,
    93.0, 37.0, 60.0, 1.0, 84.0, 25.0, 53.0, 72.0, 16.0, 98.0
])

# INITIALIZE THE CONDITION AS THE MEAN OF THE DATASET
x_condition = jnp.mean(x_data)
print(f'Initial condition: {x_condition.item():2.4f}')

# SET TRUE THE FOR TARGET OR ABOVE
TARGET_CONDITION = 20.0
x_target = (x_data>TARGET_CONDITION).astype(jnp.float32)
print(x_target)

As you see from below, we have a binary classification task where $x_{\text{Cond}} > Cond_{\text{target}}$ is 1 else is 0. Our job is to learn and update the initial $x_{\text{Cond}}$ using $x_{\text{target}}$ such that the $Cond_{\text{target}}$ is achived.

Initial condition: 49.0000
[1. 0. 1. 0. 1. 0. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 1. 1. 1. 0. 1. 1. 1. 0.
 1. 1. 1. 1. 0. 1.]

Feature Scaling

We discuessed before that sigmoid relaxation works better when feature values ($x_{\text{data}}$) are scaled into $[-4.0, 4.0]$. Here we use the scikit-learn’s MinMaxScaler to do the job.

1
2
3
4
5
6
7
8
9
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler(feature_range=(-4.0, 4.0))

x_data_scaled = scaler.fit_transform(x_data.reshape(-1, 1).copy()).ravel()
print(x_data_scaled)

x_condition_scaled = scaler.transform(x_condition.reshape(-1, 1).copy()).ravel()
print(x_condition_scaled)

Features are now in scaled range:

[-0.68686867 -3.5151515   3.1111112  -3.030303    0.44444418 -3.838384
  1.8989897   3.272727   -1.818182    1.1717172  -2.7070708   3.9999995
 -1.3333335   2.5454545  -3.6767678  -0.12121224  2.060606   -2.3838384
  1.4141412  -3.1919193   3.4343433  -1.0909092   0.76767683 -4.
  2.7070708  -2.0606062   0.20202017  1.7373738  -2.787879    3.8383837 ]

Scale the $x_{\text{Cond}}$ as well:

1
2
x_condition_scaled = scaler.transform(x_condition.reshape(-1, 1).copy()).ravel()
print(x_condition_scaled)
[-0.12121201]

From the plotting below, we can see that there is no flat surfaces in the scaled range. This stabilizes the gradient updates and overall learning.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
STEEPNESS = 1.0

# GRADS ARE MUCH STABLE HERE
plt.scatter(
    x_data_scaled, 
    logistic_sigmoid_relaxation_gt(x_data_scaled, x_condition_scaled, STEEPNESS),
    linewidth=3.0
)
plt.title(f'Relaxation of Sigmoid for {r"$x_i$"} < {x_condition_scaled.item():2.4f}')
plt.xlabel(r"$x_i$")
plt.ylabel('Truth Value')
plt.grid('on')
plt.tight_layout()
plt.savefig(
    'logistic_sigmoid_relaxation_gt_scaled_input.png',
    bbox_inches='tight',
    dpi=300
)
A plot showing continuous relaxation outputs of logistic sigmoid without any flat surface

Main Optimization Loop

Our training objective is to maximize the truth value $\mathcal T_{i}$ of equation 4 where $x_{i}$ is a sample of $x_{\text{data}}$, $x_{\text{Cond}}$ is the condition value we wish to optimize and $s$ is the steepness of the condition. Logical equivalence is used to bidirectonally map the truth output of condition given $x_{\text{Cond}}$ that should be equal to our target $x_{\text{target}}$.

$$ \mathcal T_{i} = \sigma_{\text{gt}}(x_{i}, x_{\text{Cond}}, s) \leftrightarrow x_{\text{target}} \tag{4} $$

Equation 4 yields truth per sample. In order to get the final truth $\mathcal T_{\text{final}}$, we calculate the average given in the equation 5 for number of $N$ total samples in our dataset.

$$ \mathcal T_{\text{final}} = \frac{1}{N}\sum_{i=1}^{N} \mathcal T_{i} \tag{5} $$

(In this case we don’t need batch processing since dataset is very small and can fit into memory.)

Although other gradient based methods exists (Krutikov et al., 2022) for relaxation, we will keep it simple and use gradient ascent to maximize the $\mathcal T_{\text{final}}$. Equation 6 shows the gradient ascent update for $x_{\text{Cond}}$ with the learning rate of $\alpha$.

$$ x_{\text{Cond}} = x_{\text{Cond}} + \alpha \cdot \frac{\partial \mathcal T_{\text{final}}}{\partial x_{\text{Cond}}} \tag{6} $$

After sufficient epochs of updates, we will get a $x_{\text{Cond}}$ such that gives us the maximum truth for satisfying our objective. Final training code is given below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from functools import partial

from triangular_norms import diff_equivalence

diff_eq_prod_sum = partial(diff_equivalence, name_tnorm='product', name_tconorm='probabilistic_sum')

def final_truth(x, c, s, target):
    pred = logistic_sigmoid_relaxation_gt(x, c, s)
    truth_i = diff_eq_prod_sum(pred, target)
    return jnp.mean(truth_i)

grad_fn = jax.value_and_grad(final_truth, argnums=(1,))

STEEPNESS = 1.0
LEARNING_RATE = 1.0
NUM_EPOCHS = 140

for epoch in range(1, NUM_EPOCHS+1):

    final_truth, grads = grad_fn(x_data_scaled, x_condition_scaled, STEEPNESS, x_target)

    # PUSH CONDITON TOWARDS TO MAX TRUTH POINT
    x_condition_scaled = x_condition_scaled + LEARNING_RATE*grads[0]

    acc = 100.0 * (jnp.sum((x_data_scaled > x_condition_scaled).astype(jnp.int32) == x_target) / len(x_target))

    if epoch % 20 == 0:
        print(f'Epoch: {epoch:>3}, Truth: {final_truth.item():2.2f} Accuracy: {acc.item():2.2f}%')
Epoch:  20, Truth: 0.82 Accuracy: 90.00%
Epoch:  40, Truth: 0.84 Accuracy: 93.33%
Epoch:  60, Truth: 0.85 Accuracy: 96.67%
Epoch:  80, Truth: 0.85 Accuracy: 96.67%
Epoch: 100, Truth: 0.85 Accuracy: 96.67%
Epoch: 120, Truth: 0.85 Accuracy: 96.67%
Epoch: 140, Truth: 0.85 Accuracy: 100.00%

Learned Condition

Maximum $\mathcal T_{\text{final}}$ and accuracy of 100% is achieved around epoch 140. Remeber target condition was set to $Cond_{\text{target}} = 20$ at the beginning of section and our learned condition is around $x_{\text{Cond}} \approx 21$. So, we learned a condition based on evidence that is very close to our target.

1
2
3
4
5
6
x_final_condition_scaled = x_condition_scaled.copy()
# RESCALE BACK TO ORIGINAL
x_final_condition = scaler.inverse_transform(x_final_condition_scaled.reshape(-1, 1)).ravel()

print(f'Target condition: {TARGET_CONDITION:2.2f}')
print(f'Learned condition: {x_final_condition.item():2.2f}')
Target condition: 20.00
Learned condition: 20.98

Final decision making is plotted below. We can observe that the learned $x_{\text{Cond}}$ makes a good split of different targets with the color emphasis of targets.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
colors = ['blue' if l == 0 else 'green' for l in x_target]

plt.scatter(
    x_data, 
    logistic_sigmoid_relaxation_gt(x_data, x_final_condition, STEEPNESS), 
    c=colors,
    linewidth=3.0
)
plt.title(f'Results for {r"$x_i$"} > {x_final_condition.item():2.2f}')
plt.xlabel(r"$x_i$")
plt.ylabel('Truth Value')
plt.grid('on')
plt.tight_layout()
plt.savefig(
    'logistic_sigmoid_relaxation_gt_training_results.png',
    bbox_inches='tight',
    dpi=300
)
A plot showing continuous relaxation outputs of logistic sigmoid for trained condition and truth results on a synthetic dataset

Weather Type Deduction

Previous section demostrated the learnable condition using continuous relaxation. In this section, we will put together everything to build a weather deduction method. First we need a dataset to use as evidences of truth. Weather Type Classification (Narayan, 2024) dataset fits the purpose. Dataset is loaded as a pandas dataframe below:

1
2
3
4
import pandas as pd

df_weather = pd.read_csv('./weather_classification_data.csv')
df_weather.head()
A screenshot of weather type classification dataset loaded as a pandas dataframe where first five rows is printed

In the previous example, we kept everything simple and minimal. This time we will build a modern data science pipeline that takes into account: class distribution, train/test split, feature scaling, better metrics and analysis, etc.

Hyperparameters

Hyperparameters are “high-level” parameters that control how learning proceeds. This also where we setup our relaxation method.

1
2
3
4
5
6
7
8
SEED = 1234 # FOR REPRODUCIBILITY
SPLIT_RATIO = 0.2 # 80% TRAINING, 20% TEST SPLIT

STEEPNESS = 1.0
NUM_EPOCHS = 20
LEARNING_RATE = 0.01

relaxation_fn = logistic_sigmoid_relaxation_gt

Class Distribution

Let’s start with investigating class distribution. This is important for avoiding possible biases that can be incuded during learning. Luckyly for us, weather type classification dataset is perfectly balanced.

1
df_weather['Weather Type'].value_counts()
Weather Type
Rainy     3300
Cloudy    3300
Sunny     3300
Snowy     3300
Name: count, dtype: int64

Train/Test Split

Splitting dataset into training and testing a must practice. It helps to measure how our method works outside the training samples. In this case, we will split 80% training and 20% testing. Scikit learn’s train_test_split function helps us equally distribute classes among training and testing splits.

1
2
3
4
5
6
7
8
9
from sklearn.model_selection import train_test_split

df_features_train, df_features_test, df_labels_train, df_labels_test = train_test_split(
    df_weather.drop(columns=['Weather Type']),
    df_weather['Weather Type'],
    test_size=SPLIT_RATIO,
    random_state=SEED,
    stratify=df_weather['Weather Type'], # ENSURE LABELS DISTRIBUTED EQUALLY
)

Select & Scale Features to Learn

The obvious must-have are features and target to use as evidence for training the condition. Here we select the feature and target columns of dataframe, scale them to stabilize the gradients and just like before, we set the initial condition $x_{\text{Cond}}$ to be the mean of the selected features.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
FEATURE_NAME = 'UV Index'
TARGET_NAME = 'Sunny'

# [-4.0, 4.0] RANGE IS FOR SIGMOID NUMERICAL STABILITY
scaler = MinMaxScaler(feature_range=(-4.0, 4.0))

df_features_train[[FEATURE_NAME]] = scaler.fit_transform(df_features_train[[FEATURE_NAME]])
df_features_test[[FEATURE_NAME]] = scaler.transform(df_features_test[[FEATURE_NAME]])

x_features_train = jnp.array(df_features_train[FEATURE_NAME])
x_features_test = jnp.array(df_features_test[FEATURE_NAME])
x_target_train = jnp.array((df_labels_train == TARGET_NAME).astype(jnp.float32))
x_target_test = jnp.array((df_labels_test == TARGET_NAME).astype(jnp.float32))

# INITIALIZE CONDIITON AS THE MEAN OF THE COLUMN
x_condition = jnp.mean(x_features_train)

Main Optimization Loop

Main objetive is very similar to the previous example. We wish to find $x_{\text{Cond}}$ such that relaxed truths are biconditional mapped to targets (in this case it is the Sunny class).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def final_avg_truth(x, c, s, target):
    pred = relaxation_fn(x, c, s)
    truth_i = diff_eq_prod_sum(pred, target)
    return jnp.mean(truth_i)

grad_fn = jax.value_and_grad(final_avg_truth, argnums=(1,))

inv_transform = lambda x: scaler.inverse_transform(x.reshape(-1, 1)).ravel()

for epoch in range(1, NUM_EPOCHS+1):
    loss, grads = grad_fn(x_features_train, x_condition, STEEPNESS, x_target_train)
    x_condition = x_condition + LEARNING_RATE*grads[0]

    ###### FOR METRICS ONLY ######
    x_pred_train = relaxation_fn(x_features_train, x_condition, STEEPNESS)
    pred_dict_train = calculate_metrics(x_pred_train, x_target_train)
    ##############################
    
    print(f'Epoch: {epoch:2d}, Truth: {loss:2.2f}, Accuracy: {pred_dict_train["Accuracy"].item():2.2f}%, F-1: {pred_dict_train["F-1"].item():2.2f}')

After roughly 20 epochs, we accuracy $\approx$ 87% with F-1 $\approx$ 0.78 as given below. F-1 metric is purposfully added here because accuracy can be misleading in unequally distributed classes. Our dataset is initial equally distributed but when we select by TARGET_NAME, we broke class distribution to 25% of “1s” and rest 75% to “0s”. Thus, resulting training/testing targets are unequally distributed.

Epoch:  1, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch:  2, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch:  3, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch:  4, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch:  5, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch:  6, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch:  7, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch:  8, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch:  9, Truth: 0.71, Accuracy: 81.61%, F-1: 0.72
Epoch: 10, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 11, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 12, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 13, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 14, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 15, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 16, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 17, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 18, Truth: 0.72, Accuracy: 81.61%, F-1: 0.72
Epoch: 19, Truth: 0.72, Accuracy: 86.96%, F-1: 0.78
Epoch: 20, Truth: 0.72, Accuracy: 86.96%, F-1: 0.78

Testing Metrics

Let’s invert back our values to original scale and test how well our learned $x_{\text{Cond}}$ performs non-training (i.e. testing split) data.

1
2
3
x_features_train = inv_transform(x_features_train)
x_features_test = inv_transform(x_features_test)
x_condition = inv_transform(x_condition)
1
2
3
4
5
6
x_pred_test = relaxation_fn(x_features_test, x_condition, STEEPNESS)

pred_dict_test = calculate_metrics(x_pred_test, x_target_test)

for m_name, m_val in pred_dict_test.items():
    print(f'{m_name:<10}:{m_val.item():2.2f}')

The calcute_metrics function calcules all the classification metrics below. We observe strong recall of 0.93 which means $x_{\text{Cond}}$ correctly seperates most samples with relatively few false negatives (43). However, its precision of 0.66 shows a notable number of false positives (320), meaning some “Sunny” predictions are correct. But remeber that we are using single column feature with single learnable condition. At this simplicity, these results are acceptable.

Accuracy  :86.25
TP        :617.00
TN        :1660.00
FP        :320.00
FN        :43.00
Precision :0.66
Recall    :0.93
F-1       :0.77

Deduction with Modus Ponens and Tollens

Finally, let’s implement the deduction methods that we discussed at the Arguments and Deduction and Fist Order Logic section. Our learned rule based on evidence is given below.

1
2
3
4
5
6
# WE WILL USE THE F-1 AS CONFIDENCE INDICATOR
rule_confidence = pred_dict_test['F-1']

print('LEARNED RULE:')
print(f'If {FEATURE_NAME} > {x_condition.item():2.2f} THEN, CLASS: {TARGET_NAME}')
print(f'(Confidence: {rule_confidence:2.2f}%)')
LEARNED RULE:
If UV Index > 4.00 THEN, CLASS: Sunny
(Confidence: 0.77%)

Based on the learned condition, we can write the modus ponens rule below:

$$ \begin{array}{l} \hspace{1.3em} (\text{UV Index} > 4.0) \rightarrow \text{The weather is sunny} \\ \hspace{1.3em} (\text{UV Index} > 4.0) \\ \hline \therefore \hspace{0.3em} \text{The weather is sunny} \end{array} $$

and the modus tollens rule below:

$$ \begin{array}{l} \hspace{1.3em} (\text{UV Index} > 4.0) \rightarrow \text{The weather is sunny} \\ \hspace{1.3em} \text{The weather is NOT sunny} \\ \hline \therefore \hspace{0.3em} \neg (\text{UV Index} > 4.0) \end{array} $$

(Note: Since our condition is based on the confidence of 77%, both of these deductions above also works with the confidence of 77%.)

Modus Ponens and Tollens Predictions

Putting everything together, let’s make some deductions. First the helper function below will print us the modus ponens and tollens inference.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def modus_ponens_inference(x, c, s, target, feature_name, target_name, p_str, q_str, verbose):
    p = relaxation_fn(x, c, s)
    q = target
        
    p_q = diff_imp_prob_sum(p, q)
    therefore = diff_and(p_q, p)
    
    if verbose:
        print(f'{p_str:<15} --> {q_str:<15}   (Truth: {p_q.item():2.2f})')
        print(f'{p_str:<18}                    (Truth: {p.item():2.2f})')
        print('-'*35)
        print(f'Therefore, {q_str:<18}         (Truth: {therefore.item():2.2f})')
        
    return therefore


def modus_tollens_inference(x, c, s, target, feature_name, target_name, p_str, q_str, verbose):
    p = relaxation_fn(x, c, s)
    q = target

    p_q = diff_imp_prob_sum(p, q)
    not_q = diff_not(q)
    therefore = diff_and(p_q, not_q)
    
    if verbose:
        print(f'{p_str:15} --> {q_str:<15}   (Truth: {p_q.item():2.2f})')
        print(f'NOT {q_str:<19}               (Truth: {not_q.item():2.2f})')
        print('-'*35)
        print(f'Therefore, NOT {p_str:<19}    (Truth: {therefore.item():2.2f})')
        
    return therefore

An example use of both modus ponens and tollens inference is given below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
x_inference_feature = jnp.array((9.3,)) # assume FEATURE_NAME value
x_test_target = jnp.array((1,)) # assume TARGET_NAME is True

_p_str = f'{FEATURE_NAME} > {x_condition.item():2.2f}'
_class_str = TARGET_NAME if x_test_target == 1 else f'NOT {TARGET_NAME}'
_q_str = f'{_class_str}'

_ = modus_ponens_inference(
    x_inference_feature, 
    x_condition, 
    STEEPNESS, 
    x_test_target,
    FEATURE_NAME,
    TARGET_NAME,
    _p_str,
    _q_str,
    True
)

print('\n')

_ = modus_tollens_inference(
    x_inference_feature, 
    x_condition, 
    STEEPNESS, 
    x_test_target,
    FEATURE_NAME,
    TARGET_NAME,
    _p_str,
    _q_str,
    True
)

And results are given below:

UV Index > 4.00 --> Sunny             (Truth: 1.00)
UV Index > 4.00                       (Truth: 1.00)
-----------------------------------
Therefore, Sunny                      (Truth: 1.00)


UV Index > 4.00 --> Sunny             (Truth: 1.00)
NOT Sunny                             (Truth: 0.00)
-----------------------------------
Therefore, NOT UV Index > 4.00        (Truth: 0.00)

Results are consistent with our learned rule If UV Index > 4.00 THEN, CLASS: Sunny. However, we made strong assumptions of input features and target class. In practice this will not be the case. Therefore, we should use a range of features for input and both True and False for the target. This will consider wide range of possible deductions and we can select the successful inferences.

Iterative Inference

We can perform iterative deduction consider a wide of possibilities. First, we should generate UV Index test inputs in range given below for inference:

1
2
x_inference_feature_range = jnp.linspace(1.0, 10.0, 5)
print(f'Inference feature samples: {x_inference_feature_range}')
Inference feature samples: [ 1.    3.25  5.5   7.75 10.  ]

And the helper function below should makes iterative inferences for both TARGET_NAME is True and TARGET_NAME is False for all input feature samples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def iterative_inference(x_f, x_c, steepness, feature_name, target_name, verbose):    
    # ASSUME BOTH TRUE AND FALSE, SELECT SUCESSFUL DEDUCTIONS!!
    for x_test_target in jnp.array((0, 1)):
        _p_str = f'{FEATURE_NAME} > {x_condition.item():2.2f}'
        _class_str = TARGET_NAME if x_test_target == 1 else f'NOT {TARGET_NAME}'
        _q_str = f'{_class_str}'
        
        therefore = modus_ponens_inference(
            x_f,
            x_c,
            steepness,
            x_test_target,
            feature_name, 
            target_name,
            _p_str,
            _q_str,
            verbose
        )
        print('*** MODUS PONENS ***')
        if binarize(therefore):
            print('  DEDUCTION SUCCESSFUL!')
        else:
            print('  DEDUCTION FAILED!')

        print()
    
        therefore = modus_tollens_inference(
            x_f,
            x_c,
            steepness,
            x_test_target,
            feature_name,
            target_name,
            _p_str,
            _q_str,
            verbose
        )
        print('*** MODUS TOLLENS ***')
        if binarize(therefore):
            print('  DEDUCTION SUCCESSFUL!')
        else:
            print('  DEDUCTION FAILED!')

        print()

Everything is ready, we can now run the iterative_inference for considering all possibilities:

1
2
3
4
5
6
for x_inference_feature in x_inference_feature_range:
    print(f'     #### ASSUME input {FEATURE_NAME}=={x_inference_feature.item():2.2f} ####')
    print()
    iterative_inference(x_inference_feature, x_condition, STEEPNESS, FEATURE_NAME, TARGET_NAME, True)
    print('     ########## END OF ITERATION ##########')
    print()

The code above outputs a lot of lines, so I filtered them by selecting the successful inferences below. You can check out the full output from the source code repo.

Given the previously learned rule “If UV Index > 4.00 THEN, CLASS: Sunny”, we can see that for UV Index < 4.0, modus tollens deduction are successful and for UV Index > 4.0 modus ponens deduction are sucessful. (Note: Double negation “NOT NOT Sunny” is equal to just Sunny.)

We can make the commentary about the results:

  • Modus tollens results deduce that:
    • IF UV Index > 4.0 imply NOT Sunny AND It is Sunny THEN, UV Index NOT greater than 4.0
    • This is correct since we get the sucessful modus tollens for UV Index < 4.0
  • Modus ponens results deduce that:
    • IF UV Index > 4.0 imply Sunny AND UV Index > 4.0 THEN, It must be Sunny
    • This is also correct since we get the sucessful modus ponens for UV Index > 4.0
     #### ASSUME input UV Index==1.00 ####
UV Index > 4.00 --> NOT Sunny         (Truth: 0.95)
NOT NOT Sunny                         (Truth: 1.00)
-----------------------------------
Therefore, NOT UV Index > 4.00        (Truth: 0.95)
*** MODUS TOLLENS ***
  DEDUCTION SUCCESSFUL!


     #### ASSUME input UV Index==3.25 ####
UV Index > 4.00 --> NOT Sunny         (Truth: 0.68)
NOT NOT Sunny                         (Truth: 1.00)
-----------------------------------
Therefore, NOT UV Index > 4.00        (Truth: 0.68)
*** MODUS TOLLENS ***
  DEDUCTION SUCCESSFUL!


     #### ASSUME input UV Index==5.50 ####
UV Index > 4.00 --> Sunny             (Truth: 1.00)
UV Index > 4.00                       (Truth: 0.82)
-----------------------------------
Therefore, Sunny                      (Truth: 0.82)
*** MODUS PONENS ***
  DEDUCTION SUCCESSFUL!


     #### ASSUME input UV Index==7.75 ####
UV Index > 4.00 --> Sunny             (Truth: 1.00)
UV Index > 4.00                       (Truth: 0.98)
-----------------------------------
Therefore, Sunny                      (Truth: 0.98)
*** MODUS PONENS ***
  DEDUCTION SUCCESSFUL!


     #### ASSUME input UV Index==10.00 ####
UV Index > 4.00 --> Sunny             (Truth: 1.00)
UV Index > 4.00                       (Truth: 1.00)
-----------------------------------
Therefore, Sunny                      (Truth: 1.00)
*** MODUS PONENS ***
  DEDUCTION SUCCESSFUL!

Referances