[{"content":"(Source code of this post is available here)\nPropositional 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.\nA statement yields either True or False. For example:\n$$ P = \\text{Earth has an atmosphere} $$\nP is a valid statement since it yields True. Another example:\n$$ Q = \\text{Istanbul is the capital of Türkiye} $$\nQ is also a valid statament since it yields False. (Despite the popular belief, Istanbul is not the capital of Türkiye, Ankara is.)\nCheck out the statement S:\n$$ S = \\text{How many integer divisors exist for 100?} $$\nS is not a valid statement since there is not a simple True or False answer to it. However, consider statement R:\n$$ R = \\text{Is 10 is a positive integer divisor of 100?} $$\nR, on the other hand, is a valid statement since it can yield either True or False.\nStatement by themselves are not particularly useful. However, if we combine and build relations among the statements, we can get insteresting outcomes.\nLogical Connectives Logical connectives are helpful for building relation among proposotinal statements. Basically we have following connectives:\n$$ \\begin{array}{l|c|c} \\text{Formal name} \u0026amp; \\text{Symbol} \u0026amp; \\text{Read as} \\\\ \\hline \\text{Negation (NOT)} \u0026amp; \\neg X_1 \u0026amp; \\text{not } X_1 \\\\ \\text{Conjunction (AND)} \u0026amp; X_1 \\land X_2 \u0026amp; X_1 \\text{ and } X_2 \\\\ \\text{Disjunction (OR)} \u0026amp; X_1 \\lor X_2 \u0026amp; X_1 \\text{ or } X_2 \\\\ \\text{Implication (Conditional)} \u0026amp; X_1 \\to X_2 \u0026amp; \\text{If } X_1 \\text{ then } X_2 \\\\ \\text{Equivalence (Biconditional)} \u0026amp; X_1 \\leftrightarrow X_2,\\ X_1 \\equiv X_2 \u0026amp; X_1 \\text{ if and only if } X_2 \\end{array} $$\nIn the previous post, I have implemented conjuction, disjuction and negation. But we also need the implementation of logical implication and equivalence as well.\n(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.)\nLogical 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\u0026rsquo;s break it down before advancing further.\n$$ \\begin{array}{c|c|c|c} X_1 \u0026amp; X_2 \u0026amp; X_1 \\rightarrow X_2 \u0026amp; \\neg X_1 \\lor X_2 \\\\ \\hline \\text{T} \u0026amp; \\text{T} \u0026amp; \\text{T} \u0026amp; \\text{T} \\\\ \\text{T} \u0026amp; \\text{F} \u0026amp; \\text{F} \u0026amp; \\text{F} \\\\ \\text{F} \u0026amp; \\text{T} \u0026amp; \\text{T} \u0026amp; \\text{T} \\\\ \\text{F} \u0026amp; \\text{F} \u0026amp; \\text{T} \u0026amp; \\text{T} \\end{array} $$\nImplication is in the form: If CONDITION STATEMENT, then OUTCOME STATEMENT. Consider the imaginatory example where I work in a research company:\n$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.\nScenerio 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.\nScenerio 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 \u0026ldquo;vacuous truth\u0026rdquo; 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.\nScenerio 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.\nDifferential 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:\n1 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=\u0026#39;maximum\u0026#39;) diff_implies_prob_sum = partial(diff_implies, name_tconorm=\u0026#39;probabilistic_sum\u0026#39;) diff_implies_bounded = partial(diff_implies, name_tconorm=\u0026#39;bounded\u0026#39;) For example, truth outpus for the probailisitic sum t-conorm realization of the implies given below:\n1 2 x_imp = diff_implies_prob_sum(x1, x2) print_binary(x_imp) 0.72 --\u0026gt; 1 (True) 0.14 --\u0026gt; 0 (False) 1.00 --\u0026gt; 1 (True) 0.86 --\u0026gt; 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.\nLogical 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)$.\n$$ \\begin{array}{c|c|c|c} X_1 \u0026amp; X_2 \u0026amp; X_1 \\leftrightarrow X_2 \u0026amp; (X_1 \\rightarrow X_2) \\land (X_2 \\rightarrow X_1) \\\\ \\hline \\text{T} \u0026amp; \\text{T} \u0026amp; \\text{T} \u0026amp; \\text{T} \\\\ \\text{T} \u0026amp; \\text{F} \u0026amp; \\text{F} \u0026amp; \\text{F} \\\\ \\text{F} \u0026amp; \\text{T} \u0026amp; \\text{F} \u0026amp; \\text{F} \\\\ \\text{F} \u0026amp; \\text{F} \u0026amp; \\text{T} \u0026amp; \\text{T} \\end{array} $$\nDifferential 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\u0026rsquo;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:\n1 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=\u0026#39;product\u0026#39;, name_tconorm=\u0026#39;probabilistic_sum\u0026#39;) x_equiv = diff_equivalence_product_prob_sum(x1, x2) print_binary(x_equiv) 0.70 --\u0026gt; 1 (True) 0.14 --\u0026gt; 0 (False) 0.22 --\u0026gt; 0 (False) 0.78 --\u0026gt; 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]$.\nArguments 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.\n$$ \\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} $$\nAll the statements above the line are premises. The symbol $\\therefore$ above mean \u0026ldquo;therefore\u0026rdquo; 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.\nIn 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.\nModus 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$.\n$$ \\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} $$\nModus 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$.\n$$ \\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} $$\nChain 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.\n$$ \\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} $$\n(Note: There is no example of this chain structure in this post. However, it shall prove useful for the upcoming posts.)\nFirst 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.\nFor example, consider the simple weather deduction example: if a variable temperature $Temp$ is above a variable condition $Cond$, then weather is sunny.\n$$ \\text{IF } (Temp \u0026gt; Cond) \\text{, THEN weather is sunny.} $$\nNotice that this is in fact a form of logical implication. So we can write the modus ponens and tollens forms of the deduction below:\n$$ \\begin{array}{l} \\hspace{1.3em} (Temp \u0026gt; Cond) \\rightarrow \\text{The weather is sunny} \\\\ \\hspace{1.3em} (Temp \u0026gt; Cond) \\\\ \\hline \\therefore \\hspace{0.3em} \\text{The weather is sunny} \\end{array} $$\n$$ \\begin{array}{l} \\hspace{1.3em} (Temp \u0026gt; Cond) \\rightarrow \\text{The weather is sunny} \\\\ \\hspace{1.3em} \\text{The weather is NOT sunny} \\\\ \\hline \\therefore \\hspace{0.3em} \\neg (Temp \u0026gt; Cond) \\end{array} $$\nPredicates 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.\nIn the example above, we need to compute the truth value of $(Temp \u0026gt; 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 \u0026gt; Cond)$ that gives dynamic range of truth given the values of $Temp$ and $Cond$? Continuous relaxation methods can help with that.\nContinuous 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.\nLogistic 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 \u0026amp; Jónás, 2022; Semenov, 2025). But first, let\u0026rsquo;s define it below:\n$$\\sigma(x) = \\frac{1}{1 + e^{-x}} \\tag{1}$$\nThis is convinent for us but we also need to set a condition.\nGreater-Than Relaxation This function provides a differentiable approximation of a binary decision that outputs near 1.0 (evaluates to True) when $x \u0026gt; 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.\n$$\\sigma_{\\text{gt}}(x, c, s) = \\sigma(s(x - c)) = \\frac{1}{1 + e^{-s(x - c)}} \\tag{2}$$\nLess-Than Relaxation Similarly, differentiable approximation of $x \u0026lt; 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.\n$$\\sigma_{\\text{lt}}(x, c, s) = \\sigma(s(c - x)) = \\frac{1}{1 + e^{-s(c - x)}} \\tag{3}$$\nImplementation of Continuous Relaxations in JAX Using JAX, implementations of equations 1, 2 and 3 are given below:\n1 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): \u0026#34;\u0026#34;\u0026#34; True for points satisfying: x \u0026gt; condition \u0026#34;\u0026#34;\u0026#34; return sigmoid(steepness*(x-condition)) def logistic_sigmoid_relaxation_lt(x, condition, steepness): \u0026#34;\u0026#34;\u0026#34; True for points satisfying x \u0026lt; condition \u0026#34;\u0026#34;\u0026#34; return sigmoid(steepness*(condition-x)) The two plots of $x_i \u0026gt; 40$ and $x_i \u0026lt; 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.\nSteepness is also another input that determines the \u0026ldquo;sharpness\u0026rdquo; 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.\nGradient 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\u0026rsquo;t update our variables to improve the desired output.\nWe can compute and plot the gradients per input sample with the code below where JAX\u0026rsquo;s vmap is used to map each input x1 to grad_fn.\n1 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=\u0026#39;Sigmoid\u0026#39;, c=\u0026#39;b\u0026#39;) plt.plot(x1, grad_c_per_sample, linewidth=3.0, label=\u0026#39;Gradients\u0026#39;, c=\u0026#39;r\u0026#39;) plt.title(f\u0026#39;Gradients per Sample for {r\u0026#34;$x_i$\u0026#34;} \u0026gt; {CONDITION}\u0026#39;) plt.xlabel(r\u0026#34;$x_i$\u0026#34;) plt.ylabel(\u0026#39;Truth/Grad Value\u0026#39;) plt.grid(\u0026#39;on\u0026#39;) plt.legend() plt.tight_layout() plt.savefig( \u0026#39;grad_fn_per_sample.png\u0026#39;, bbox_inches=\u0026#39;tight\u0026#39;, 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.\nFortunately, 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.\nDifferential Optimziation of Relaxations So far so good, let\u0026rsquo;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.\n1 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\u0026#39;Initial condition: {x_condition.item():2.4f}\u0026#39;) # SET TRUE THE FOR TARGET OR ABOVE TARGET_CONDITION = 20.0 x_target = (x_data\u0026gt;TARGET_CONDITION).astype(jnp.float32) print(x_target) As you see from below, we have a binary classification task where $x_{\\text{Cond}} \u0026gt; 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.\nInitial 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\u0026rsquo;s MinMaxScaler to do the job.\n1 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:\n[-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:\n1 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.\n1 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\u0026#39;Relaxation of Sigmoid for {r\u0026#34;$x_i$\u0026#34;} \u0026lt; {x_condition_scaled.item():2.4f}\u0026#39;) plt.xlabel(r\u0026#34;$x_i$\u0026#34;) plt.ylabel(\u0026#39;Truth Value\u0026#39;) plt.grid(\u0026#39;on\u0026#39;) plt.tight_layout() plt.savefig( \u0026#39;logistic_sigmoid_relaxation_gt_scaled_input.png\u0026#39;, bbox_inches=\u0026#39;tight\u0026#39;, dpi=300 ) 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}}$.\n$$ \\mathcal T_{i} = \\sigma_{\\text{gt}}(x_{i}, x_{\\text{Cond}}, s) \\leftrightarrow x_{\\text{target}} \\tag{4} $$\nEquation 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.\n$$ \\mathcal T_{\\text{final}} = \\frac{1}{N}\\sum_{i=1}^{N} \\mathcal T_{i} \\tag{5} $$\n(In this case we don\u0026rsquo;t need batch processing since dataset is very small and can fit into memory.)\nAlthough 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$.\n$$ x_{\\text{Cond}} = x_{\\text{Cond}} + \\alpha \\cdot \\frac{\\partial \\mathcal T_{\\text{final}}}{\\partial x_{\\text{Cond}}} \\tag{6} $$\nAfter 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:\n1 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=\u0026#39;product\u0026#39;, name_tconorm=\u0026#39;probabilistic_sum\u0026#39;) 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 \u0026gt; x_condition_scaled).astype(jnp.int32) == x_target) / len(x_target)) if epoch % 20 == 0: print(f\u0026#39;Epoch: {epoch:\u0026gt;3}, Truth: {final_truth.item():2.2f} Accuracy: {acc.item():2.2f}%\u0026#39;) 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.\n1 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\u0026#39;Target condition: {TARGET_CONDITION:2.2f}\u0026#39;) print(f\u0026#39;Learned condition: {x_final_condition.item():2.2f}\u0026#39;) 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.\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 colors = [\u0026#39;blue\u0026#39; if l == 0 else \u0026#39;green\u0026#39; 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\u0026#39;Results for {r\u0026#34;$x_i$\u0026#34;} \u0026gt; {x_final_condition.item():2.2f}\u0026#39;) plt.xlabel(r\u0026#34;$x_i$\u0026#34;) plt.ylabel(\u0026#39;Truth Value\u0026#39;) plt.grid(\u0026#39;on\u0026#39;) plt.tight_layout() plt.savefig( \u0026#39;logistic_sigmoid_relaxation_gt_training_results.png\u0026#39;, bbox_inches=\u0026#39;tight\u0026#39;, dpi=300 ) 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:\n1 2 3 4 import pandas as pd df_weather = pd.read_csv(\u0026#39;./weather_classification_data.csv\u0026#39;) df_weather.head() 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.\nHyperparameters Hyperparameters are \u0026ldquo;high-level\u0026rdquo; parameters that control how learning proceeds. This also where we setup our relaxation method.\n1 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\u0026rsquo;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.\n1 df_weather[\u0026#39;Weather Type\u0026#39;].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\u0026rsquo;s train_test_split function helps us equally distribute classes among training and testing splits.\n1 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=[\u0026#39;Weather Type\u0026#39;]), df_weather[\u0026#39;Weather Type\u0026#39;], test_size=SPLIT_RATIO, random_state=SEED, stratify=df_weather[\u0026#39;Weather Type\u0026#39;], # ENSURE LABELS DISTRIBUTED EQUALLY ) Select \u0026amp; 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.\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 FEATURE_NAME = \u0026#39;UV Index\u0026#39; TARGET_NAME = \u0026#39;Sunny\u0026#39; # [-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).\n1 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\u0026#39;Epoch: {epoch:2d}, Truth: {loss:2.2f}, Accuracy: {pred_dict_train[\u0026#34;Accuracy\u0026#34;].item():2.2f}%, F-1: {pred_dict_train[\u0026#34;F-1\u0026#34;].item():2.2f}\u0026#39;) 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 \u0026ldquo;1s\u0026rdquo; and rest 75% to \u0026ldquo;0s\u0026rdquo;. Thus, resulting training/testing targets are unequally distributed.\nEpoch: 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\u0026rsquo;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.\n1 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\u0026#39;{m_name:\u0026lt;10}:{m_val.item():2.2f}\u0026#39;) 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 \u0026ldquo;Sunny\u0026rdquo; predictions are correct. But remeber that we are using single column feature with single learnable condition. At this simplicity, these results are acceptable.\nAccuracy :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\u0026rsquo;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.\n1 2 3 4 5 6 # WE WILL USE THE F-1 AS CONFIDENCE INDICATOR rule_confidence = pred_dict_test[\u0026#39;F-1\u0026#39;] print(\u0026#39;LEARNED RULE:\u0026#39;) print(f\u0026#39;If {FEATURE_NAME} \u0026gt; {x_condition.item():2.2f} THEN, CLASS: {TARGET_NAME}\u0026#39;) print(f\u0026#39;(Confidence: {rule_confidence:2.2f}%)\u0026#39;) LEARNED RULE: If UV Index \u0026gt; 4.00 THEN, CLASS: Sunny (Confidence: 0.77%) Based on the learned condition, we can write the modus ponens rule below:\n$$ \\begin{array}{l} \\hspace{1.3em} (\\text{UV Index} \u0026gt; 4.0) \\rightarrow \\text{The weather is sunny} \\\\ \\hspace{1.3em} (\\text{UV Index} \u0026gt; 4.0) \\\\ \\hline \\therefore \\hspace{0.3em} \\text{The weather is sunny} \\end{array} $$\nand the modus tollens rule below:\n$$ \\begin{array}{l} \\hspace{1.3em} (\\text{UV Index} \u0026gt; 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} \u0026gt; 4.0) \\end{array} $$\n(Note: Since our condition is based on the confidence of 77%, both of these deductions above also works with the confidence of 77%.)\nModus Ponens and Tollens Predictions Putting everything together, let\u0026rsquo;s make some deductions. First the helper function below will print us the modus ponens and tollens inference.\n1 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\u0026#39;{p_str:\u0026lt;15} --\u0026gt; {q_str:\u0026lt;15} (Truth: {p_q.item():2.2f})\u0026#39;) print(f\u0026#39;{p_str:\u0026lt;18} (Truth: {p.item():2.2f})\u0026#39;) print(\u0026#39;-\u0026#39;*35) print(f\u0026#39;Therefore, {q_str:\u0026lt;18} (Truth: {therefore.item():2.2f})\u0026#39;) 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\u0026#39;{p_str:15} --\u0026gt; {q_str:\u0026lt;15} (Truth: {p_q.item():2.2f})\u0026#39;) print(f\u0026#39;NOT {q_str:\u0026lt;19} (Truth: {not_q.item():2.2f})\u0026#39;) print(\u0026#39;-\u0026#39;*35) print(f\u0026#39;Therefore, NOT {p_str:\u0026lt;19} (Truth: {therefore.item():2.2f})\u0026#39;) return therefore An example use of both modus ponens and tollens inference is given below:\n1 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\u0026#39;{FEATURE_NAME} \u0026gt; {x_condition.item():2.2f}\u0026#39; _class_str = TARGET_NAME if x_test_target == 1 else f\u0026#39;NOT {TARGET_NAME}\u0026#39; _q_str = f\u0026#39;{_class_str}\u0026#39; _ = modus_ponens_inference( x_inference_feature, x_condition, STEEPNESS, x_test_target, FEATURE_NAME, TARGET_NAME, _p_str, _q_str, True ) print(\u0026#39;\\n\u0026#39;) _ = 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:\nUV Index \u0026gt; 4.00 --\u0026gt; Sunny (Truth: 1.00) UV Index \u0026gt; 4.00 (Truth: 1.00) ----------------------------------- Therefore, Sunny (Truth: 1.00) UV Index \u0026gt; 4.00 --\u0026gt; Sunny (Truth: 1.00) NOT Sunny (Truth: 0.00) ----------------------------------- Therefore, NOT UV Index \u0026gt; 4.00 (Truth: 0.00) Results are consistent with our learned rule If UV Index \u0026gt; 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.\nIterative 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:\n1 2 x_inference_feature_range = jnp.linspace(1.0, 10.0, 5) print(f\u0026#39;Inference feature samples: {x_inference_feature_range}\u0026#39;) 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:\n1 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\u0026#39;{FEATURE_NAME} \u0026gt; {x_condition.item():2.2f}\u0026#39; _class_str = TARGET_NAME if x_test_target == 1 else f\u0026#39;NOT {TARGET_NAME}\u0026#39; _q_str = f\u0026#39;{_class_str}\u0026#39; therefore = modus_ponens_inference( x_f, x_c, steepness, x_test_target, feature_name, target_name, _p_str, _q_str, verbose ) print(\u0026#39;*** MODUS PONENS ***\u0026#39;) if binarize(therefore): print(\u0026#39; DEDUCTION SUCCESSFUL!\u0026#39;) else: print(\u0026#39; DEDUCTION FAILED!\u0026#39;) print() therefore = modus_tollens_inference( x_f, x_c, steepness, x_test_target, feature_name, target_name, _p_str, _q_str, verbose ) print(\u0026#39;*** MODUS TOLLENS ***\u0026#39;) if binarize(therefore): print(\u0026#39; DEDUCTION SUCCESSFUL!\u0026#39;) else: print(\u0026#39; DEDUCTION FAILED!\u0026#39;) print() Everything is ready, we can now run the iterative_inference for considering all possibilities:\n1 2 3 4 5 6 for x_inference_feature in x_inference_feature_range: print(f\u0026#39; #### ASSUME input {FEATURE_NAME}=={x_inference_feature.item():2.2f} ####\u0026#39;) print() iterative_inference(x_inference_feature, x_condition, STEEPNESS, FEATURE_NAME, TARGET_NAME, True) print(\u0026#39; ########## END OF ITERATION ##########\u0026#39;) 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.\nGiven the previously learned rule \u0026ldquo;If UV Index \u0026gt; 4.00 THEN, CLASS: Sunny\u0026rdquo;, we can see that for UV Index \u0026lt; 4.0, modus tollens deduction are successful and for UV Index \u0026gt; 4.0 modus ponens deduction are sucessful. (Note: Double negation \u0026ldquo;NOT NOT Sunny\u0026rdquo; is equal to just Sunny.)\nWe can make the commentary about the results:\nModus tollens results deduce that: IF UV Index \u0026gt; 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 \u0026lt; 4.0 Modus ponens results deduce that: IF UV Index \u0026gt; 4.0 imply Sunny AND UV Index \u0026gt; 4.0 THEN, It must be Sunny This is also correct since we get the sucessful modus ponens for UV Index \u0026gt; 4.0 #### ASSUME input UV Index==1.00 #### UV Index \u0026gt; 4.00 --\u0026gt; NOT Sunny (Truth: 0.95) NOT NOT Sunny (Truth: 1.00) ----------------------------------- Therefore, NOT UV Index \u0026gt; 4.00 (Truth: 0.95) *** MODUS TOLLENS *** DEDUCTION SUCCESSFUL! #### ASSUME input UV Index==3.25 #### UV Index \u0026gt; 4.00 --\u0026gt; NOT Sunny (Truth: 0.68) NOT NOT Sunny (Truth: 1.00) ----------------------------------- Therefore, NOT UV Index \u0026gt; 4.00 (Truth: 0.68) *** MODUS TOLLENS *** DEDUCTION SUCCESSFUL! #### ASSUME input UV Index==5.50 #### UV Index \u0026gt; 4.00 --\u0026gt; Sunny (Truth: 1.00) UV Index \u0026gt; 4.00 (Truth: 0.82) ----------------------------------- Therefore, Sunny (Truth: 0.82) *** MODUS PONENS *** DEDUCTION SUCCESSFUL! #### ASSUME input UV Index==7.75 #### UV Index \u0026gt; 4.00 --\u0026gt; Sunny (Truth: 1.00) UV Index \u0026gt; 4.00 (Truth: 0.98) ----------------------------------- Therefore, Sunny (Truth: 0.98) *** MODUS PONENS *** DEDUCTION SUCCESSFUL! #### ASSUME input UV Index==10.00 #### UV Index \u0026gt; 4.00 --\u0026gt; Sunny (Truth: 1.00) UV Index \u0026gt; 4.00 (Truth: 1.00) ----------------------------------- Therefore, Sunny (Truth: 1.00) *** MODUS PONENS *** DEDUCTION SUCCESSFUL! Referances Bourguignon, S., Ninin, J., Carfantan, H., \u0026amp; Mongeau, M. (2016). Exact sparse approximation problems via mixed-integer programming: Formulations and computational performance. IEEE Transactions on Signal Processing, 64(6), 1405–1419. https://doi.org/10.1109/tsp.2015.2496367 Dombi, J., \u0026amp; Jónás, T. (2022). Generalizing the sigmoid function using continuous-valued logic. Fuzzy Sets and Systems, 449, 79–99. https://doi.org/10.1016/j.fss.2022.02.010 Krutikov, V., Gutova, S., Tovbis, E., Kazakovtsev, L., \u0026amp; Semenkin, E. (2022). Relaxation subgradient algorithms with machine learning procedures. Mathematics, 10(21), 3959. https://doi.org/10.3390/math10213959 Narayan, N. (2024). Weather type classification [Data set]. Kaggle. https://www.kaggle.com/datasets/nikhil7280/weather-type-classification Nowak, I. (2005). Relaxation and decomposition methods for mixed integer nonlinear programming. Birkhäuser Basel. https://doi.org/10.1007/3-7643-7374-1 Semenov, S. (2025). Smooth approximations of the rounding function. arXiv. https://doi.org/10.48550/arxiv.2504.19026 ","permalink":"https://fualsan.github.io/posts/differential-logic-part-2/","summary":"\u003cp\u003e\u003ca href=\"https://github.com/fualsan/DifferentialReasoningAlgorithms/tree/main/differential-logic-part-2\"\u003e\u003cem\u003e(Source code of this post is available here)\u003c/em\u003e\u003c/a\u003e\u003c/p\u003e\n\u003ch2 id=\"propositional-logic\"\u003ePropositional Logic\u003c/h2\u003e\n\u003cp\u003ePropositional 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 \u003cem\u003eproposition\u003c/em\u003e in classical logic.\u003c/p\u003e\n\u003cp\u003eA statement yields either True or False. For example:\u003c/p\u003e\n\u003cp\u003e$$\nP = \\text{Earth has an atmosphere}\n$$\u003c/p\u003e","title":"Differential Logic Part 2"},{"content":"(Source code of this post is available here)\nIntroduction to Logic I always though researching logic to help me implement AI methods that are more focused on reasoning, planning, explainability, etc. However, the logic is discrete by nature which has two strict values: $\\{ \\text{True}, \\text{False} \\}$ This limits the expressibility and makes it difficult to implement in a differential manner. One alternative is to use approximations of logical values which can have any real value between $[ 0.0, 1.0 ]$. This makes logic more flexiable and expressive. For any approximated Boolean variable $x$, logic expression $x \\in [ 0.0, 1.0 ]$, can be expressed as floating-point values instead of discerete two states.\nAssuming the Boolean variable $x$ values are uniformly distributed in $[ 0.0, 1.0 ]$, we can make the binarization decision given below:\n$$ \\mathcal{T}_{binary} = \\begin{cases} \\text{True } \u0026amp; \\text{if } x \\geq 0.5 \\\\ \\text{False } \u0026amp; \\text{if } x \u0026lt; 0.5 \\end{cases} $$\nWhere, $\\mathcal{T}_{binary}$ is final dicrete truth value in traditional sense. So, any value close to $0.0$ is considered more False and any value to close $1.0$ is considered more True. This is similar to any binary classification model with sigmoid output and decision boundary is set to $0.5$. However, it would be beneficial to keep everything strictly numerical. Alternatively, we can assign True to 1 and False to 0 for strict numerical results, given below:\n$$ \\mathcal{T}_{binary} = \\begin{cases} \\text{1 } \u0026amp; \\text{if } x \\geq 0.5 \\\\ \\text{0 } \u0026amp; \\text{if } x \u0026lt; 0.5 \\end{cases} $$\nImplementing Logic Approximations I will use JAX (which is my favorite) for implementations. First, let\u0026rsquo;s initilize two JAX arrays with approximated logic values:\n1 2 3 4 5 import jax import jax.numpy as jnp x1 = jnp.array((0.50, 0.50, 0.75, 0.25)) x2 = jnp.array((0.55, 0.25, 0.15, 0.45)) We can implement binarize function to convert approximated Boolean values into dicrete logic:\n1 2 def binarize(x): return jnp.where(x\u0026gt;=0.5, 1, 0) Also print the mappings:\n1 2 3 4 5 6 7 8 9 def print_binary(x): for x_real, x_binary in zip(x.tolist(), binarize(x).tolist()): x_binary_str = \u0026#39;True\u0026#39; if x_binary == 1 else \u0026#39;False\u0026#39; print(f\u0026#39;{x_real:2.2f} --\u0026gt; {x_binary:1d} ({x_binary_str})\u0026#39;) print(\u0026#39;x1:\u0026#39;) print_binary(x1) print(\u0026#39;x2:\u0026#39;) print_binary(x2) As we can see below, values that $\\geq 0.5$ are mapped to 1 and values $\u0026lt; 0.5$ are mapped to 0.\nx1: 0.50 --\u0026gt; 1 (True) 0.50 --\u0026gt; 1 (True) 0.75 --\u0026gt; 1 (True) 0.25 --\u0026gt; 0 (False) x2: 0.55 --\u0026gt; 1 (True) 0.25 --\u0026gt; 0 (False) 0.15 --\u0026gt; 0 (False) 0.45 --\u0026gt; 0 (False) T-Norm and T-Conorms We have Boolean variables approximated to represent True or False, it is time to build logical connectives to perform operations on variables. Triangular norms (T-norms, T-conorms) are useful for building such operations.\nT-Norms and T-conorms are classes of functions that operate in interval $T: [ 0.0, 1.0 ] \\times [ 0.0, 1.0 ] \\rightarrow [ 0.0, 1.0 ]$. They go back as far as Probabilistic Metric Spaces (Menger, K., 1942) which lays the foundation. Their properties investigated later as triangle functions (Schweizer, B., and Sklar, A., 1960). Fuzzy logic is commonly used in approximations of logic operators for real values (Hájek, P., 1998).\nFor building logical connectives, basically we have:\nConjuction (logical AND) is defined as T-norm Disjunction (logical OR) is defined as T-conorm (also called S-norm) T-Norm implementations Three types of t-norms strike me the most: minimum (also called the Gödel), product and bounded (also called the Łukasiewicz) t-norm.\nMinimum (Gödel) t-norm: $T_{min} (x_1, x_2) = \\text{min} \\{x_1, x_2\\}$ Product t-norm: $T_{prod} (x_1, x_2) = x_1 \\cdot x_2$ Bounded (Łukasiewicz) t-norm: $T_{boun} (x_1, x_2) = \\text{max} \\{0, x_1 + x_2 - 1 \\} $ Their implementation in JAX is given below:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def t_norm_min(x1, x2): \u0026#34;\u0026#34;\u0026#34; Minimum (Gödel) T-norm \u0026#34;\u0026#34;\u0026#34; return jnp.minimum(x1, x2) def t_norm_product(x1, x2): \u0026#34;\u0026#34;\u0026#34; Product T-norm \u0026#34;\u0026#34;\u0026#34; return x1*x2 def t_norm_bounded(x1, x2): \u0026#34;\u0026#34;\u0026#34; Bounded (Łukasiewicz) T-norm \u0026#34;\u0026#34;\u0026#34; return jnp.maximum(0.0, x1+x2-1.0) Plotting T-Norm Truths Investigating the plots above, we can see that logical conjuction (AND) operation between $x_1$ and $x_2$ is approximated in real space. Truth values peak around $x_1 = 1.0$, $x_2 = 1.0$ for all three but each with own characterisics. Minimum and product t-norms are similar but product t-norm outputs smoother increase then minimum t-norm. The Łukasiewicz t-norm forms a strict upper surface boundary, hence it is \u0026ldquo;bounded\u0026rdquo;. This bounded characteristic makes a difference in generation of norm functions (which we will study later).\nT-conorm implementations T-conorms are used for disjunction connectives instead of conjuction (like t-norms). Similarly for the t-conorms, maximum (Gödel) t-conorm, probabilistic sum and bounded (Łukasiewicz) sum t-conorm.\n(They are also called S-norms and I will use notation $S$ to avoid confusion with t-norms.)\nMaximum t-conorm: $S_{max} (x_1, x_2) = \\text{max}\\{ x_1, x_2 \\}$ Probabilistic sum: $S_{sum} (x_1, x_2) = x_1 + x_2 - x_1 \\cdot x_2 = 1 - (1-x_1) \\cdot (1 - x_2)$ Bounded (Łukasiewicz) t-conorm: $S_{boun} (x_1, x_2) = \\text{min} \\{ x_1 + x_2, 1 \\}$ And their implementation in JAX:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def t_conorm_maximum(x1, x2): \u0026#34;\u0026#34;\u0026#34; Maximum (Gödel) T-conorm \u0026#34;\u0026#34;\u0026#34; return jnp.maximum(x1, x2) def t_conorm_sum(x1, x2): \u0026#34;\u0026#34;\u0026#34; Probabilistic Sum \u0026#34;\u0026#34;\u0026#34; return x1+x2-x1*x2 def t_conorm_bounded(x1, x2): \u0026#34;\u0026#34;\u0026#34; Bounded (Łukasiewicz) T-conorm \u0026#34;\u0026#34;\u0026#34; return jnp.minimum(x1+x2, 1.0) (Of course, t-norms and t-conorms are not limited to these above, but I decided to implement them.)\nPlotting T-Conorm Truths We can see that logical disjunction (OR) operation between $x_1$ and $x_2$ is approximated in real space. Truth values are lowest around $x_1 = 0.0$, $x_2 = 0.0$ and higher elsewhere. Similarly to t-norms, maximum and probabilistic sum shows similar yet second show smoother while the Łukasiewicz t-conorm show a \u0026ldquo;bounded\u0026rdquo; characteristic.\nNegation We convered conjuction and disjuction implementations. However, we also need negation (logical NOT) to fully realize logical expressions. We do not need triangular norms for negation, it is straightforward as given below:\n1 2 def negation(x): return 1.0-x Differential Optimization of Truth Initialization Now that we have the basics, let\u0026rsquo;s get into the differential part. Let\u0026rsquo;s assume we want to find $x_1$ and $x_2$ values that yields True for the logical statement below, where $\\mathcal{T}_{final}$ denotes overall final truth value:\n$$ \\mathcal{T}_{final} = X_1 \\land \\neg X_2 \\tag{1} $$\nFirst we need to initialize boolean variables $x_1, x_2 \\in [0.0, 1.0 ]$. To keep values in valid range, I decided to initialize values around 0.5 with some variations:\n$$ x_{1,2} = 0.5 + \\mathcal{N}(0.0, \\sigma^2) $$\nI use \u0026ldquo;noise_scale\u0026rdquo; constant to adjust the noise variance. To keep values around 0.5, standart deviation of $\\sigma = 0.1$ should be enough.\n1 2 3 4 5 6 7 8 9 10 11 import jax.random as jrd SEED = 1234 def init_logical_array(array_shape, key, noise_scale=0.1): noise = jrd.normal(jrd.key(key), array_shape) * noise_scale # any shaped array centered around 0.5 return 0.5 * jnp.ones(array_shape) + noise x1, x2 = init_logical_array((2,), SEED) print(f\u0026#39;Initial value of X_1: {float(x1):.3f} and X_2: {float(x2):.3f}\u0026#39;) Initial value of X_1: 0.610 and X_2: 0.586 Select T-norm and T-conorm Functions We have multiple t-norm and t-conorm options, the code below helps us try different realizations:\n(Product and probabilistic sum norm functions provide smoother transitions, so I prefer them for now.)\n1 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 VALID_TNORM_FUNCTIONS = { \u0026#39;minimum\u0026#39;: t_norm_min, \u0026#39;product\u0026#39;: t_norm_product, \u0026#39;bounded\u0026#39;: t_norm_bounded, } VALID_TCONORM_FUNCTIONS = { \u0026#39;maximum\u0026#39;: t_conorm_maximum, \u0026#39;probabilistic_sum\u0026#39;: t_conorm_sum, \u0026#39;bounded\u0026#39;: t_conorm_bounded } def diff_and(x1, x2, name=\u0026#39;product\u0026#39;): _name = name.lower().strip() if _name not in VALID_TNORM_FUNCTIONS.keys(): raise ValueError(f\u0026#39;{name} is a valid AND realization, select from: {VALID_TNORM_FUNCTIONS.keys()}\u0026#39;) selected_realization = VALID_TNORM_FUNCTIONS[_name] return selected_realization(x1, x2) def diff_or(x1, x2, name=\u0026#39;probabilistic_sum\u0026#39;): _name = name.lower().strip() if _name not in VALID_TCONORM_FUNCTIONS.keys(): raise ValueError(f\u0026#39;{name} is a valid AND realization, select from: {VALID_TCONORM_FUNCTIONS.keys()}\u0026#39;) selected_realization = VALID_TCONORM_FUNCTIONS[_name] return selected_realization(x1, x2) def diff_not(x): # (SINGLE REALIZATION OF NOT, BUT CAN BE ADDED LATER) # (THIS IS FOR FUTURE COMPATIBILITY) return negation(x) Updates with Gradients Since we wish to maximize the truth $\\mathcal{T}_{final}$, I prefer gradient ascent instead of descent to update randomly initialized $x_1$ and $x_1$. Gradient vector in this case will point to the maximum truth value.\nThe equations 2 and 3 below, will update the $x_1$ and $x_2$ towards the point where $\\mathcal{T}_{final}$ is maximum, with learning rate $\\alpha$.\n$$ x_1 = x_1 + \\alpha \\cdot \\frac{\\partial \\mathcal{T}_{final}}{\\partial x_1} \\tag{2} $$\n$$ x_2 = x_2 + \\alpha \\cdot \\frac{\\partial \\mathcal{T}_{final}}{\\partial x_2} \\tag{3} $$\nWe don\u0026rsquo;t need to compute derivaties manually, JAX provides automatic differentiation that builds the compute graph to calculate partial derivaties of $\\mathcal{T}_{final}$ w.r.t $x_1$ and $x_2$.\n1 2 3 4 def truth_fn(x1, x2): return diff_and(x1, diff_not(x2)) grad_fn = jax.value_and_grad(truth_fn, argnums=(0, 1)) Main Optimization Loop The loop below, computes gradients, updates variables and keeps the variables in range with clipping. (If you are familiar with machine/deep learning, this loop is essetially the forward and backward propagation)\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 NUM_EPOCHS = 10 LEARNING_RATE = 1e-1 for epoch in range(1, NUM_EPOCHS+1): # CALCULATE GRADIENTS truth_val, (dT_dx1, dT_dx2) = grad_fn(x1, x2) # UPDATE VALUES USING GRADIENT ASCENT x1 = x1 + LEARNING_RATE*dT_dx1 x2 = x2 + LEARNING_RATE*dT_dx2 # (ENSURE LOGICAL APPROXIMATIONS IN VALID RANGE) x1 = jnp.clip(x1, 0.0, 1.0) x2 = jnp.clip(x2, 0.0, 1.0) print(f\u0026#34;{\u0026#39;Epoch\u0026#39;:\u0026lt;6} | {\u0026#39;Truth\u0026#39;:\u0026lt;8} | {\u0026#39;X_1\u0026#39;:\u0026lt;8} | {\u0026#39;X_2\u0026#39;:\u0026lt;8}\u0026#34;) print(f\u0026#39;{epoch:\u0026lt;6} | {truth_val:\u0026lt;8.4f} | {x1:\u0026lt;8.4f} | {x2:\u0026lt;8.4f}\u0026#39;) print() Epoch | Truth | X_1 | X_2 1 | 0.2525 | 0.6517 | 0.5253 Epoch | Truth | X_1 | X_2 2 | 0.3094 | 0.6992 | 0.4601 Epoch | Truth | X_1 | X_2 3 | 0.3775 | 0.7531 | 0.3902 Epoch | Truth | X_1 | X_2 4 | 0.4593 | 0.8141 | 0.3149 Epoch | Truth | X_1 | X_2 5 | 0.5578 | 0.8826 | 0.2335 Epoch | Truth | X_1 | X_2 6 | 0.6766 | 0.9593 | 0.1452 Epoch | Truth | X_1 | X_2 7 | 0.8200 | 1.0000 | 0.0493 Epoch | Truth | X_1 | X_2 8 | 0.9507 | 1.0000 | 0.0000 Epoch | Truth | X_1 | X_2 9 | 1.0000 | 1.0000 | 0.0000 Epoch | Truth | X_1 | X_2 10 | 1.0000 | 1.0000 | 0.0000 As we can see from the results above, randomly intializing boolean variables $x_1$ and $x_2$ yield low truth values at first, but as we update roughly 10 iterations (epochs), we find that $x_1=1.0$ and $x_2=0.0$ gives us the maximum truth for statement in equation 1.\nBinary Evaluation We can also verify this with binary evaluation as well:\n1 2 3 4 5 6 7 8 9 10 11 12 def evaluate_binary(x1, x2): x1_binary = binarize(x1) x2_binary = binarize(x2) truth_binary = (x1_binary and (not x2_binary)) print(f\u0026#39;Binary logic value of x_1: {bool(x1_binary)}\u0026#39;) print(f\u0026#39;Binary logic value of x_2: {bool(x2_binary)}\u0026#39;) print(f\u0026#39;Binary logic value of T_final: {truth_binary}\u0026#39;) evaluate_binary(x1, x2) Again we see that for $x_1 = \\text{True}$, $x_2 = \\text{False}$ we get desired $\\mathcal{T}_{final} = \\text{True}$ result for the statement given in the equation 1.\nBinary logic value of x_1: True Binary logic value of x_2: False Binary logic value of T_final: True We convered the simple case in this post. You can manually derive the result without any differential optimization. However, this is the foundation that we need for more insteresting examples in the future.\nReferences Klement, E. P., Mesiar, R., \u0026amp; Pap, E. (2000). Triangular norms. Kluwer Academic Publishers. https://doi.org/10.1007/978-94-015-9540-7\nKlement, E. P., Mesiar, R., \u0026amp; Pap, E. (2004). Triangular norms. position paper I: Basic analytical and algebraic properties. Fuzzy Sets and Systems, 143(1), 5–26. https://doi.org/10.1016/j.fss.2003.06.007\nMenger, K. (1942). Statistical metrics. Proceedings of the National Academy of Sciences of the United States of America, 28(12), 535–537. https://doi.org/10.1073/pnas.28.12.535\nHájek, P. (1998). Metamathematics of fuzzy logic. Kluwer Academic Publishers.\nSun, J. (2025). Characterization of t-norms on normal convex functions. arXiv. https://doi.org/10.48550/arxiv.2511.17640\nSchweizer, B. and Sklar, A. (1960) Statistical Metric Spaces. Pacific Journal of Math., 10, 313-334. http://dx.doi.org/10.2140/pjm.1960.10.313\n","permalink":"https://fualsan.github.io/posts/differential-logic-part-1/","summary":"\u003cp\u003e\u003ca href=\"https://github.com/fualsan/DifferentialReasoningAlgorithms/tree/main/differential-logic-part-1\"\u003e\u003cem\u003e(Source code of this post is available here)\u003c/em\u003e\u003c/a\u003e\u003c/p\u003e\n\u003ch2 id=\"introduction-to-logic\"\u003eIntroduction to Logic\u003c/h2\u003e\n\u003cp\u003eI always though researching logic to help me implement AI methods that are more focused on reasoning, planning, explainability, etc. However, the logic is discrete by nature which has two strict values: $\\{ \\text{True}, \\text{False} \\}$ This limits the expressibility and makes it difficult to implement in a differential manner. One alternative is to use approximations of logical values which can have any real value between $[ 0.0, 1.0 ]$. This makes logic more flexiable and expressive. For any approximated Boolean variable $x$, logic expression $x \\in [ 0.0, 1.0 ]$, can be expressed as floating-point values instead of discerete two states.\u003c/p\u003e","title":"Differential Logic Part 1"}]