<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Serhii Barskyi on Medium]]></title>
        <description><![CDATA[Stories by Serhii Barskyi on Medium]]></description>
        <link>https://medium.com/@serhii.barskyi?source=rss-6960a7e8ad52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bZcF869Xav3HRYUdDqnkSA.jpeg</url>
            <title>Stories by Serhii Barskyi on Medium</title>
            <link>https://medium.com/@serhii.barskyi?source=rss-6960a7e8ad52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:37:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@serhii.barskyi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Nina Karlovna Bari and the Mathematical Theory of Harmonic Expansions: From Classical Fourier…]]></title>
            <link>https://medium.com/@serhii.barskyi/nina-karlovna-bari-and-the-mathematical-theory-of-harmonic-expansions-from-classical-fourier-36e28a8ae01a?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/36e28a8ae01a</guid>
            <category><![CDATA[harmonic-analysis]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[fourier-analysis]]></category>
            <category><![CDATA[serhii-barskyi]]></category>
            <category><![CDATA[nina-bari]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 07:38:28 GMT</pubDate>
            <atom:updated>2026-11-19T07:48:36.192Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Nina Karlovna Bari and the Mathematical Theory of Harmonic Expansions: From Classical Fourier Analysis to Modern Machine Learning. A 125th Anniversary Tribute</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53Qy_vdmGmPH5r_DYOfpKA.png" /></figure><h4><strong>Introduction</strong></h4><p>November 19, 2026, marks the 125th anniversary of the birth of Nina Karlovna Bari (1901–1961), an outstanding twentieth-century mathematician whose fundamental research encompassed the theory of trigonometric series, metric set theory, approximation theory, orthogonal and biorthogonal systems, and the geometry and basis structure of Hilbert spaces.</p><p>The theory of trigonometric series occupies an exceptional position in the history of mathematical analysis. Originating in Joseph Fourier’s investigations into the mathematical theory of heat propagation, it gave rise to a complex of fundamental problems that shaped the development of the theory of functions of a real variable, functional analysis, and the modern theory of function representation. The investigation of trigonometric expansions necessitated a reconsideration of the very concepts of functions, convergence, integrability, measure, and the geometric structure of sets of real numbers.</p><p>Nina Karlovna Bari’s scientific legacy belongs to one of the deepest currents of this development. Her research addressed not only the principles governing the representation of functions by harmonic components but also the fundamental conditions for the existence, uniqueness, completeness, and stability of such representations. Her work revealed intricate relationships between the analytical properties of trigonometric series, the topological structure of exceptional sets, the arithmetic properties of real numbers, and the geometry of infinite-dimensional function spaces.</p><p>In the twenty-first century, these problems have acquired particular significance in the mathematical theory of machine learning. Constructing a learnable functional mapping from a finite collection of observations inevitably involves questions of identifiability, the well-posedness of inverse problems, the stability of parameter recovery, the completeness of functional systems, approximation complexity, and the generalization capabilities of computational models.</p><p>Of fundamental importance is the distinction between the existence of a functional representation, the uniqueness of its coefficients, and the stability of their recovery. The universal approximation capability of a neural architecture does not, in itself, guarantee the identifiability of its learnable parameters, the well-conditioning of the learning problem, or the convergence of a sequence of approximations to the unknown target mapping.</p><p>Bari’s investigations into biorthogonal systems and bases in Hilbert spaces provide a functional-analytic framework for studying stable spectral representations. Her work on the uniqueness of trigonometric expansions reveals the fundamental nature of ambiguity in functional reconstruction, while her contributions to approximation theory establish relationships between the regularity of a function and the mathematical limits of its approximation accuracy.</p><p>These research directions are particularly relevant to complex-valued neural networks, trainable harmonic dictionaries, spectral learning dynamics, periodic activation functions, random Fourier features, and neural operators designed to approximate mappings between infinite-dimensional function spaces.</p><h4><strong>The Formation of a Mathematical Talent</strong></h4><p>Nina Karlovna Bari was born in Moscow into the family of the distinguished physician Karl Adolfovich Bari. The intellectually stimulating atmosphere of her family contributed to the development of her diverse interests. Alongside mathematics, she was interested in literature, painting, and music, attended art exhibitions and concerts, enjoyed travelling, and undertook demanding hiking expeditions through the mountainous regions of the Caucasus, the Pamirs, and the Tien Shan.</p><p>In 1918, having graduated from a private girls’ gymnasium and passed the examinations required for a matriculation certificate, Nina Bari entered the Faculty of Physics and Mathematics at Moscow University. She completed her university education in just three years, graduating in 1921.</p><p>Her development as a researcher coincided with a period of intensive growth within the Moscow Mathematical School, when investigations into set theory, the theory of functions of a real variable, and mathematical analysis were shaping new directions in mathematics worldwide.</p><p>In 1935, Nina Karlovna was awarded the degree of Doctor of Physical and Mathematical Sciences. By that time, her research on trigonometric series had already received international recognition [1, 2].</p><h4><strong>Luzitania and the Scientific Traditions of the Moscow Mathematical School</strong></h4><p>Nikolai Nikolaevich Luzin exerted a decisive influence on the formation of Nina Karlovna Bari’s mathematical worldview.</p><p>The scientific school he established, known as Luzitania, constituted a unique intellectual community in which mathematical education was inseparable from independent scientific research.</p><p>Luzin regarded teaching not as the transmission of a completed body of mathematical knowledge but as the involvement of students in the investigation of unresolved problems. Particular importance was attached to constructing counterexamples, identifying necessary and sufficient conditions for the validity of theorems, examining limiting cases, and discovering hidden relationships between different mathematical objects.</p><p>From this scientific environment emerged researchers who shaped the development of probability theory, topology, functional analysis, number theory, and mathematical logic.</p><p>Nina Bari concentrated on one of the most difficult problems of classical analysis — the uniqueness of the representation of functions by trigonometric series.</p><p>On January 22, 1922, she presented a research paper at a meeting of the Moscow Mathematical Society, becoming the first woman to address this scientific community. As early as 1923, the results of her investigations were published in the proceedings of the Paris Academy of Sciences.</p><p>Bari subsequently participated in the research seminars of Jacques Hadamard and Arnaud Denjoy in Paris and attended the International Congresses of Mathematicians in Bologna in 1928 and Edinburgh in 1958 [1, 2].</p><h4><strong>From Classical Fourier Theory to the General Theory of Trigonometric Series</strong></h4><p>Classical Fourier theory is based on the representation of a periodic function by harmonic components characterized by different frequencies, amplitudes, and phases.</p><p>The fundamental distinction between a Fourier series and a general trigonometric series, however, lies in the manner in which their coefficients are defined. The coefficients of a Fourier series are related to the original function through integral functionals. The coefficients of a general trigonometric series may be specified independently of any previously defined function.</p><p>This distinction gives rise to a complex of fundamental questions. Does a function represented by a given series exist? In what sense does convergence occur? Must the coefficients of a convergent trigonometric series coincide with the Fourier coefficients of its sum? Can a single function possess several distinct trigonometric representations?</p><p>In the space of square-integrable functions, the classical trigonometric system forms a complete orthonormal basis. Within this functional framework, the expansion coefficients are uniquely determined, and the convergence of orthogonal projections is ensured by the structure of the Hilbert space.</p><p>However, the transition from convergence in the norm of the space to pointwise convergence substantially changes the mathematical nature of the problem. The pointwise behaviour of partial sums is determined not only by the integral characteristics of a function but also by more subtle properties of its local structure.</p><p>The investigation of these distinctions constitutes one of the central themes of Bari’s fundamental monograph, <em>Trigonometric Series</em> [3].</p><h4><strong>The Uniqueness Problem for Harmonic Expansions</strong></h4><p>One of the most remarkable results in the theory of trigonometric series is the possibility of constructing a nontrivial series that converges to zero almost everywhere.</p><p>From the perspective of classical orthogonal expansions, such a situation appears paradoxical. If a function is identically zero, all its Fourier coefficients must also vanish. For general trigonometric series that do not belong to the corresponding class of orthogonal expansions in a Hilbert space, however, this conclusion is no longer valid.</p><p>In 1916, Dmitri Evgenievich Menshov constructed a nontrivial trigonometric series converging to zero almost everywhere. This result demonstrated the fundamental inadequacy of characterizing exceptional sets solely in terms of Lebesgue measure.</p><p>It became necessary to classify sets according to whether they permit the existence of nontrivial trigonometric series converging to zero outside those sets.</p><p>This gave rise to the theory of sets of uniqueness and sets of multiplicity.</p><p>A set of uniqueness is characterized by the property that if a trigonometric series converges to zero outside the set, all its coefficients must vanish. For a set of multiplicity, there exists a nontrivial trigonometric series converging to zero at every point outside that set.</p><p>Bari’s fundamental theorem establishes that a countable union of closed sets of uniqueness is itself a set of uniqueness.</p><p>The significance of this result extends far beyond the formal classification of sets. It establishes conditions under which analytical uniqueness is preserved under operations on topological objects and reveals the relationship between the structure of exceptional sets and the possibility of recovering harmonic representations [3, 4].</p><h4><strong>The Geometry of Sets and the Arithmetic Nature of Uniqueness</strong></h4><p>Sets of uniqueness cannot be fully characterized by the classical concept of measure.</p><p>There exist perfect sets of measure zero that are sets of uniqueness, as well as perfect sets of measure zero that permit nonuniqueness of trigonometric expansions.</p><p>Consequently, sets that are indistinguishable in terms of Lebesgue measure may possess fundamentally different properties from the perspective of harmonic analysis.</p><p>A particularly profound direction of Bari’s research concerns the study of Cantor-type perfect sets. Their geometric structure is determined by the successive removal of intervals, while their analytical properties depend on the distribution of the remaining points, the scales involved in their construction, and the arithmetic nature of the corresponding parameters.</p><p>Of particular importance are the Diophantine properties of numbers, which govern the possibility of approximating certain numerical sequences by integers.</p><p>In her 1937 paper, Bari directly investigated the role of Diophantine relations in the uniqueness problem for trigonometric expansions [5].</p><p>Thus, a fundamental problem of harmonic analysis becomes simultaneously connected with topology, metric set theory, number theory, and the arithmetic properties of spectral representations.</p><h4><strong>Paradoxes of Fourier Series Convergence</strong></h4><p>One of the deepest features of harmonic analysis is the absence of a direct equivalence between different modes of convergence of functional expansions.</p><p>Convergence in the mean does not guarantee convergence at every point. Pointwise convergence does not ensure uniform convergence. The continuity of the represented function is likewise insufficient to guarantee the convergence of its Fourier series at every point.</p><p>Bari’s fundamental monograph systematically presents numerous results demonstrating the complexity of the interaction between function regularity and the behaviour of harmonic expansions.</p><p>Particularly important are investigations into the divergence of Fourier series of continuous functions, divergence on prescribed sets, the behaviour of subsequences of partial sums, absolute convergence, and various summability methods.</p><p>From a functional-analytic perspective, the partial sums of a Fourier series constitute a sequence of linear operators. Their properties depend substantially on the space in which the problem is formulated.</p><p>In the Hilbert space of square-integrable functions, these operators are orthogonal projections. In the space of continuous functions equipped with the uniform norm, their operator norms are not uniformly bounded.</p><p>This difference in operator properties explains why the same spectral expansion mechanism exhibits fundamentally different convergence characteristics in different function spaces.</p><h4><strong>Modification of Functions and Universal Trigonometric Series</strong></h4><p>Results concerning the modification of functions on sets of arbitrarily small measure occupy an exceptional position in Bari’s monograph.</p><p>The central mathematical idea of this research direction is the possibility of substantially improving the analytical properties of a function by modifying its values on a specially constructed exceptional set.</p><p>The smallness of the measure of the modification set does not, however, imply the smallness of the modifications themselves in the uniform norm.</p><p>Classical function modification theorems demonstrate the essential role played by the geometry of exceptional sets in functional representations. They make it possible to investigate the construction of continuous functions whose Fourier series have improved convergence properties.</p><p>No less profound is the theory of universal trigonometric series.</p><p>Universality in this context refers to the existence of trigonometric series whose various subsequences of partial sums can approximate a broad class of functions in an appropriate topology.</p><p>Universality differs substantially from the ordinary completeness of a functional system. Completeness establishes the possibility of approximating different functions by using different expansion coefficients. A universal series exhibits a considerably more intricate phenomenon: a diversity of functional approximations arises within the sequence of partial sums of a single series.</p><h4><strong>Lacunary Series and the Structure of Harmonic Spectra</strong></h4><p>Lacunary trigonometric series are characterized by substantial gaps between the successive frequencies of their harmonic components.</p><p>Under the classical Hadamard lacunarity condition, the sequence of frequencies grows at least geometrically.</p><p>Such a spectral organization gives rise to analytical and probabilistic properties that differ substantially from those of arbitrary trigonometric series.</p><p>Under appropriate conditions, lacunary harmonic components exhibit behaviour analogous to that of independent random variables, even though they are themselves deterministic functions of a single variable.</p><p>The study of lacunary systems reveals profound relationships between the spectral structure of a function, the convergence of series, the distribution of values of harmonic sums, and their moment characteristics.</p><p>Related problems arise in modern computational mathematics when constructing sparse spectral representations. Sparsity and lacunarity, however, are not equivalent concepts. Sparsity refers to a limited number of essential components, whereas lacunarity imposes structural restrictions on the arrangement of their frequencies.</p><h4><strong>Biorthogonal Systems and Bases in Hilbert Spaces</strong></h4><p>In 1951, Nina Karlovna Bari published her fundamental work, <em>Biorthogonal Systems and Bases in Hilbert Space</em>, whose significance extends far beyond the classical theory of trigonometric series [6].</p><p>Orthonormal bases possess an exceptionally convenient geometric structure. Expansion coefficients are recovered through inner products, while the norm of the represented element is directly related to the square summability of its coefficients.</p><p>In both theoretical and applied problems of functional analysis, however, systems that do not possess strict orthogonality frequently arise.</p><p>A fundamental question therefore emerges: under what conditions does a nonorthogonal system retain the principal analytical advantages of an orthonormal basis?</p><p>Bari investigated this question through the theory of biorthogonal systems.</p><p>Biorthogonality presupposes the existence of a dual system of functional elements that enables the coefficients of the original expansion to be recovered. Each element of the dual system extracts the corresponding component while annihilating all the others.</p><p>The existence of a biorthogonal system, however, does not by itself guarantee the stable recovery of an arbitrary element of the space.</p><p>The properties of Riesz bases are of fundamental importance for such stability. A Riesz basis can be obtained from an orthonormal basis through a bounded linear operator possessing a bounded inverse.</p><p>Consequently, the geometry of the coefficient space and that of the represented functional elements remain quantitatively equivalent.</p><p>One of Bari’s fundamental theorems establishes that a system quadratically close to a Riesz basis and satisfying an appropriate condition of omega-linear independence is itself a Riesz basis.</p><p>The underlying operator-theoretic nature of this result lies in the fact that quadratic closeness between functional systems allows the corresponding transformation to be represented as a perturbation of an invertible operator by a Hilbert-Schmidt operator. The compactness of this perturbation makes it possible to invoke the Fredholm alternative, while the independence condition excludes the existence of a nontrivial kernel.</p><p>The stability of functional expansions is thus investigated through the geometry of Hilbert spaces, the theory of compact operators, and the spectral properties of synthesis operators.</p><h4><strong>Bari-Stechkin Approximation Theory</strong></h4><p>During the final decade of her life, Nina Karlovna Bari actively pursued research in approximation theory.</p><p>Of particular significance was her joint paper with Sergei Borisovich Stechkin, published in 1956 under the title <em>Best Approximations and Differential Properties of Two Conjugate Functions</em> [7].</p><p>The theory of best approximation investigates the minimum attainable error in representing a function by elements of a prescribed functional class.</p><p>For trigonometric polynomials, the relevant restriction is the maximum frequency of the harmonic components included in the representation.</p><p>The fundamental question is to establish the relationship between the analytical regularity of a function and the rate at which its best approximation error decreases as the admissible spectrum expands.</p><p>Direct theorems in approximation theory provide estimates of approximation accuracy based on known regularity characteristics of a function. Inverse theorems establish which properties of a function can be inferred from the observed rate of its best approximation.</p><p>In the investigations of Bari and Stechkin, particular attention was devoted to the relationships between moduli of continuity, best approximations, and the differential properties of conjugate functions.</p><p>The significance of these results also lies in their applicability to functional classes whose regularity cannot be exhaustively described solely in terms of integer orders of differentiability.</p><p>They thus establish analytical foundations for investigating the fine structure of function spaces and determining quantitative laws of spectral approximation.</p><h4><strong>Bari’s Mathematical Legacy and Modern Machine Learning</strong></h4><p><strong>The Functional-Analytic Nature of Learning</strong></p><p>The mathematical theory of machine learning addresses the construction of functional mappings from a limited collection of observations.</p><p>Within this framework, a fundamental distinction must be made between the input data space, the model parameter space, the space of representable functions, and the space of observed values.</p><p>The mapping from the parameter space into the function space determines the approximation capabilities of the architecture. The observation operator maps functional elements into the finite-dimensional space of training data. The learning algorithm seeks an approximate solution to the corresponding inverse problem.</p><p>In this formulation, learning error is determined by the interaction of several mathematically distinct mechanisms: the limitations of the admissible function class, the incompleteness of observations, the conditioning of the reconstruction problem, statistical perturbations, and imperfections in the optimization algorithm.</p><p>It is precisely this functional-analytic distinction between different sources of error that makes it possible to move beyond empirical investigations of neural networks towards a mathematical theory of learnable representations.</p><p><strong>Uniqueness of Expansions and Model Identifiability<br></strong>The uniqueness problem for trigonometric expansions bears a profound structural relationship to the problem of identifiability in machine learning.</p><p>A training dataset imposes a finite collection of constraints on an unknown functional mapping. If several distinct functions satisfy all these constraints, reconstructing the original mapping becomes an ambiguous problem.</p><p>This issue is particularly evident in models that employ a fixed system of harmonic features together with trainable spectral expansion coefficients.</p><p>The uniqueness of these coefficients is determined by the absence of a nontrivial kernel of the observation operator restricted to the selected functional space.</p><p>Even a linearly independent system of functions may become linearly dependent after discretization on a particular training dataset. Consequently, the completeness of a functional system in a continuous space does not guarantee the identifiability of its finite-dimensional representation from arbitrary observations.</p><p>This distinction is of fundamental importance in investigating overfitting, the nonuniqueness of optimal solutions, and the ability of trained models to recover underlying regularities beyond the observed data.</p><p>Bari’s classical sets of uniqueness and observation sets in machine learning belong to different mathematical frameworks. Both theories, however, investigate how the uniqueness of functional reconstruction depends on the structure of the available information and the class of admissible representations.</p><p><strong>Bari and Riesz Bases as a Framework for Analysing Learning Stability<br></strong>For a spectral model that is linear with respect to its trainable coefficients, the learning problem can be reduced to recovering an element of the coefficient space from observations of the corresponding functional combination.</p><p>The stability of this reconstruction is determined by the geometric properties of the feature system and the observation operator.</p><p>If the functional elements form a Riesz basis, changes in the coefficients control changes in the represented function in the Hilbert space norm. A converse bound simultaneously holds, excluding the possibility of arbitrarily large changes in the coefficients producing arbitrarily small changes in the function.</p><p>Stable machine learning, however, requires an additional condition: discrete observations must preserve the geometric properties of the corresponding functional subspace.</p><p>In other words, the empirical norm induced by the training dataset must be quantitatively comparable to the norm of the original function space.</p><p>Otherwise, even a well-conditioned continuous basis may give rise to a nearly singular reconstruction problem.</p><p>Bari’s theory makes it possible to investigate the conditions under which basis properties are preserved when the original harmonic system undergoes perturbations. In machine learning, such perturbations arise through frequency adaptation, modifications of phase parameters, coordinate deformations, and the construction of trainable spectral dictionaries.</p><p>Provided that the relevant mathematical conditions are satisfied, basis stability theorems can serve as an analytical framework for investigating such architectures, without replacing the independent analysis required for the discrete observation operator.</p><p><strong>Biorthogonality, Pseudoinverse Operators, and Conditioning<br></strong>In nonorthogonal functional systems, the recovery of expansion coefficients requires consideration of the interactions between different elements of the spectral dictionary.</p><p>The Gram operator provides a mathematical instrument for investigating these interactions by characterizing the mutual inner products of the functional elements.</p><p>As the system approaches linear dependence, the lower spectral bound of the Gram operator approaches zero. Consequently, even small perturbations in the observed data may cause substantial changes in the recovered coefficients.</p><p>For finite-dimensional spectral models, an analogous role is played by the singular value spectrum of the observation matrix.</p><p>The Moore-Penrose pseudoinverse provides a minimum-norm solution to the least-squares problem. The mere existence of such a solution, however, does not imply the stability of the reconstruction.</p><p>Without sufficient spectral separation from zero, pseudoinversion may substantially amplify observational noise.</p><p>Tikhonov regularization, truncated singular value decomposition, and spectral filtering make it possible to limit the influence of poorly observed components. Improved stability is achieved, however, by modifying the original reconstruction problem and introducing an additional approximation error.</p><p>Thus, the mathematical well-posedness of the learning process is determined not only by the number of model parameters and the size of the training dataset but also by the spectral structure of the observation operator.</p><p><strong>Bari-Stechkin Theory and the Limits of Neural Network Approximation<br></strong>Universal approximation theorems for neural networks establish the existence of approximations of prescribed accuracy for sufficiently broad classes of architectures.</p><p>In general, however, these theorems do not determine the computational complexity required by a model, the stability of parameter recovery, or the rate at which a prescribed accuracy can be achieved.</p><p>Classical approximation theory provides a framework for investigating precisely these quantitative characteristics.</p><p>For harmonic models, the rate at which spectral approximation error decreases depends on the regularity of the original function, the distribution of its spectral energy, and the geometry of its domain.</p><p>Under appropriate conditions, smooth functions permit a sufficiently rapid decrease in spectral truncation error. For functions with discontinuities, local singularities, or complex high-frequency structures, the approximation problem becomes substantially more difficult.</p><p>Direct and inverse theorems in approximation theory make it possible to investigate the mathematical relationship between the complexity of a functional object and the required complexity of its spectral representation.</p><p>In this context, the investigations of Bari and Stechkin acquire particular significance for developing mathematically justified criteria for selecting functional classes, determining sufficient spectral dimensionality, and analysing the approximation limitations of learnable models.</p><p><strong>Spectral Bias and Neural Network Learning Dynamics<br></strong>One of the fundamental problems of modern machine learning is the spectral bias of neural networks.</p><p>Under certain architectural and algorithmic conditions, low-frequency components of the represented function are recovered considerably faster than high-frequency components.</p><p>Research on spectral bias has demonstrated that the high expressive capacity of a neural network does not ensure that all functional components are equally accessible to the learning algorithm [8].</p><p>In mathematical models of learning based on the neural tangent kernel, differences in the rates of component recovery are related to the spectral properties of the corresponding integral operator.</p><p>Errors associated with functional components corresponding to larger eigenvalues of the operator decay more rapidly than errors associated with spectral directions corresponding to smaller eigenvalues.</p><p>When the kernel is translation-invariant and the domain satisfies the appropriate conditions, Fourier harmonics may constitute the eigenfunctions of such an operator.</p><p>This formulation establishes a relationship between machine learning dynamics and the classical spectral theory of operators.</p><p>A fundamental distinction must nevertheless be maintained between the convergence of a harmonic series, the approximation convergence of a functional model as its dimensionality increases, and the convergence of the learning algorithm for a fixed architecture.</p><p><strong>Fourier Features and Periodic Activation Functions<br></strong>Modern spectral machine learning architectures employ harmonic transformations of input coordinates to construct functional feature spaces.</p><p>The Random Fourier Features method uses randomly sampled harmonic features to obtain finite-dimensional approximations of translation-invariant positive-definite kernels [9].</p><p>The theoretical foundation of this approach is Bochner’s theorem, which relates continuous positive-definite functions to Fourier transforms of finite positive measures.</p><p>Another direction is represented by Fourier Feature Networks, in which a preliminary harmonic transformation of the input data makes it possible to modify the spectral characteristics of the effective learning kernel and improve the recovery of high-frequency functional components [10].</p><p>SIREN neural networks incorporate periodic activation functions directly into multilayer architectures. Such models are employed to construct continuous representations of images, audio signals, wave fields, and solutions to differential equations [11].</p><p>Multilayer compositions of periodic functions, however, differ fundamentally from linear trigonometric expansions. They may generate additional harmonics, combination frequencies, and nonlinear interactions between spectral components.</p><p>The mathematical investigation of such architectures therefore requires the integration of classical Fourier theory with nonlinear operator theory, functional composition, and spectral analysis of learnable mappings.</p><p><strong>Complex-Valued Neural Networks<br></strong>Complex-valued neural networks occupy a distinctive position in the spectral theory of machine learning.</p><p>Complex-valued functional representations make it possible to describe the amplitude and phase characteristics of harmonic components jointly while preserving their natural geometric relationship.</p><p>Systems of complex exponentials constitute a fundamental mathematical instrument of harmonic analysis. A complex-valued neural network, however, may employ a considerably more intricate representational structure involving nonlinear phase transformations, complex weights, and compositions of operators.</p><p>For networks employing phase-based activation functions, the topology of the unit circle, the periodicity of phase coordinates, and multidimensional toroidal spaces acquire particular importance.</p><p>Functional mappings defined on such spaces naturally admit analysis through multidimensional Fourier series.</p><p>The learning problem for a complex-valued model, however, cannot automatically be reduced to the computation of Fourier coefficients. Such a reduction is possible only when the appropriate structural properties of the architecture, the function class, and the parameterization have been established.</p><p>The theory of biorthogonal systems and stable bases provides a mathematical framework for analysing the linear spectral components of such models, while nonlinear operator theory is required to investigate their multilayer compositional structures.</p><p><strong>Fourier Neural Operators<br></strong>One of the most significant contemporary directions in machine learning concerns the approximation of operators acting between function spaces.</p><p>Unlike conventional regression models that reconstruct mappings between finite-dimensional vectors, neural operators are designed to approximate the underlying laws governing transformations of entire functions.</p><p>The Fourier Neural Operator, first introduced in 2020 and published at ICLR in 2021, employs a spectral parameterization of integral operators [12].</p><p>Functional data are transformed into the frequency domain, where a trainable transformation of spectral components is performed. Subsequent inverse transformations and nonlinear operations produce an approximation of the target operator mapping.</p><p>This approach is employed in modelling families of solutions to differential equations, dynamical systems, fluid dynamics processes, and physical fields.</p><p>Questions concerning the boundedness of operators, the compactness of approximated classes, spectral truncation, stability under changes in discretization, and the convergence of finite-dimensional approximations in function spaces acquire fundamental importance in this setting.</p><p>It is precisely these questions that connect the modern theory of neural operators with the tradition of functional and harmonic analysis to which Bari’s mathematical legacy belongs.</p><p><strong>The Geometry of Training Sets and Generalization<br></strong>The number of training observations alone is not a sufficient measure of the informational completeness of a dataset.</p><p>Essential factors include the distribution of observation points, the geometry of the domain, the spectral properties of the function being reconstructed, and the relationships between elements of the functional dictionary.</p><p>A large dataset concentrated within a restricted region of the domain may contain less useful information for spectral reconstruction than a substantially smaller but mathematically justified system of observations.</p><p>Moreover, exact agreement between predictions and training data does not exclude the possibility of substantial errors outside the observation set.</p><p>The investigation of generalization requires additional assumptions concerning the regularity of the unknown mapping, the probability distribution of the data, the complexity of the functional class, and the stability of the learning algorithm.</p><p>The classical theory of sets of uniqueness demonstrates how subtle the relationships between the geometric structure of sets and the uniqueness of functional representations can be.</p><p>Modern machine learning faces an analogous necessity to investigate not merely the quantity of available information but also its mathematical organization.</p><p><strong>Nina Karlovna Bari’s Pedagogical Legacy<br></strong>Nina Karlovna’s scientific work was inseparably connected with the teaching of mathematics.</p><p>Her lectures were distinguished by exceptional mathematical rigour, clarity of formulation, meticulous proofs, and particular attention to the construction of counterexamples.</p><p>Whenever the conditions of a theorem were not simultaneously necessary and sufficient, she sought to demonstrate to her students which restrictions were essential, which could be weakened, and which new research problems emerged when the original assumptions were modified.</p><p>This reflected the fundamental pedagogical tradition of Luzitania: a mathematical theorem was regarded not merely as a completed result but also as a source of further scientific investigation.</p><p>A particularly illustrative episode concerns Naum Yakovlevich Vilenkin, who would subsequently become an outstanding mathematician. During the evacuation of Moscow University, Nina Karlovna continued teaching him individually even after all the other students had ceased attending the optional course she had announced. These individual lessons exerted a substantial influence on Vilenkin’s subsequent investigations into orthogonal systems [2].</p><p>The joint research seminar conducted by Nina Karlovna Bari and Dmitri Evgenievich Menshov became one of the most important centres for the development of function theory and harmonic analysis.</p><p><strong>The Final Years and the Fundamental Monograph<br></strong>The final years of Nina Karlovna Bari’s life were marked by intensive scientific activity.</p><p>Alongside her own investigations, she participated in preparing the works of Nikolai Nikolaevich Luzin for publication. Of enormous scientific value are the extensive commentaries on his doctoral dissertation, <em>Integral and Trigonometric Series</em>, prepared jointly by Bari and Menshov.</p><p>The principal culmination of her many years of work was the fundamental monograph <em>Trigonometric Series</em>, published in 1961.</p><p>This work is distinguished by the exceptional breadth of its mathematical content, encompassing classical Fourier theory, general trigonometric series, subtle convergence problems, the theory of exceptional sets, lacunary systems, universal expansions, and numerous directions in the metric theory of functions.</p><p>The monograph is not confined to the systematic presentation of known mathematical results. Its structure reflects a profound understanding of the internal logic of harmonic analysis, the interrelationships between its fundamental problems, and the nature of the mathematical contradictions that arise within it.</p><p>Nina Karlovna dedicated this work to the memory of Nikolai Nikolaevich Luzin.</p><p>On July 15, 1961, Nina Karlovna Bari’s life came to a tragic end. She was fifty-nine years old.</p><p><strong>Conclusion<br></strong>The mathematical legacy of Nina Karlovna Bari encompasses fundamental problems whose significance extends far beyond the historical boundaries of twentieth-century classical analysis.</p><p>The uniqueness of functional representations, the geometry of exceptional sets, the stability of nonorthogonal bases, biorthogonality, the spectral structure of functional systems, and the quantitative principles of approximation constitute a complex of mathematical ideas that remains relevant to the modern theory of machine learning.</p><p>Her legacy is particularly significant for investigating architectures that employ harmonic features, complex-valued representations, adaptive spectral dictionaries, and the approximation of operators acting between function spaces.</p><p>The fundamental mathematical problem of machine learning lies not merely in constructing a functional approximation but also in establishing the conditions under which that approximation is unique, stable, identifiable, and amenable to quantitative error control.</p><p>It is the depth with which such problems are investigated that determines the enduring significance of Nina Karlovna Bari’s mathematical work.</p><p><strong>References<br></strong>1. Menshov, D. E., Stechkin, S. B., and Ulyanov, P. L. Nina Karlovna Bari. <em>Uspekhi Matematicheskikh Nauk</em>, 1962, Vol. 17, №1, pp. 121–133.</p><p>2. Videnskii, V. S. “Bera, Take It, Bari…” (On the Centenary of N. K. Bari’s Birth). <em>Istoriko-Matematicheskie Issledovaniya</em> (Historical and Mathematical Investigations), 2002, №7 (42), pp. 149–159.</p><p>3. Bari, N. K. <em>Trigonometric Series</em>. Moscow: Fizmatgiz, 1961.</p><p>4. Bari, N. K. The Problem of the Uniqueness of the Expansion of a Function into a Trigonometric Series. <em>Uspekhi Matematicheskikh Nauk</em>, 1949, Vol. 4, №3, pp. 3–68.</p><p>5. Bary, N. Sur le rôle des lois diophantiques dans le problème d’unicité du développement trigonométrique. <em>Matematicheskii Sbornik</em>, 1937, Vol. 2 (44), №4, pp. 699–724.</p><p>6. Bari, N. K. Biorthogonal Systems and Bases in Hilbert Space. <em>Uchenye Zapiski Moskovskogo Gosudarstvennogo Universiteta</em> (Scientific Notes of Moscow State University), 1951, №148, pp. 69–107.</p><p>7. Bari, N. K., and Stechkin, S. B. Best Approximations and Differential Properties of Two Conjugate Functions. <em>Trudy Moskovskogo Matematicheskogo Obshchestva</em> (Transactions of the Moscow Mathematical Society), 1956, Vol. 5, pp. 483–522.</p><p>8. Rahaman, N., et al. On the Spectral Bias of Neural Networks. <em>Proceedings of the 36th International Conference on Machine Learning</em>, 2019, pp. 5301–5310.</p><p>9. Rahimi, A., and Recht, B. Random Features for Large-Scale Kernel Machines. <em>Advances in Neural Information Processing Systems</em>, 2007.</p><p>10. Tancik, M., et al. Fourier Features Let Networks Learn High Frequency Functions in Low Dimensional Domains. <em>Advances in Neural Information Processing Systems</em>, 2020.</p><p>11. Sitzmann, V., et al. Implicit Neural Representations with Periodic Activation Functions. <em>Advances in Neural Information Processing Systems</em>, 2020.</p><p>12. Li, Z., et al. Fourier Neural Operator for Parametric Partial Differential Equations. <em>International Conference on Learning Representations</em>, 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36e28a8ae01a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Annealing Trigonometrization]]></title>
            <link>https://medium.com/@serhii.barskyi/quantum-annealing-trigonometrization-aae5b49dec64?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/aae5b49dec64</guid>
            <category><![CDATA[quantum]]></category>
            <category><![CDATA[quantum-optimization]]></category>
            <category><![CDATA[quantum-computer]]></category>
            <category><![CDATA[quantum-annealing]]></category>
            <category><![CDATA[besss]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 05:19:23 GMT</pubDate>
            <atom:updated>2026-10-28T03:16:27.327Z</atom:updated>
            <content:encoded><![CDATA[<h4>via Aizenberg MVN Theory. Applications to BESS Placement</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TB155POSt2d1BKMWUYYtlA.jpeg" /></figure><p>🔹Your Guide to Quantum Annealing Control <br><a href="https://leanpub.com/quantum-annealing-trigonometrization">https://leanpub.com/quantum-annealing-trigonometrization</a></p><p>🔹Quantum Annealing Trigonometrization develops a mathematical and engineering framework for representing quantum-annealing control and measured hardware response in complex spectral coordinates.</p><p>🔹This monograph supports practical preparation for Co-Ops and Internships in companies working with industrial quantum annealing and quantum optimization. Readers gain access to the public CSSF(QA) repository — Complex Spectral Surrogate Framework for Quantum Annealing — and to a complete experimental playground: QUBO/Ising → Pegasus embedding → Leap quantum cloud service → QPU experiment → spectral surrogate → statistical validation, together with a GPU mode in Google Colab <a href="https://github.com/Serhii-Barskyi/Quantum-Annealing-Trigonometrization-Framework">https://github.com/Serhii-Barskyi/Quantum-Annealing-Trigonometrization-Framework</a></p><p>🔹The monograph and the CSSF(QA) code can be used for LLM training and LLM-assisted support of quantum-classical experiments. The same technology stack can serve as a foundation for DeepTech startups and projects developed through startup centers, startup schools, accelerators, and international technology competitions in the field of quantum optimization.</p><p>🔹Starting from Aizenberg MVN theory and Hermitian complex least-squares estimation, the monograph develops operator-phase representations, complex harmonic models, regularized spectral surrogates, identifiability analysis, sequential updating, and validation procedures.</p><p>🔹The book connects continuous quantum annealing with QAOA-like angular coordinates while keeping the two models conceptually distinct. It studies frequency structures generated by Hamiltonian spectra and reconstructs measured response functions in complex-harmonic space. Particular emphasis is placed on validation: a surrogate is admitted to control only after independent testing supports its reliability.</p><p>🔹The applied part develops the Complex Spectral Surrogate Framework for Quantum Annealing — CSSF(QA) — for battery energy storage system (BESS) placement in power networks. It combines AC-network physics, complex neural-spectral features, physically informed QUBO formulations, quantum-annealing experiments, active QPU data acquisition, and out-of-distribution evaluation.</p><p>Topics include:</p><p>• Hermitian complex estimation and regularization<br>• Exponential and toric spectral approximation<br>• QUBO and Ising optimization<br>• Quantum annealing and operator-phase geometry<br>• QAOA-related spectral representations<br>• Active QPU learning and statistical validation<br>• BESS placement and power-system analysis</p><p>The monograph is intended for researchers and advanced practitioners working in quantum optimization, applied mathematics, machine learning, energy storage, and electrical power systems.</p><p><strong>Download </strong><a href="https://www.amazon.co.uk/dp/B0HGC64HB4">https://www.amazon.co.uk/dp/B0HGC64HB4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aae5b49dec64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aizenberg Neuron for JPMorgan Chase’s Quantum Optimization Kit (QOKit): Enhancing Initial States…]]></title>
            <link>https://medium.com/@serhii.barskyi/aizenberg-neuron-for-jpmorgan-chases-quantum-optimization-kit-qokit-enhancing-initial-states-05294ac9968e?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/05294ac9968e</guid>
            <category><![CDATA[sigma-publishing]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[qaoa]]></category>
            <category><![CDATA[serhii-barskyi]]></category>
            <category><![CDATA[aizenberg-neuron]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 00:16:11 GMT</pubDate>
            <atom:updated>2026-05-02T07:31:23.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>Aizenberg Neuron for JPMorgan Chase’s Quantum Optimization Kit (QOKit): Enhancing Initial States and Mixers for Portfolio Optimization</h3><p>My Data Science Course <a href="https://preply.com/en/tutor/7756455">https://preply.com/en/tutor/7756455</a></p><p>How can you use qo-MLMVN (TensorFlow) to boost Quantum Entanglement and Superposition in QAOA, VQE, and QUBO for DeepTech startups?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDeARCuaucJ1R8fyp_BzvQ.png" /></figure><p>qo-MLMVM (quantum optimization Multi-Layered Neural Network Based on Multi-Valued Neurons) is a modified version of MLMVM based on the Aizenberg neuron (MVN), designed to address tasks related to enhancing superposition and entanglement for algorithms like QAOA (Quantum Approximate Optimization Algorithm).</p><p><a href="https://medium.com/@serhii.barskyi/quantum-projection-of-the-aizenberg-neuron-hilbert-space-through-the-prism-of-q-mlmvn-2cf472c78f37">Learn more about the mathematical richness and potential of <strong>Aizenberg MLMVN</strong> in this <strong>course</strong>.</a></p><blockquote>In this lesson from <a href="http://linkedin.com/company/sigma-publishinq/posts/"><strong>Sigma Publishinq</strong></a>, we will explore the task:</blockquote><h4><strong>&quot;Improving initial states and mixers, as well as aligning the initial state with the mixer for portfolio optimization - using qo-MLMVM and QOKit</strong>.&quot;</h4><p><a href="https://github.com/jpmorganchase/QOKit"><strong>QOKit</strong></a> is a high-performance simulator from <a href="https://www.jpmorganchase.com/"><strong>JPMorgan Chase</strong></a> for the Quantum Approximate Optimization Algorithm (QAOA), designed for fast simulation of quantum circuits on CPU and GPU.</p><p>It provides a user-friendly API for solving optimization problems, such as MaxCut and LABS, with optimization through pre-computation of target function values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtssbAV0tbWehYBygWRHfA.png" /></figure><blockquote>QOKit can utilize 1024 graphics processing units (GPUs) simultaneously for distributed simulation of QAOA quantum circuits with 40 qubits. This enables handling massive computational tasks by distributing the quantum system&#39;s state across multiple GPUs, significantly accelerating simulation. For 40 qubits, it requires storing and processing a state vector of 2⁴⁰ complex numbers, made possible through efficient parallelization and communication between GPUs.</blockquote><p>The lesson from <a href="http://linkedin.com/company/sigma-publishinq/posts/"><strong>Sigma Publishinq</strong></a> primarily focuses on optimizing the angles γ and β in the Quantum Approximate Optimization Algorithm (QAOA) for solving Quadratic Unconstrained Binary Optimization (QUBO) problems in the Hilbert space H = (C²)^⊗n.<br> It covers the formation of the parameterized state |ψ(γ, β)&gt;, which minimizes the energy of the cost Hamiltonian H_C encoding the QUBO, using unitary operators: U_C(γ) (cost operator) and U_M(β) (mixer operator).</p><p>The methods of the qo-MLMVN framework are described, including compute_adaptive_threshold, apply, optimize_qaoa, and frequency_pooling, which adjust the angles to enhance the amplitudes of low-energy states and maintain a uniform superposition. Special attention is given to frequency analysis and neural approaches for structuring angles to ensure convergence to optimal solutions.</p><blockquote><strong>Particularly important is the description of integrating qo-MLMVN elements into QOKit.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cmfY83XoAazGJCH0_u2qEA.jpeg" /></figure><p>This lesson, featuring <strong>qo-MLMVN</strong>, QOKit, and the portfolio optimization task, effectively illustrates the practical application of the QAOA (Quantum Approximate Optimization Algorithm).</p><p>If you are a top manager, businessman, or algorithm developer, the following statistic is crucial for you: approximately 80% of all management tasks can be reduced to combinatorial solutions, particularly in discrete systems, planning, and optimization.</p><p>As its mission, <a href="http://linkedin.com/company/sigma-publishinq/posts/"><strong>Sigma Publishinq</strong></a> offers investors, clients, and stakeholders the development of quantum computing technologies capable of creating innovative products at the level of quantum advantage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3-tME3VUgWGRLtJb30G7Q.png" /><figcaption><a href="https://aqora.io/Sigma_Publishinq">QAOA and Quantum Reinforcement Learning on Qiskit: Quantum Optimization, Prototypes &amp; Consulting Papers</a></figcaption></figure><p>Modern DeepTech startups require quantum utility and commercial quantum computing. <a href="http://linkedin.com/company/sigma-publishinq/posts/"><strong>Sigma Publishinq</strong></a>, based on the qo-MLMVN framework, can offer the production of quantum solutions for industrial use cases that go beyond classical capabilities.</p><p>The qo-MLMVN framework can serve as the foundation for industry solutions with quantum advantages in broad classes of combinatorial optimization, quantum material simulation, and quantum machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeFP0UxDf67s_X9YJj3crg.png" /></figure><h3>1.Introduction to “angles”: γ and β</h3><p>In quantum algorithms, such as the Quantum Approximate Optimization Algorithm (QAOA), the parameters γ (gamma) and β (beta) are critical for controlling the evolution of a quantum state in a finite-dimensional Hilbert space, defined by n qubits with a dimension of 2ⁿ. These parameters, being real numbers, determine the strength of the unitary operators e⁻ⁱγHₚ and e⁻ⁱβHₘ, where Hₚ is the problem Hamiltonian encoding the optimization task, and Hₘ is the mixing Hamiltonian facilitating state exploration. In certain models, such as multi-valued neurons (MVN), γ and β are not directly encoded as phases of complex numbers (eⁱγ, eⁱβ) to determine neuron activation. Instead, γ and β are transformed via the Fast Fourier Transform (FFT) into frequency coefficients that influence the phase shifts of MVN input data, indirectly modulating activation. This transformation links the spectral characteristics of the parameters to neural processing, but MVN activation depends on the phases of weighted input sums, not directly on γ and β. Additionally, to analyze patterns in these parameters or related data (e.g., financial metrics in applied tasks), techniques like FFT can be applied to a vector derived from γ and β, decomposing them into frequency components to filter noise or extract significant features. In this context, γ and β govern the quantum operators that rotate the quantum state in Hilbert space, and their representation through frequency analysis in MVN provides a framework for optimizing the structure of the task, such as finding the minimum energy configuration in combinatorial optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5wqLyaLKGbqgD4MYZ0o1Q.png" /></figure><h4>1.1 Gamma (γ) and its connection to the phase operator</h4><p>The parameter γ controls the unitary operator e⁻ⁱγHₚ in the Quantum Approximate Optimization Algorithm (QAOA), which evolves the quantum state under the influence of the problem Hamiltonian Hₚ—a mathematical object encoding the optimization objective, such as minimizing costs in portfolio optimization. For example, in portfolio optimization, Hₚ may represent a quadratic function balancing expected returns and risk. The operator e⁻ⁱγHₚ acts on the quantum state by applying phase shifts to its components in the eigenbasis of Hₚ, where the phase for each eigenstate depends on γ and the corresponding eigenvalue. Here, γ scales the phase shifts, influencing how strongly the system responds to the objective function: larger γ values increase phase differences between states, which can highlight low-energy states (better solutions) when optimized alongside β. In the context of multi-valued neurons (MVN), γ is not directly encoded as the phase of neuron activation. Instead, γ is transformed via the Fast Fourier Transform (FFT) into frequency coefficients that influence the phase shifts of MVN input data, indirectly modulating activation. When analyzing sequences of parameters or related data (e.g., financial metrics), FFT is applied to a vector of phases derived from γ values, decomposing them into frequency components to filter noise or identify significant features. Thus, γ governs phase evolution in QAOA, and its representation through frequency analysis in MVN aids in optimizing the solution to combinatorial tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBDreaKB4orgXxC-WxBQHw.png" /></figure><h4>1.2 Beta (β) and the mixing operator</h4><p>The parameter β in the Quantum Approximate Optimization Algorithm (QAOA) controls the mixing operator e⁻ⁱβHₘ, where Hₘ is the mixing Hamiltonian responsible for transitions between quantum states in Hilbert space. This operator facilitates the creation of superposition, distributing probability amplitudes across states, but it does not always preserve task constraints, such as fixed Hamming weight, since the standard Hₘ = ∑ᵢXᵢ arbitrarily flips bits. The value of β determines the rotation angle: small β values ensure weak mixing, preserving local correlations, while large β values enhance global exploration of the solution space. In the context of multi-valued neurons (MVN), β is not directly encoded as the phase of neuron activation. Instead, β is transformed via the Fast Fourier Transform (FFT) into frequency coefficients that influence the phase shifts of MVN input data, indirectly modulating activation. From an FFT perspective, β may introduce high-frequency components into the angle spectrum if its values vary rapidly, but this depends on the task dynamics, and β is not always associated with high frequencies. This processing allows MVN to adapt to the spectral characteristics of β, supporting data optimization, but the direct influence of β on the phase of neuron activation is limited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyF5nFVYIfJaMTw9Itgspw.png" /></figure><h4><strong>1.3 Role of γ and β in quantum system evolution</strong></h4><p>In the Quantum Approximate Optimization Algorithm (QAOA), the quantum state begins with an initial superposition, typically uniform, where all possible solutions have equal probability. Then, phase and mixing operators are applied alternately p times, where p is the algorithm’s depth, determining the number of alternations. Each application of the phase operator with “angle” γ amplifies the probability of states corresponding to low objective function values by applying phase shifts in the eigenbasis of the problem Hamiltonian Hₚ. In multi-valued neurons (MVN), γ is not directly encoded as a phase to select an activation sector. Instead, γ is transformed via the Fast Fourier Transform (FFT) into frequency coefficients that indirectly influence the phase shifts of MVN input data, modulating activation. The mixing operator with “angle” β, applied after the phase operator, facilitates quantum transitions between states, maintaining solution diversity. Similarly, in MVN, β is processed through FFT into frequency coefficients that adjust input phase shifts, not directly shifting activation along the unit circle. Frequency analysis via FFT decomposes the sequence of γ and β “angles” into harmonic components, revealing dominant frequencies: low-frequency γ components may indicate stable, large-scale changes in the solution, while high-frequency β components reflect fine-tuning needed to avoid local minima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DfP4W_dS7Msa5EvK_Mnhw.png" /></figure><h4><strong>1.4 “Angle” optimization and connection to the unit circle</strong></h4><p>The process of optimizing γ and β involves finding values that minimize the system’s energy, bringing the quantum state as close as possible to the optimal solution. These “angles” define the evolution trajectory in Hilbert space, where each state is a vector, and operators are rotations altering its direction. In multi-valued neurons (MVN), γ and β are not directly used to select a phase on the unit circle for aligning activation with a target sector. Instead, they are transformed via the Fast Fourier Transform (FFT) into frequency coefficients that influence the phase of weighted input sums, indirectly modulating MVN activation to minimize error. Angle optimization in QAOA is often performed using classical methods like gradient descent, adjusting “angles” to reduce energy, similar to training an MVN where weights are tuned to optimize output phase alignment. Frequency analysis via FFT aids this process by identifying key harmonics in the “angle” sequence: for instance, if FFT shows low frequencies dominating γ, it may suggest enhancing global changes in the phase operator, while a focus on high frequencies in β could indicate a need for more intensive mixing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0Yws8s1IH6Mzg9-Sw0S_Q.png" /></figure><h4>1.5 Practical significance and limitations</h4><p>The “angles” γ and β determine the balance between exploring the solution space and exploiting current problem information: γ focuses on amplifying better solutions by applying phase shifts to states in the eigenbasis of Hₚ, while β ensures diversity, preventing the system from getting stuck in suboptimal configurations by facilitating state transitions. In multi-valued neurons (MVN), this balance is not directly reflected in selecting an activation sector based on γ or β phases. Instead, γ and β are transformed via the Fast Fourier Transform (FFT) into frequency coefficients that modulate the phase shifts of MVN input data, indirectly affecting activation. However, on noisy quantum devices, precisely tuning γ and β is challenging, as noise distorts rotations in Hilbert space, similar to inaccuracies in phase processing in MVN. Frequency analysis via FFT can help identify stable angle components, filtering out noisy high-frequency oscillations, thus improving optimization stability. For example, isolating low-frequency harmonics in γ can simplify phase operator tuning, making the algorithm more robust to errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-A4NmP-KjmsegLsvWZ29w.png" /></figure><h4>1.6 Frequency perspective and connection to MVN</h4><p>Using FFT to analyze γ and β allows them to be treated as signals, where each frequency component corresponds to a specific aspect of the quantum system’s dynamics: low frequencies may reflect global solution trends, while high frequencies indicate local adjustments. In multi-valued neurons (MVN), frequency analysis is applied to input data or parameters like γ and β, transformed via FFT into frequency coefficients that influence phase shifts, which are then used to modulate activations rather than directly mapping to phases on the unit circle. For instance, in quantum optimization tasks, γ and β parameters can be transformed via FFT to identify dominant frequencies, which are then used to adjust MVN input processing, providing a more compact problem representation. This bridges quantum algorithms and neural networks, with frequency analysis serving as a common tool for analyzing their structure, enabling optimization of both quantum and classical system components.</p><p>Thus, γ and β in QAOA are parameters that define rotations in Hilbert space, guiding the quantum system toward an optimal solution. Their processing in multi-valued neurons (MVN) does not involve direct interpretation as activation phases on the unit circle. Instead, γ and β are transformed via the Fast Fourier Transform (FFT) into frequency coefficients that indirectly modulate MVN activation through phase shifts in input data. Frequency analysis via FFT reveals their dynamic structure, enabling the identification of key components for efficient optimization, bridging quantum optimization and neural network processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1m2baNFJn8BfJSBzlvjJA.png" /></figure><h3>2. QAOA and the Hamiltonian</h3><p>As is known, QAOA is applied to solve problems reducible to combinatorial optimization problems, often formulated as QUBO (Quadratic</p><p>Unconstrained Binary Optimization) or graph-based problems. In terms of functional analysis, these problems reduce to minimizing the energy functional ⟨ψ|H_C|ψ⟩, where the Hamiltonian H_C encodes the target function. However, QAOA does not guarantee a global optimum, providing an approximate solution instead.</p><p>What is a Hamiltonian? A Hamiltonian is a key concept in physics, mathematics, and quantum computing, describing the energy of a system or the target function in optimization problems.</p><h4>2.1 Hamiltonian in Classical Physics</h4><p>The Hamiltonian (denoted H) is a function that describes the total energy of a system:<br> • Kinetic energy (energy of motion, dependent on velocity).<br> • Potential energy (energy of position, e.g., from gravity or a spring).</p><p>Simply put, the Hamiltonian is a number indicating the total energy of a system, given the position and velocity of all its parts. For example, for a ball rolling down a hill, the Hamiltonian combines the energy of motion (how fast it rolls) and the energy of height (how high it is).<br> The Hamiltonian helps predict how a system evolves over time through specific equations (Hamilton’s equations).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQcSnStn-1TLM57U8UlJrQ.jpeg" /></figure><h4>2.2 Hamiltonian in Quantum Mechanics</h4><p>In quantum mechanics, the Hamiltonian becomes an operator (denoted Ĥ), which acts on the quantum state of the system, represented as |ψ⟩. It still describes energy, but now in the quantum realm, where everything is governed by probabilities.</p><p>The Hamiltonian determines how a quantum state evolves over time through the Schrödinger equation. Its eigenvalues represent the possible energy levels of the system. For example, for an electron in an atom, the Hamiltonian accounts for:<br> • The electron’s kinetic energy.<br> • The energy of attraction to the nucleus.</p><h4>2.3 Hamiltonian in QAOA</h4><p>In quantum algorithms like QAOA (Quantum Approximate Optimization Algorithm), the Hamiltonian is used to describe the optimization problem. As mentioned earlier, the Hamiltonian H_C is the cost Hamiltonian, which encodes the target function to be minimized.</p><p>In QAOA, problems like QUBO or graph-based tasks (e.g., MaxCut) are transformed into the Hamiltonian H_C. The value ⟨ψ|H_C|ψ⟩ (the expected energy for the state |ψ⟩) corresponds to the value of the target function. The goal of QAOA is to find a state |ψ⟩ that minimizes ⟨ψ|H_C|ψ⟩, thus solving the problem.</p><p><strong>Example:</strong><br> • For the MaxCut problem, the Hamiltonian H_C is constructed so that its minimum value corresponds to the best partitioning of the graph’s vertices.<br> • H_C is typically expressed in terms of quantum operators, but in simplified terms, it is a way to encode the problem.</p><h4>2.4 Hamiltonian as a Universal Tool</h4><p>• In physics, it describes energy and dynamics.<br> • In quantum computing, it encodes optimization problems.<br> • In QAOA, it bridges the physical concept of energy with the mathematical task of finding the best solution.<br> The Hamiltonian is like the “energy formula” of a system. In QAOA, it translates a problem like “find the best option” into a language that a quantum computer understands. The computer searches for the state with the minimum energy, which corresponds to the best solution.</p><h4>2.5 Answers to Common Questions</h4><p>• Is the Hamiltonian always energy?<br> In physics, yes. In optimization, it encodes the target function but is called energy for convenience.<br> • Why do we talk about the Hamiltonian H_C?<br> H_C is the Hamiltonian specifically constructed for the optimization problem.<br> • How does it work in QAOA?<br> QAOA uses two Hamiltonians: H_C (for the problem) and H_M (for mixing states). Their alternation helps find the optimal solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgB3Ah_WMa5b0rrgAsRCqw.jpeg" /></figure><h3><strong>3. How the Alternation of Hamiltonians and State Mixing Works in Quantum Algorithms</strong></h3><p>In quantum algorithms like QAOA, the core idea is to use two Hamiltonians: H_C (the cost Hamiltonian) and H_M (the mixing Hamiltonian). Their alternation enables efficient searching for the optimal solution to combinatorial optimization problems. Below, we explain how this alternation works, what state mixing is, why it is needed, and how it is mathematically organized.</p><h4>3.1 Context and Problem Setup</h4><p>Consider a combinatorial optimization problem, such as finding the maximum cut in a graph. The goal is to partition the vertices into two groups to maximize the number of edges between them. This problem reduces to minimizing a target function, which, in the quantum context, is represented by the Hamiltonian H_C. The value ⟨ψ|H_C|ψ⟩ for a quantum state |ψ⟩ corresponds to the value of the target function for a given solution. Our objective is to find a state |ψ⟩ that minimizes ⟨ψ|H_C|ψ⟩, i.e., corresponds to the optimal solution.</p><p>However, a quantum computer cannot directly compute this state. Instead, it evolves a quantum state under the influence of two Hamiltonians: H_C, which &quot;knows&quot; about the problem, and H_M, which facilitates exploration of possible solutions. Alternating these Hamiltonians creates dynamics that gradually approach the optimal state.</p><h4>3.2 What is Hamiltonian Alternation?</h4><p>Hamiltonian alternation means sequentially applying two evolution operators to the quantum state, each defined by its respective Hamiltonian.</p><p>In quantum mechanics, the evolution of a state |ψ⟩ over time is described by the Schrödinger equation. If a Hamiltonian H acts for time t, the state evolves according to the unitary operator U = exp(−iHt). Here, exp denotes the operator exponential, and i is the imaginary unit. This operator &quot;rotates&quot; the state |ψ⟩ in Hilbert space, preserving its norm.</p><p>In our case, we have two Hamiltonians:</p><ul><li>H_C: the cost Hamiltonian, which &quot;pulls&quot; the state toward low-energy solutions (good solutions to the problem).</li><li>H_M: the mixing Hamiltonian, which &quot;mixes&quot; the state to explore different possible solutions.</li></ul><p>Alternation involves applying the operators U_C = exp(−iβH_C) and U_M = exp(−iγH_M) sequentially, where β and γ are time parameters (or angles) that we choose. For example, starting from an initial state |ψ_0⟩, we apply U_M with parameter γ_1, then U_C with parameter β_1, then U_M with γ_2, and so on. This creates a sequence: |ψ⟩ → U_M(γ_1)|ψ⟩ → U_C(β_1)U_M(γ_1)|ψ⟩ → U_M(γ_2)U_C(β_1)U_M(γ_1)|ψ⟩ → ...</p><p>This sequence repeats p times (where p is the number of layers in the algorithm), with parameters β_k and γ_k optimized at each step to ensure the final state |ψ⟩ has a minimal value of ⟨ψ|H_C|ψ⟩.</p><h4>3.3 Role of the Hamiltonian H_C</h4><p>The Hamiltonian H_C encodes the target function of the problem. Its structure is such that its eigenstates with the smallest eigenvalues correspond to optimal solutions. For example, in the maximum cut problem, H_C is constructed so that its minimum eigenvalue corresponds to the vertex configuration with the maximum number of edges between groups.</p><p>Applying the operator U_C = exp(−iβH_C) induces a &quot;phase rotation&quot; in the quantum state. This means each basis state |z⟩ (where z is a possible solution, e.g., a string of 0s and 1s) acquires a phase factor exp(−iβE_z), where E_z is the energy of solution z, i.e., E_z = ⟨z|H_C|z⟩. The lower the energy E_z, the slower the phase changes for that state.</p><p>This process amplifies low-energy states, making them more “significant” in the final state. However, applying only H_C risks getting stuck in a local minimum or failing to explore other solutions, as H_C only modifies phases without changing the amplitudes of basis states.</p><h4>3.4 What is State Mixing and Why is it Needed?</h4><p>Now, let’s examine the Hamiltonian H_M and the concept of state mixing. State mixing is the process that allows a quantum state to &quot;flow&quot; between different basis states, redistributing probability amplitudes among possible solutions. Without mixing, the algorithm could not explore the solution space and would simply amplify the initial state in the direction dictated by H_C.</p><p>The Hamiltonian H_M is typically chosen to be simple and independent of the specific problem. A common choice for H_M is the transverse-field Hamiltonian: H_M = −∑X_i, where X_i is the Pauli X operator acting on the i-th qubit. This Hamiltonian induces mixing between the |0⟩ and |1⟩ states for each qubit.</p><p>Applying the operator U_M = exp(−iγH_M) rotates amplitudes between basis states. If the initial state is a superposition of all possible solutions (as in QAOA), U_M redistributes amplitudes, altering the relative weights of basis states. This is akin to diffusion: amplitudes &quot;spread&quot; across the state space, enabling the algorithm to explore new combinations.</p><p>Why is this needed? While H_C highlights good solutions, H_M ensures the algorithm doesn’t get stuck in a single solution, allowing it to &quot;jump&quot; between them. Without H_M, we would only amplify the initial state in the direction of H_C, which is inefficient for complex problems with many local minima.</p><p>Mathematically, H_M acts as a generator of transitions between states. Its eigenstates are superpositions of all basis states (e.g., |+⟩ = (|0⟩ + |1⟩)/√2 for a single qubit), ensuring that amplitudes in the initial state (typically a superposition of all solutions) do not vanish but are redistributed.</p><h4>3.5 How Does Alternating H_C and H_M Work?</h4><p>Alternating H_C and H_M creates a balance between exploitation (amplifying good solutions via H_C) and exploration (searching for new solutions via H_M).</p><p><strong>Initial State</strong><br> The algorithm starts with an initial state, typically a uniform superposition of all basis states: |ψ_0⟩ = (1/√2^n)∑|z⟩, where n is the number of qubits, and the sum is over all possible strings z of 0s and 1s. This state corresponds to &quot;equal probability&quot; for all solutions.</p><p><strong>First Step:</strong> applying U_M<br> The operator U_M = exp(−iγH_M) is applied to |ψ_0⟩. Since H_M = −∑X_i, it rotates amplitudes between |0⟩ and |1⟩ states for each qubit, redistributing amplitudes while preserving superposition but altering the relative weights of basis states. The parameter γ_1 determines the strength of this mixing.</p><p><strong>Second Step:</strong> applying U_C<br> Next, U_C = exp(−iβH_C) is applied. This operator adds phase factors to each basis state |z⟩ based on its energy E_z = ⟨z|H_C|z⟩. States with lower energy (better solutions) receive smaller phase shifts, making them more &quot;favorable&quot; in the final state. The parameter β_1 controls the magnitude of this effect.</p><p><strong>Repetition</strong><br> The steps repeat p times, each with new parameters γ_k and β_k. At each layer, U_M facilitates exploration of the state space, while U_C amplifies the amplitudes of low-energy states. The final state after p layers is: |ψ⟩ = [U_M(γ_p)U_C(β_p)]...[U_M(γ_1)U_C(β_1)]|ψ_0⟩.</p><p><strong>Measurement</strong><br> After all layers, the state |ψ⟩ is measured in the computational basis, yielding one basis state |z⟩ corresponding to a solution. The probability of obtaining |z⟩ is proportional to |⟨z|ψ⟩|^2, and the goal is to maximize the probability of low-energy states (good solutions).</p><h4><strong>3.6 Mathematics of Alternation: why it works</strong></h4><p>Alternation is connected to adiabatic quantum computing. In adiabatic computing, a system starts in the ground state of a simple Hamiltonian (e.g., H_M) and slowly evolves toward the problem Hamiltonian H_C. If the process is slow enough, the system remains in the ground state, yielding the problem’s solution.</p><p>Alternation in QAOA can be seen as a discrete version of this process. Instead of continuous evolution, we apply H_M and H_C alternately, breaking the process into p steps. Each U_M step &quot;blurs&quot; the state, enabling exploration, while U_C &quot;focuses&quot; it on low-energy states. The parameters γ_k and β_k act as the &quot;speed&quot; of this evolution.</p><p>Mathematically, the final state |ψ⟩ depends on the choice of parameters {γ_k, β_k}. To find optimal parameters, classical optimization (e.g., gradient descent) minimizes the expectation value ⟨ψ|H_C|ψ⟩. This makes QAOA a hybrid algorithm: the quantum computer prepares and measures states, while the classical computer optimizes parameters.</p><h4><strong>3.7 Why is State Mixing Critical?</strong></h4><p>Mixing, induced by H_M, is critical for several reasons:</p><ul><li>Solution Space Exploration: without H_M, the algorithm would get stuck in the initial state or near a local minimum, as H_C only amplifies existing amplitudes. H_M enables &quot;jumping&quot; between solutions, increasing the chance of finding the global minimum.</li><li>Preserving Superposition: H_M maintains quantum superposition, allowing simultaneous evaluation of multiple solutions.</li><li>Connection to Adiabatic Computing: H_M provides an initial state that is easy to prepare (e.g., a superposition) and supports dynamics resembling adiabatic evolution.</li></ul><p>Without H_M, the algorithm would resemble classical local search, losing its quantum advantage.</p><h4>3.8 Practical Aspects and Limitations</h4><p>Alternating H_C and H_M does not guarantee finding the global minimum, especially for problems with many local minima. Effectiveness depends on:</p><ul><li>The number of layers p: more layers increase accuracy but complicate parameter optimization.</li><li>Quality of γ_k and β_k optimization: poor parameter choices can lead to suboptimal results.</li><li>Problem structure: some problems are better suited for this approach than others.</li></ul><p>Additionally, implementation on real quantum computers is limited by noise and inaccuracies in applying U_C and U_M, necessitating error correction methods.</p><h4>3.9 Conclusion</h4><p>Alternating the Hamiltonians H_C and H_M in quantum algorithms like QAOA creates dynamics that balance exploration of the solution space with amplification of good solutions. H_C encodes the problem and highlights low-energy states, while H_M facilitates mixing, allowing the algorithm to jump between possible solutions. Mathematically, this is achieved through sequential application of unitary operators U_C and U_M, with parameter optimization to minimize ⟨ψ|H_C|ψ⟩. State mixing, induced by H_M, is critical for exploring the solution space and maintaining quantum superposition, making this approach powerful for combinatorial problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7GQSlaeJRmPbOBE6ECD9g.png" /></figure><h3>4.Applied problems for QAOA</h3><h4><strong>The most common applied problems for QAOA include:</strong></h4><ul><li>Maximum Cut (Max-Cut): partitioning a graph into two parts to maximize the weight of edges between them.<br> H_C = -Σ_{i,j} w_{ij} (1 - Z_i Z_j) / 2, where w_{ij} are edge weights.</li><li>Graph Coloring: minimizing conflicts when assigning colors to vertices.<br> H_C = Σ_{i,j} A_{ij} (1 - Z_i Z_j) + Σ_i P_i (1 - Z_i), where A_{ij} is the graph adjacency, P_i is the coloring penalty.</li><li>Graph Partitioning: dividing a graph into equal subsets with minimal connections.<br> H_C = Σ_{i,j} w_{ij} (1 - Z_i Z_j) / 2 + λ (Σ_i Z_i)^2, where λ is a balancing coefficient.</li><li>Portfolio Optimization: maximizing returns under risk constraints.<br> H_C = -Σ_i μ_i Z_i + γ Σ_{i,j} σ_{ij} Z_i Z_j, where μ_i is return, σ_{ij} is covariance, γ is risk.</li><li>Resource Allocation: optimizing resource distribution in networks.<br> H_C = Σ_{i,j} c_{ij} Z_i Z_j + Σ_i d_i Z_i, where c_{ij}, d_i are resource costs.</li><li>Job Shop Scheduling: optimizing task execution schedules.<br> H_C = Σ_{i,j} c_{ij} Z_i Z_j + Σ_i p_i (1 - Z_i), where c_{ij} are task conflicts, p_i are penalties for non-execution.</li><li>Transport Routing: minimizing distances or costs in delivery problems.<br> H_C = Σ_{i,j} d_{ij} Z_i Z_j + Σ_i c_i Z_i, where d_{ij} are distances, c_i are costs.</li><li>Supply Chain Optimization: minimizing logistics costs.<br> H_C = Σ_{i,j} c_{ij} Z_i Z_j + Σ_i f_i Z_i, where c_{ij} are logistics costs, f_i are fixed costs.</li><li>Facility Location: optimizing object placement on a graph.<br> H_C = Σ_{i,j} d_{ij} Z_i Z_j + Σ_i c_i Z_i, where d_{ij} are distances, c_i are costs.</li><li>Data Clustering: optimizing data partitioning into groups.<br> H_C = -Σ_{i,j} w_{ij} (1 - Z_i Z_j) / 2, where w_{ij} is similarity.</li><li>Machine Learning Training: optimizing model hyperparameters or weights.<br> H_C = Σ_{i,j} w_{ij} Z_i Z_j + Σ_i b_i Z_i, where w_{ij}, b_i are weights and biases.</li><li>Pattern Recognition: optimizing classification on graph structures.<br> H_C = Σ_{i,j} w_{ij} (1 - Z_i Z_j) + Σ_i c_i Z_i, where w_{ij} are connections, c_i are error penalties.</li><li>Telecom Network optimization: Minimizing delays or costs.<br> H_C = Σ_{i,j} l_{ij} Z_i Z_j + Σ_i c_i Z_i, where l_{ij} are delays, c_i are costs.</li><li>Energy Planning: optimizing energy distribution in networks.<br> H_C = Σ_{i,j} c_{ij} Z_i Z_j + Σ_i e_i Z_i, where c_{ij} are transmission costs, e_i is energy.</li><li>Advertising Campaign Optimization: maximizing ROI under budget constraints.<br> H_C = -Σ_i r_i Z_i + γ Σ_{i,j} c_{ij} Z_i Z_j, where r_i is ROI, c_{ij} is budget.</li><li>Project Budgeting: optimizing financial resource allocation.<br> H_C = Σ_{i,j} c_{ij} Z_i Z_j + Σ_i b_i Z_i, where c_{ij} are costs, b_i is budget.</li><li>Next Best Action (NBA): selecting optimal actions in CRM systems.<br> H_C = -Σ_i v_i Z_i + Σ_{i,j} c_{ij} Z_i Z_j, where v_i is value, c_{ij} are conflicts.</li><li>Recommendation Systems: optimizing personalized recommendations.<br> H_C = -Σ_i s_i Z_i + Σ_{i,j} w_{ij} Z_i Z_j, where s_i is relevance, w_{ij} are conflicts.</li><li>5G Network Route Optimization: minimizing interference.<br> H_C = Σ_{i,j} l_{ij} Z_i Z_j + Σ_i c_i Z_i, where l_{ij} is interference, c_i are costs.</li><li>Molecular Optimization: finding stable chemical configurations.<br> H_C = Σ_{i,j} J_{ij} Z_i Z_j + Σ_i h_i Z_i, where J_{ij}, h_i are interactions.</li><li>Quantum Circuit Optimization: minimizing circuit depth.<br> H_C = Σ_{i,j} c_{ij} Z_i Z_j + Σ_i d_i Z_i, where c_{ij}, d_i are circuit costs.</li><li>Data Encoding: optimizing error-resistant codes.<br> H_C = Σ_{i,j} e_{ij} Z_i Z_j + Σ_i f_i Z_i, where e_{ij}, f_i are errors and penalties.</li><li>Bioinformatics Optimization: analyzing DNA sequences.<br> H_C = Σ_{i,j} s_{ij} Z_i Z_j + Σ_i a_i Z_i, where s_{ij} is similarity, a_i are penalties.</li><li>Financial Trading: optimizing trading strategies.<br> H_C = -Σ_i p_i Z_i + γ Σ_{i,j} r_{ij} Z_i Z_j, where p_i is profit, r_{ij} is risk.</li><li>Game Optimization: finding optimal strategies in game graphs.<br> H_C = -Σ_i u_i Z_i + Σ_{i,j} c_{ij} Z_i Z_j, where u_i is utility, c_{ij} are conflicts.</li><li>Antenna Placement: optimizing coverage in wireless networks.<br> H_C = Σ_{i,j} l_{ij} Z_i Z_j + Σ_i c_i Z_i, where l_{ij} is interference, c_i are costs.</li><li>Robotics Optimization: planning trajectories.<br> H_C = Σ_{i,j} d_{ij} Z_i Z_j + Σ_i c_i Z_i, where d_{ij} are distances, c_i are penalties.</li><li>Image Segmentation: optimizing pixel partitioning.<br> H_C = Σ_{i,j} w_{ij} (1 - Z_i Z_j) + Σ_i c_i Z_i, where w_{ij} is similarity, c_i are penalties.</li><li>Social Network Analysis: optimizing community detection.<br> H_C = -Σ_{i,j} w_{ij} (1 - Z_i Z_j) / 2, where w_{ij} are connections.</li></ul><p>These problems reduce to a Hamiltonian H_C, typically expressed through Pauli operators (e.g., Z_i Z_j), and QAOA seeks a state ψ that minimizes &lt;ψ|H_C|ψ&gt;.</p><blockquote><strong>Note:</strong> the materials for this lesson are aimed at machine learning enthusiasts who may not yet be deeply familiar with quantum computing. Therefore, we will provide a brief explanation of quantum computing concepts encountered in this lesson.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKr5mzHa71oxqha_s_M0KQ.jpeg" /></figure><h3>5. Correct interpretation of quantum abstractions</h3><h4>Let’s start with Hilbert space</h4><p>Hilbert space H is the foundation upon which the mathematical language of quantum mechanics is built, a key mathematical structure underlying the modeling of quantum processes, enabling the description of states and evolution of quantum systems.</p><p><strong>Quantum states and their mathematical description in Hilbert space</strong></p><h4><strong>5.1 State vectors</strong></h4><p><strong>Formal definition:</strong> quantum states of a system are described by state vectors |ψ⟩, belonging to a complex Hilbert space H, and normalized such that ⟨ψ|ψ⟩ = 1.</p><p><strong>Explanation:</strong> in quantum mechanics, the state of a system, such as a particle’s spin, an electron’s position, or a photon’s polarization, is fully described by a state vector |ψ⟩. The Hilbert space H is a mathematical structure providing linearity and an inner product for computing probabilities. The vector |ψ⟩ encodes all information about the system accessible through measurements but is not a physical object like a classical trajectory. For example, for a two-level system like a qubit, the state vector can be written as |ψ⟩ = c_1|0⟩ + c_2|1⟩, where |0⟩ and |1⟩ are basis states, and c_1, c_2 are complex numbers.</p><p><strong>Normalization:</strong> the normalization condition ⟨ψ|ψ⟩ = 1 ensures a probabilistic interpretation: the squared modulus of the amplitude |⟨φ|ψ⟩|^2 gives the probability of finding the system in state |φ⟩ upon measurement. Normalization is not a classical “length” but a mathematical requirement ensuring the sum of probabilities of all possible measurement outcomes equals 1. For instance, for an electron in a hydrogen atom, the normalization of the wave function ψ_{1s}(r) allows calculating the probability of finding the electron in a given spatial region.</p><p><strong>Physical meaning:</strong> the state vector has no direct classical analog, such as a particle’s coordinates or velocity. Its role is to provide probability amplitudes for all observable quantities of the system. In the Copenhagen interpretation, |ψ⟩ describes complete knowledge of the system before measurement, while in the Many-Worlds Interpretation (MWI), it encompasses all possible outcomes in different branches. Misrepresenting the vector as an “arrow in space” can be misleading, as |ψ⟩ is an abstract entity in an infinite-dimensional space, not a physical object.</p><h4><strong>5.2 Linear structure and superposition</strong></h4><p><strong>Formal definition:</strong> state vectors in Hilbert space can be linearly combined, forming superpositions: |ψ⟩ = c_1|ψ_1⟩ + c_2|ψ_2⟩, where c_1, c_2 are complex numbers, and |c_1|^2 + |c_2|^2 = 1 for normalization.</p><p><strong>Explanation: </strong>the linear structure of Hilbert space allows any quantum state to be represented as a superposition of basis states. Superposition is a fundamental property of quantum mechanics, reflecting a system’s ability to exist in a coherent combination of multiple states simultaneously. For example, a qubit in the state |ψ⟩ = (1/√2)(|0⟩ + |1⟩) has equal probabilities (1/2) of being measured in |0⟩ or |1⟩, but before measurement, it exists in a coherent superposition. This differs from a classical mixture, where the system is definitively in one state with a given probability.</p><p><strong>Coherence and interference:</strong> the coherence of superposition, driven by non-zero phase relationships between c_1 and c_2, leads to interference effects, as in the double-slit experiment, where the probability of detecting a particle P(x) = |ψ_1(x) + ψ_2(x)|^2 includes an interference term 2Re(ψ_1*ψ_2). This has no classical analog, such as “mixing colors,” as interference arises from probability amplitudes, not physical overlap.</p><p><strong>Physical meaning:</strong> superposition underlies quantum phenomena like interference and quantum computing. For instance, in Shor’s algorithm, the superposition of multiple input states enables parallel computation of an exponential number of solutions. Comparing superposition to a classical mixture (e.g., “part of the electron is here, part is there”) overlooks its coherent nature and probabilistic interpretation.</p><h4><strong>5.3 Inner product</strong></h4><p><strong>Formal definition:</strong> the inner product ⟨φ|ψ⟩ yields a complex amplitude, and |⟨φ|ψ⟩|^2 determines the probability of a system transitioning from state |ψ⟩ to state |φ⟩ upon measurement. States are orthogonal if ⟨φ|ψ⟩ = 0.</p><p><strong>Explanation:</strong> the inner product is a mathematical operation in Hilbert space that quantifies the <em>similarity</em> between states |φ⟩ and |ψ⟩. It is not a measure of physical overlap, like the angle between vectors in three-dimensional space, but defines the probability amplitude for quantum transitions. For example, for a qubit in state |ψ⟩ = (1/√2)(|0⟩ + |1⟩), the probability of measuring it in state |0⟩ is |⟨0|ψ⟩|^2 = |(1/√2)|^2 = 1/2.</p><p><strong>Orthogonality:</strong> if ⟨φ|ψ⟩ = 0, states |φ⟩ and |ψ⟩ are orthogonal, meaning they represent mutually exclusive measurement outcomes. For instance, spin states |↑⟩ and |↓⟩ are orthogonal (⟨↑|↓⟩ = 0), and measuring spin along the z-axis cannot yield both outcomes simultaneously. Orthogonality is a mathematical property, not physical independence as in classical systems.</p><p><strong>Physical meaning: </strong>the inner product is central to calculating probabilities in quantum mechanics and plays a key role in phenomena like interference and entanglement. Misinterpreting it as a <em>measure of physical similarity</em> can lead to confusion, as it describes probabilistic amplitudes, not classical correlations.</p><h4>5.4 Orthonormal basis</h4><p><strong>Formal definition:</strong> an orthonormal basis {|e_i⟩} in Hilbert space satisfies ⟨e_i|e_j⟩ = δ_{ij}, where δ_{ij} is the Kronecker delta (δ_{ij} = 1 if i = j, and 0 otherwise).</p><p><strong>Explanation:</strong> abasis in Hilbert space is a set of vectors {|e_i⟩} allowing any state |ψ⟩ to be expressed as a linear combination: |ψ⟩ = Σ_i c_i|e_i⟩. Orthonormality (⟨e_i|e_j⟩ = δ_{ij}) means the basis vectors are orthogonal and normalized (⟨e_i|e_i⟩ = 1). For example, for a spin-1/2 system, the basis {|↑⟩, |↓⟩} satisfies ⟨↑|↓⟩ = 0, ⟨↑|↑⟩ = 1.</p><p><strong>Physical meaning:</strong> an orthonormal basis simplifies the decomposition of quantum states and probability calculations. For instance, in the basis of eigenstates of the Hamiltonian H, H|e_i⟩ = E_i|e_i⟩, a state |ψ⟩ = Σ c_i|e_i⟩ allows calculating the average energy ⟨H⟩ = Σ |c_i|^2 E_i. Comparing a basis to <em>primary colors</em> can be misleading, as the basis is a mathematical tool, not a physical entity.</p><h4>5.5 Operators and observables</h4><p><strong>Formal definition: </strong>physical quantities in quantum mechanics are represented by Hermitian operators A, whose eigenvalues a_i correspond to possible measurement outcomes: A|a_i⟩ = a_i|a_i⟩.</p><p><strong>Explanation:</strong> operators in quantum mechanics, such as the Hamiltonian H, position operator x, or spin operator σ_z, act on state vectors, transforming them according to physical laws. Hermiticity (A = A†) ensures real eigenvalues, necessary for interpreting them as measurement outcomes. For example, for the hydrogen atom Hamiltonian, H|n⟩ = E_n|n⟩, where E_n = -13.6/n^2 eV are discrete energy levels.</p><p><strong>Measurements:</strong> when measuring an observable represented by operator A, the system collapses to one of its eigenstates |a_i⟩ with probability |⟨a_i|ψ⟩|^2. This has no classical analog, as measurement alters the system’s state, not merely revealing its properties. For example, measuring an electron’s spin along the z-axis yields ±ħ/2, not a <em>mean value</em> as in classical mechanics.</p><p><strong>Physical meaning:</strong> operators are not physical objects like classical measuring devices but mathematical constructs describing observables. Misrepresenting operators as <em>energy sources</em> or <em>forces</em> can lead to confusion, as their role is limited to the probabilistic description of quantum phenomena.</p><h4>5.6 Tensor product</h4><p><strong>Formal definition:</strong> for composite systems, the Hilbert space is constructed as the tensor product of subsystem spaces: H = H_1 ⊗ H_2.</p><p><strong>Explanation:</strong> the tensor product describes quantum states of systems comprising multiple subsystems, such as two qubits or an electron and a photon. If H_1 and H_2 have bases {|e_i⟩} and {|f_j⟩}, the basis of H consists of states |e_i⟩⊗|f_j⟩. For example, for two qubits, the space H = ℂ^2⊗ℂ^2 has the basis {|00⟩, |01⟩, |10⟩, |11⟩}, and the state |ψ⟩ = (1/√2)(|00⟩ + |11⟩) is a Bell entangled state.</p><p><strong>Entanglement:</strong> the tensor product enables the description of non-classical correlations, such as entanglement, where the system’s state cannot be factored: |ψ⟩ ≠ |ψ_1⟩⊗|ψ_2⟩. For instance, in a Bell state, measuring one subsystem instantly determines the other’s state, demonstrating quantum non-locality, unexplainable by classical correlations.</p><p><strong>Physical meaning: </strong>the tensor product is a mathematical tool, not a physical merging of systems. Misrepresenting it as <em>adding spaces</em> can be misleading, as it describes the exponential growth of state dimensionality, underpinning quantum technologies like quantum teleportation.</p><h4>5.7 Unitary evolution</h4><p><strong>Formal definition:</strong> the dynamics of a quantum system without measurements are described by a unitary operator U(t), such that |ψ(t)⟩ = U(t)|ψ(0)⟩, where U†U = I.</p><p><strong>Explanation:</strong> unitary evolution governs how a quantum state evolves over time according to the Schrödinger equation iħ d/dt |ψ(t)⟩ = H|ψ(t)⟩, where H is the Hamiltonian. The unitary operator U(t) = e^(-iHt/ħ) preserves normalization (⟨ψ(t)|ψ(t)⟩ = 1) and the probabilistic interpretation. For example, for a free particle, the Hamiltonian H = p^2/(2m) leads to the evolution of a wave packet that disperses over time.</p><p><strong>Physical meaning: </strong>unitary evolution describes the coherent development of quantum systems without interaction with the environment or measurements. It underpins predictions of system behavior, such as atoms or quantum computers. Comparing it to <em>rotating an arrow</em> can be misleading, as unitarity is a mathematical property ensuring probability conservation, not physical motion.</p><h3>Let’s recap once more:</h3><h4>🐈 State vector as an arrow in space</h4><ul><li><strong>Misconception:</strong> the state vector |ψ⟩ is mistakenly interpreted as a geometric vector in three-dimensional Euclidean space, possessing direction and length, akin to a physical arrow.</li><li><strong>Explanation:</strong> in Hilbert space, the state vector |ψ⟩ is an element of an infinite-dimensional complex vector space, normalized by the condition ⟨ψ|ψ⟩ = 1, and encodes probability amplitudes for all possible measurements. Its abstract nature does not allow direct visualization as a physical arrow, and any geometric analogies, such as the Bloch sphere for qubits, are simplified representations that do not capture the full structure of Hilbert space. Attempting to view |ψ⟩ as an arrow ignores the complexity and infinite dimensionality of the space, as well as the probabilistic interpretation tied to the inner product.</li><li>The vector |ψ⟩ is not localized in physical space and lacks classical attributes like trajectory or orientation; its components in a basis define quantum amplitudes, not coordinates. For example, for a particle in a potential, the wave function ψ(x) in the position basis only specifies a probabilistic distribution, not a physical position like an arrow. This misconception often arises from an intuitive desire to reduce quantum abstraction to classical mechanics, which is impossible in the context of Hilbert space.</li></ul><h4>🐈 Superposition as a classical mixture, e.g., &quot;part of the electron here, part there&quot;</h4><ul><li><strong>Misconception: </strong>the superposition |ψ⟩ = c₁|ψ₁⟩ + c₂|ψ₂⟩ in Hilbert space is mistakenly compared to a classical mixture, assuming the system is physically split between states |ψ₁⟩ and |ψ₂⟩ with definite proportions.</li><li><strong>Explanation:</strong> in Hilbert space, superposition represents a coherent linear combination of state vectors, where complex coefficients c₁ and c₂ determine probability amplitudes and phase relationships, leading to interference effects. This fundamentally differs from a classical mixture, described by a density matrix, as superposition preserves quantum coherence, absent in incoherent statistical ensembles. The misconception ignores the role of phases in Hilbert space, which enable interference, as seen in the double-slit experiment.</li><li>The coherence of superposition manifests in non-zero interference terms, such as 2Re(c₁*c₂⟨ψ₁|ψ₂⟩), which are absent in classical mixtures where probabilities simply add. For example, a qubit in state |ψ⟩ = (1/√2)(|0⟩ + |1⟩) exhibits interference when measured in an alternative basis, which is impossible for a classical probability distribution. This misconception often stems from attempting to interpret quantum uncertainty as a physical division of the system, ignoring the unique role of Hilbert space.</li></ul><h4>🐈 Inner product as a measure of physical similarity</h4><ul><li><strong>Misconception:</strong> the inner product ⟨φ|ψ⟩ in Hilbert space is mistakenly considered analogous to the dot product in Euclidean space, interpreted as a measure of geometric or physical similarity between states |φ⟩ and |ψ⟩.</li><li><strong>Explanation: </strong>in Hilbert space, ⟨φ|ψ⟩ is a complex amplitude determining the probability of the system transitioning from state |ψ⟩ to |φ⟩ upon measurement, with |⟨φ|ψ⟩|² as the outcome probability. It does not reflect physical similarity but serves as a tool for computing quantum probabilities and describing orthogonality (⟨φ|ψ⟩ = 0 for mutually exclusive states). The analogy with Euclidean space is misleading, as the complex nature and infinite dimensionality of Hilbert space preclude direct geometric interpretation.</li><li>The complex phase of ⟨φ|ψ⟩ affects interference effects, absent in the classical dot product, where the angle between vectors has a purely geometric meaning. For example, for orthogonal spin states |↑⟩ and |↓⟩ (⟨↑|↓⟩ = 0), the inner product indicates the impossibility of simultaneous measurement, not physical independence. The misconception arises from applying intuition from finite-dimensional real spaces to the abstract Hilbert space, ignoring its probabilistic role.</li></ul><h4>🐈 Orthonormal basis as primary colors</h4><ul><li><strong>Misconception:</strong> the orthonormal basis {|eᵢ⟩} in Hilbert space is compared to primary colors, suggesting that basis vectors represent fundamental physical components of the system, akin to red, blue, and green.</li><li><strong>Explanation:</strong> in Hilbert space, an orthonormal basis is an arbitrary set of vectors satisfying ⟨eᵢ|eⱼ⟩ = δᵢⱼ, used to decompose any state vector |ψ⟩ = Σ cᵢ|eᵢ⟩. The choice of basis is not tied to the system’s physical properties but is determined by descriptive convenience, such as the eigenstates of an observable, and lacks unique physical significance. Comparing it to colors is misleading, as the basis is a purely mathematical tool, not a reflection of real physical characteristics, as in the additive color model.</li><li>Different bases, e.g., eigenstates of operators σ_z and σ_x for a qubit, are equivalent in Hilbert space and related by unitary transformations, ruling out their uniqueness, unlike colors. The coefficients cᵢ in the decomposition |ψ⟩ determine measurement probabilities in the given basis, not physical proportions, as in color mixing. The misconception often stems from attempting to assign physical reality to basis vectors, ignoring their conditional role in the structure of Hilbert space.</li></ul><h4>🐈 Operators as sources of energy or forces</h4><ul><li><strong>Misconception: </strong>hermitian operators in Hilbert space, representing observables, are mistakenly interpreted as physical entities, like forces or energy sources, acting on the system.</li><li><strong>Explanation:</strong> in Hilbert space, Hermitian operators A, satisfying A = A†, define observable quantities, with eigenvalues aᵢ corresponding to possible measurement outcomes, and probabilities given by |⟨aᵢ|ψ⟩|². They are mathematical constructs transforming state vectors, not physical agents causing changes in the system. Viewing operators as forces ignores their role in the probabilistic interpretation of quantum mechanics and their abstract nature in the structure of Hilbert space.</li><li>For example, the Hamiltonian H determines time evolution via the Schrödinger equation but is not an energy source, only an operator whose eigenvalues correspond to the system’s energies. Operators like σ_z for spin do not cause physical interactions but define a measurement basis in Hilbert space. The misconception arises from applying classical mechanics concepts, where forces have a physical nature, to the quantum abstraction of operators.</li></ul><h4>🐈 Tensor product as adding spaces</h4><ul><li><strong>Misconception:</strong> the tensor product H = H₁ ⊗ H₂ of Hilbert spaces of subsystems is mistakenly interpreted as a simple union or summation of spaces, akin to combining physical regions.</li><li><strong>Explanation:</strong> in Hilbert space, the tensor product creates a new space with dimension dim(H₁) × dim(H₂), with a basis formed as {|eᵢ⟩⊗|fⱼ⟩}, enabling the description of composite system states. It is essential for representing non-classical correlations, such as entanglement, where the state |ψ⟩ cannot be factored as |ψ₁⟩⊗|ψ₂⟩. Comparing it to &quot;addition&quot; ignores the exponential growth in dimensionality and the unique role of the tensor structure in quantum mechanics.</li><li>Entangled states, such as |ψ⟩ = (1/√2)(|00⟩ + |11⟩), exhibit correlations unexplainable within separate H₁ and H₂, highlighting the non-classical nature of the tensor product. The dimension of H grows exponentially with the number of subsystems, underpinning the computational power of quantum systems, not a mere union. The misconception often stems from intuitively viewing space as a physical region, not an abstract mathematical structure.</li></ul><h4>🐈 Unitary evolution as rotating an arrow</h4><ul><li><strong>Misconception:</strong> the unitary evolution |ψ(t)⟩ = U(t)|ψ(0)⟩ in Hilbert space is mistakenly depicted as a physical rotation of the state vector, similar to an arrow moving in Euclidean space.</li><li><strong>Explanation: </strong>in Hilbert space, the unitary operator U(t), satisfying U†U = I, describes the time evolution of the state vector according to the Schrödinger equation, preserving normalization ⟨ψ(t)|ψ(t)⟩ = 1. This evolution is an abstract transformation in an infinite-dimensional complex space, not a geometric rotation, and governs the coherent development of probability amplitudes. The analogy with rotating an arrow is misleading, as it ignores the complex nature of U(t) and its role in preserving quantum information.</li><li>Unitary evolution, e.g., under the Hamiltonian H, describes continuous changes in phases and amplitudes in Hilbert space, as in qubit oscillations. Unlike rotation in real space, U(t) acts on all components of the state vector simultaneously, potentially involving an infinite number of basis states. The misconception arises from simplified visualizations, such as the rotation of a vector on the Bloch sphere, which applies only to two-level systems and does not generalize to the full Hilbert space.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnzqYlLEYsqn5fOcFZF7FA.jpeg" /></figure><h3>6. Problem formulation for portfolio optimization</h3><h4><strong>6.1 What is portfolio optimization?</strong></h4><p>Portfolio optimization is the task of selecting an optimal set of assets (e.g., stocks or bonds) for an investment portfolio to maximize returns while minimizing risk. In the classical formulation, known as the Markowitz model, the task reduces to optimizing an objective function that accounts for expected returns and risk, subject to certain constraints.</p><h4><strong>6.2 Mathematical formulation</strong></h4><p>Consider the portfolio optimization problem with N assets. Let x be a vector of binary variables, where x_i = 1 if asset i is included in the portfolio, and x_i = 0 if excluded. The objective function f(x) to be minimized is:<br> f(x) = q * x^T * W * x - μ^T * x,<br> where:</p><ul><li>x ∈ {0,1}^N — binary decision vector,</li><li>μ ∈ ℝ^N — vector of expected returns of assets,</li><li>W ∈ ℝ^(N×N) — covariance matrix describing correlations between assets,</li><li>q &gt; 0 — coefficient balancing risk and return,</li><li>^T denotes transposition.</li></ul><p><strong>Constraint:</strong> the sum of the elements of vector x equals K, i.e., Σ x_i = K, where K is the fixed number of assets in the portfolio. This constraint is called the Hamming weight constraint, as it fixes the number of ones in the binary vector x.</p><h4><strong>6.3 Why is it challenging?</strong></h4><p>Portfolio optimization belongs to the class of combinatorial optimization problems, which can be computationally complex, especially for a large number of assets N. Classical algorithms may be inefficient for finding the global optimum, particularly when the objective function has multiple local minima. Quantum algorithms, such as QAOA, offer a potential way to accelerate solving such problems.</p><p><strong>Hamiltonians in QAOA</strong><br>As mentioned earlier, a Hamiltonian in quantum mechanics is an operator describing the total energy of a system. In the context of QAOA, Hamiltonians are used to encode the optimization problem and control the evolution of the quantum state. QAOA employs two types of Hamiltonians:</p><ul><li>Phase Hamiltonian (H_P): encodes the optimization objective function.</li><li>Mixer Hamiltonian (H_M): facilitates mixing of quantum states to explore the solution space.</li></ul><p><strong>Phase Hamiltonian</strong><br>The phase Hamiltonian H_P encodes the objective function f(x). For portfolio optimization, it is constructed as a diagonal operator, where diagonal elements correspond to the values of f(x) for all possible binary vectors x.</p><p>Mathematically: H_P = diag(f(x)).</p><p>For implementation on a quantum computer, binary variables x_i are transformed into Pauli Z operators using the substitution x_i → (I - Z_i)/2, where I is the identity matrix, and Z_i is the Pauli Z operator for the i-th qubit. Then H_P takes the form:<br> H_P = (q/2) * Σ_{i,j} W_{ij} * Z_i * Z_j - (1/2) * Σ_i (q * Σ_j W_{ij} - μ_i) * Z_i + c,<br> where c is a constant that does not affect optimization.<br>Evolution under H_P is governed by the unitary operator exp(-i * γ * H_P), where γ is a classically optimized parameter.</p><p><strong>Mixer Hamiltonian</strong><br>The mixer Hamiltonian H_M is responsible for mixing the probability amplitudes of quantum states while preserving problem constraints, such as the fixed Hamming weight. In QAOA, mixers based on the XY Heisenberg model, describing interactions between qubits, are often used:<br> H_M = Σ_{(i,j)∈S} (X_i * X_j + Y_i * Y_j),<br> where:</p><ul><li>X_i, Y_i — Pauli X and Y operators for the i-th qubit,</li><li>S — set of index pairs (i,j) defining the interaction topology (e.g., a ring or complete graph).</li></ul><p>Evolution under H_M is governed by the operator exp(-i * β * H_M), where β is an optimized parameter.</p><h4><strong>Mixers and mixing</strong></h4><p><strong>What are mixers?</strong><br> Mixers in QAOA are unitary operators generated by the mixer Hamiltonian H_M, enabling transitions between different quantum states in the solution space. Their primary role is to uniformly &quot;mix&quot; probability amplitudes, allowing the algorithm to explore all possible solutions while respecting problem constraints.</p><p><strong>What types of mixers exist?</strong><br> In the context of portfolio optimization with a Hamming weight constraint, mixers that preserve this constraint are used. The most common types of mixers based on the XY model are:</p><h4><strong>Ring mixer (ring-XY):</strong></h4><p>Topology: qubits are connected in a ring, where each qubit interacts only with its neighbors.</p><p>Mathematically: S = {(i, i+1 mod N) | i = 1,2,...,N}.</p><p>Advantages: simple implementation, lower circuit depth.</p><p>Disadvantages: limited connectivity may slow exploration of the solution space.</p><h4><strong>Complete mixer (complete-XY):</strong></h4><p>Topology: each qubit interacts with all others.</p><p>Mathematically: S = {(i,j) | i &lt; j; i,j = 1,2,...,N}.</p><p>Advantages: high connectivity, more efficient exploration of the solution space.</p><p>Disadvantages: complex implementation, especially on current quantum devices.</p><h4><strong>Mixers with arbitrary connectivity:</strong></h4><ul><li>Topology: the set S is chosen according to specific hardware constraints or optimization needs.</li><li>Advantages: flexibility in adapting to hardware architectures.</li><li>Disadvantages: may require careful design to balance connectivity and implementability.</li><li>Topology: interactions between qubits are defined by an arbitrary graph, such as partitioning a complete graph into chains.</li><li>Example: for N=6 qubits, a complete graph can be split into three chains, each forming its own Hamiltonian H_M.</li><li>Application: allows balancing between implementation complexity and efficiency.</li></ul><h4>6.4 What is mixing?</h4><p>Mixing is the process of applying the operator exp(-i * β * H_M) to a quantum state to redistribute probability amplitudes among states corresponding to valid solutions. For portfolio optimization, the mixer ensures that states with Hamming weight K remain in the solution subspace with the same weight K. This is achieved due to the properties of the XY model, which preserves the sum of spins (or Hamming weight) in the quantum system.</p><h4>Initial states</h4><p>What is an initial state?<br>The initial state |ψ_0⟩ is the quantum state from which the QAOA algorithm begins. It must be valid with respect to the problem constraints, i.e., lie in the solution subspace satisfying, for example, the constraint Σ x_i = K. The choice of initial state significantly impacts the algorithm’s performance.</p><h4>Types of initial states</h4><p><strong>Dicke state:</strong></p><ul><li>A uniform superposition of all binary vectors with fixed Hamming weight K.</li><li>Example: for N=3 and K=2, the Dicke state is: |ψ_0⟩ = (1/√3)(|110⟩ + |101⟩ + |011⟩).</li><li>Advantages: easy to prepare on a quantum computer, neutral with respect to all valid solutions.</li><li>Disadvantages: may not be optimal for problems where prior solution information is useful.</li></ul><p><strong>Eigenstate of the mixer Hamiltonian:</strong></p><p>The initial state is chosen as the ground state (lowest energy state) of the mixer Hamiltonian H_M.</p><ul><li>Example: for a complete XY mixer, the ground state is the Dicke state; for a ring mixer, it depends on the ring topology.</li><li>Advantages: connection to adiabatic algorithms, potentially better convergence to the optimal solution.</li><li>Disadvantages: complex preparation, especially for sophisticated mixers.</li></ul><p><strong>“Warm start”:</strong></p><ul><li>The initial state is chosen based on prior classical information, e.g., an approximate solution to the problem.</li><li>Application: can improve performance but requires modifying the mixer for consistency.</li></ul><h4>6.5 Alignment between initial state and mixer</h4><p><strong>What is alignment?</strong><br>Alignment between the initial state and the mixer means that the initial state |ψ_0⟩ is the ground state of the mixer Hamiltonian H_M. This condition is borrowed from the adiabatic quantum algorithm (AQA), where the initial state must be the ground state of the initial Hamiltonian to ensure correct evolution toward the solution.</p><p>In QAOA, alignment improves performance, as consistency between |ψ_0⟩ and H_M allows the algorithm to more efficiently explore the solution space. Without alignment (e.g., if |ψ_0⟩ is not the ground state of H_M), performance may degrade, especially at low circuit depth (p).</p><h4><strong>Why is alignment important?</strong></h4><h4><strong>Connection to the adiabatic algorithm:</strong></h4><ul><li>QAOA can be viewed as a discretization of the adiabatic algorithm. In AQA, the initial state must be the ground state of the initial Hamiltonian to remain in the ground state during evolution. Similarly, in QAOA, alignment enhances convergence to the optimal solution.</li></ul><h4><strong>Efficiency in exploring the solution space:</strong></h4><ul><li>When |ψ_0⟩ is the ground state of H_M, the mixer effectively distributes amplitudes among states corresponding to valid solutions, accelerating the search for the optimum.</li></ul><h4><strong>Robustness to errors:</strong></h4><ul><li>Alignment is particularly important for complex mixers (e.g., complete-XY), where misalignment can lead to significant performance losses.</li></ul><h4><strong>How to achieve alignment?</strong></h4><p>Choosing an appropriate initial state:</p><ul><li>For each mixer H_M, compute its ground state (e.g., via numerical diagonalization) and use it as |ψ_0⟩.</li><li>For a complete XY mixer, the ground state is the Dicke state, which can be prepared using known algorithms.</li></ul><h4>Accurate mixer implementation:</h4><ul><li>Ensure that the mixer exp(-i * β * H_M) is implemented precisely. For complex mixers (e.g., complete-XY), this may require a large number of quantum gates, increasing circuit depth.</li></ul><h4>Trotterization for approximate implementation:</h4><ul><li>If exact implementation of H_M is not feasible (e.g., due to hardware limitations), use Trotterization — a method that decomposes the operator’s exponential into a sequence of simpler operations. For example:</li><li>For a ring mixer: decomposition into even and odd qubit pairs.</li><li>For complex mixers: two-level Trotterization (across chains and within chains).</li><li>Increasing the number of Trotterization steps (T) improves accuracy, bringing the effective ground state closer to the true ground state of H_M.</li></ul><h4>Accounting for hardware noise:</h4><ul><li>On current quantum devices (NISQ), noise can reduce the effect of alignment. To minimize noise:</li><li>Use simple mixers (e.g., ring-XY), which require lower circuit depth.</li><li>Apply error mitigation techniques, such as symmetry verification or post-selection of valid solutions.</li></ul><h4>Practical limitations</h4><ul><li>Complexity of initial state preparation: the ground state of a complex mixer (e.g., complete-XY) can be difficult to prepare on NISQ devices. In such cases, the Dicke state is often used as a compromise.</li><li>Trotterization and circuit depth: increasing the number of Trotterization steps improves alignment but increases circuit depth, which may lead to error accumulation on NISQ devices.</li><li>Balance between alignment and noise: studies show that for simple mixers (e.g., ring-XY), QAOA performance is robust to small Trotterization errors, while complex mixers require more precise implementation.</li></ul><h4>6.6 Practical application and results</h4><p><strong>Experiments on a quantum processor</strong><br>To demonstrate the effect of alignment, researchers applied QAOA with a ring-XY mixer on the Quantinuum H2-1 quantum processor with 32 qubits. The initial state was chosen as the Dicke state, and the mixer was implemented using Trotterization (T=1 and T=2). Key findings:</p><ul><li>In noise-free simulations, increasing the number of Trotterization steps (T=2) improved solution quality due to better alignment.</li><li>On real hardware, the effect of alignment was less pronounced due to noise, and the T=1 circuit performed better because of its lower depth.</li></ul><h4>6.7 Quality metric: approximation ratio (AR)</h4><p>Solution quality was evaluated using the Approximation Ratio (AR), defined as:<br> AR(x) = (f(x) - f_max)/(f_min - f_max), if Σ x_i = K, AR(x) = 0, if Σ x_i ≠ K,<br> where f_min and f_max are the minimum and maximum values of the objective function f(x) among all valid portfolios. An AR close to 1 indicates high solution quality.</p><h4>6.8 Research findings</h4><p><strong>Effect of alignment:</strong></p><ul><li>Alignment between |ψ_0⟩ and H_M improves AR for all studied mixers (ring-XY, complete-XY, arbitrary).</li><li>The effect persists at both low (p=1,2,3) and high (p=100) QAOA depths.</li></ul><p><strong>Impact of Trotterization:</strong></p><ul><li>For complex mixers (complete-XY), increasing the number of Trotterization steps significantly improves performance.</li><li>For simple mixers (ring-XY), performance is robust to Trotterization errors, and T=1 or T=2 is often sufficient.</li></ul><h4>6.9 NISQ device limitations:</h4><ul><li>On noisy devices, increasing circuit depth (e.g., via larger T) can degrade results due to error accumulation.</li><li>Simple mixers are preferable for NISQ devices, as they minimize circuit depth.</li></ul><h4>6.10 Key takeaways</h4><ul><li>Portfolio optimization is a combinatorial problem that can be effectively addressed with QAOA, using Hamiltonians to encode the objective function and constraints.</li><li>Mixers (ring-XY, complete-XY, arbitrary) play a critical role in exploring the solution space while preserving constraints, such as the Hamming weight.</li><li>The initial state should be aligned with the mixer Hamiltonian to achieve optimal performance (alignment).</li><li>Alignment between the initial state and mixer improves solution quality, but on NISQ devices, the effect may be limited due to noise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3HZoJLX0TgOO_UvJqPJqQ.jpeg" /></figure><h3>7. Optimization of γ and β via FFT and MVN for Portfolio Optimization</h3><h4>7.1 Role of γ and β in Portfolio Optimization</h4><p>In portfolio optimization, which involves selecting the optimal allocation of assets to maximize returns while minimizing risk, quantum algorithms like QAOA use parameters γ and β to control the evolution of a quantum system in Hilbert space — an infinite-dimensional vector space where quantum states are represented by vectors, and their transformations are described by unitary operators that preserve probabilities.</p><p>These parameters determine how the quantum system, starting from an initial state, typically a uniform superposition of all possible portfolio configurations (e.g., which assets to include), evolves toward a state corresponding to an optimal portfolio, where assets are balanced by return and risk. Parameter γ controls the phase operator, which adjusts the phases of quantum states based on the portfolio optimization objective function, such as maximizing expected returns minus a risk penalty expressed through the covariance matrix of assets, while β controls the mixing operator, which facilitates quantum transitions between different portfolio configurations, maintaining solution diversity and enabling exploration of the entire portfolio space.</p><p>The impact of γ and β lies in defining the trajectory of the quantum state’s evolution, where the correct choice of γ amplifies the probability of states corresponding to portfolios with high returns and low risk, and β prevents getting stuck in suboptimal solutions, such as portfolios overly concentrated in one asset. The initial state, often a uniform superposition, is defined as |s⟩ = 1/√(2ⁿ) ∑ₓ |x⟩, where n is the number of assets, and |x⟩ represents possible portfolio configurations. Its alignment with the mixer, determined by β, ensures that the mixing operator e⁻ⁱᵝᴴᴹ, where Hₘ is the mixing Hamiltonian, typically ∑ᵢ Xᵢ (Pauli X operators on each qubit), effectively shuffles amplitudes while preserving task constraints, such as a fixed budget (the sum of asset weights equals a constant). Improving initial states and mixers involves tuning γ and β, which is achieved through integration with multi-valued neural networks (MLMVN), where γ and β are processed as complex inputs and analyzed using Fast Fourier Transform (FFT) to optimize the quantum state for portfolio optimization.</p><h4>7.2 Input of γ and β into qo-MLMVN</h4><p>In a multi-valued neural network (qo-MLMVN), which consists of layers of multi-valued neurons (MVN), where each neuron processes complex inputs and produces complex outputs lying on the unit circle (the set of complex numbers with modulus 1, described as {z ∈ ℂ : |z| = 1}), parameters γ and β from QAOA for portfolio optimization are input as complex numbers representing angles that control quantum operators, which are then processed by the network to optimize the quantum state.</p><p>These parameters, initially defined as real numbers in the range [0, 2π], are represented as complex numbers with type tf.complex64 in the network, but they are not directly encoded as phases of complex numbers (eⁱγ, eⁱβ). Instead, γ and β are treated as complex inputs that encode angle information associated with the portfolio optimization objective function (e.g., ∑ᵢⱼ wᵢ wⱼ σᵢⱼ − ∑ᵢ wᵢ μᵢ, where wᵢ are asset weights, σᵢⱼ is the covariance, and μᵢ is the expected return) and transitions between portfolio configurations, respectively. In qo-MLMVN, γ and β are provided as a tensor of complex numbers with shape [batch_size, num_angles], where batch_size is the number of parallel optimizations (e.g., 32 sets of parameters for different initial conditions), and num_angles is the total number of parameters (e.g., 2p for QAOA with p layers, where p is the algorithm’s depth).</p><p>The goal of qo-MLMVN is to process γ and β to optimize the quantum state, improving the initial state and mixer. This is achieved by tuning the neurons’ weights, which are also complex and lie on the unit circle, and, in the case of FreqMLMVN, through frequency analysis using FFT, which decomposes the parameters into frequency coefficients that indirectly influence the network’s dynamics. In portfolio optimization, MLMVN uses γ and β to control superposition (uniform probability distribution across all possible portfolios) and entanglement (quantum correlations between assets that can enhance solution quality), ensuring precise alignment of the quantum state with the optimal portfolio configuration.</p><h4>7.3 γ and β on the Unit Circle in MLMVN</h4><p><strong>Input of γ and β and Their Representation</strong></p><p>In qo-MLMVN, γ and β are input as complex numbers in a tensor [batch_size, num_angles], where each element is a complex number with real and imaginary parts, but not necessarily of the form eⁱθ (where θ is γ or β). These inputs represent angles that control quantum operators in QAOA: γ influences the phase operator e⁻ⁱᵞᴴᴾ, where Hₚ is the portfolio optimization Hamiltonian encoding return and risk, and β influences the mixing operator e⁻ⁱᵝᴴᴹ, enabling transitions between portfolios. The purpose of this representation is to allow qo-MLMVN to process γ and β as part of the complex input data that the network transforms to optimize the quantum state, amplifying the probabilities of portfolios with high returns and low risk.</p><p><strong>Weighted Sum and Phase Transformations</strong></p><p>Each multi-valued neuron (MVN) in MLMVN performs a weighted sum of input complex numbers, where inputs x₁, x₂, ..., xₙ (including a unit bias) are multiplied by complex weights w₀, w₁, ..., wₙ, also lying on the unit circle (|wᵢ| = 1), and summed: z = w₀ x₀ + w₁ x₁ + ... + wₙ xₙ, where x₀ = 1 is the bias. The result z is a complex number that generally does not lie on the unit circle, as its modulus |z| may be greater or less than 1, but its phase arg(z) encodes a combination of the input parameters and weights.</p><p>This weighted sum in Hilbert space is equivalent to a linear transformation of the state vector, where weights wᵢ define rotations, and inputs xᵢ are complex representations of γ and β or their frequency coefficients (in FreqMLMVN). The goal of this operation is to transform the input data so that the resulting phase arg(z) brings the quantum state closer to the optimal one, amplifying the amplitudes of states corresponding to portfolios with low risk and high returns. For example, if input γ is associated with high-return portfolios, the neuron’s weights are adjusted to reinforce the phase arg(z), aligning z with the target sector on the unit circle.</p><p><strong>Activation Function and Projection onto the Unit Circle</strong></p><p>After computing the weighted sum z, the neuron applies an activation function that projects z onto the unit circle, returning a complex number with modulus 1: y = z / |z|, if continuous activation is used (k = 0), or y = eⁱᵟ, where φ is a quantized phase, if discrete activation is used (k &gt; 0). For continuous activation, the result y = eⁱᵃʳᵍ⁽ᶻ⁾ preserves the phase arg(z) but normalizes the modulus, which in Hilbert space corresponds to projecting the state vector onto the unit sphere, ensuring probability preservation. For discrete activation, the phase arg(z) is quantized into one of k sectors of the unit circle, where each sector has a width of 2π / k, and the output is y = eⁱ⁽²ᵖⁱʲ/ᵏ⁾, where j is the nearest sector number, determined as j = ⌊arg(z) k / (2π) + 0.5⌋.</p><p>This phase quantization is equivalent to partitioning Hilbert space into discrete subsectors, where each state is classified by its phase, which is useful for portfolio optimization as it allows grouping portfolios with similar characteristics (e.g., high-risk or low-return portfolios). In the case of periodic activation (MVN-P), the output is y = eⁱᵏᵃʳᵍ⁽ᶻ⁾, amplifying the phase by k times, creating more complex rotations on the unit circle that can model nonlinear dependencies in the quantum state, enhancing correlations between assets. The activation function’s goal is to transform the processed inputs (γ, β, or their frequency coefficients) so that the neuron’s output corresponds to an optimal quantum state, amplifying the probabilities of the best portfolios.</p><p><strong>Training and Error Correction</strong></p><p>Training qo-MLMVN involves tuning the complex weights of neurons to minimize the error between the desired output (e.g., a complex number eⁱᵟᵈ representing the phase of the optimal portfolio) and the actual output y = eⁱᵟᵃ.</p><p>The error is computed as δ = eⁱᵟᵈ − eⁱᵟᵃ, which on the unit circle corresponds to the vector difference between two points, where the error modulus |δ| is related to the angular distance |φᵈ − φᵃ|. In Hilbert space, this error represents the difference between the target quantum state and the current one, and its minimization is equivalent to rotating the state vector toward the target direction. Error correction uses the error correction method or the least squares method (LLS), where weights are updated according to the rule wᵢ = wᵢ + η δ conj(xᵢ), where η is the learning rate, conj(xᵢ) is the complex conjugate of the input, and δ is the error.</p><p>This update rotates the weights on the unit circle, adjusting their phases so that the weighted sum z approaches the desired phase. In portfolio optimization, training ensures that the neurons’ output phases correspond to portfolios with maximum returns and minimum risk, and γ and β (or their frequency coefficients) are adjusted through weights to enhance superposition and entanglement.</p><p><strong>Soft Margins and Adaptive Tuning</strong></p><p>To improve training accuracy, qo-MLMVN uses a soft margin mechanism that guides the phases of weighted sums arg(z) toward the bisectors of target sectors on the unit circle, where the bisector of sector j is the angle (2j + 1) π / k, representing the sector’s midpoint. If the phase arg(z) deviates from the bisector by more than a threshold (e.g., 0.1 radians) or if the output sector is incorrect, the error is corrected to bring arg(z) closer to the bisector, equivalent to minimizing the angular distance in Hilbert space.</p><p>The adaptive threshold accounts for quantum metrics like superposition (probability uniformity) and entanglement (von Neumann entropy), reducing the threshold when these metrics are low to enhance accuracy. In portfolio optimization, soft margins help align the processed inputs (γ, β, or their frequency coefficients) with optimal portfolio configurations, ensuring that the quantum state amplifies the probabilities of the best portfolios, while the mixer, influenced by β, maintains solution diversity.</p><p><strong>Regularization of Superposition and Entanglement</strong></p><p>MLMVN applies regularization to maximize superposition and entanglement, which is critical for portfolio optimization, where superposition ensures uniform exploration of all possible portfolios, and entanglement enhances correlations between assets, improving solution quality. Superposition is measured as probabilities pᵢ = |ψᵢ|², where ψᵢ are the components of the quantum state, and regularization minimizes the deviation |pᵢ − 1/2ⁿ|, where 1/2ⁿ is the target uniformity for n qubits. Entanglement is measured via von Neumann entropy S = −Tr(ρ ln(ρ)), where ρ is the state’s density matrix, and regularization minimizes |S − ln(2)|, where ln(2) is the target entropy.</p><p>These metrics influence weight updates to ensure that the processed inputs enhance quantum properties, moving points on the unit circle toward optimal phases. In Hilbert space, this corresponds to rotating the state vector toward a direction where superposition and entanglement are maximized, improving the initial state and mixer for finding the optimal portfolio.</p><p><strong>Products and Results</strong></p><p>The product of processing γ and β in MLMVN is an optimized quantum state, represented as a vector in Hilbert space, where the amplitudes of states corresponding to optimal portfolios are amplified. The input is a tensor of complex numbers [batch_size, num_angles], representing γ and β as complex angles.</p><p>The output is a tensor of complex numbers [batch_size, n_outputs], where each element is a point on the unit circle encoding a phase associated with the optimal portfolio, along with metrics such as energy (objective function value), superposition, and entanglement. These results are used to construct a QAOA quantum circuit, where γ and β define operators that drive evolution toward the optimal state, improving the initial state and mixer for portfolio optimization.</p><h4>7.4 γ and β with FFT in qo-MLMVN</h4><p><strong>Frequency Analysis of γ and β</strong></p><p>In FreqMLMVN, γ and β undergo frequency analysis using Fast Fourier Transform (FFT), which decomposes the sequence of parameters, represented as complex numbers, into frequency coefficients. FFT transforms the parameter tensor [batch_size, num_angles] into a tensor of frequency coefficients [batch_size, freq_size], where freq_size is the number of selected frequencies, determined by the frequency range (e.g., from min_freq to max_freq). In Hilbert space, this is equivalent to decomposing the state vector into a basis, where each frequency component represents a projection of the state onto a specific subspace associated with the frequency.</p><p>The goal of frequency analysis is to identify key harmonics that determine how γ and β influence the quantum state’s evolution, e.g., low frequencies may correspond to global changes in portfolio configuration, while high frequencies relate to local adjustments tied to fine-tuning asset weights. In portfolio optimization, FFT helps identify which γ amplify low-risk portfolios and which β ensure effective mixing, maintaining solution diversity.</p><p><strong>Adaptive Frequency Range Selection</strong></p><p>FreqMLMVN uses adaptive frequency range selection by analyzing the amplitudes of FFT coefficients to select frequencies with the greatest contribution, achieved by sorting amplitudes |cₖ|, where cₖ are FFT coefficients, and selecting the top 20% of frequencies by amplitude, forming the range [min_freq, max_freq].</p><p>This process in Hilbert space corresponds to selecting subspaces most significant for describing the quantum state’s dynamics, excluding noisy components with low amplitudes. In portfolio optimization, the adaptive range focuses on frequencies tied to key task aspects, such as maximizing returns (low frequencies for γ) or ensuring portfolio diversity (high frequencies for β), improving the initial state and mixer.</p><p><strong>Frequency Pooling</strong></p><p>After computing FFT, the parameters undergo frequency pooling, where coefficients in the range [min_freq, max_freq] are selected, forming a tensor [batch_size, freq_size], where freq_size = max_freq − min_freq + 1. To enhance robustness, wavelet-like compression is applied, where adjacent frequency coefficients are averaged using a convolutional kernel (e.g., [1/3, 1/3, 1/3]), smoothing noise and reinforcing key harmonics. In Hilbert space, this corresponds to filtering the state vector, retaining only significant projections onto frequency subspaces, improving the quantum state’s representation.</p><p>If freq_size does not match the expected input layer size of FreqMLMVN, the tensor is either truncated or padded with zeros, equivalent to projecting onto a subspace of the required dimensionality. In portfolio optimization, pooling highlights frequencies associated with optimal portfolio configurations, amplifying γ linked to low risk and β ensuring diversity.</p><p><strong>Reconstruction of γ and β via Inverse FFT</strong></p><p>Frequency coefficients can be used to reconstruct γ and β using inverse FFT (IFFT), which transforms the tensor [batch_size, freq_size] back into a tensor [batch_size, num_angles], recovering γ and β with emphasis on selected frequencies. If freq_size &lt; num_angles, the tensor is padded with zeros, equivalent to ignoring high-frequency components, and the result is normalized to lie on the unit circle: ψ = ψ / |ψ|, where ψ are the reconstructed parameters.</p><p>In Hilbert space, this corresponds to recovering the state vector from its projections onto selected frequency subspaces, preserving only key components. In portfolio optimization, reconstruction adjusts γ and β to better match the optimal portfolio, amplifying low-frequency components for stability and high-frequency components for fine-tuning.</p><p><strong>Integration with Neurons and Activation</strong></p><p>Frequency coefficients obtained after pooling are fed into the first layer of FreqMLMVN, where each neuron performs a weighted sum, as described earlier, but now the inputs are cₖ = aₖ eⁱᵟₖ, where aₖ is the amplitude, and φₖ is the phase of the frequency component. The weighted sum z = ∑ wᵢ cᵢ combines frequency phases, and the activation function projects z onto the unit circle, yielding y = eⁱᵃʳᵍ⁽ᶻ⁾ (for k = 0) or a quantized phase (for k &gt; 0).</p><p>This transformation in Hilbert space is equivalent to rotating the state vector, where frequency phases determine the rotation direction, and neuron weights adjust amplitudes. In portfolio optimization, frequency coefficients amplify γ associated with high-return portfolios and β ensuring effective mixing, improving the initial state and mixer.</p><p><strong>Training with Frequency Regularization</strong></p><p>Training FreqMLMVN with frequency coefficients involves regularization, where frequency phases φₖ are adjusted to minimize error and maximize superposition and entanglement. The error is computed as the difference between desired and actual phases on the unit circle, and frequency coefficients influence weight updates to reinforce key harmonics. For example, low-frequency γ components may be amplified to stabilize portfolio configurations, while high-frequency β components are used for fine-tuning.</p><p>In Hilbert space, this corresponds to optimizing the state vector in the frequency basis, where gradients with respect to φₖ guide rotations toward the target state. In portfolio optimization, frequency regularization improves the initial state, enhancing superposition, and the mixer, maximizing entanglement, leading to more accurate portfolios.</p><p><strong>Products and Results</strong></p><p>The product of processing γ and β with FFT in FreqMLMVN is an optimized quantum state, where γ and β are adjusted through frequency analysis, amplifying low-frequency components for stability and high-frequency components for diversity. The input is a parameter tensor [batch_size, num_angles], and the output is a tensor of outputs [batch_size, n_outputs], representing the phases of the optimal portfolio, and frequency coefficients [batch_size, freq_size], which can be recovered into γ and β via IFFT.</p><p>Metrics include energy (portfolio objective function), superposition, and entanglement, used to construct a QAOA quantum circuit with an improved initial state and mixer, ensuring optimal asset allocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dknmoZkfJN1u9bDB-tE2kA.jpeg" /></figure><h3>Announcement of the next lesson</h3><h4>Optimization of angles in QAOA for solving QUBO using the qo-MLMVN framework</h4><blockquote>In the next lesson, using code examples from the qo-MLMVN framework, we will continue analyzing the solution to the problem Improving initial states and mixers, as well as aligning the initial state with the mixer for portfolio optimization. Below is a brief overview of the topics to be covered in the next lesson.</blockquote><h4>Section 1: The role of angles in QAOA</h4><p>The Quantum Approximate Optimization Algorithm (QAOA) solves the Quadratic Unconstrained Binary Optimization (QUBO) problem in the Hilbert space H = (C^2)^⊗n, where n is the number of qubits representing binary variables (e.g., asset selection). QAOA constructs a parameterized quantum state |ψ(γ, β)&gt; ∈ H, dependent on angles γ = (γ_1, ..., γ_P) and β = (β_1, ..., β_P), where P is the number of layers. The goal is to minimize the energy E = &lt;ψ(γ, β)|H_C|ψ(γ, β)&gt;, where H_C is the cost Hamiltonian encoding the QUBO as H_C = Σ_i Q_ii Z_i + Σ_{i&lt;j} Q_ij Z_i Z_j, and Q is the QUBO matrix. The energy E reflects the quality of the solution: a lower value corresponds to an optimal combination of variables.</p><p>The angles γ control the unitary operator U_C(γ_p) = exp(-i γ_p H_C), which rotates the state in H, enhancing basis states |z&gt; (z ∈ {0,1}^n) corresponding to low values of &lt;z|H_C|z&gt;. The angles β control the mixer U_M(β_p) = exp(-i β_p H_M), where H_M = Σ_i X_i is the Hamiltonian facilitating transitions between states |z&gt;. The state is formed as |ψ(γ, β)&gt; = Π_{p=1}^P U_M(β_p) U_C(γ_p) |+&gt;^n, where |+&gt;^n = (1/√2^n) Σ_z |z&gt; is the initial superposition. For P layers, 2P angles need to be optimized using gradient descent on E = Σ_k c_k &lt;ψ(γ, β)|P_k|ψ(γ, β)&gt;, where P_k are Pauli operators (Z_i, Z_i Z_j), and c_k are QUBO coefficients.</p><p>Explanation in terms of Hilbert space: H_C acts diagonally in the basis {|z&gt;}, setting phases exp(-i γ_p &lt;z|H_C|z&gt;) that increase the amplitudes of low-energy states. H_M, containing X_i operators, is non-diagonal and induces transitions |z&gt; ↔ |z ⊕ e_i&gt;, where e_i is a vector with 1 in the i-th position. The angles γ and β define the trajectory of |ψ(γ, β)&gt; in H, balancing localization in optimal |z&gt; and exploration of the state space.</p><p>Example calculation: For n=2, P=1, H_C = Z_0 + 0.5 Z_0 Z_1, the energy E = &lt;ψ|Z_0|ψ&gt; + 0.5 &lt;ψ|Z_0 Z_1|ψ&gt;. The state |ψ&gt; = exp(-i β_1 (X_0 + X_1)) exp(-i γ_1 (Z_0 + 0.5 Z_0 Z_1)) |+&gt;^2 ∈ C^4. Optimization requires finding γ_1, β_1 ∈ [0, 2π].</p><h4>Section 2: Angle optimization using methods and functions</h4><p><strong>2.1. Method </strong><strong>compute_adaptive_threshold</strong><br>Function: computes the threshold θ_a, limiting permissible phase deviations set by angles γ and β, to enhance the amplitudes of optimal states |z&gt;. The threshold depends on the superposition measure Δ_s = mean_i |p_i - 1/2^n| and entanglement Δ_e = |S - ln(2)|, where p_i = |&lt;i|ψ&gt;|^2 are probabilities of basis states, S = -Σ_i λ_i log(λ_i) is the von Neumann entropy, and λ_i are eigenvalues of the reduced density matrix of one qubit. Formula: θ_a = θ_b * (1 + 0.5 Δ_s + 0.5 Δ_e), where θ_b is the base threshold (e.g., 0.1 radians).</p><p>Impact on angles: limits phase rotations exp(-i γ_p H_C) and exp(-i β_p H_M) to keep |ψ&gt; near low-energy states.</p><p>Explanation in terms of H: probabilities p_i reflect the projection of |ψ&gt; onto the basis {|i&gt;}. Ideal superposition gives p_i = 1/2^n, and Δ_s measures deviation of |ψ&gt; from uniform distribution in H. Entropy S characterizes quantum correlations: S ≈ ln(2) for maximal entanglement of one qubit with others. The threshold θ_a adjusts angles to enhance projections &lt;i|ψ&gt; and correlations λ_i for optimal |z&gt;.</p><p>Calculation: for n=4, ideal p_i = 1/2^4 = 0.0625. If p_i = {0.07, 0.06, ...}, then Δ_s ≈ 0.01; if S = 0.65, then Δ_e = |0.65 - ln(2)| ≈ 0.043. Thus, θ_a = 0.1 * (1 + 0.5 * 0.01 + 0.5 * 0.043) ≈ 0.103 radians. Angles γ_p, β_p are adjusted if their phases deviate by more than θ_a.</p><p>Application: angles γ enhance amplitudes of |z&gt; with low &lt;z|H_C|z&gt;, β maintain uniformity of &lt;i|ψ&gt;^2.</p><p><strong>2.2. Method </strong><strong>apply </strong><br>Function: adjusts angles γ and β by comparing the phase φ_z = arg(&lt;ψ|Π_p exp(-i γ_p H_C) exp(-i β_p H_M)|ψ&gt;) with the target phase φ_b = (2k + 1) π / k in sector k. Error δ = ε - z/|z|, where ε = exp(i φ_b), z = Σ_i &lt;ψ|P_i|ψ&gt;, P_i are Pauli operators. If |φ_z - φ_b| &gt; θ_a, angles are updated: γ_p ← γ_p - η ∂δ/∂γ_p, β_p ← β_p - η ∂δ/∂β_p, where η = 0.01 is the gradient step.</p><p>Impact on angles: shifts γ and β to project |ψ&gt; onto the low-energy subspace of H.</p><p>Explanation in terms of H: phase φ_z determines the rotation angle of |ψ&gt; in H relative to operators U_C, U_M. Sector k is the region of angle values where &lt;ψ|H_C|ψ&gt; is minimal. The apply method projects the trajectory of |ψ&gt; onto the subspace where amplitudes of optimal |z&gt; are maximal, minimizing δ in H.</p><p>Calculation: for k=1, φ_b = 3π/4 ≈ 2.356 radians. If φ_z = 2.8, θ_a = 0.103, then |2.8 - 2.356| ≈ 0.444 &gt; 0.103, so angles are adjusted. For example, ∂δ/∂γ_p ≈ &lt;ψ|[H_C, P_i]|ψ&gt;, γ_p decreases by η * &lt;ψ|[H_C, P_i]|ψ&gt;.</p><p>Application: angles γ enhance &lt;z|H_C|z&gt; for optimal |z&gt;, β support transitions between |z&gt;.</p><p><strong>2.3. Method </strong><strong>compute_angular_rmse </strong><br>Function: computes the root mean square error RMSE = sqrt(mean((φ_b - φ_z)^2) * (1 + Δ_s)), measuring the deviation of phase φ_z from target φ_b, considering superposition Δ_s.</p><p>Impact on angles: guides γ and β toward values minimizing RMSE, reducing &lt;ψ|H_C|ψ&gt;.</p><p>Explanation in terms of H: RMSE quantifies the distance between the current |ψ&gt; and the target state in H, where φ_b sets optimal phase rotations. The factor (1 + Δ_s) amplifies the error if |ψ&gt; deviates from uniform superposition, adjusting projections &lt;i|ψ&gt;.</p><p>Calculation: if φ_b = π/2, φ_z = π/2 + 0.05, Δ_s = 0.01, then RMSE = sqrt((0.05)^2 * 1.01) ≈ 0.0503. Angles γ_p, β_p are updated to reduce RMSE.</p><p>Application: angles γ minimize &lt;ψ|H_C|ψ&gt;, β align &lt;i|ψ&gt;^2.</p><p><strong>2.4. Method </strong><strong>is_converged</strong><br>Function: checks convergence: RMSE ≤ θ_a, Δ_s &lt; 0.1, Δ_e &lt; 0.1. If satisfied, angle optimization stops.</p><p>Impact on angles: fixes γ and β if |ψ&gt; is sufficiently close to the optimal subspace.</p><p>Explanation in terms of H: convergence means |ψ&gt; is near an eigenvector of H_C with minimal eigenvalue. Conditions Δ_s, Δ_e ensure |ψ&gt; maintains uniform superposition and correct correlations in H.</p><p>Calculation: if RMSE = 0.05, θ_a = 0.103, Δ_s = 0.08, Δ_e = 0.07, the process stops as |ψ&gt; is near optimal.</p><p>Application: confirms that γ and β form |ψ&gt; with minimal &lt;ψ|H_C|ψ&gt;.</p><p><strong>2.5. Method </strong><strong>optimize_qaoa</strong><br>Function: minimizes the loss L = &lt;ψ|H_C|ψ&gt; + 0.1 L_s + 0.1 L_e, where L_s = mean_i |p_i - 1/2^n|, L_e = |S - ln(2)|. Angles are updated: γ_p ← γ_p - η ∂L/∂γ_p, β_p ← β_p - η ∂L/∂β_p, η = 0.1.</p><p>Impact on angles: optimizes γ and β to minimize &lt;ψ|H_C|ψ&gt; with balanced p_i and S.</p><p>Explanation in terms of H: loss L is a functional on H, combining energy and penalties for deviations from ideal superposition (L_s) and entanglement (L_e). Gradients ∂L/∂γ_p ≈ &lt;ψ|[H_C, H_C]|ψ&gt;, ∂L/∂β_p ≈ &lt;ψ|[H_M, H_C]|ψ&gt; define the descent direction in parameter space, aligning |ψ&gt; with the optimal subspace.</p><p>Calculation: if &lt;ψ|H_C|ψ&gt; = 1.5, L_s = 0.1, L_e = 0.043, then L = 1.5 + 0.1 * 0.1 + 0.1 * 0.043 ≈ 1.5143. Angles are adjusted to reduce L.</p><p>Application: angles γ focus |ψ&gt; on low-energy |z&gt;, β maintain uniformity of &lt;i|ψ&gt;.</p><p><strong>2.6. Method </strong><strong>optimize_qubo</strong><br>Function: transforms the QUBO matrix into H_C = Σ_i Q_ii Z_i + Σ_{i&lt;j} Q_ij Z_i Z_j and runs optimize_qaoa with initial γ_p, β_p ∈ [0, 2π].</p><p>Impact on angles: initializes γ and β, tailoring them to the structure of H_C in H.</p><p>Explanation in terms of H: H_C sets a diagonal form in the basis {|z&gt;}, where &lt;z|H_C|z&gt; = Σ_i Q_ii z_i + Σ_{i&lt;j} Q_ij z_i z_j. The method ensures U_C(γ_p) enhances amplitudes of |z&gt; with minimal &lt;z|H_C|z&gt;, while U_M(β_p) supports transitions in H.</p><p>Calculation: for Q = [[1, 0.5], [0.5, 2]], H_C = Z_0 + 2 Z_1 + 0.5 Z_0 Z_1. Initial γ_1, β_1 are chosen randomly, then optimized.</p><p>Application: angles γ minimize &lt;z|H_C|z&gt;, β ensure exploration of H.</p><p><strong>2.7. Method </strong><strong>compute_superposition</strong></p><p>Function: computes p_i = |&lt;i|ψ&gt;|^2 and L_s = mean_i |p_i - 1/2^n|.</p><p>Impact on angles: adjusts β to minimize L_s, aligning projections &lt;i|ψ&gt;.</p><p>Explanation in terms of H: L_s measures deviation of |ψ&gt; from uniform superposition (1/sqrt(2^n)) Σ_i |i&gt;. Minimizing L_s maximizes uniformity of |&lt;i|ψ&gt;|^2 in H, improving U_M(β_p) action.</p><p>Calculation: for n=4, p_i = 0.07, 1/2^4 = 0.0625, L_s = |0.07 - 0.0625| = 0.0075. Angles β_p are adjusted: β_p ← β_p - η ∂L_s/∂β_p.</p><p>Application: angles β align amplitudes of |ψ&gt; in the basis {|i&gt;}.</p><p><strong>2.8. Method </strong><strong>compute_entanglement</strong><br>Function: computes S = -Σ_i λ_i log(λ_i) and L_e = |S - ln(2)|, where λ_i are eigenvalues of the reduced density matrix.</p><p>Impact on angles: adjusts γ and β to minimize L_e, ensuring correct correlations.</p><p>Explanation in terms of H: entropy S reflects entanglement of subsystems in |ψ&gt;. For one qubit, S = ln(2) in a fully entangled state. Minimizing L_e tunes |ψ&gt; to a state with optimal correlations tied to QUBO.</p><p>Calculation: if S = 0.65, L_e = |0.65 - ln(2)| ≈ 0.043. Angles are adjusted: γ_p ← γ_p - η ∂L_e/∂γ_p.</p><p>Application: angles γ account for correlations, β support superposition.</p><p><strong>2.9. Method </strong><strong>train_step</strong><br>Function: updates neural network weights, minimizing L = mean|δ| + 0.1 L_s + 0.1 L_e, where δ is the phase error from the apply method. Weights: w ← w - η ∂L/∂w.</p><p>Impact on angles: indirectly improves γ and β via neural inputs.</p><p>Explanation in terms of H: the neural network transforms inputs related to &lt;ψ|P_i|ψ&gt; into angle adjustments, minimizing projection of |ψ&gt; onto high-energy states. Penalties L_s, L_e keep |ψ&gt; balanced.</p><p>Calculation: if |δ| = 0.1, L_s = 0.05, L_e = 0.043, then L = 0.1 + 0.1 * 0.05 + 0.1 * 0.043 ≈ 0.1093.</p><p>Application: angles γ and β are tuned to H_C.</p><p><strong>2.10. Method </strong><strong>frequency_pooling</strong><br> Function: applies Fast Fourier Transform (FFT) to angles α (γ or β): F(α) = FFT(α). Normalizes: F&#39;(α) = F(α) / (|F(α)| + ε), ε = 1e-8, selecting frequencies from f_min to f_max.</p><p>Impact on angles: simplifies γ and β, emphasizing low-frequency components tied to QUBO.</p><p>Explanation in terms of H: FFT decomposes angles in a sinusoidal basis, where low frequencies correspond to global features of H_C. Normalization F&#39;(α) enhances these frequencies, simplifying the trajectory of |ψ&gt; in H.</p><p>Calculation: for α = {γ_1, ..., γ_20}, f_min=1, f_max=5, F&#39;(α) contains frequencies 1–5, others are suppressed.</p><p>Application: angles γ and β focus on low-energy |z&gt;.</p><p><strong>2.11. Method </strong><strong>reconstruct_quantum_angles</strong><br> Function: reconstructs angles α&#39; = IFFT(pad(F&#39;(α))) with normalization α&#39; = α&#39; / sqrt(Σ |α&#39;|^2 + ε).</p><p>Impact on angles: forms β preserving key frequencies.</p><p>Explanation in terms of H: IFFT restores angles, retaining components tied to the global structure of H_C and H_M. Normalization ensures |ψ&gt; remains a unit vector in H.</p><p>Calculation: for F&#39;(α) with 5 frequencies, pad adds 15 zeros, α&#39; contains 20 angles.</p><p>Application: angles β improve transitions in H.</p><p><strong>2.12. Method </strong><strong>optimize_quantum_angles</strong><br> Function: minimizes L = &lt;ψ|H_C|ψ&gt; + 0.1 L_s + 0.1 L_e using FFT to structure angles.</p><p>Impact: optimizes γ and β, simplifying their frequency structure.</p><p>Explanation: frequency analysis reduces trajectory complexity in H, focusing on low-energy subspaces.</p><p>Calculation: L = 1.2 + 0.1 * 0.1 + 0.1 * 0.043 ≈ 1.2143.</p><p>Application: angles minimize &lt;ψ|H_C|ψ&gt;.</p><p><strong>2.13. Method </strong><strong>_compute_adaptive_freq_range</strong><br>Function: selects 20% of frequencies with maximum amplitude |F(α)|.</p><p>Impact: limits f_min, f_max for γ and β.</p><p>Explanation: focuses U_C, U_M on global H_C features, simplifying |ψ&gt;.</p><p>Calculation: top 4 frequencies from 20 set f_min, f_max.</p><p>Application: angles align with H_C structure.</p><p><strong>2.14. Method </strong><strong>activation</strong><br>Function: computes phase φ_z of input z tied to angles, applies activation y = exp(i 2π s / k), s = floor(φ_z k / 2π + 0.5). Adjusts: φ_z&#39; = φ_z + 0.1 Σ_j (φ_j |F_j| / Σ |F_j|).</p><p>Impact: tunes phases of γ and β for QUBO.</p><p>Explanation: activation enhances low-energy |z&gt; contributions, frequency correction aligns |ψ&gt; with H_C.</p><p>Calculation: φ_z = π/4, k=4, s = 1, y = exp(i π/2).</p><p>Application: angles enhance optimal |z&gt;.</p><p><strong>2.15. Method </strong><strong>lls_learn</strong><br>Function: updates weights: w ← w + η X^+ (d - y), minimizing L = mean|d - y| + 0.1 L_s + 0.1 L_e.</p><p>Impact: indirectly improves γ and β via neural inputs.</p><p>Explanation: weights adjust inputs tied to &lt;ψ|P_i|ψ&gt;, minimizing high-energy projections.</p><p>Calculation: L = 0.1 + 0.1 * 0.05 + 0.1 * 0.043 ≈ 0.1093.</p><p>Application: angles align with H_C.</p><p><strong>2.16. Function </strong><strong>enhance_superposition</strong><br>Function: minimizes L_s = mean_i |p_i - 1/2^n|. Angles: α ← α - 0.05 ∂L_s/∂α.</p><p>Impact: adjusts β for uniform superposition.</p><p>Explanation: minimizing L_s aligns |&lt;i|ψ&gt;|^2, improving U_M action in H.</p><p>Calculation: p_i = 0.07, L_s = 0.0075.</p><p>Application: angles β align &lt;i|ψ&gt;.</p><p><strong>2.17. Function </strong><strong>enhance_entanglement</strong><br>Function: minimizes L_e = |S - ln(2)|. Angles: α ← α - 0.05 ∂L_e/∂α.</p><p>Impact: adjusts γ and β for optimal entanglement.</p><p>Explanation: minimizing L_e tunes correlations in |ψ&gt;, enhancing H_C ties.</p><p>Calculation: S = 0.65, L_e = 0.043.</p><p>Application: angles γ account for correlations.</p><p><strong>2.18. Function </strong><strong>simulate_quantum_state</strong><br>Function: forms |ψ(γ, β)&gt; = Π_{p=1}^P U_M(β_p) U_C(γ_p) |+&gt;^n, normalizing: |ψ&gt; = |ψ&gt; / sqrt(&lt;ψ|ψ&gt; + ε).</p><p>Impact: provides |ψ&gt; for computing L_s, L_e.</p><p>Explanation: creates unit vector |ψ&gt; ∈ H reflecting γ and β action.</p><p>Calculation: for n=4, |ψ&gt; ∈ C^16.</p><p>Application: angles form |ψ&gt; for optimization.</p><p><strong>2.19. Function </strong><strong>measure_expectation</strong><br>Function: computes E = Σ_k c_k &lt;ψ|P_k|ψ&gt;.</p><p>Impact: adjusts γ to minimize E.</p><p>Explanation: E is the projection of |ψ&gt; onto H_C; minimizing E enhances low-energy |z&gt; amplitudes.</p><p>Calculation: for H_C = Z_0 + 0.5 Z_0 Z_1, E = &lt;ψ|Z_0|ψ&gt; + 0.5 &lt;ψ|Z_0 Z_1|ψ&gt;.</p><p>Application: angles γ minimize &lt;ψ|H_C|ψ&gt;.</p><h4>Section 3: Initial state optimization</h4><p>The initial state |+&gt;^n = (1/sqrt(2^n)) Σ_z |z&gt; is a uniform superposition in H. Angle optimization improves its projection onto low-energy states:</p><p>frequency_pooling: emphasizes low-frequency γ, β, simplifying |ψ&gt; trajectory.<br> activation: tunes phases to enhance &lt;z|H_C|z&gt;.<br> enhance_superposition: minimizes L_s, aligning |&lt;i|ψ&gt;|^2.<br> apply: guides γ to low-energy sectors. Explanation in terms of H: angles γ enhance amplitudes of |z&gt; with minimal &lt;z|H_C|z&gt;, β maintain uniform projections, preparing |ψ&gt; for further evolution in H. Calculation: for n=4, L_s = 0.01 means |&lt;i|ψ&gt;|^2 ≈ 0.0625, enhancing optimal |z&gt;.</p><h4>Section 4: Mixer optimization</h4><p>The mixer H_M = Σ_i X_i induces transitions |z&gt; ↔ |z ⊕ e_i&gt; in H. Angles β are optimized:</p><p>reconstruct_quantum_angles: restores β with key frequencies.<br> enhance_superposition: minimizes L_s for uniform |&lt;i|ψ&gt;|^2.<br> optimize_quantum_angles: minimizes L with frequency analysis.<br> apply: guides β to sectors enhancing transitions. Explanation in terms of H: angles β control U_M, ensuring uniform exploration of the basis {|z&gt;}, preventing |ψ&gt; localization in suboptimal subspaces. Calculation: if L_s = 0.05, β are adjusted to align |&lt;i|ψ&gt;|^2.</p><h4>Section 5: Aligning initial state and mixer</h4><p>Angles γ and β are jointly optimized to synchronize U_C and U_M:</p><p>optimize_qaoa: minimizes L, balancing γ and β.<br> optimize_quantum_angles: uses frequencies for synchronization.<br> enhance_superposition, enhance_entanglement: align |&lt;i|ψ&gt;|^2 and S.<br> apply: ensures γ and β phases are compatible. Explanation in terms of H: joint optimization ensures U_C enhances optimal |z&gt; amplitudes, while U_M supports transitions, forming |ψ&gt; in a low-energy subspace of H. Calculation: If L = 1.3, alignment reduces &lt;ψ|H_C|ψ&gt; by 10–20%.</p><h4>Section 6: Solving QUBO</h4><p>QAOA minimizes &lt;ψ|H_C|ψ&gt; to find the optimal |z&gt;:</p><p>optimize_qubo: forms H_C and optimizes γ, β.<br> measure_expectation: computes E for γ correction.<br> frequency_pooling, reconstruct_quantum_angles: simplify γ, β.<br> compute_superposition, compute_entanglement: balance β.<br> apply: guides angles to optimal sectors. Explanation in terms of H: angles tune |ψ&gt; to the eigenvector of H_C with minimal eigenvalue, minimizing projection onto high-energy states. Calculation: for a 4x4 QUBO, E reaches a minimum in ~100 iterations.</p><h4>Section 7: Efficiency of methods</h4><p>The methods are efficient because they:</p><p>Minimize &lt;ψ|H_C|ψ&gt; (optimize_qaoa, measure_expectation).<br>Align |&lt;i|ψ&gt;|^2 and S (enhance_superposition, compute_entanglement).<br>Simplify angles via frequencies (frequency_pooling).<br>Refine phases (apply).<br>Synchronize γ and β (optimize_quantum_angles). Explanation in terms of H: The methods form |ψ&gt; in a low-energy subspace of H, balancing localization (γ) and exploration (β).</p><p>In the next lesson, we will explore how the qo-MLMVN framework methods, such as compute_adaptive_threshold, apply, compute_angular_rmse, is_converged, optimize_qaoa, optimize_qubo, compute_superposition, compute_entanglement, train_step, frequency_pooling, reconstruct_quantum_angles, optimize_quantum_angles, _compute_adaptive_freq_range, activation, lls_learn, enhance_superposition, enhance_entanglement, simulate_quantum_state, and measure_expectation, optimize angles γ and β, forming |ψ&gt; with minimal &lt;ψ|H_C|ψ&gt; in H, solving QUBO with high accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WIF6oHXr4hyAkUtzvVHYvQ.jpeg" /></figure><p>We will thoroughly analyze the complete TensorFlow code for the <strong>qo-MLMVN</strong> framework in the next lesson — 🚀 Follow the link: Coming soon</p><p>If anything is unclear, contact <a href="https://www.linkedin.com/in/serhii-barskyi/"><strong>Serhii Barskyi | LinkedIn</strong></a> or carefully reread the lesson text with your AI assistant 😉</p><p>🎓 <strong>For a complete individual QRL development course on Qiskit and for one-on-one tutoring on machine Reinforcement Learning topics, please contact: </strong><a href="http://linkedin.com/company/sigma-publishinq/posts/"><strong>Sigma Publishinq</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05294ac9968e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Projection of the Aizenberg Neuron: Hilbert Space through the Lens of Q-MLMVN]]></title>
            <link>https://medium.com/@serhii.barskyi/quantum-projection-of-the-aizenberg-neuron-hilbert-space-through-the-prism-of-q-mlmvn-2cf472c78f37?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf472c78f37</guid>
            <category><![CDATA[sigma-publishing]]></category>
            <category><![CDATA[aizenberg-neuron]]></category>
            <category><![CDATA[serhii-barskyi]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 23:50:47 GMT</pubDate>
            <atom:updated>2026-05-02T07:32:28.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yL7FqEZ_EhBVOaMPxbcRA.png" /></figure><p>Fundamentals of Quantum Reinforcement Learning on Qiskit by <a href="http://linkedin.com/company/sigma-publishinq/posts/"><strong>Sigma Publishinq</strong></a></p><p>My Data Science Course <a href="https://preply.com/en/tutor/7756455">https://preply.com/en/tutor/7756455</a></p><h4><strong>Table of Contents</strong></h4><blockquote><strong>1. Computational Significance of QRL and q-MDP</strong><br><strong>2. The Role of Hilbert Spaces in the Formalization of Quantum Reinforcement Learning</strong><br>2.1 Quantum State Vectors in QRL Dynamics<br>2.2 Hermitian Observables in QRL Probabilistic Yield<br>2.3 Unitary Evolution of QRL Agent Trajectories<br>2.4 Superposition Encoding of QRL Strategic Multiverse<br>2.5 Projectors Collapsing QRL Quantum Uncertainty<br>2.6 Spectral Decomposition Optimizing QRL Reward Horizons<br><strong>3. How Much Hilbert Space Knowledge Does a Qiskit Programmer Need?</strong><br><strong>4. Hilbert Space and MLMVN</strong><br>4.1 Metric Spaces: <strong>phase distance mapping</strong><br>4.2 Linear Spaces: <strong>complex vector encoding</strong><br>4.3 Normed Spaces: <strong>unit circle normalization</strong><br>4.4 Banach Spaces: <strong>learning convergence dynamics</strong><br>4.5 Inner Product: <strong>phase neuron alignment</strong><br>4.6 Gram–Schmidt Orthogonalization: <strong>weight space orthogonalization</strong><br>4.7 Orthogonal Projection: <strong>error projection correction</strong><br>4.8 Completeness and Closure. Hilbert Basis: <strong>feature basis decomposition</strong><br>4.9 Isomorphism of Hilbert Spaces: <strong>network topology mapping</strong><br>4.10 Functionals and Weak Convergence: <strong>complex output refinement</strong><br><strong>5. Principles of MLMVN Architecture in Terms of Hilbert Space<br>6. Quantization: Creating</strong> <strong>Q-MLMVN on Qiskit<br>7. Quantum Interpretation of Aizenberg’s Ideas for QRL</strong></blockquote><p><strong>This publication serves as an introduction to a course on Quantum MDP and Quantum Reinforcement Learning (QRL).</strong></p><h3>And now, let’s embark on developing your quantum intuition<strong>!</strong></h3><p>In this and subsequent QRL lessons, we will frequently utilize computational principles and fragments of the mathematical framework developed by <strong>Professor Aizenberg</strong> in his well-known work - <strong><em>MLMVN</em></strong> <a href="https://link.springer.com/book/10.1007/978-3-642-20353-4">https://link.springer.com/book/10.1007/978-3-642-20353-4</a></p><p>Aizenberg’s MLMVN can be regarded as a <strong>pedagogical bridge</strong> between classical and quantum machine learning paradigms. We will explore this property of MLMVN in greater detail below. Igor Aizenberg is the Department Chairperson of Computer Science, Graduate Director of Computer Science, and Graduate Professor at Manhattan University (Riverdale, NY) <a href="https://manhattan.edu/campus-directory/iaizenberg01">https://manhattan.edu/campus-directory/iaizenberg01</a></p><blockquote><strong>What is the computational significance of </strong><strong>QRL and </strong><strong>q-MDP for artificial intelligence tasks?</strong></blockquote><blockquote>Quantum Markov Decision Processes (q-MDPs) generalize classical MDPs by using quantum states (density operators) and quantum channels to model decision-making processes in quantum systems. Under ideal quantum conditions, when implemented on quantum computers, algorithms solving problems framed within the q-MDPs formalism can exploit quantum superposition and entanglement to process up to 2^n states in parallel. This potentially reduces temporal complexity for certain tasks — for example, from O(n) in classical methods to O(log n) in quantum algorithms such as quantum search or quantum optimization — especially for problems involving exponentially large state spaces, such as control of multi-agent systems or real-time quantum processes.</blockquote><p>In turn, Quantum Reinforcement Learning (QRL), under ideal conditions, can achieve exponential speedup by employing quantum analogs of dynamic programming and algorithms like Q-learning. Here, finding an optimal policy for n states and m actions reduces from O(n * m * T) to O(log n * m * T), making it ideal for tasks with continuous action spaces — such as generating arbitrary quantum states with precision approaching 1 without discretization losses.</p><p>Potential applications include the development of universal quantum policies capable of instantly adapting to any initial states and target functions, as well as integration with quantum games and nonlocal correlations. In such cases, QRL can outperform classical methods by orders of magnitude in terms of cost and convergence speed, for instance, delivering a 1000-fold advantage for systems with n = 30 qubits.</p><p>The reality is that those aiming to master the practical application of QRL need a solid understanding of mathematics beyond a standard introduction to linear algebra. Many foundational and novel ideas in QRL rely on deeper mathematical concepts often overlooked in beginner-level materials.</p><p><strong>To confidently work with QRL and q-MDP in the quantum realm, we will need:</strong></p><blockquote>1.Mathematical foundations of quantum computing.</blockquote><blockquote>2.A brief course on group theory, topology, and manifolds.</blockquote><blockquote>3.Lie groups with applications.</blockquote><p>Before taking the first step and diving into Quantum Reinforcement Learning and quantum computing, we must familiarize ourselves with the theoretical aspects of <a href="https://en.wikipedia.org/wiki/Hilbert_space">Hilbert space</a> as a fundamental mathematical basis of quantum mechanics, and with <a href="https://docs.quantum.ibm.com/guides/hello-world">Qiskit</a> — a tool for developing quantum algorithms.</p><p>For a better understanding of this lesson on the basics of Hilbert space, it is important to have a foundational background in <strong>MLMVN:</strong> <a href="http://pipad.org/tmp/Complex-Valued%20Neural%20Networks%20with%20Multi-Valued%20Neurons.pdf"><strong>Complex-Valued Neural Networks with Multi-Valued Neurons - Tutorial</strong></a>. You can explore MLMVN materials in depth on Igor Aizenberg’s website: <a href="https://www.igoraizenberg.com/">https://www.igoraizenberg.com/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dij_Ngu3-mAj2ufwkvBdbA.jpeg" /></figure><h3><strong>A brief note on the fundamentality of Hilbert space concepts in Quantum Reinforcement Learning.</strong></h3><p><em>Why Hilbert Space Is Not Just a Convenience but an Ontological Necessity for Quantum RL.</em></p><h4><strong>2.1 System States in QRL</strong></h4><p>In quantum reinforcement learning, an agent is represented by a quantum state — a vector in a Hilbert space H = (C²)^n, where n is the number of qubits. This state evolves through quantum gates (unitary operators), and measurements yield probabilities of action choices or reward values, shaping the agent&#39;s strategy.</p><p>If an agent uses qubits, its state resides in H = (C²)^n, with each qubit adding a new dimension. The quantum agent interacts with the environment, altering its state, and measurements determine which action to take or what reward to receive. In Qiskit, qubit states are stored as amplitude sets and modified by applying gates.</p><p>Here’s an example of Qiskit code for an agent’s initial state:</p><pre>from qiskit import QuantumCircuit<br>qc = QuantumCircuit(2)  # Two qubits<br>qc.h(0)  # Hadamard gate creates superposition<br>qc.cx(0, 1)  # CNOT gate creates entanglement<br>qc.measure_all()  # Measure the state<br>print(qc.draw())</pre><p>This code generates an entangled state that could serve as the agent’s initial strategy. Measurements reveal the probabilities of possible outcomes.</p><p>This code generates an entangled state that could serve as the agent’s initial strategy. Measurements reveal the probabilities of possible outcomes.</p><p><strong>Detailed line-by-line comments:</strong></p><p>from qiskit import QuantumCircuit — imports the QuantumCircuit class from Qiskit to create quantum circuits.<br> qc = QuantumCircuit(2) — initializes a quantum circuit with 2 qubits.<br> qc.h(0) — applies a Hadamard gate to qubit 0, creating a superposition of |0⟩ and |1⟩.<br> qc.cx(0, 1) — applies a CNOT gate with qubit 0 as control and qubit 1 as target, entangling the qubits.<br> qc.measure_all() — measures all qubits, collapsing the state into a classical outcome.<br> print(qc.draw()) — prints a text-based diagram of the circuit.</p><p>The Hilbert space H = (C²)^n defines the quantum state of an agent as a vector whose dimension grows exponentially with the number of qubits n, requiring understanding of basis vectors and tensor products to analyze the code. Unitary operators, such as gates in Qiskit, transform this vector within H, and knowing their effect on multidimensional states is essential for interpreting agent evolution. Measurements in Hilbert space project the state vector onto basis states, and the outcome probabilities depend on amplitudes, which is critical for understanding qc.measure_all(). Superposition, created via the Hadamard gate qc.h(0), represents a linear combination of basis vectors in H, and without Hilbert space theory, one cannot comprehend its role in action selection. Entanglement, caused by qc.cx(0, 1), requires understanding of inseparable states in the tensor product of H to assess correlations between qubits in the code. Initialization through qc = QuantumCircuit(2) sets the dimension of H, and without structural knowledge of this space, it is impossible to predict the behavior of print(qc.draw()).</p><p><strong>Strategy as a Coherent Amplitude Profile, Not a Probabilistic Vector</strong><br>In classical RL, a policy is defined as a probability distribution over a discrete action space: each probability is a real, non-negative number, and their sum is one. In the quantum case, the strategy is described as a state vector in Hilbert space — defined by complex amplitudes that can interfere. <strong>Formally:</strong></p><h3>ψ = Σᵢ αᵢ |aᵢ⟩, where αᵢ ∈ ℂ, Σ |αᵢ|² = 1</h3><p>ψ — represents the quantum strategy as a single state vector in a Hilbert space. Unlike a classical policy (a list of probabilities), this is a coherent superposition of all possible actions, capturing their relationships through amplitudes and phases. Think of ψ as the &quot;wavefunction&quot; describing the agent’s decision-making state.</p><p>Σᵢ — denotes a summation over all possible actions, indexed by i. Each term in the sum corresponds to a specific action the agent can take, and the summation combines them into a unified quantum state. This is similar to adding up contributions in a vector, but here they can interfere due to their complex nature.</p><p>αᵢ — represents the amplitude associated with action aᵢ. These are complex numbers (αᵢ ∈ ℂ), meaning each has a magnitude (size) and a phase (angle). The magnitude influences the likelihood of the action, while the phase allows for constructive or destructive interference with other actions, a feature absent in classical probabilities.</p><p>∈ ℂ — indicates that αᵢ belongs to the set of complex numbers. A complex number can be written as αᵢ = r e^(iθ), where r is the real-valued magnitude and θ is the phase. This complexity enables quantum effects like superposition and entanglement, distinguishing it from classical real-valued probabilities.</p><p>|aᵢ⟩ — denotes a basis state in Hilbert space, representing a specific action aᵢ (e.g., &quot;move left&quot; or &quot;choose option A&quot;). These are orthonormal vectors (⟨aᵢ|aⱼ⟩ = 0 if i ≠ j, and 1 if i = j), forming the building blocks of the quantum state. The notation uses &quot;ket&quot; from Dirac’s bra-ket formalism.</p><p>Σ |αᵢ|² = 1 — enforces normalization of the state vector. The absolute square of each amplitude, |αᵢ|², represents a probability-like quantity, and their sum equaling 1 ensures the total probability across all actions is 100%. This is a quantum analog to the classical rule that probabilities sum to 1, but here it’s the magnitudes of complex numbers that matter.</p><p>No probabilistic space can express interference between policy components — only Hilbert space, equipped with an inner product, allows for phase definitions, superpositions, and coherent amplitude interactions. This is not a cosmetic difference: without interference, the agent cannot realize quantum analogs of generalization or hidden preferences among actions. The inner product provides more than just a norm — it defines the probability metric:</p><h3>P(aᵢ) = |⟨aᵢ|ψ⟩|²</h3><p>P(aᵢ) - defines the probability of the agent selecting action aᵢ. Unlike classical reinforcement learning, where probabilities are directly assigned, here the probability emerges from the quantum state ψ through a mathematical operation, reflecting interference effects between actions. In QRL, this captures how the agent’s quantum policy distributes amplitudes across all actions, influenced by phase and entanglement.</p><p>⟨aᵢ| - represents the &quot;bra&quot; part of the inner product, corresponding to the basis state |aᵢ⟩. It&#39;s the conjugate transpose of the ket |aᵢ⟩, written as a row vector in Hilbert space. This is used to &quot;project&quot; the state ψ onto the specific action aᵢ. In QRL, this projection determines how much the agent&#39;s quantum strategy aligns with a given action.</p><p>ψ⟩ - is the state vector from the first formula (ψ = Σᵢ αᵢ |aᵢ⟩), written as a &quot;ket.&quot; It&#39;s a column vector in Hilbert space, encapsulating the full quantum strategy with all its amplitudes and phases. In QRL ψ⟩ encodes the agent&#39;s coherent control policy, enabling it to represent multiple potential actions simultaneously.</p><p>⟨aᵢ|ψ⟩ - computes the inner product between ⟨aᵢ| and |ψ⟩. Mathematically, this is a dot product: if ψ = Σᵢ αᵢ |aᵢ⟩, then ⟨aᵢ|ψ⟩ = αᵢ, because ⟨aᵢ|aⱼ⟩ = 0 for i ≠ j and 1 for i = j (orthonormality). The result, αᵢ, is the complex amplitude of action aᵢ in the state ψ. In QRL this amplitude governs both the probability and interference potential of selecting aᵢ.</p><p>|…|² - takes the absolute square of the inner product. For a complex number αᵢ = x + iy, the absolute square is |αᵢ|² = x² + y², where x and y are the real and imaginary parts. This operation converts the complex amplitude into a real, non-negative number between 0 and 1, interpretable as a probability. In QRL this ensures that measurement of the agent’s quantum state yields classical decision probabilities.</p><p>P(aᵢ) = |⟨aᵢ|ψ⟩|² - ties it all together: the probability of choosing action aᵢ is the squared magnitude of its amplitude in the state ψ. This reflects the Born rule in quantum mechanics, where probabilities arise from amplitudes, allowing interference to shape the final outcome — unlike classical policies where no such interplay exists. In QRL this mechanism enables policy learning that can exploit superposition and phase coherence for more expressive decision-making.</p><p><strong>Thus, choosing Hilbert space is not a matter of syntax — it is the only way to formulate strategy as a coherent quantum entity.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJ9ORAOFSkff2tL7I44YnQ.png" /></figure><h4><strong>2.2 Observable Operators in QRL</strong></h4><p>In QRL, observables—physical quantities like rewards or action choices—are evaluated through measurements of the agent’s quantum state. These are represented by Hermitian operators, whose eigenvalues indicate possible measurement outcomes.<br> A quantum agent assesses the environment via measurements tied to Hermitian operators. These operators’ eigenvalues can be interpreted as measurement results, such as rewards or actions.</p><p>Here’s a Qiskit example with the Z operator (Pauli Z matrix):</p><pre>from qiskit.quantum_info import Operator<br>from qiskit import Aer, execute<br>qc = QuantumCircuit(1)<br>qc.h(0)  # Superposition<br>qc.measure_all()<br>result = execute(qc, Aer.get_backend(&#39;qasm_simulator&#39;)).result()<br>counts = result.get_counts()<br>print(counts)  # Probabilities for Z</pre><p>The Z operator here measures the qubit’s state, potentially linked to a reward.</p><p><strong>Detailed line-by-line comments:</strong></p><p>from qiskit.quantum_info import Operator — Imports the Operator class for defining custom operators.<br> from qiskit import Aer, execute — Imports Aer (simulator) and execute (to run circuits).<br> qc = QuantumCircuit(1) — Creates a circuit with 1 qubit.<br> qc.h(0) — Applies a Hadamard gate to qubit 0 for superposition.<br> qc.measure_all() — Measures the qubit.<br> result = execute(...) — Runs the circuit on a QASM simulator.<br> counts = result.get_counts() — Retrieves measurement outcomes as a dictionary.<br> print(counts) — Displays probabilities (e.g., {&#39;0&#39;: 512, &#39;1&#39;: 512} for 1024 shots).</p><p>Hermitian operators in Hilbert space represent observables such as rewards, and their spectral decomposition defines possible outcomes — vital for analyzing code using Operator. Understanding the eigenvalues of these operators in H is necessary to link measurement results (counts) to physical quantities in QRL. The state vector in H interacts with the Z operator via the inner product, and without Hilbert space theory, the output of print(counts) cannot be interpreted. Superposition from qc.h(0) alters basis projections in H, and understanding their evolution under operators is crucial for grasping probabilities. Simulation using execute(qc, Aer.get_backend(&#39;qasm_simulator&#39;)) relies on the orthonormal basis of H, requiring knowledge of its properties to evaluate the outcome. The code presumes an awareness of how Hermiticity in Hilbert space ensures real eigenvalues, linking them to the agent’s task.</p><p><strong>Rewards as Hermitian Spectral Operators, Not Scalar Utility Functions</strong><br>In classical RL, the reward function maps a state-action pair to a real number. In quantum RL, the agent doesn’t aim to maximize a scalar but instead aligns its quantum state with the eigenstates of a Hermitian reward operator. This operator R̂ acts in Hilbert space and admits a spectral decomposition:</p><h3>R = Σᵢ rᵢ |rᵢ⟩⟨rᵢ|</h3><p>R — represents the reward in quantum reinforcement learning as a Hermitian operator (often written as R̂ to emphasize it’s an operator) acting in Hilbert space. Unlike classical RL, where reward is a single real number, here R is a mathematical object that encodes rewards through its spectral properties, allowing quantum interactions with the agent’s state and guiding the agent’s learning through operator dynamics.</p><p>Σᵢ — denotes a summation over all possible indices i, each corresponding to an eigenstate of the reward operator. This sum constructs R by combining contributions from all its eigenvectors and eigenvalues, similar to how a matrix is built from its spectral decomposition in linear algebra, which in quantum RL enables encoding a rich and distributed reward landscape over quantum states.</p><p>rᵢ — represents the eigenvalue associated with the eigenstate |rᵢ⟩. These are real numbers (since R is Hermitian), and each rᵢ quantifies the reward value tied to a specific spectral component of the operator. In QRL these eigenvalues correspond to possible observed reward outcomes, forming the quantum analog of scalar rewards in classical setups.</p><p>|rᵢ⟩ — denotes an eigenvector of the reward operator R, written as a &quot;ket&quot; in Dirac notation. Each |rᵢ⟩ is a basis state in Hilbert space, representing a possible reward configuration. In quantum RL these states describe distinct strategies or environments that the agent may align with to extract maximal reward from its quantum interactions.</p><p>⟨rᵢ| — represents the &quot;bra&quot; corresponding to the eigenvector |rᵢ⟩. It’s the conjugate transpose of |rᵢ⟩, acting as a row vector. When paired with |rᵢ⟩, it forms the outer product |rᵢ⟩⟨rᵢ|, a projection operator that isolates the contribution of the rᵢ eigenvalue. In QRL these projection operators define how much a given state overlaps with reward-relevant subspaces, informing learning via quantum measurements.</p><p>|rᵢ⟩⟨rᵢ| — constructs a projection operator for the eigenstate |rᵢ⟩. This operator projects any quantum state onto the subspace spanned by |rᵢ⟩. When multiplied by rᵢ and summed, these projections define the full reward operator R, capturing all possible reward states. In quantum RL this structure allows the agent to compute expected rewards by projecting its own state onto reward-eigenstates.</p><p>R = Σᵢ rᵢ |rᵢ⟩⟨rᵢ| — combines all terms into the spectral decomposition of R. This form guarantees that R is Hermitian (self-adjoint), meaning its eigenvalues rᵢ are real and its eigenvectors form an orthonormal basis—key properties for defining observable quantities like rewards in quantum mechanics. In quantum reinforcement learning, this spectral form is essential: it defines the agent’s reward landscape and determines how the quantum state must evolve to maximize long-term gains.</p><p>The reward arises as the expectation value of this operator on the current state vector:</p><h3>⟨ψ|R|ψ⟩</h3><p>⟨ψ| — represents the &quot;bra&quot; form of the agent&#39;s current quantum state vector |ψ⟩. It&#39;s the conjugate transpose of |ψ⟩, written as a row vector in Hilbert space. This is the starting point for computing the reward expectation, projecting the state onto itself after interaction with R. In QRL this projection defines how the agent evaluates its expected reward based on its current quantum configuration.</p><p>|ψ⟩ — denotes the agent&#39;s quantum state vector, written as a &quot;ket.&quot; It&#39;s a column vector in Hilbert space (e.g., |ψ⟩ = Σᵢ αᵢ |aᵢ⟩ from earlier), encoding the strategy or configuration of the agent at a given moment. Here, it&#39;s the state on which the reward operator acts. In quantum reinforcement learning, |ψ⟩ evolves through interactions with the environment and serves as the agent&#39;s internal policy representation.</p><p>R — is the Hermitian reward operator (R = Σᵢ rᵢ |rᵢ⟩⟨rᵢ|), inserted between ⟨ψ| and |ψ⟩. It acts on |ψ⟩ first, transforming it into a new vector R|ψ⟩, which represents the reward operator&#39;s effect on the agent&#39;s state. In quantum reinforcement learning this models the environmental feedback received by the agent through operator-state interaction rather than scalar signals.</p><p>R|ψ⟩ — applies the reward operator R to the state |ψ⟩. Since R = Σᵢ rᵢ |rᵢ⟩⟨rᵢ|, this operation becomes R|ψ⟩ = Σᵢ rᵢ |rᵢ⟩⟨rᵢ|ψ⟩. Each term ⟨rᵢ|ψ⟩ is the projection of |ψ⟩ onto |rᵢ⟩, scaled by the eigenvalue rᵢ, blending the state with reward components. In QRL this models how each part of the agent&#39;s policy is evaluated according to the reward structure.</p><p>⟨ψ|R|ψ⟩ — computes the expectation value of the reward operator R in the state |ψ⟩. Mathematically, it&#39;s the inner product of ⟨ψ| with R|ψ⟩:<br> ⟨ψ|R|ψ⟩ = ⟨ψ| (Σᵢ rᵢ |rᵢ⟩⟨rᵢ|) |ψ⟩ = Σᵢ rᵢ |⟨rᵢ|ψ⟩|².<br> This is a real number (since R is Hermitian), representing the average reward the agent experiences in state |ψ⟩. In quantum reinforcement learning this expectation guides the optimization process, helping the agent adjust its state to maximize future rewards.</p><p><strong>Thus, measuring reward is not extracting a value but projecting the state onto spectral subspaces.</strong> Such projections are only defined in Hilbert space, which possesses an orthonormal basis of eigenvectors corresponding to observables. Without Hilbert space, the agent cannot <em>experience reward as a quantum interaction with the environment</em> — only as a primitive tag, severely limiting the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRg6LqcBHPt6Q1ZRw5O7XQ.png" /></figure><h4>2.3 System Evolution in QRL</h4><p>The agent’s state evolution is described by unitary evolution, as in the Schrödinger equation. In Qiskit, this is implemented via quantum gates that model how the agent’s state adapts during learning.<br> Gates are matrices that rotate or transform qubit states. A sequence of gates shapes the learning dynamics, updating the agent’s strategy.</p><p>Example of state evolution:</p><pre>from qiskit import QuantumCircuit<br>from numpy import pi<br>qc = QuantumCircuit(1)<br>qc.rx(pi/4, 0)  # Rotate qubit by π/4<br>qc.draw()</pre><p>This code demonstrates how an agent adjusts its state, potentially as part of strategy updates.</p><p><strong>Detailed line-by-line comments:</strong></p><p>from qiskit import QuantumCircuit — Imports QuantumCircuit.<br> from numpy import pi — Imports π for angle specification.<br> qc = QuantumCircuit(1) — Initializes a 1-qubit circuit.<br> qc.rx(pi/4, 0) — Applies an X-rotation gate by π/4 radians to qubit 0.<br> qc.draw() — Returns a circuit diagram (not printed here).</p><p>Unitary evolution in Hilbert space, implemented via qc.rx(pi/4, 0), preserves the norm of the state vector, and understanding this property is necessary for analyzing changes in agent strategy. In H, rotation operators such as Rx act as complex plane rotations, requiring knowledge of unitary transformations to interpret the code. The sequence of gates defines a trajectory in H, and without Hilbert space theory, one cannot trace how qc.draw() reflects learning dynamics. The state vector in H is linearly transformed, and understanding basis decompositions allows prediction of the final state after evolution. The angle π/4 in qc.rx() defines a specific unitary action, and knowledge of operator exponentiation in H is key to linking the code to the QRL task. The agent’s evolution in code depends on the continuity of H as a vector space, which is critical for interpreting quantum updates.</p><p><strong>Strategy Update as Unitary Phase Control, Not Stochastic Optimization</strong><br>Classical learning updates are based on stochastic gradients and error corrections — essentially, a local descent in parameter space. In quantum RL, the update is a unitary transformation that preserves the norm of the vector:</p><h3>|ψ’⟩ = U |ψ⟩</h3><p>|ψ&#39;⟩ — represents the updated quantum state vector after the learning process, written as a &quot;ket&quot; in Dirac notation. This is the new strategy of the agent in Hilbert space, resulting from a transformation applied to the original state. Unlike classical updates that tweak probabilities, |ψ&#39;⟩ maintains the quantum properties of the original state, such as superposition and coherence, which are essential in quantum reinforcement learning for encoding complex, parallel exploration policies.</p><p>U — denotes a unitary operator, a special type of linear transformation in Hilbert space. A unitary operator satisfies U† U = I (where U† is the conjugate transpose of U, and I is the identity operator), ensuring that it preserves the norm of the state vector. In QRLU embodies the learning update, adjusting the strategy through controlled phase shifts and rotations rather than stochastic changes, maintaining the reversibility and coherence of the agent’s evolution.</p><p>|ψ⟩ — represents the original quantum state vector of the agent before the update, also written as a &quot;ket.&quot; This is the starting strategy (e.g., |ψ⟩ = Σᵢ αᵢ |aᵢ⟩ from earlier discussions), a column vector in Hilbert space that encodes the agent&#39;s current action preferences via complex amplitudes. In quantum reinforcement learning this state contains the full information of the agent’s behavior policy in a coherent form.</p><p>U |ψ⟩ — applies the unitary operator U to the state |ψ⟩. This operation transforms |ψ⟩ into |ψ&#39;⟩ by rotating its components in Hilbert space. Mathematically, if |ψ⟩ = Σᵢ αᵢ |aᵢ⟩, then U |ψ⟩ = Σᵢ αᵢ U |aᵢ⟩, where U acts on each basis state |aᵢ⟩. The result is a new superposition with adjusted amplitudes and phases, but the total norm (⟨ψ&#39;|ψ&#39;⟩ = ⟨ψ|ψ⟩ = 1) remains unchanged due to unitarity. In quantum reinforcement learning, this reflects a noise-free, information-preserving policy update.</p><p>|ψ&#39;⟩ = U |ψ⟩ — defines the full update process: the new state |ψ&#39;⟩ is the result of applying U to |ψ⟩. This unitary transformation is the quantum equivalent of learning, preserving the vector&#39;s norm while allowing phase control. It reflects a deterministic, reversible evolution (like in the Schrödinger equation), contrasting with the probabilistic, norm-altering updates of classical stochastic optimization. In QRL this mechanism ensures the agent learns without decohering its strategy representation.</p><p>Unitarity is not a constraint but the physical requirement of quantum evolution. Any valid motion in Hilbert space corresponding to legitimate quantum learning must preserve the norm — this necessitates an inner product and complex linear structure. Only Hilbert space allows the construction of such operators, where dynamics are governed by the Schrödinger equation or its discrete analog.</p><p><strong>Moreover, phase rotations of the strategy vector, which change amplitudes without affecting magnitudes, enable subtle preference shifts without collapse. </strong>This unique mode of adaptation is impossible in stochastic optimization. Hence, learning in quantum RL is <em>phase control</em>, not gradient descent — and it cannot be formalized outside Hilbert space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXo6oypzOaKId7cz5QA42g.png" /></figure><h4>2.4 Superposition Principle in QRL</h4><p>A key advantage of QRL is superposition, which allows an agent to encode multiple strategies in a single state simultaneously.<br> In classical learning, an agent tests strategies sequentially. In QRL, superposition enables encoding multiple options, processed by quantum algorithms.</p><p>Example in Qiskit:</p><pre>from qiskit import QuantumCircuit<br>qc = QuantumCircuit(1)<br>qc.h(0)  # Creates superposition: 0 and 1 simultaneously<br>qc.measure_all()<br>print(qc.draw())</pre><p>This is akin to an agent “considering” two actions at once, with measurement selecting one probabilistically.</p><p><strong>Detailed line-by-line comments:</strong></p><p>from qiskit import QuantumCircuit — Imports QuantumCircuit.<br> qc = QuantumCircuit(1) — Creates a 1-qubit circuit.<br> qc.h(0) — Applies a Hadamard gate, creating superposition.<br> qc.measure_all() — Measures the qubit.<br> print(qc.draw()) — Prints the circuit diagram.</p><p>Superposition in Hilbert space H allows the state vector to be a linear combination of basis vectors, implemented via qc.h(0), requiring understanding of linear independence to analyze the code. The multidimensionality of H via (C²)^n enables simultaneous encoding of strategies, and without space theory, one cannot appreciate the advantage over classical approaches. The measurement qc.measure_all() projects the superposition onto the basis of H, and knowledge of decomposition coefficients is crucial to predicting print(qc.draw()). Outcome probabilities depend on the squared norms of amplitudes in H, demanding understanding of the space&#39;s metric to interpret results. The state vector in H before measurement exists in a continuum of possibilities, and without the Hilbert approach, it is impossible to grasp how the code models action selection. The code demonstrates a fundamental property of H—the quantum agent’s ability to “consider” multiple paths, which is inaccessible without superposition theory.</p><p><strong>Coherent Policy Sets: Multiplicity Within a Single State</strong><br>In classical systems, policy ensembles are modeled via agent populations, bootstrapping, or ensemble regularization. In quantum RL, however, a single state vector can describe a coherent set of strategies via superposition:</p><h3>|Ψ⟩ = c₁|π₁⟩ + c₂|π₂⟩ + …</h3><p>|Ψ⟩ — represents a single quantum state vector in Hilbert space, written as a &quot;ket&quot; in Dirac notation. This state encapsulates a coherent set of multiple policy strategies simultaneously through superposition. Unlike classical reinforcement learning, where multiple policies require separate agents or models, |Ψ⟩ unifies them into one quantum state, enabling quantum reinforcement learning agents to explore policy spaces in parallel through quantum interference.</p><p>c₁, c₂, ... — denote the complex coefficients (amplitudes) associated with each policy strategy. Each cᵢ is a complex number (cᵢ ∈ ℂ), with a magnitude (|cᵢ|) and phase, regulating the influence of its corresponding policy |πᵢ⟩. The magnitudes satisfy Σᵢ |cᵢ|² = 1 to ensure the state is normalized, while the phases allow for interference effects. In quantum reinforcement learning, these amplitudes determine how strategies interfere constructively or destructively, enabling richer learning dynamics than classical mixtures.</p><p>|π₁⟩, |π₂⟩, ... — represent distinct behavioral strategies (policies), each written as a &quot;ket&quot; in Hilbert space. Each |πᵢ⟩ is a basis state corresponding to a specific strategy (e.g., &quot;aggressive play&quot; or &quot;defensive retreat&quot;). These are assumed to be orthonormal (⟨πᵢ|πⱼ⟩ = 0 if i ≠ j, and 1 if i = j), forming a basis for the policy subspace. In quantum reinforcement learning each |πᵢ⟩ can be seen as a quantum-encoded classical policy, enabling flexible representation and transformation of strategies.</p><p>c₁|π₁⟩, c₂|π₂⟩, ... — indicate the weighted contribution of each policy to the superposition. For example, c₁|π₁⟩ scales the strategy |π₁⟩ by the amplitude c₁, blending its influence into the overall state. The complex nature of cᵢ means that both the strength (via |cᵢ|) and relative alignment (via phase) of each policy affect the final behavior. In QRL these contributions dynamically interact, allowing policy interference that can enhance or suppress behavior patterns.</p><p>+ — signifies the linear combination of policies within the superposition. In Hilbert space, adding these terms (c₁|π₁⟩ + c₂|π₂⟩ + ...) creates a new state |Ψ⟩ that is a coherent blend of all |πᵢ⟩ states. This addition allows interference between policies, unlike classical sums of probabilities that remain independent. In QRL this coherence enables the agent to evaluate and optimize across an entangled space of strategies simultaneously.</p><p>|Ψ⟩ = c₁|π₁⟩ + c₂|π₂⟩ + ... — defines the full quantum state as a superposition of multiple policy vectors. This single state |Ψ⟩ simultaneously encodes a set of strategies, with their interplay governed by the amplitudes cᵢ. The result is a &quot;quantum ensemble,&quot; where new strategies emerge from coherent blending, not external selection mechanisms. In quantum reinforcement learning this unified encoding enables efficient search, parallel exploration, and interference-driven optimization in policy space.</p><p>Each policy |π₁&gt; represents a distinct behavioral strategy, with coefficients cᵢ regulating their influence. A quantum system not only stores them simultaneously but enables interference between them, generating new strategies via coherent blending of preferences. This forms a quantum ensemble mechanism, achievable without external Bayesian selection.</p><p><strong>Such coherence is impossible in real-valued probability spaces, where linear combinations of strategies leave the valid simplex. Only Hilbert space — with its linear, orthonormal, complex structure — permits this kind of parallelism.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYo6Nr6oPIhd-MEhaYCSzw.png" /></figure><h4>2.5 Projectors and Measurements in QRL</h4><p>After acting, the agent measures its state to gain environmental feedback. This involves projectors—mathematical objects that “collapse” the state to a specific outcome.<br> In classical learning, rewards are computed directly. In QRL, measurements introduce a probabilistic element, depending on the pre-measurement state.</p><p>Example:</p><pre>from qiskit import QuantumCircuit, Aer, execute<br>qc = QuantumCircuit(1)<br>qc.h(0)  # Superposition<br>qc.measure_all()  # Measurement<br>result = execute(qc, Aer.get_backend(&#39;qasm_simulator&#39;)).result()<br>print(result.get_counts())  # Probability distribution</pre><p>This code shows how measurement yields a probabilistic reward or action choice</p><p><strong>Detailed line-by-line comments:</strong></p><p>from qiskit import QuantumCircuit, Aer, execute — Imports necessary modules<br> qc = QuantumCircuit(1) — Initializes a 1-qubit circuit<br> qc.h(0) — Creates superposition<br> qc.measure_all() — Measures the qubit<br> result = execute(...) — Runs the circuit on a simulator<br> print(result.get_counts()) — Outputs measurement probabilities</p><p>Projectors in Hilbert space H, realized through qc.measure_all(), orthogonally decompose the state vector, and understanding their idempotence is necessary for code analysis. Measurement transfers the state from H into the classical basis, and knowledge of projection operators is important for interpreting result.get_counts(). Superposition from qc.h(0) defines amplitudes in H that determine outcome probabilities, requiring space theory to connect with the QRL task. State collapse in H post-measurement depends on the orthonormality of the basis, and without this, the stochastic nature of print(result.get_counts()) cannot be understood. Simulation using execute(qc, Aer.get_backend(&#39;qasm_simulator&#39;)) relies on H as a complete space, which is critical for assessing agent feedback. The code reflects a transition from quantum uncertainty in H to a deterministic outcome, and without Hilbert space projectors, its meaning is lost.</p><p><strong>Measurement as Reduction: Observation Destroys Coherence</strong><br>In quantum systems, observation is not passive reading but reduction: it irreversibly projects the state vector onto one of the basis vectors:</p><h3>|ψ⟩ → |aᵢ⟩ with probability |⟨aᵢ|ψ⟩|²</h3><p>|ψ⟩ — represents the initial quantum state vector of the agent before measurement, written as a &quot;ket&quot; in Dirac notation. This state is typically a superposition (e.g., |ψ⟩ = Σᵢ αᵢ |aᵢ⟩), encoding multiple possibilities with complex amplitudes αᵢ. It exists in Hilbert space and carries coherent information through its phases and amplitudes. In quantum reinforcement learning, |ψ⟩ encodes the agent’s policy as a coherent strategy across many possibilities, enabling parallel evaluation of actions before selection.</p><p>→ — indicates the process of quantum measurement, known as state reduction or collapse. Unlike classical observation, which simply reads a value, this arrow signifies an irreversible transformation of |ψ⟩ into a single basis state, triggered by interaction with the environment or an observer. In quantum reinforcement learning, this corresponds to action selection or outcome realization, where the agent’s policy collapses into a specific decision due to environmental feedback.</p><p>|aᵢ⟩ — denotes the specific basis state onto which |ψ⟩ collapses, written as a &quot;ket.&quot; Each |aᵢ⟩ is an eigenvector of the measurement operator (e.g., a projector), representing one possible outcome (e.g., a specific action or state). These basis states are orthonormal (⟨aᵢ|aⱼ⟩ = 0 if i ≠ j, and 1 if i = j), forming a complete set in Hilbert space. In quantum QRL |aᵢ⟩ represents a particular action the agent might take when its state is measured.</p><p>|⟨aᵢ|ψ⟩|² — calculates the probability of the state |ψ⟩ collapsing to |aᵢ⟩. Here, ⟨aᵢ| is the &quot;bra&quot; of |aᵢ⟩, and ⟨aᵢ|ψ⟩ is the inner product, yielding the amplitude αᵢ of |aᵢ⟩ in |ψ⟩. The squared magnitude |⟨aᵢ|ψ⟩|² = |αᵢ|² (a real number between 0 and 1) follows the Born rule, determining the likelihood of this outcome. In quantum reinforcement learning, this represents the probability of the agent choosing a specific action under policy |ψ⟩.</p><p>with probability — specifies that the collapse |ψ⟩ → |aᵢ⟩ is probabilistic, not deterministic. The measurement process randomly selects one |aᵢ⟩ from the superposition, with the chance of each outcome governed by |⟨aᵢ|ψ⟩|². This randomness is inherent to quantum mechanics and contrasts with classical sampling, where probabilities don&#39;t involve coherence. In quantum reinforcement learning it introduces non-classical exploration mechanisms through collapse-induced stochasticity.</p><p>|ψ⟩ → |aᵢ⟩ with probability |⟨aᵢ|ψ⟩|² — encapsulates the full measurement process: the state |ψ⟩ reduces to |aᵢ⟩ upon observation, with the probability of this event given by |⟨aᵢ|ψ⟩|². This collapse discards all other components of |ψ⟩, destroying its coherence and irreversibly altering the agent&#39;s state. In QRL this measurement marks the point of decision or environmental interaction, transitioning the agent from quantum superposition to classical outcome.</p><p>Collapse results from the action of projectors — self-adjoint operators that are orthogonal and idempotent. A projector is only defined in Hilbert space, as a mapping onto a subspace. Collapse discards information: all phases and coherent components outside the chosen basis vanish. Hence, reduction is an irreversible loss of information, explainable only through orthogonal decomposition — not through ordinary sampling.</p><p><strong>This has deep consequences: observation not only informs the agent — it transforms the agent. Only Hilbert space permits a rigorous mathematical description of this transformation via projectors and orthonormal bases.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYo6Nr6oPIhd-MEhaYCSzw.png" /></figure><h4>2.6 Spectral Theorem in QRL</h4><p>The spectral theorem states that any Hermitian operator can be decomposed into basis states and eigenvalues. In QRL, this aids in analyzing rewards and optimizing strategies.<br> An agent’s reward is broken down into components tied to different states, useful for quantum algorithms like variational methods that refine strategies.</p><p>Example:</p><pre>from qiskit.quantum_info import Operator<br>I = Operator([[1, 0], [0, 1]])<br>X = Operator([[0, 1], [1, 0]])<br>H = 0.5 * (I + X)  # Reward operator<br>print(H)</pre><p>This operator models a reward dependent on the qubit’s state</p><p><strong>Detailed line-by-line comments:</strong></p><p>from qiskit.quantum_info import Operator — Imports Operator class<br> I = Operator([[1, 0], [0, 1]]) — Defines the identity operator<br> X = Operator([[0, 1], [1, 0]]) — Defines the Pauli X operator<br> H = 0.5 * (I + X) — Constructs a custom operator (e.g., for reward)<br> print(H) — Displays the operator matrix</p><p>The spectral theorem in Hilbert space asserts that Hermitian operators, such as H = 0.5 * (I + X), are diagonalizable in the basis of H, and this knowledge is essential for code analysis. The eigenvalues of an operator in H determine possible rewards, and their decomposition is crucial for understanding print(H) in the QRL context. Operators I and X in H form a linear combination, and without a spectral approach, one cannot interpret the resulting matrix as a function of the agent&#39;s state. The state vector in H projects onto the eigenvectors of the operator, requiring understanding of basis orthogonality to connect with the optimization task. The code models reward as an observable quantity in H, and knowing the spectral theorem enables linking it to quantum algorithms. Hilbert space theory explains how operator decomposition in H simplifies strategy analysis, which is otherwise inaccessible without this mathematical framework.</p><p><strong>Policy Optimization Through Environment Operator Spectra</strong><br>A quantum agent doesn’t merely update weights — it seeks a state that is an eigenvector of the reward operator with the maximal eigenvalue. This is a problem of spectral optimization:</p><h3>R |ψ_opt⟩ = r_max |ψ_opt⟩</h3><p>R — represents the reward operator, a Hermitian operator in Hilbert space (previously seen as R = Σᵢ rᵢ |rᵢ⟩⟨rᵢ| in spectral form). This operator encodes the environment&#39;s reward structure, and its eigenvalues rᵢ are the possible reward values. In QRL the agent optimizes its strategy by aligning with R&#39;s spectral properties, not by adjusting weights as in classical methods—making use of operator-based optimization principles.</p><p>|ψ_opt⟩ — denotes the optimal quantum state vector of the agent, written as a ket. This is the ideal strategy the agent seeks, an eigenvector of R corresponding to its maximal eigenvalue. Unlike a classical policy (a probability distribution), |ψ_opt⟩ is a coherent state in Hilbert space that maximizes the expected reward when acted upon by R. In quantum reinforcement learning this state reflects full exploitation of the reward structure via alignment with the optimal spectral direction.</p><p>R |ψ_opt⟩ — applies the reward operator R to the state |ψ_opt⟩. Since |ψ_opt⟩ is an eigenvector of R, this operation scales |ψ_opt⟩ by its associated eigenvalue: R |ψ_opt⟩ = r_max |ψ_opt⟩. This reflects the eigen-equation, where the action of R doesn&#39;t rotate or distort |ψ_opt⟩, only amplifies it by r_max. In QRL this reveals that the agent&#39;s chosen strategy perfectly aligns with the maximal reward response.</p><p>r_max — represents the maximal eigenvalue of the Hermitian operator R. As R is Hermitian, all its eigenvalues rᵢ are real, and r_max is the largest among them. This value is the highest possible reward achievable, and the agent&#39;s goal is to find the corresponding eigenvector |ψ_opt⟩ to maximize its performance. In QRL finding r_max corresponds to identifying the best achievable return encoded in the reward operator’s spectrum.</p><p>|ψ_opt⟩ (on the right side) — indicates that after applying R, the resulting state is proportional to the original |ψ_opt⟩. The equality R |ψ_opt⟩ = r_max |ψ_opt⟩ confirms that |ψ_opt⟩ is indeed an eigenvector, unchanged in direction but scaled by r_max, aligning the agent&#39;s strategy with the environment&#39;s optimal reward condition. This form of quantum policy optimality replaces classical convergence through trial-and-error.</p><p>R |ψ_opt⟩ = r_max |ψ_opt⟩ — defines the spectral optimization goal: the agent seeks a state |ψ_opt⟩ that satisfies this eigenvalue equation, where R acting on |ψ_opt⟩ yields the maximum reward r_max. This is a quantum optimization problem, leveraging the operator&#39;s spectrum rather than iterative weight updates, and serves as a foundational target condition in QRL models.</p><p>Such solutions are only possible given a Hermitian operator and full spectral decomposition — structures that exist exclusively in Hilbert space. This enables tools from functional analysis: variational principles, the Rayleigh theorem, and quantum versions of the conjugate gradient method — none of which translate into probabilistic spaces without losing physical meaning.</p><p><strong>Hilbert space becomes more than just a repository of state vectors — it is an <em>analytic instrument</em>, unifying the objective function, agent strategy, and environment dynamics into a single mathematical framework.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYo6Nr6oPIhd-MEhaYCSzw.png" /></figure><h4>Thus, Hilbert space and its properties underpin QRL because:</h4><ul><li>System states are quantum vectors describing the agent’s strategies.</li><li>Observable operators define actions and rewards via measurements.</li><li>System evolution updates the agent’s state with gates.</li><li>Superposition encodes multiple strategies simultaneously.</li><li>Projectors and measurements provide probabilistic action and reward outcomes.</li><li>The spectral theorem decomposes rewards, enhancing strategies via quantum algorithms.</li></ul><p>All these elements tie into Hilbert space, making QRL in Qiskit a powerful tool for quantum computing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*PQyF1vEnsnwW1UYJboi4zw.png" /></figure><h3><strong>3. To what extent does a Qiskit programmer need to understand Hilbert space nuances?</strong></h3><blockquote>For a programmer working with Qiskit (IBM’s quantum computing library), understanding Hilbert space nuances is required at a <strong>basic or intermediate</strong> level, depending on the task. Qiskit abstracts many quantum mechanics details, offering a high-level interface for building quantum circuits, running simulations, and using real quantum devices. However, a grasp of Hilbert space basics aids in effective work and result interpretation.</blockquote><h3>🟣<strong>Basic Level (Required):</strong></h3><ul><li>Understanding that quantum states are vectors (or density operators) in a Hilbert space H.</li><li>Knowledge of basis concepts (e.g., computational basis |0⟩ and |1⟩) and superposition.</li><li>Awareness that unitary operators (gates) transform states in this space.</li><li>Basics of measurements: probabilities arise from projections onto basis states.</li></ul><p>This suffices for creating simple circuits, running them on simulators or devices, and analyzing outcomes (e.g., probability histograms).</p><h3>🟡<strong>Intermediate Level (Desirable for Complex Tasks):</strong></h3><ul><li>Understanding tensor products for multi-qubit systems (e.g., H^n for n qubits).</li><li>Knowledge of density operators for mixed states and noisy systems.</li><li>Ability to interpret state evolution via quantum channels or unitary transformations.</li><li>Insight into how finite Hilbert space dimensionality (2^n for n qubits) affects computations.</li></ul><p>This is key for developing algorithms (e.g., quantum teleportation, Shor’s algorithm) or optimizing circuits.</p><h3>🟢<strong>Advanced Level (Optional):</strong></h3><ul><li>Detailed grasp of Hilbert space properties (e.g., separability, orthonormality, completeness).</li><li>Work with infinite-dimensional spaces (rare in Qiskit, which focuses on finite qubit systems).</li><li>Operator theory (e.g., spectral decomposition, complete positivity).</li></ul><p>This is only needed for research or building new low-level tools, not typical Qiskit use.</p><p>Thus, a Qiskit programmer needs basic Hilbert space knowledge (vectors, bases, unitarity) to start, while an intermediate level (tensor products, density operators) unlocks more complex tasks. Deep nuances are typically unnecessary, as Qiskit hides them behind its API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dw0v4TZv09zNP0oGXR7uQ.png" /></figure><h3><strong>To what extent does working with quantum MDP require understanding Hilbert space nuances?</strong></h3><blockquote>Working with quantum Markov Decision Processes (q-MDP) demands a <strong>deeper Hilbert space understanding</strong> than Qiskit programming. As a theoretical model blending quantum mechanics and control theory, q-MDP relies heavily on Hilbert space formalism. The required knowledge level depends on whether you’re doing theoretical analysis, algorithm development, or implementation.</blockquote><h3>🔵Basic Level (Minimally Required):</h3><ul><li>Understanding that q-MDP states are density operators in a Hilbert space D(H).</li><li>Knowledge that actions and transitions are modeled by quantum channels (superoperators) between Hilbert spaces.</li><li>Awareness of how expectations are computed (via operator trace) and how states evolve through quantum channels.</li></ul><p>This is enough for a conceptual grasp of q-MDP and surface-level document reading.</p><h3>🟡Intermediate Level (Needed for Practical Work):</h3><ul><li>Knowledge of finite-dimensional Hilbert spaces (e.g., H_X and H_A).</li><li>Understanding tensor products for joint states and actions (e.g., H_X ⊗ H_A).</li><li>Ability to work with quantum channels in Kraus representation and their properties (complete positivity, trace preservation).</li><li>Familiarity with partial trace as an analog to classical marginalization.</li><li>Insight into pure vs. mixed states and their roles in q-MDP.</li></ul><p>This is essential for practical implementation (e.g., simulations) or structural analysis (e.g., open vs. closed policies).</p><h3>🟢Advanced Level (Required for Theoretical Analysis):</h3><ul><li>Detailed understanding of Hilbert space properties (separability, orthonormal bases, dimensionality) and their impact on q-MDP.</li><li>Knowledge of quantum policy structures (e.g., open vs. state-preserving closed policies) and their ties to operators in H_X ⊗ H_A.</li><li>Ability to prove theorems like the verification theorem, requiring operator and channel analysis in Hilbert space.</li><li>Work with infinite-dimensional spaces if extending beyond finite systems.</li><li>Understanding q-MDP’s link to classical MDP via deterministic representations and quantum generalizations.</li></ul><p>This is necessary for fully grasping q-MDP, developing new algorithms (e.g., dynamic or semi-infinite programming), or exploring theoretical properties.</p><p>Thus, q-MDP work requires at least an <strong>intermediate</strong> Hilbert space understanding (density operators, quantum channels, tensor products), with <strong>advanced</strong> knowledge (space structure, channel properties, theorem proofs) for deep analysis and development. Unlike Qiskit’s <strong>practical focus</strong>, q-MDP demands <strong>greater mathematical detail</strong>.</p><p>Therefore, on our journey through the <strong>conceptual expanse</strong> of Hilbert space, we’ll bring a crucial tool: Q-MLMVN (a Qiskit-based framework inheriting MLMVN’s core principles). It will serve as our <strong>bridge</strong> between classical examples and quantum solutions in Hilbert space.</p><h3>Formation of Quantum Intuition🎓</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6Zz93zwU-rIVVbYfbDvNg.jpeg" /></figure><p>In the next <strong>QRL lesson</strong>, we’ll build a <strong>QML framework</strong> by projecting some of Aizenberg’s principles into quantum reinforcement learning, revealing their <strong>pedagogical value</strong>.</p><p><strong>Professor Aizenberg</strong> has made significant contributions to neurocomputing technologies, and this scientific legacy will aid our transition from <strong>classical</strong> to <strong>quantum computing</strong>—particularly in mastering Hilbert space concepts, a <strong>cornerstone</strong> of the quantum computational paradigm.</p><p>You can also explore <strong>Igor N. Aizenberg</strong>’s unique works on his <strong>ResearchGate</strong> page: <a href="https://www.researchgate.net/profile/Igor-Aizenberg">https://www.researchgate.net/profile/Igor-Aizenberg</a>.</p><p>MLMVN, when interpreted within the framework of Hilbert space, exhibits strong parallels to the principles of quantum computing. It operates on complex numbers, normalized states on the unit circle, multi-valued logic, and phase information — all of which align with the structure of Hilbert space. Although MLMVN is a classical system and does not involve quantum entanglement, its architecture positions it as an intermediate step between classical and quantum neural networks, especially in problems involving frequency characteristics and phase.</p><h3>1. Complex-Valued Computations and Fourier-Oriented Data</h3><p>MLMVN utilizes complex-valued weights, inputs, and outputs, and relies on frequency domain analysis (Fourier), which aligns with the properties of Hilbert space, where complex numbers and Fourier transforms are natural tools.</p><p>Professor Aizenberg emphasizes that complex numbers are fundamental to computation, especially in signal processing tasks in the frequency domain, where both magnitude and phase are crucial. MLMVN inherently uses phase information, making it highly suitable for Fourier data processing.</p><p>The Fourier transform projects signals into the basis of Hilbert space, where MLMVN can effectively operate on both phase and amplitude.</p><p>Hilbert space includes complex functions such as exponentials e^(iωt), which serve as the basis for Fourier decomposition. MLMVN, by operating with complex values, works effectively in this space, representing frequency components of signals as vectors with complex amplitudes.</p><h3>2. MVN Unit Circle and the Bloch Sphere</h3><p>The inputs and outputs of a Multi-Valued Neuron (MVN) lie on the unit circle in the complex plane, analogous to the Bloch sphere in quantum computing, where quantum states reside on the surface of a unit sphere.</p><p>Professor Aizenberg describes that the MVN activation function depends solely on the phase of the weighted sum, and values are constrained to the unit circle (|z| = 1), restricting states to discrete points.</p><p>The unit circle is a 2D subset of Hilbert space, while the Bloch sphere is 3D. In both cases, the state is defined by an angle (phase), revealing the geometric closeness of MVNs to quantum systems.</p><p>In Hilbert space, state vectors are often normalized (&lt;ψ|ψ&gt; = 1), which corresponds to the unit circle in the complex plane. MVNs, by constraining outputs to this set, model normalized states where the phase acts as a coordinate in this space.</p><h3>3. Multi-Valued Logic and Superposition</h3><p>MVN’s multi-valued logic (k-valued threshold logic) allows a single neuron to represent multiple states, analogous to quantum superposition in Hilbert space, where a system exists in a combination of basis states.</p><p>Professor Aizenberg explains that MVNs implement multi-valued threshold functions over complex fields, enhancing their computational power. This enables solving problems like XOR and Parity n, which require nonlinear separability.</p><p>In quantum neural networks, superposition encodes multiple states simultaneously — similar to how MVNs process k values on the unit circle.</p><p>In Hilbert space, superposition is represented as |ψ&gt; = Σ c_i |i&gt;, where c_i are complex coefficients. MVNs model a discrete analog of this, representing k states as points on a circle, equivalent to projecting a state vector onto basis directions.</p><h3>4. Derivative-Free Learning and Quantum Parallelism</h3><p>The MLMVN learning algorithm does not require differentiability of the activation function and uses an error-correction rule, echoing quantum parallelism by avoiding step-by-step optimization.</p><p>Professor Aizenberg emphasizes that MLMVN learning is based on derivative-free backpropagation and an error-correction rule, diverging from gradient descent and circumventing local minima.</p><p>Quantum computing applies parallel operations to superposed states. MLMVN bypasses derivative computation, making its process closer to global correction akin to quantum approaches.</p><p>In Hilbert space, quantum operators act on all components of the state vector simultaneously. MLMVN adjusts weights using global error corrections, imitating this process within complex vector space without local gradients.</p><h3>5. Phase Processing and Quantum Measurement</h3><p>MLMVN’s ability to process phase information aligns it with quantum systems, where phase plays a crucial role in interference and measurement.</p><p>Professor Aizenberg highlights that accurate phase processing is a strength of CVNNs, including MLMVN, especially in tasks like Fourier-phase recognition and associative memories.</p><p>In quantum computing, phase determines interference and measurement outcomes. MLMVN uses phase as a core feature, mirroring this principle.</p><p>In Hilbert space, the phase of a vector |ψ&gt; = e^(iθ) |φ&gt; influences measurement probabilities (|&lt;ψ|φ&gt;|^2). MLMVN, preserving phase on the unit circle, works with equivalent information, where phase governs the input-to-output mapping.</p><h3>6. Periodic Activation and Quantum Oscillations</h3><p>The periodic activation function in MVN-P models cyclic states, analogous to quantum oscillations, where systems evolve between states at specific frequencies.</p><p>Professor Aizenberg describes MVN-P’s function as P(z) = e^(i * 2π * floor(k * arg(z)/(2π))), mapping inputs to k discrete values on the unit circle, solving problems like XOR and Parity n.</p><p>Periodicity reflects cyclic behavior similar to wave functions in quantum systems, though applied in a classical context.</p><p>In Hilbert space, oscillations are described by unitary evolution |ψ(t)&gt; = e^(-iHt) |ψ(0)&gt;, with phase changing periodically. MVN-P models discrete cyclic transitions, representing states as points on a circle, corresponding to periodic basis functions.</p><h3>7. Unitarity and Norm Preservation in MLMVN</h3><p>Constraining MVN inputs and outputs to the unit circle and transmitting errors through normalized complex values resembles unitary transformations in quantum computing, which preserve vector norms.</p><p>Professor Aizenberg demonstrates that MVNs operate with |z| = 1, and the backpropagation rule in MLMVN adjusts weights while preserving their complex nature, ensuring learning stability.</p><p>Though MLMVN is not fully unitary, the constraint to the circle and phase operations create similarities with unitary evolution.</p><p>In Hilbert space, unitary operators preserve norm (&lt;ψ|ψ&gt; = 1). MVN’s unit circle ensures output normalization, and weight correction maintains this structure, resembling unitary transformations of state vectors.</p><h3>8. High Functionality and Quantum Speedup</h3><p>The high functionality of MVNs — where one neuron solves tasks requiring many classical neurons — parallels quantum speedup, where a single quantum state replaces many classical ones.</p><p>Professor Aizenberg highlights MVN’s ability to solve nonlinearly separable problems (e.g., XOR, Parity n) through complex weights and multi-valued logic. MLMVN scales this capability further.</p><p>MVNs demonstrate computation “compactness,” increasing the information capacity of a single neuron.</p><p>In Hilbert space, superposition (|ψ&gt; = Σ c_i |i&gt;) allows one vector to encode an exponential number of states. MVNs, using k values in complex space, model analogous compactness by encoding complex relationships in one vector.</p><h3>9. Associative Memory and Quantum Correlation</h3><p>MVN-based associative memories that use phase to store and retrieve patterns resemble quantum correlations, where states are related through interference.</p><p>Professor Aizenberg describes implementations of associative memories (CNN-MVN, Hopfield MVN), where phase encodes data, enabling recovery of distorted patterns.</p><p>MVNs use phase as a “correlation marker,” bringing them closer to quantum models, though without entanglement.</p><p>In Hilbert space, correlations between states are defined via the inner product (&lt;ψ|φ&gt;), which depends on phase. MVN-based memories use phase for similarity computation, equivalent to vector projection in this space.</p><h3>10. Energy-Based Interpretation and Quantum Hamiltonian</h3><p>MLMVN learning through error minimization resembles energy minimization in quantum systems, where dynamics are governed by the Hamiltonian.</p><p>Professor Aizenberg outlines MLMVN’s learning algorithm that minimizes error via error-correction rules without gradients, differing from classical energy minimization.</p><p>The learning process through global error correction parallels the search for an optimal state.</p><p>In Hilbert space, the Hamiltonian H drives evolution (iℏ d/dt |ψ&gt; = H |ψ&gt;), minimizing system energy. MLMVN minimizes error in complex space, imitating the search for a stable state, albeit without an explicit H operator.</p><h3>Advantages of the MLMVN Topology over the Approach Derivable from Cover’s Theorem (Cover’s Approach) in Terms of Hilbert Space and Similarity to QNN</h3><p>Cover’s theorem asserts that the probability of linear separability increases when data is projected into a higher-dimensional space. MLMVN offers an alternative approach, interpretable through Hilbert space and comparable to quantum neural networks (QNN). Below are the advantages of the MLMVN topology over Cover’s approach:</p><h4>✅ Efficient Use of Low-Dimensional Hilbert Space</h4><ul><li><strong>Description</strong>: MLMVN solves non-linearly separable problems (e.g., Parity n) with fewer neurons and <strong>without</strong> increasing dimensionality. This is achieved using the unit circle topology and the multivalued logic of MVN.</li><li><strong>Hilbert Space</strong>: instead of projecting data into high-dimensional ℝⁿ (as in Cover’s theorem), MLMVN operates in complex Hilbert space ℂⁿ with normalized states (|z| = 1). The unit circle is a subset of ℂ, where a single neuron effectively encodes nonlinear dependencies via phase.</li><li><strong>Similarity to QNN</strong>: in QNN, superposition (ψ = Σ cᵢ |i⟩) encodes exponentially more information in a fixed number of qubits, without dimensional growth. MLMVN similarly uses phase and multivaluedness for compact data representation in low-dimensional space.</li></ul><h4>✅ Unitary Topology Instead of Kernel Methods</h4><ul><li><strong>Description</strong>: SVMs based on Cover’s theorem use kernel functions for implicit projection into higher-dimensional space. MLMVN instead uses the unit circle topology, adjusting weights through unitary transformations.</li><li><strong>Hilbert Space</strong>: weight adjustment along the unit circle is a unitary transformation (U†U = I), preserving vector norms in ℂⁿ. This contrasts with kernel methods, which increase dimensionality through scalar products in L².</li><li><strong>Similarity to QNN</strong>: Quantum gates perform unitary operations that preserve norm in Hilbert space. The MLMVN topology, constrained to the unit circle, mimics this behavior, ensuring stability without requiring kernel lifting.</li></ul><h4>✅ Phase Compactness vs Dimensional Expansion</h4><ul><li><strong>Description</strong>: Cover’s theorem relies on increasing dimensionality for separability. MLMVN, however, encodes complex dependencies via phase on the unit circle.</li><li><strong>Hilbert Space</strong>: in ℂⁿ, the phase of a complex number (arg(z)) acts as an extra coordinate. One neuron can represent k states without increasing dimensions, using a basis like {e^(i2πj/k)} in Hilbert space.</li><li><strong>Similarity to QNN</strong>: in QNN, phase governs interference and superposition, enabling compact encoding in a fixed number of qubits. MLMVN uses phase in a similar way, avoiding the dimensional expansion typical of Cover’s approach.</li></ul><h4>✅ Parallelism Through Multivaluedness</h4><ul><li><strong>Description</strong>: MVN with k-valued logic allows one neuron to process multiple states at once. Cover’s linear separation needs additional neurons for such behavior.</li><li><strong>Hilbert Space</strong>: Multivaluedness corresponds to discrete superposition in ℂⁿ, where the state is εₖ^ⱼ = e^(i2πj/k), projecting onto a finite orthonormal basis.</li><li><strong>Similarity to QNN</strong>: Quantum parallelism allows simultaneous computation over all superposed states. MLMVN mimics this with k states per neuron, achieving efficiency without increased dimensionality.</li></ul><h4>✅ Frequency Topology as Quantum Basis</h4><ul><li><strong>Description</strong>: in the frequency domain, MLMVN uses the Fourier transform, treating first-layer neurons as convolutional filters. This eliminates the need for spatial dimensional expansion.</li><li><strong>Hilbert Space</strong>: the Fourier transform is a unitary operator in L², converting data into a basis of exponentials (e^(iωt)). MLMVN operates directly with complex frequency amplitudes — more efficient than Cover’s ℝⁿ projection.</li><li><strong>Similarity to QNN</strong>: the Quantum Fourier Transform (QFT) is central to quantum algorithms like Shor’s algorithm, operating in the frequency basis of Hilbert space. MLMVN likewise manipulates frequency, approaching quantum methods in structure.</li></ul><h3>🔍 Summary: Why MLMVN Topology Outperforms Cover’s Approach</h3><p>These five pillars demonstrate the superiority of MLMVN in the following areas:</p><ul><li><strong>Compactness</strong>: operates in low-dimensional ℂⁿ rather than high-dimensional ℝⁿ.</li><li><strong>Unitarity</strong>: uses unitary transformations instead of kernel projections.</li><li><strong>Phase Efficiency</strong>: encodes dependencies via phase, not spatial dimensions.</li><li><strong>Parallelism</strong>: Multivaluedness emulates superposition.</li><li><strong>Frequency Basis</strong>: functions in L² with Fourier components.</li></ul><blockquote><strong><em>Similarity to QNN</em></strong><em>: these properties (</em><em>unitarity, </em><em>superposition, </em><em>phase logic, </em><em>frequency basis) make </em><em>MLMVN a bridge between classical and quantum models, especially in tasks rich in </em><em>phase and </em><em>frequency-based information.</em></blockquote><h3>Comparing MLMVN to Other Neural Network Types in Terms of Similarity to Quantum Computing and QNN via Hilbert Space</h3><p>Let’s compare the multilayer neural network based on multivalued neurons (MLMVN) with other types of neural networks in the context of their similarity to quantum computing and quantum neural networks (QNN), especially through the lens of Hilbert space. We will analyze why MLMVN may be closer to quantum models than other neural networks, and what aspects distinguish it from both classical and other complex-valued architectures.</p><h3>Why is MLMVN Closer to Quantum Computing?</h3><p>MLMVN possesses unique characteristics that bring it closer to the principles of quantum computing in Hilbert space. These features, emphasized in the literature, arise from its architecture and operational principles. Let’s examine them in comparison to other neural network types:</p><p><strong>1.Complex-Valued Computation and the </strong><strong>Unit Circle</strong></p><ul><li><strong>MLMVN:</strong> uses complex-valued weights, inputs, and outputs constrained to the unit circle, resembling the Bloch sphere for qubits in Hilbert space. This enables phase modeling and multivalued state representation.</li><li><strong>Other Neural Networks:</strong> classical multilayer perceptrons (MLP) and convolutional neural networks (CNN) use real-valued numbers and lack built-in structure for complex-valued data. Even other complex-valued neural networks (CVNN), such as those described by Akira Hirose, do not always constrain states to the unit circle, weakening their geometric analogy with quantum states.</li></ul><p><strong>2.Multivalued Logic and </strong><strong>Superposition</strong></p><ul><li><strong>MLMVN:</strong> the multivalued neuron (MVN) implements k-valued logic, allowing a single neuron to encode multiple discrete states — an analogy to quantum superposition. This is particularly evident in the MVN with periodic activation (MVN-P).</li><li><strong>Other Neural Networks:</strong> classical neurons (e.g., sigmoid in MLP) are limited to binary or continuous real outputs, and cannot support multivaluedness in a single unit. Even in CVNN models like those by Tohru Nitta, activation functions are often continuous, reducing their resemblance to discrete quantum states.</li></ul><p><strong>3.Derivative-Free Learning and </strong><strong>Parallelism</strong></p><ul><li><strong>MLMVN:</strong> trains via derivative-free backpropagation and error correction rules, avoiding gradient-based methods. This parallels quantum parallelism, where global state adjustment replaces sequential updates.</li><li><strong>Other Neural Networks:</strong> most classical networks (MLP, RNN) and many CVNNs (e.g., with complex backpropagation) use gradient descent, requiring differentiable activations. This enforces sequential, iterative computation, unlike quantum dynamics.</li></ul><p><strong>4.Phase Sensitivity</strong></p><ul><li><strong>MLMVN:</strong> properly processes phase, making it suitable for tasks where phase is critical (e.g., Fourier analysis, associative memory), resembling quantum interference.</li><li><strong>Other Neural Networks:</strong> classical networks ignore phase due to their real-valued nature. Even in CVNN, phase is not always central (e.g., amplitude-based activations), distancing them from quantum models, where phase dictates measurement probabilities.</li></ul><p><strong>5.High Functionality of a Single Neuron</strong></p><ul><li><strong>MLMVN:</strong> asingle MVN can solve nonlinearly separable problems (XOR, Parity n), reducing the need for deep architectures — reminiscent of quantum acceleration via computational compactness.</li><li><strong>Other Neural Networks:</strong> a classical perceptron is limited to linear separability. MLPs require multiple layers to solve similar tasks. CVNNs like those by Akira Hirose may be more functional than real-valued models, but still lack the compact expressiveness of MVN.</li></ul><h3>Comparison with Other Neural Network Types</h3><p>To determine whether other neural networks are indeed less quantum-like than MLMVN, let’s examine the main categories:</p><p><strong>Classical Neural Networks (</strong><strong>MLP, </strong><strong>CNN, </strong><strong>RNN)</strong></p><ul><li>Operate on real numbers with no usage of complex spaces or reference to Hilbert space.</li><li>Learning via gradient descent lacks analogy to quantum parallelism.</li><li>No built-in phase processing or multivaluedness.</li><li><strong>Conclusion:</strong> significantly less similar to quantum models than MLMVN.</li></ul><p><strong>Other Complex-Valued Neural Networks (</strong><strong>CVNN)</strong></p><p>Models by researchers like Akira Hirose, Tohru Nitta, and Danilo Mandić use complex numbers, which brings them closer to Hilbert space. However:</p><ul><li>Their activation functions are often continuous (e.g., complex sigmoid), not discrete as in MVN, reducing resemblance to quantum states.</li><li>Learning generally relies on gradients (e.g., Complex Backpropagation, see p. 55), unlike the derivative-free approach of MLMVN.</li><li>Not all CVNNs constrain states to the unit circle or emphasize phase to the same degree.</li><li><strong>Conclusion:</strong> closer to quantum models than classical networks, but MLMVN surpasses them in specific aspects (discreteness, phase geometry, derivative independence).</li></ul><p><strong>Quantum Neural Networks (</strong><strong>QNN)</strong></p><ul><li>Implemented on quantum hardware, QNNs natively utilize Hilbert space, superposition, entanglement, and unitary operations (e.g., quantum gates).</li><li>MLMVN imitates some of these properties (superposition via multivaluedness, unitarity via the unit circle), but remains a classical system lacking physical entanglement.</li><li><strong>Conclusion:</strong> QNNs are inherently more quantum-like, but MLMVN acts as an intermediate model between classical CVNNs and QNNs.</li></ul><p><strong>Spiking Neural Networks (</strong><strong>SNN)</strong></p><ul><li>SNNs model biological neurons with temporal dynamics, resembling quantum oscillations. However, they typically use real values and don’t operate in complex space.</li><li><strong>Conclusion:</strong> less similar to quantum models than MLMVN due to lack of complex structure and phase processing.</li></ul><h3>Final Verdict: Are Other Neural Networks Less Quantum-Like?</h3><p>In general, other neural networks — especially classical types (MLP, CNN, RNN) — are significantly less quantum-like than MLMVN, due to the absence of complex numbers, phase sensitivity, and multivalued logic. Among CVNNs, MLMVN stands out because of:</p><ul><li>Unit circle state constraint (analogous to the Bloch sphere),</li><li>Multivalued logic and periodic activation (mirroring superposition and oscillations),</li><li>Derivative-free learning (parallel to quantum dynamics).</li></ul><p>It’s important to note that CVNNs like those of Akira Hirose or Tohru Nitta do possess quantum-like traits (e.g., complexity, potential phase processing), but their similarity is less pronounced due to continuous activations and gradient reliance.</p><p>Thus, MLMVN occupies a unique position — closer to quantum principles than most classical architectures, while still not reaching the level of true QNNs implemented on quantum hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*RzFh3_Q7tdw3BmPsDPNXaA.png" /></figure><h3>4.Hilbert Space and MLMVN</h3><h4>4.1 Metric Spaces and MLMVN</h4><p>In this section, we delve into how a multilayer neural network based on multivalent neurons (MLMVN) can be understood in terms of metric spaces, building upon their properties and connections to the network’s architecture. We begin by reviewing the formal definition of a metric space, then move on to interpreting MLMVN within this framework, focusing on input data, weights, the angular distance metric, and their role in learning. Finally, we relate these concepts to the network architecture, showing how the metric space provides the foundation for class separation and weight optimization.</p><h4>4.1.1 Metric Spaces: what are they and how to live with them?</h4><blockquote>Introduction: Why Do We Need This?</blockquote><blockquote>Imagine you want to measure how far your home is from school or how different two people are in their music tastes. In everyday life, we constantly measure things: distances, time, differences. Mathematics also has a way to measure “distances” between objects, and this is called <strong>a metric space</strong>. It’s a set of rules that help us understand how far apart things are — not just on a map, but in more abstract ways, like numbers or even sets. Let’s break it down step by step!</blockquote><h4>What Is a Metric Space?</h4><p>A metric space is simply a place (let’s call it <strong>M</strong>) where some objects (points) exist, and we have a “ruler” (called a <strong>metric</strong>, denoted as <strong>d</strong>) to measure distances between them. But for this “ruler” to work properly, it must follow three important rules:</p><ol><li><strong>Distance is zero only between the same point</strong><br> If you measure the distance between two points and get 0, it means they are the same point. For example, the distance from your home to your home is 0 meters. In mathematics: d(u, v) = 0 if and only if u = v.</li><li><strong>Triangle inequality</strong><br> Imagine you walk from home to the store and then to the park. The direct path from home to the park is always shorter (or equal to) the path through the store. In mathematics, this is written as: d(u, v) ≤ d(u, w) + d(w, v). That is, the distance from point <strong>u</strong> to point <strong>v</strong> is at most the sum of the distances through a third point <strong>w</strong>.</li><li><strong>Symmetry</strong><br> If you measure the distance from home to school, the distance from school to home is the same. In mathematics: d(u, v) = d(v, u). Distance doesn’t depend on direction.</li></ol><p>If we have a set <strong>M</strong> (for example, all points on a map) and a “ruler” <strong>d</strong> that follows these three rules, then we have a <strong>metric space</strong> — a place where distances can be measured. It is denoted as (M, d).</p><h4>A Real-Life Example: A City Map</h4><p>Let’s say <strong>M</strong> represents all the houses in your city, and <strong>d(u, v)</strong> is the distance in kilometers between houses <strong>u</strong> and <strong>v</strong>.</p><ul><li>If <strong>u</strong> and <strong>v</strong> are the same house, then d(u, v) = 0.</li><li>If you walk from house <strong>u</strong> to house <strong>v</strong> through another house <strong>w</strong>, the direct path is shorter or equal: d(u, v) ≤ d(u, w) + d(w, v).</li><li>And the distance from <strong>u</strong> to <strong>v</strong> is the same as from <strong>v</strong> to <strong>u</strong>.<br> This is a metric space!</li></ul><h4>Examples of Metric Spaces</h4><p>Now, let’s explore some examples in a way that even a child would understand.</p><p><strong>Example 1.1.1: Euclidean Space (A Normal Ruler)</strong></p><p>Take <strong>M</strong> as all points in a three-dimensional world (like coordinates on a map: latitude, longitude, altitude). This is called <strong>ℝ³</strong> (three-dimensional space). The metric here is the usual distance, like between two points on paper. The formula is:</p><pre>d(x, y) = √((x₁ - y₁)² + (x₂ - y₂)² + (x₃ - y₃)²)</pre><p>If you have point x = (1, 2, 3) and point y = (4, 6, 8), then the distance is:</p><pre>d(x, y) = √((1-4)² + (2-6)² + (3-8)²) = √(9 + 16 + 25) = √50 ≈ 7.07</pre><p>This is like measuring the number of meters between two lamp posts in a park.</p><p><strong>Checking the rules:</strong></p><ul><li>d(x, x) = 0, because if x = y, all differences are zero.</li><li>Triangle inequality holds (the direct path is shorter).</li><li>d(x, y) = d(y, x), since subtraction order doesn’t change the result inside the square root.<br> This is a metric space, and it’s even &quot;complete&quot; (more on that later).</li></ul><p><strong>Example 1.1.2: Strange Metrics</strong></p><p>Let’s take any set <strong>M</strong> (for example, all your friends). Define distance as follows:</p><p>d₁(u, v) = 1 if u ≠ v (different friends), and 0 if u = v (same friend).</p><p><strong>Checking:</strong></p><ul><li>d₁(u, u) = 0, and if u ≠ v, then d₁(u, v) = 1—Rule 1 holds.</li><li>d₁(u, v) ≤ d₁(u, w) + d₁(w, v): If u ≠ v, the left side is 1, and the right side is either 1+1=2 or 1+0=1—it works.</li><li>d₁(u, v) = d₁(v, u)—yes, always symmetric.<br> This is a metric space! It’s like saying, &quot;All different friends are 1 unit apart.&quot;</li></ul><p>Another “ruler,” d₂(u, v) = ∞ if u ≠ v, and 0 if u = v, doesn’t work because distances must be numbers, not infinity.</p><p><strong>Example 1.1.3: distance Between Clusters of Points (Hausdorff Metric)</strong></p><p>Now imagine you have two piles of candies on a table: pile <strong>A</strong> and pile <strong>B</strong>. How do you measure how “far apart” they are? The <strong>Hausdorff metric</strong> says:</p><ul><li>Find how far the farthest candy in <strong>A</strong> is from the closest candy in <strong>B</strong>, and vice versa.</li><li>Take the maximum of these two numbers.</li></ul><p><strong>Formula:</strong></p><pre>d(A, B) = max{sup inf |x - y| for x∈A, y∈B; sup inf |x - y| for x∈B, y∈A}</pre><p>In simple terms:</p><ul><li>sup is the largest distance.</li><li>inf is the smallest distance.<br> Example: if <strong>A</strong> is a circle of radius 1, and <strong>B</strong> is a square of side 2, their distance is determined by their edges. It’s complicated, but trust me—it’s a metric, and even &quot;complete.&quot;</li></ul><p><strong>Example 1.1.4: Fréchet-Nikodym Metric</strong></p><p>Imagine you have two paint blobs on a piece of paper: <strong>A</strong> and <strong>B</strong>. The distance between them is the area where they don’t overlap (A Δ B).</p><p><strong>Formula:</strong></p><pre>d(A, B) = λ(A Δ B)</pre><p>where λ is the measure (area).</p><ul><li>If the blobs are identical, d = 0.</li><li>If they differ, measure the area of their difference.<br> This is also a metric space, and it’s “complete.”</li></ul><h4>What Is “Completeness”?</h4><p>A <strong>complete</strong> metric space is a place where all “roads” lead somewhere inside it. Imagine you’re walking on a path, and it suddenly ends in a cliff — that’s an <strong>incomplete</strong> space. But if all paths lead to some point inside, the space is <strong>complete</strong>.</p><p>Mathematically: if points keep getting closer (a fundamental sequence), they must converge to some point inside the space.</p><ul><li>In Example 1.1.1 (ℝ³), this works: if points get closer, they must reach a limit inside the space.</li><li>In Examples 1.1.3 and 1.1.4, it’s also proven that they are complete (just take my word for it).</li></ul><h4>Practice Problems</h4><ol><li><strong>Problem 1.1.1</strong>: prove that the following “rulers” work as metrics:</li></ol><pre>d₁(x, y) = d(x, y) / (1 + d(x, y))<br>d₂(x, y) = ln(1 + d(x, y))<br>d₃(x, y) = min{1, d(x, y)}</pre><ul><li>Check the three rules for each!</li><li><strong>Problem 1.1.2</strong>: compute the distance between a circle of radius 1 and a square of side 2 using the Hausdorff and Fréchet-Nikodym metrics.<br> Hint: draw them and think about their edges.</li><li><strong>Problems 1.1.3</strong>: verify different “rulers” for numbers, functions, and random variables.</li></ul><p>Now, let’s review what we’ve learned for reinforcement and delve deeper into the topic of metric spaces in a more mathematical form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*c29b57KlX0uUfII8IF1VTA.png" /></figure><h3>4.1.2 Metric Spaces: measuring everything around us!</h3><h4>What Is a “Space” in Mathematics?</h4><p>Before diving into metric spaces, let’s first understand what mathematicians mean by the word “space.” Forget, for a moment, about outer space or the room you’re sitting in. In mathematics, a <em>space</em> is primarily a set of certain objects, which we call <em>points</em> or <em>elements</em>, along with some structure or “rules of the game” for these objects.</p><h4>Set (Set):</h4><p>Imagine a bag. In this bag, we can put various things: apples, stones, numbers, letters, or even other bags! A <em>set</em> is just such a “mathematical bag” — a collection of objects grouped together by some characteristic (or even without one). Examples include:</p><ul><li>The set of all integers: {..., -3, -2, -1, 0, 1, 2, 3, ...}</li><li>The set of letters in the English alphabet: {a, b, c, ..., z}</li><li>The set of all people in your city.</li><li>The set of points on a sheet of paper.</li></ul><h4>Elements (Elements) or Points (Points):</h4><p>These are the objects we “placed” in our set. In the set of integers, elements are numbers like -2, 0, 15, etc. In the set of letters, elements are &#39;а&#39;, &#39;б&#39;, &#39;в&#39;.</p><p>In a mathematical space, we often call elements <em>points</em>, even if they don’t resemble points in the usual sense. (For example, a function can also be a “point” in a function space!)</p><p>We typically denote sets with uppercase letters (X, Y, M), while their elements are written in lowercase (x, y, z). If an element x belongs to a set X, we write x ∈ X.</p><h4>Structure: Adding the Rules of the Game</h4><p>A set alone is just a collection of objects. To turn it into a <em>space</em> in the mathematical sense, we need to add some rules that connect these objects. Different rules create different types of spaces.</p><p>For <em>metric spaces</em>, the key rule is the ability to measure the <em>distance</em> between any two elements (points) in the set.</p><h4>What Is a “Metric” or “Distance”?</h4><p>Imagine you have a map of your city. There are different points on it: your home, your workplace, a store, a park. You can take a ruler and measure the distance between any two points on the map. Or, if you know the addresses, you can use a GPS navigator to find the driving distance.</p><p>In mathematics, a <strong>metric</strong> (or distance function) is exactly this kind of <em>rule</em> or <em>tool</em> that allows us to compute a number for any two points x and y in our set X. This number is called the <em>distance</em> between them. It is usually denoted as d(x, y) or using the Greek letter ρ(x, y) (read as &quot;rho of x and y&quot;).</p><h4>Important:</h4><blockquote>This distance must always be a <strong>non-negative real number</strong>. That is, it cannot be less than zero. The minimum possible distance is 0.</blockquote><h4>Metric Axioms: The Rules of “Fair” Distance</h4><p>For our “measurement rule” d(x, y) to be called a true <strong>metric</strong>, it must obey three strict rules, known as the <strong>axioms of a metric</strong>. These rules may seem obvious when thinking about ordinary distance, but they are very important for mathematical rigor.</p><p>Let’s examine these axioms in detail. Suppose we have a set X, and we have come up with some function d that assigns a number d(x, y) to every pair of elements x, y from X. This function d will be a <strong>metric</strong> if the following conditions hold for ANY elements x, y, z from the set X:</p><h4>🔹 Axiom of Non-negativity and Identity</h4><ul><li>d(x, y) ≥ 0 <em>(Distance cannot be negative).</em></li><li>d(x, y) = 0 <strong>if and only if</strong> x = y <em>(Distance is zero only if the points coincide. And vice versa, if the points coincide, the distance between them is zero).</em></li></ul><h4>Explanation for Beginners:</h4><p>The first part (d(x, y) ≥ 0) is obvious: you cannot travel &quot;-5 kilometers&quot; from home to the store. Distance is either zero (if you are already at the store) or a positive number.</p><p>The second part (d(x, y) = 0 ⇔ x = y) is also logical. If the distance from point A to point B is zero, then A and B are actually the same point. If you measure the distance from point A to itself, it is, of course, zero.</p><p>The symbol ⇔ means <strong>&quot;if and only if&quot;</strong>, meaning the condition works both ways.</p><h4>🔸 Axiom of Symmetry</h4><ul><li>d(x, y) = d(y, x) <em>(The distance from </em><em>x to </em><em>y is exactly the same as the distance from </em><em>y to </em><em>x).</em></li></ul><h4>Explanation for Beginners:</h4><p>If the distance from your home to work is <strong>5 kilometers</strong>, then the distance from work to your home is also <strong>5 kilometers</strong>. The metric must be “fair” in this regard.</p><h4>🔺 Axiom of the Triangle (Triangle Inequality)</h4><ul><li>d(x, z) ≤ d(x, y) + d(y, z) <em>(The distance between two points </em><em>x and </em><em>z cannot be greater than the sum of the distances from </em><em>x to some third point </em><em>y and from that point </em><em>y to </em><em>z).</em></li></ul><h4>Explanation for Beginners:</h4><p>This is the most interesting rule! Imagine three cities: A, B, and C. The <strong>triangle inequality</strong> says that the direct path from A to C (d(A, C)) is always <strong>no longer</strong> than the path from A to C via city B (d(A, B) + d(B, C)).</p><h4>Why “no longer” (≤) and not “strictly shorter”?</h4><p>Because point B might lie <strong>exactly on</strong> the straight line between A and C. In this case, the path A → B → C will be equal to the direct path A → C.</p><p>This axiom <strong>forbids “cutting corners” through a third point in such a way that the path becomes shorter than the direct one</strong>. The direct path is always the shortest (or equal to an indirect path if the third point lies on it).</p><p>Think of a <strong>stretched string</strong> between two points — any attempt to pull it to the side (through a third point) will only make the total length <strong>longer</strong>.</p><h4>Definition of a Metric Space</h4><p>Now we are ready to define it!</p><p>A <strong>metric space</strong> is a pair (X, d), consisting of:</p><ul><li>A <strong>non-empty set</strong> X (our points or elements).</li><li>A <strong>metric</strong> d (a distance function) defined on this set X (i.e., for any x, y in X, we can compute d(x, y)) that satisfies all three axioms (non-negativity and identity, symmetry, and the triangle inequality).</li></ul><p><strong>Important:</strong> The same set X can generate different metric spaces depending on the metric we define on it! For example, on a set of points in a plane, we can measure distance <strong>&quot;as the crow flies&quot;</strong> or <strong>&quot;by city blocks&quot;</strong> (as a taxi moves along the streets). These are two different metrics and thus two different metric spaces, even though the set of points is the same.</p><h4>Examples of Metric Spaces (in Detail!)</h4><p>Let’s go through specific examples to make everything crystal clear. For each example, we will define the set X and the metric d, and also verify (at least mentally) whether the axioms hold.</p><h3>Example 1: The Real Line (Standard Distance)</h3><ul><li><strong>Set </strong><strong>X:</strong> The set of all real numbers, denoted as R. This includes all numbers that can be represented on an infinite number line:</li><li>Integers (..., -2, -1, 0, 1, 2, ...)</li><li>Fractions (1/2, -3/4, 2.5)</li><li>Irrational numbers (√2, π, e)</li><li><strong>Metric </strong><strong>d:</strong> The usual distance between two numbers x and y is the absolute value of their difference:</li></ul><pre>d(x, y) = |x - y|</pre><p>The absolute value |a| gives a itself if a is non-negative, and -a if a is negative. Essentially, it always returns a non-negative result.</p><p><strong>Axiom check:</strong></p><ul><li>|x - y| &gt;= 0? ✅ Yes, absolute value is always non-negative.</li><li>|x - y| = 0? ✅ Yes, this happens only if x - y = 0, i.e., x = y</li><li>|x - y| = |-(y - x)| = |y - x|? ✅ Yes, by the properties of absolute value.</li><li>|x - z| &lt;= |x - y| + |y - z|? ✅ Yes, this is the <strong>triangle inequality</strong> for numbers.</li><li><strong>Conclusion:</strong> The pair (R, d) where d(x, y) = |x - y| is a <strong>metric space</strong>. This is the simplest and most intuitive metric space.</li></ul><h3>Example 2: The Plane (Euclidean Distance)</h3><p><strong>Set </strong><strong>X:</strong> The set of all points in the two-dimensional plane. Each point is defined by a pair of coordinates (x, y). This set is denoted as R^2 (or R × R). Example points:</p><pre>P1 = (1, 2),  P2 = (4, 6)</pre><p><strong>Metric </strong><strong>d:</strong> The usual &quot;schoolbook&quot; distance between two points P1 = (x1, y1) and P2 = (x2, y2), calculated using the Pythagorean theorem:</p><pre>d(P1, P2) = sqrt((x1 - x2)^2 + (y1 - y2)^2)</pre><ul><li>Here, sqrt(...) means the square root. We:</li><li>Find the difference along the X-axis, square it.</li><li>Find the difference along the Y-axis, square it.</li><li>Sum these squares and take the square root.</li></ul><p><strong>Axiom check:</strong></p><ul><li>The square root of a sum of squares is always <strong>non-negative</strong>. It equals zero only if x1 = x2 and y1 = y2, meaning P1 and P2 coincide. ✅</li><li>The order of points doesn’t matter:</li></ul><pre>(x1 - x2)^2 = (x2 - x1)^2</pre><ul><li>So, d(P1, P2) = d(P2, P1). ✅</li><li>The <strong>triangle inequality</strong> d(P1, P3) ≤ d(P1, P2) + d(P2, P3) holds (it can be proven mathematically via the <strong>Cauchy–Schwarz inequality</strong>, but it&#39;s also clear geometrically). ✅</li></ul><p><strong>Conclusion:</strong> The pair (R^2, d) with Euclidean metric is a <strong>metric space</strong>. This is our <strong>familiar geometry on the plane</strong>.</p><h3>Example 3: Three-Dimensional Space (and n-Dimensional Space!)</h3><p><strong>Set </strong><strong>X:</strong> The set of points in three-dimensional space R^3. Each point is a triple of coordinates P = (x, y, z). More generally, in n-dimensional space R^n, each point is a collection of n real numbers:</p><pre>P = (x1, x2, ..., xn)</pre><p><strong>Metric </strong><strong>d:</strong> The <strong>Euclidean distance</strong> generalizes as follows:</p><p>In R^3:</p><pre>d(P1, P2) = sqrt((x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2)</pre><p>In R^n:</p><pre>d(P1, P2) = sqrt((x1 - y1)^2 + (x2 - y2)^2 + ... + (xn - yn)^2)</pre><p><strong>Axiom check:</strong> As in R^2, all axioms hold. ✅</p><p><strong>Conclusion:</strong> (R^n, d) with Euclidean metric is a <strong>metric space for any </strong><strong>n = 1, 2, 3, ...</strong>.</p><h3>Example 4: The “Manhattan” Metric (City Block Distance)</h3><p>Let’s go back to the plane R^2, but define a <strong>different metric!</strong> Imagine a city with perpendicular streets (like Manhattan). You <strong>cannot</strong> walk diagonally through buildings—only along streets.</p><ul><li><strong>Set </strong><strong>X:</strong> Still R^2 (points in the plane).</li><li><strong>Metric </strong><strong>d1:</strong> The distance between P1 = (x1, y1) and P2 = (x2, y2) is the <strong>sum of the absolute differences</strong> of their coordinates:</li></ul><pre>d1(P1, P2) = |x1 - x2| + |y1 - y2|</pre><p><strong>Axiom check:</strong></p><ul><li>The sum of absolute values is non-negative and zero only if P1 = P2. ✅</li><li>|x1 - x2| + |y1 - y2| = |x2 - x1| + |y2 - y1|, so symmetry holds. ✅</li><li>The <strong>triangle inequality</strong> follows from the <strong>triangle inequality for real numbers</strong>, applied separately to x and y:</li></ul><pre>|x1 - x3| ≤ |x1 - x2| + |x2 - x3|<br>|y1 - y3| ≤ |y1 - y2| + |y2 - y3|</pre><p>Adding these, we get:</p><pre>|x1 - x3| + |y1 - y3| ≤ (|x1 - x2| + |y1 - y2|) + (|x2 - x3| + |y2 - y3|)</pre><p><strong>Conclusion:</strong> The pair (R^2, d1) with the &quot;Manhattan&quot; metric is <strong>also a metric space!</strong> Notice that the <strong>set is the same (</strong><strong>R^2), but the metric is different</strong>, leading to a <strong>different geometry</strong>. For example, a <strong>&quot;circle&quot;</strong> (the set of points equidistant from a center) in this metric looks like a <strong>square rotated 45 degrees!</strong></p><h3>Example 5: Discrete Metric (All or Nothing)</h3><p>This metric may seem strange, but it is very important in theory. It can be defined on <strong>any</strong> set X.</p><p><strong>Set X</strong>: Any non-empty set. For example, {apple, pear, orange}.</p><p><strong>Metric </strong><strong>d (discrete)</strong>:</p><ul><li>d(x, y) = 0 if x = y (if the points coincide).</li><li>d(x, y) = 1 if x ≠ y (if the points are different). The distance can only be 0 or 1.</li></ul><p><strong>Axiom Check:</strong></p><p>The values 0 and 1 are non-negative. d(x, y) = 0 if and only if x = y (by definition). ✅ Axiom 1 holds.</p><p>If x = y, then d(x, y) = 0 and d(y, x) = 0. If x ≠ y, then d(x, y) = 1 and d(y, x) = 1. Symmetry holds. ✅</p><p><strong>Triangle inequality:</strong> d(x, z) &lt;= d(x, y) + d(y, z). Consider different cases:</p><p>If x = z: Left-hand side d(x, z) = 0. The right-hand side d(x, y) + d(y, z) is always ≥ 0. The inequality 0 &lt;= ... is valid.</p><p>If x ≠ z: Left-hand side d(x, z) = 1. Now let&#39;s analyze d(x, y) + d(y, z).</p><p>If y = x, then d(x, y) = 0, so the right-hand side is 0 + d(x, z). Since x ≠ z, we get d(x, z) = 1, so 1 &lt;= 1. ✅</p><p>If y = z, then d(y, z) = 0, so the right-hand side is d(x, z) + 0. Since x ≠ z, we get d(x, z) = 1, so 1 &lt;= 1. ✅</p><p>If y ≠ x and y ≠ z, then d(x, y) = 1 and d(y, z) = 1, so d(x, y) + d(y, z) = 1 + 1 = 2. Since 1 &lt;= 2, the inequality holds. ✅</p><p><strong>Conclusion:</strong> Any set X with the discrete metric d forms a <strong>metric space</strong> (X, d). In this space, all distinct points are at a &quot;standard&quot; distance of 1 from each other.</p><h3>Example 6: Space of Continuous Functions C[a, b] (Maximum Metric)</h3><p>Now, let’s look at a more complex example where the “points” are not numbers or vectors, but entire <strong>functions</strong>!</p><p><strong>Set X</strong>: The set of all real-valued <strong>continuous</strong> functions defined on a closed interval [a, b]. Denoted as C[a, b].</p><p>A <strong>continuous function</strong> is one whose graph can be drawn <strong>without lifting the pencil</strong>. On [a, b], this means there are no &quot;jumps&quot; or &quot;holes&quot; between x = a and x = b.<br> Examples: f(x) = x^2 on [0, 1], g(x) = sin(x) on [0, 2π].</p><p><strong>Metric </strong><strong>d_max</strong>: The distance between two functions f and g in C[a, b] is defined as the <strong>maximum absolute difference</strong> over the entire interval [a, b]:</p><pre>d_max(f, g) = max |f(t) - g(t)|  for all t in [a, b]</pre><p><strong>Explanation:</strong> Imagine the graphs of f(t) and g(t) on [a, b]. At each t, we measure the vertical distance |f(t) - g(t)|. We find the largest such distance and define it as d_max(f, g).<br> (The <strong>maximum</strong> exists because we are working with continuous functions on a closed interval, guaranteed by the <strong>Weierstrass theorem</strong>.)</p><p><strong>Axiom Check:</strong></p><ul><li>max |f(t) - g(t)| is always ≥ 0 because absolute values are non-negative. If the maximum is 0, it means |f(t) - g(t)| = 0 for all t, meaning f(t) = g(t). ✅ Axiom 1 holds.</li><li>Since |f(t) - g(t)| = |g(t) - f(t)|, their maximums are equal: d_max(f, g) = d_max(g, f). ✅ Symmetry holds.</li><li><strong>Triangle inequality:</strong> d_max(f, h) &lt;= d_max(f, g) + d_max(g, h).<br> Suppose t₀ is the point where the maximum |f(t) - h(t)| is attained, i.e., d_max(f, h) = |f(t₀) - h(t₀)|.<br> Since the triangle inequality holds for real numbers:</li></ul><pre>|f(t₀) - h(t₀)| = |f(t₀) - g(t₀) + g(t₀) - h(t₀)| &lt;= |f(t₀) - g(t₀)| + |g(t₀) - h(t₀)|</pre><p>Since d_max(f, g) is the <strong>maximum</strong> of |f(t) - g(t)|, we have |f(t₀) - g(t₀)| ≤ d_max(f, g).<br> Similarly, |g(t₀) - h(t₀)| ≤ d_max(g, h).<br> Substituting these bounds:</p><pre>d_max(f, h) &lt;= d_max(f, g) + d_max(g, h)</pre><p>✅ Triangle inequality holds.</p><p><strong>Conclusion:</strong> (C[a, b], d_max) is a <strong>metric space</strong>. This metric is important because it is related to <strong>uniform convergence</strong> of functions: two functions are &quot;close&quot; in this metric if their graphs stay very close to each other <strong>over the entire interval</strong>.</p><h3>Example 7: Space C[a, b] (Integral Metric)</h3><p>Now, let’s consider the <strong>same set</strong> C[a, b], but with a <strong>different metric</strong>.</p><ul><li><strong>Set X</strong>: C[a, b] (continuous functions on [a, b]).</li><li><strong>Metric </strong><strong>d_int</strong>: The distance is defined using an <strong>integral</strong> of the absolute difference:</li></ul><pre>d_int(f, g) = ∫[a, b] |f(t) - g(t)| dt</pre><p><strong>Explanation:</strong> This measures the <strong>area between the graphs</strong> of y = f(t) and y = g(t) over [a, b]. This metric captures how much the functions differ <strong>on average</strong> over the interval.<br> Two functions can be <strong>close</strong> in this metric even if they differ greatly at a single point, as long as they are similar over most of [a, b].</p><p><strong>Axiom Check:</strong></p><ul><li>The integral of a non-negative function |f(t) - g(t)| is always ≥ 0. If the integral is 0, then |f(t) - g(t)| = 0 everywhere on [a, b], meaning f(t) = g(t). ✅ Axiom 1 holds.</li><li>Since ∫ |f(t) - g(t)| dt = ∫ |g(t) - f(t)| dt, symmetry holds. ✅</li><li><strong>Triangle inequality:</strong> d_int(f, h) &lt;= d_int(f, g) + d_int(g, h).</li></ul><pre>d_int(f, h) = ∫[a, b] |f(t) - h(t)| dt</pre><p>Using the standard inequality |A + B| ≤ |A| + |B|:</p><pre>|f(t) - h(t)| = |f(t) - g(t) + g(t) - h(t)| ≤ |f(t) - g(t)| + |g(t) - h(t)|</pre><p>Integrating both sides:</p><pre>∫[a, b] |f(t) - h(t)| dt ≤ ∫[a, b] |f(t) - g(t)| dt + ∫[a, b] |g(t) - h(t)| dt</pre><p>✅ Triangle inequality holds.</p><p><strong>Conclusion:</strong> (C[a, b], d_int) is also a <strong>metric space</strong>, but different from (C[a, b], d_max).<br> For example, two functions can be <strong>close</strong> in d_int (small area between graphs) but <strong>far</strong> in d_max (if they have a single sharp peak of difference).</p><h3>Why Does This Matter?</h3><p>The concept of <strong>metric spaces</strong> is a <strong>fundamental</strong> abstraction. It allows us to talk about <strong>closeness, convergence, and continuity</strong> in various settings — not just for numbers or points, but also for <strong>functions, sequences, and many other mathematical objects</strong>.</p><p>By studying the <strong>general properties</strong> of metric spaces, we can apply these results <strong>universally</strong> to all examples at once. This is a <strong>powerful</strong> mathematical tool that enables abstraction and generalization.</p><h3>Key Takeaways from Section 4.1.1.1:</h3><ul><li><strong>Metric space</strong> = <strong>Set</strong> + <strong>Metric</strong></li><li><strong>Metric</strong> d(x, y) is a function that measures distance between elements.</li><li><strong>Metric axioms</strong>: <strong>Non-negativity/identity</strong>, <strong>symmetry</strong>, and <strong>triangle inequality</strong>.</li><li><strong>Many different metric spaces exist</strong>:</li><li>The real line, Euclidean spaces (R^n), Manhattan and discrete metrics.</li><li>Function spaces (C[a, b]) with various metrics.</li><li><strong>A single set can generate multiple metric spaces</strong> depending on the metric used.</li></ul><p>This was our <strong>first deep dive</strong> into metric spaces. We have built the <strong>foundation</strong>. In future sections, we will expand on it, introducing <strong>new structures</strong> and exploring <strong>more advanced spaces</strong>. 🚀</p><h3>4.1.3 MLMVN in a Metric Space</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*Kxabo1dA4VmIndrjHdGZHA.png" /></figure><p>Let us now apply this concept to the MLMVN — a multilayer neural network built from multivalent neurons (MVNs). Each neuron in MLMVN operates on complex numbers, with its inputs, weights, and outputs forming a structure that fits naturally into the metric space framework.</p><p><strong>Inputs and Weights as Elements of </strong>C^(n+1)</p><p>In MLMVN, the input to each neuron is a vector x = (x_1, x_2, ..., x_n), where each x_j ∈ C and |x_j| = 1, i.e., the inputs lie on the unit circle. Similarly, the weights form a vector w = (w_0, w_1, ..., w_n), where each w_j ∈ C and |w_j| = 1, including the bias term w_0. Inputs are often extended to (1, x_1, ..., x_n) to include this bias. Hence, both inputs and weights reside in C^(n+1), a finite-dimensional Hilbert space.</p><p>The constraint |x_j| = 1 and |w_j| = 1 implies that these vectors lie on the unit sphere in C^(n+1). The information is encoded not in the magnitude but in the <strong>phase</strong> arg(z) of each complex number— a key characteristic of multivalent neurons.</p><p><strong>Angular Distance Metric</strong></p><p>Unlike the standard Euclidean metric d(x, y) = ||x - y||, MLMVN uses a metric based on the angular distance between complex phases. For two complex numbers z_1, z_2 ∈ C with |z_1| = |z_2| = 1, the distance is defined as:</p><pre>d(z_1, z_2) = |arg(z_1) - arg(z_2)|</pre><p>This metric measures the shortest angular distance between points on the unit circle in the complex plane. For example, if z_1 = e^(i * theta_1) and z_2 = e^(i * theta_2), then:</p><pre>d(z_1, z_2) = |theta_1 - theta_2| mod 2π</pre><p>In MLMVN, this metric applies to neuron outputs. Both the output y and desired output d lie on the unit circle (|y| = |d| = 1), and the learning error is the angular deviation:</p><pre>delta = d - y</pre><p>The magnitude of the error is related to |arg(d) - arg(y)|. The MLMVN learning algorithm adjusts weights to minimize this angular distance, aiming to align the output phase with the target sector on the unit circle.</p><p><strong>Example from the Learning Algorithm</strong></p><p>Consider a single neuron during training. It computes a weighted sum:</p><pre>z = w_0 + w_1 * x_1 + ... + w_n * x_n</pre><p>followed by an activation function P(z) = e^(i * 2π * k / m), where k depends on which sector arg(z) falls into. If the output y = P(z) differs from the desired d, the error delta is used to update the weights:</p><pre>w_j^(t+1) = w_j^(t) + (c / (n + 1)) * delta * conj(x_j)</pre><p>where c is the learning rate and conj(x_j) is the complex conjugate of the input. The metric d(y, d) = |arg(y) - arg(d)| guides the update to reduce phase discrepancy.</p><h4>Relation to MLMVN Architecture</h4><p>MLMVN’s architecture comprises a sequence of layers, each composed of multivalent neurons transforming input vectors into output vectors. From the metric space perspective, each layer is a mapping between metric spaces with angular distance as the metric.</p><p><strong>Mapping Between Layers</strong></p><ul><li><strong>Input layer</strong>: Inputs x = (x_1, ..., x_n) define a space M_0 = (C^n, d) with d(x, y) = sum_j |arg(x_j) - arg(y_j)|</li><li><strong>Hidden layer</strong>: Applies activations h_j = P(w_j * x), resulting in outputs h = (h_1, ..., h_m) in M_1 = (C^m, d)</li><li><strong>Output layer</strong>: Produces y = (y_1, ..., y_k) forming the output space M_2 = (C^k, d)</li></ul><p>Each mapping f: M_l -&gt; M_(l+1) preserves unit-circle constraints (|h_j| = 1, |y_j| = 1) and uses angular distance to measure vector differences. In classification, the quality of mapping is determined by how close y is to d in angular distance.</p><p><strong>Role of the Metric in Class Separation</strong></p><p>In MLMVN, class separation is based on output phase. Each class corresponds to a sector on the unit circle, and the network must map inputs to outputs with arg(y) in the correct sector. The metric d(y, d) quantitatively measures classification accuracy.</p><p>For example, in a 3-class problem, output values are:</p><pre>e^(i * 0), e^(i * 2π / 3), e^(i * 4π / 3)</pre><p>Learning minimizes |arg(y) - arg(d)| by adjusting weights across layers.</p><p><strong>Learning as Distance Minimization</strong></p><p>The backpropagation-like algorithm in MLMVN propagates the error delta through layers, updating weights to reduce the angular distance between the current and target outputs. Unlike gradient descent minimizing Euclidean norm, MLMVN employs a derivative-free correction rule:</p><pre>w -&gt; w* such that d(y(w), d) -&gt; 0</pre><h4>Illustration by Example</h4><p>Consider a simple network with one hidden layer solving a 3-class classification problem. Let the input be:</p><pre>x = (1, e^(i * π / 4), e^(i * π / 2))</pre><p>The desired output is:</p><pre>d = e^(i * 2π / 3)</pre><p>and the current output:</p><pre>y = e^(i * π / 3)</pre><p>Then:</p><ul><li>Metric:</li></ul><pre>d(y, d) = |π / 3 - 2π / 3| = π / 3</pre><ul><li>Error:</li></ul><pre>delta = d - y = e^(i * 2π / 3) - e^(i * π / 3)</pre><p>Weight updates reduce this distance iteratively. Eventually, y approaches d, and d(y, d) → 0, illustrating how the metric drives learning.</p><h4>Conclusion</h4><p>Representing MLMVN in terms of metric spaces highlights its unique nature: instead of operating on signal magnitudes, the network focuses on <strong>phases</strong>, making angular distance the natural metric. Each layer acts as a mapping between metric spaces (C^n, d), and training reduces d(y, d) to achieve effective class separation. This view not only aligns with MVN theory but also emphasizes the geometric intuition behind MLMVN architecture— making it a powerful tool for classification and prediction tasks.</p><p>If anything is unclear, contact <a href="https://www.linkedin.com/in/serhii-barskyi/"><strong>Serhii Barskyi | LinkedIn</strong></a> or carefully reread the lesson text with your AI assistant 😉</p><p>The next topic is <strong>Linear Spaces and MLMVN</strong>. Follow the link and take the next step toward mastering <strong>Hilbert Spaces</strong> before diving into <strong>Quantum Reinforcement Learning</strong>. Good luck<a href="https://neuverso.ai/">!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbG-a8CfANkU-sNz2q0b-A.png" /></figure><h3>Announcement of the next lesson “<strong>Linear Spaces and MLMVN”</strong></h3><p>Linear spaces are a fundamental mathematical tool that allow us to describe vectors and their transformations, opening doors to the worlds of data analysis, physics, and even artificial intelligence. They become especially powerful when extended into Hilbert spaces, where the introduction of an inner product enables the measurement of distances and angles, adding depth and geometry to the linear world.</p><p>In quantum reinforcement learning, these spaces come to life: the agent’s states are represented as vectors in a Hilbert space, evolving through elegant unitary transformations, like a dance of quantum possibilities. Hermitian operators acting in this space determine what the agent “sees” and how it evaluates its chances, bridging abstract mathematics with real-world decision-making. Thus, through Hilbert spaces, linear spaces serve as a bridge between classical theory and quantum computing, making learning not just intelligent, but truly revolutionary.</p><p>🚀<strong>Follow the link: </strong>Coming soon</p><p>🎓<strong>For Complete individual QRL development course on Qiskit and for one-on-one tutoring on machine Reinforcement Learning topics, please, contact: </strong><a href="http://linkedin.com/company/sigma-publishinq/posts/"><strong>Sigma Publishinq</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf472c78f37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Methods for Reinforcement Learning Projects]]></title>
            <link>https://medium.com/@serhii.barskyi/testing-methods-in-reinforcement-learning-projects-for-dynamics-365-6e83570b10fd?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e83570b10fd</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[neuverso]]></category>
            <category><![CDATA[dynamics-365]]></category>
            <category><![CDATA[nextbestactions]]></category>
            <category><![CDATA[serhii-barskyi]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 11:36:45 GMT</pubDate>
            <atom:updated>2026-05-02T07:33:01.288Z</atom:updated>
            <content:encoded><![CDATA[<h3>In the context of developing external RL-modules for <strong>Dynamics 365</strong></h3><p>My Data Science Course <a href="https://preply.com/en/tutor/7756455">https://preply.com/en/tutor/7756455</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFMeDgpgf_wvV8D4xr83Mg.png" /></figure><p><strong><em>*</em></strong><em>The image depicts a diagram of the main components of our RL (</em><strong><em>Reinforcement Learning</em></strong><em>) application that we will be testing.</em></p><p><em>Our testing stack for this large </em><strong><em>Testing Course</em></strong><em> includes more than 50 components — see the full description below in the section </em><strong><em>“Mapping of Testing Stack Components to Architecture Components”.</em></strong></p><h3>On this course, you will:</h3><p>👉 Write test scenario code using <strong>Python</strong> and powerful automation tools (<strong>Pytest, Unittest, Pytest-asyncio</strong>, and more).<br> 👉 Create your own innovative RL-application for a <strong>Next Best Action</strong> task with integration with <a href="https://www.microsoft.com/en-us/dynamics-365"><strong>Dynamics 365</strong></a><strong>.</strong><br> 👉 Develop test frameworks based on <strong>Page Object</strong> principles and other automation patterns.<br> 👉 Master testing components for machine learning (<strong>PyTorch, Transformers</strong>), reinforcement learning libraries (<strong>Stable-Baselines3, Gym</strong>), and data processing systems (<strong>Pandas, SQLite</strong>).<br> 👉 Learn to use profiling tools (<strong>Memory-Profiler, Line-Profiler</strong>) and report generation tools (<strong>Pytest-html, Coverage</strong>).<br> 👉 Explore test data generation (<strong>Hypothesis, Faker</strong>) and set up complex automated testing scenarios.</p><h3>Course Highlights:</h3><ol><li><strong>Practical application of skills</strong> to real-world tasks in machine learning, reinforcement learning and DevOps.</li><li>Use of <strong>modern profiling and performance monitoring tools</strong> for Python programs.</li><li>A focus on creating <strong>comprehensive tests</strong>, including integration and performance tests.</li><li>Hands-on experience with <strong>project documentation</strong> and API testing.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgzGr8MQSXVGIjt4w0m5cQ.png" /></figure><blockquote>By the end of this course, you will gain skills to automate testing for complex systems, design test frameworks, and leverage Python for ML, RL and data analysis.</blockquote><p>In the previous <a href="https://medium.com/@serhii.barskyi/teaching-dynamics-365-to-play-frozen-market-a-reinforcement-learning-approach-to-business-746ec71c799e"><strong>lesson, we discussed the prospects of expanding the ML</strong></a><strong> </strong>(Machine Learning) infrastructure of Dynamics 365 using external RL (Reinforcement Learning) modules.</p><p>In the context of improving the efficiency of the Next Best Action task for <a href="https://www.microsoft.com/en-us/dynamics-365">Dynamics 365</a> products such as <strong>Sales</strong>, <strong>Customer Insights</strong>, <strong>Supply Chain Management</strong>, <strong>Finance</strong> and <strong>Project Operations</strong>, the advantages of Reinforcement Learning can be highlighted in optimizing customer interactions and managing business processes through sequential decision-making in a dynamic environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXQDCvb0NznQNhwuAlMCSQ.png" /></figure><blockquote>Pro-code approach in Dynamics 365 allows integration of Copilot with existing X++ business logic, however, at the moment, Copilot in Dynamics 365 uses pre-trained AI models provided by Microsoft. These models are developed for general use cases and may not be specific enough for non-standard or highly specialized tasks, such as <strong>Next Best Action (NBA)</strong> in specialized industry applications.</blockquote><h3>1. Briefly about integration: Copilot plus RL</h3><p>Integration of Copilot with external applications using Reinforcement Learning (RL) through X++ in Dynamics 365 is technically possible, but requires careful configuration. Dynamics 365 provides tools for interacting with external systems through REST API, event models, and platform services such as Azure Functions or Service Bus.</p><h4>1.1 Integration Architecture</h4><p>Integration includes the following key components:</p><p><strong>Copilot:</strong> an assistant for interacting with Dynamics 365 data. It is not a programmable component, but displays recommendations and other information from the system.</p><p><strong>External RL Application:</strong> our NBA (Next Best Action) application using Reinforcement Learning algorithms to generate personalized recommendations.</p><p><strong>REST API:</strong> the main communication channel for data transfer between Dynamics 365 and the RL application.</p><p><strong>Azure Services: </strong>a middleware for routing, managing, and processing requests.</p><p><strong>X++:</strong> development language for implementing custom logic in Dynamics 365.</p><h4>1.2 Integration Action Sequence</h4><p>▫️ <strong>1.2.1 Data Definition for Transfer:</strong><br><em>defining the data structure to be transferred from Dynamics 365 to the RL application (e.g., user ID, action being performed, product metadata).</em><br>▫️ <strong>1.2.2 REST API Configuration:</strong><br><em>creating an API in the RL application to process requests and generate recommendations. Security standards (OAuth 2.0).</em><br>▫️ <strong>1.2.3 X++ Logic Development:</strong><br><em>implementing HTTP requests to transfer data and process RL application responses.</em><br>▫️ <strong>1.2.4 Azure Functions Utilization:</strong><br><em>setting up an Azure Function as an intermediate layer for data processing between Dynamics 365 and the RL application, which will simplify logic modification.</em><br>▫️ <strong>1.2.5 Event Model Configuration:</strong><br><em>setting up events in Dynamics 365 that will initiate RL application calls (for example, adding an item to the cart).</em><br>▫️ <strong>1.2.6 Testing and Monitoring:</strong><br><em>verifying correct data transfer, system performance, and error handling.</em><br>▫️ <strong>1.2.7 Secrets Management:</strong><br><em>configuring Azure Key Vault for secure storage of tokens and other confidential data.</em></p><h4><strong>1.3 Implementation Example</strong></h4><p><strong>1.3.1 Creating a REST API for the RL Application</strong><br>Example API in Python (Django + DRF):</p><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework import status<br><br>class RecommendationsView(APIView):<br>    def post(self, request):<br>        data = request.data<br>        # Process the data and call the RL model<br>        recommended_action = &quot;add_to_cart&quot;  # Example<br>        return Response({&quot;recommendedAction&quot;: recommended_action}, status=status.HTTP_200_OK)</pre><p><strong>1.3.2 X++ Configuration for API Calling</strong><br>Example code in X++:</p><pre><br><br>HttpClient httpClient = new HttpClient();<br>HttpResponseMessage response;<br>Map headers = new Map(Types::String, Types::String);<br>JsonObject jsonRequest = new JsonObject();<br>JsonObject jsonResponse;<br><br>// Setting up the URL<br>str url = &quot;https://rl-application.com/api/recommendations&quot;;<br><br>// Creating the request body<br>jsonRequest.set(&quot;userId&quot;, &quot;12345&quot;);<br>jsonRequest.set(&quot;action&quot;, &quot;added_to_cart&quot;);<br>jsonRequest.set(&quot;productId&quot;, &quot;67890&quot;);<br><br>// Setting headers<br>headers.insert(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>headers.insert(&quot;Authorization&quot;, &quot;Bearer YOUR_API_TOKEN&quot;);<br>httpClient.setHeaders(headers);<br><br>// Sending the request with error handling<br>try<br>{<br>    response = httpClient.post(url, jsonRequest.toString());<br>    if (response.isSuccessful())<br>    {<br>        jsonResponse = JsonObject::parse(response.getResponse());<br>        info(&quot;Recommendation: &quot; + jsonResponse.getValue(&quot;recommendedAction&quot;).toString());<br>    }<br>    else<br>    {<br>        error(&quot;Failed to get response: &quot; + response.getErrorMessage() + <br>              &quot;, Status code: &quot; + response.getStatusCode());<br>    }<br>}<br>catch (Exception::CLRError)<br>{<br>    error(&quot;An error occurred during the API call.&quot;);<br>}</pre><p><strong>1.3.3 Using Azure Functions</strong><br>Example function in C#:</p><pre>[FunctionName(&quot;ProcessRecommendation&quot;)]<br>public static async Task&lt;IActionResult&gt; Run(<br>    [HttpTrigger(AuthorizationLevel.Function, &quot;post&quot;, Route = null)] HttpRequest req)<br>{<br>    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();<br>    var inputData = JsonConvert.DeserializeObject&lt;dynamic&gt;(requestBody);<br><br>    // Call the RL application<br>    var rlResponse = await CallRLApp(inputData);<br>    return new OkObjectResult(rlResponse);<br>}</pre><p><strong>1.3.4 Event Model Configuration</strong><br>Configuring Power Automate or using the Dynamics 365 SDK to subscribe to events. For example, you can set up an event for adding an item to the cart and automatically send the corresponding data to the RL application through REST API.</p><p>Real-time operation, driven by reinforcement learning (RL) algorithms, remains essential for dynamic strategy adaptation as new data on customer behavior or business process metrics become available.</p><blockquote>For example, <strong>Next Best Action (NBA)</strong> in Dynamics 365 Sales or Customer Insights enables brands to deliver hyper-relevant customer experiences by analyzing individual preferences, needs, and contextual factors. This allows businesses to identify the most effective and meaningful actions to engage with customers across any channel at any time.</blockquote><p>NBA tasks that adapt to changes in customer behavior, as well as business process optimization tasks, benefit from the integration of RL algorithms within the Dynamics 365 ecosystem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GdG5yRkeqa_r1AocdoWKQ.png" /></figure><p><a href="https://www.microsoft.com/en-us/dynamics-365/products/sales"><strong>Dynamics 365 Sales</strong></a><strong> and </strong><a href="https://www.microsoft.com/en-us/dynamics-365/products/customer-insights"><strong>Customer Insights</strong></a></p><ul><li>RL modules can recommend the most suitable product or service offers to enhance customer satisfaction and maximize customer lifetime value (CLV).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dS9FoiEJrhDKbb13yzTXHg.png" /></figure><p><a href="https://www.microsoft.com/en-us/dynamics-365/products/finance"><strong>Dynamics 365 Finance</strong></a></p><ul><li>RL can optimize financial operations, such as cash flow management or cost allocation, to improve profitability and reduce financial risks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r7NLTGRY-sg6dUnnWySHzQ.png" /></figure><p><a href="https://www.microsoft.com/en-us/dynamics-365/products/supply-chain-management"><strong>Dynamics 365 Supply Chain Management</strong></a></p><ul><li>RL modules focus on streamlining inventory management, improving supply planning, and ensuring efficient logistics to reduce operational costs and enhance service reliability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLH9IHHybmHXLVKeeEgu6g.png" /></figure><p><a href="https://www.microsoft.com/en-us/dynamics-365/products/project-operations"><strong>Dynamics 365 Project Operations</strong></a></p><ul><li>RL can support project scheduling, resource allocation, and budgeting to optimize project outcomes and profitability.</li></ul><p><em>Integrating RL into these Dynamics 365 modules empowers businesses to achieve data-driven decision-making and continuous process improvements in real-time, ensuring resilience and agility in a dynamic environment.</em></p><h3><strong>2. Testing Tasks for our Reinforcement Learning Application</strong></h3><p>Now let’s touch on one of the central topics of our lesson. To help you better understand the focus of the course, let’s introduce 10 key testing challenges when developing an RL application in the context of the Next Best Action challenge for Dynamics 365.</p><blockquote><em>💡 </em>In this section we will not list all the test tasks of our course — we will only give a brief overview of the upcoming testing of the RL agent.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTzClsfCOpa_8I4UbTbXYQ.png" /><figcaption>Verification of RL Algorithm Correctness</figcaption></figure><h3>2.1 Verification of RL Algorithm Correctness</h3><p>Errors in the implementation of basic RL components (e.g., Q-table updates, gradient calculations) can lead to incorrect learning and reduced recommendation quality.<br> <strong>Methods</strong>:</p><p>2.1.1 Writing unit tests for functions responsible for updating Q-values or policies (e.g., update_Q, policy_update).</p><p>2.1.2 Testing gradient calculation correctness using analytical and numerical methods (e.g., through automatic differentiation).</p><p>2.1.3 Using predefined scenarios with fixed input data to check expected values.</p><p>2.1.4 Comparing implementation with reference implementations from popular libraries (e.g., TensorFlow or PyTorch).</p><p>2.1.5 Validating the mathematical accuracy of all operations related to learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H4hU4qtX8-K1SYgTPXXfA.png" /><figcaption>Testing Learning Stability</figcaption></figure><h3>2.2 Testing Learning Stability</h3><p>Unstable learning can lead to algorithm divergence, especially when inappropriate hyperparameters are chosen.<br> <strong>Methods</strong>:</p><p>2.2.1 Generating test sets by varying key hyperparameters (e.g., learning rate, gamma, epsilon).</p><p>2.2.2 Running learning with different initial conditions (e.g., random and fixed weights).</p><p>2.2.3 Checking trend metrics such as convergence speed and average reward.</p><p>2.2.4 Evaluating learning reproducibility on identical data with fixed initial conditions.</p><p>2.2.5 Analyzing robustness when small noise is introduced to data or parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*OZybuU37pWOT_4ag-VHsKg.png" /><figcaption>Testing State Generation Correctness</figcaption></figure><h3>2.3 Testing State Generation Correctness</h3><p>Errors in state space formation can lead to incorrect learning and erroneous actions.<br> <strong>Methods</strong>:</p><p>2.3.1 Verifying the format of generated states to meet algorithm requirements (e.g., dimensionality, data types).</p><p>2.3.2 Testing functions that transform input data into states (e.g., normalization or category splitting).</p><p>2.3.3 Validating the correctness of mapping original data to state space through visualization.</p><p>2.3.4 Using test datasets with known states for conformity checks.</p><p>2.3.5 Testing edge and exceptional cases (e.g., missing values).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfPn0E-KlK9w5ptSsQRyow.png" /><figcaption>Action Selection Verification</figcaption></figure><h3>2.4 Action Selection Verification</h3><p>Incorrect implementation of action selection strategies (e.g., ε-greedy) can reduce learning efficiency.<br> <strong>Methods</strong>:</p><p>2.4.1 Unit tests for verifying the functioning of action selection algorithms (softmax, ε-greedy strategy, Boltzmann selection).</p><p>2.4.2 Analyzing strategy behavior with boundary parameters (e.g., ε=0, ε=1).</p><p>2.4.3 Testing the correct handling of randomness in strategies (e.g., random number generation).</p><p>2.4.4 Comparing the probability distribution of selected actions with a benchmark.</p><p>2.4.5 Checking strategy robustness against changes in input parameters.</p><h3>2.5 Reward Function Validation</h3><p>Incorrect reward computation can distort learning and policy optimization.<br> <strong>Methods</strong>:</p><p>2.5.1 Writing tests for reward calculation functions on test scenarios with fixed expected outcomes.</p><p>2.5.2 Verifying algorithm behavior under extreme reward values (e.g., large positive or negative values).</p><p>2.5.3 Creating simple environments for manual reward verification (e.g., tasks with a single optimal action).</p><p>2.5.4 Analyzing reward function changes based on input data.</p><p>2.5.5 Visualizing reward trends to check their logical consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LinJGMhx7U2dRdgRZx4vQ.png" /><figcaption>Multithreading or Asynchronous Execution Testing</figcaption></figure><h3>2.6 Multithreading or Asynchronous Execution Testing</h3><p>If the RL algorithm uses parallel learning, synchronization errors can lead to crashes or incorrect learning.<br> <strong>Methods</strong>:</p><p>2.6.1 Writing tests to detect race conditions in multithreaded execution.</p><p>2.6.2 Testing correct synchronization between threads (e.g., locks).</p><p>2.6.3 Verifying the functioning of asynchronous calls (e.g., Actor-Critic methods).</p><p>2.6.4 Load testing to assess performance in a multithreaded environment.</p><p>2.6.5 Analyzing behavior during partial thread failures.</p><h3>2.7 Performance Testing</h3><p>RL algorithms can be computationally intensive, and their performance should be acceptable under real conditions.<br> <strong>Methods</strong>:</p><p>2.7.1 Measuring the execution time of key operations (e.g., Q-table updates).</p><p>2.7.2 Profiling code to identify performance bottlenecks (e.g., cProfile, PyTorch Profiler).</p><p>2.7.3 Testing scalability with increased data volumes.</p><p>2.7.4 Comparing performance with implementations from other libraries.</p><p>2.7.5 Optimizing computations through vectorization or GPU usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfplqRYTVn8TuUuN7u3KVQ.png" /><figcaption>Training Verification on Synthetic Data</figcaption></figure><h3>2.8 Training Verification on Synthetic Data</h3><p>The RL module should function correctly in conditions where the optimal policy is known in advance to confirm its validity.<br> <strong>Methods</strong>:</p><p>2.8.1 Using standard test environments (e.g., OpenAI Gym, CartPole).</p><p>2.8.2 Creating simplified environments with known optimal solutions for testing.</p><p>2.8.3 Verifying convergence of training on synthetic data.</p><p>2.8.4 Comparing learned policies with theoretically optimal ones.</p><p>2.8.5 Validating algorithm behavior in short training cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JUExMgF8CyeP-y5S64M_A.png" /><figcaption>Error Robustness Testing</figcaption></figure><h3>2.9 Error Robustness Testing</h3><p>The RL module should correctly handle incorrect data, exceptions, and failures during operation.<br> <strong>Methods</strong>:</p><p>2.9.1 Writing tests for inputting incorrect data (e.g., missing values, incorrect types).</p><p>2.9.2 Checking error handling such as division by zero or array out-of-bounds.</p><p>2.9.3 Simulating system failures to ensure data integrity is maintained.</p><p>2.9.4 Analyzing logs to identify unhandled errors.</p><p>2.9.5 Verifying the informativeness of error messages.</p><h3>2.10 Output Interpretability Verification</h3><p>To analyze the functioning of an external RL module, it is important that the learning outcomes and recommendations are understandable.<br> <strong>Methods</strong>:</p><p>2.10.1 Testing logs for content and structure.</p><p>2.10.2 Verifying learning metrics (e.g., average reward, Q-value error) for clarity.</p><p>2.10.3 Visualizing results (e.g., convergence graphs, policy changes).</p><p>2.10.4 Generating reports with algorithm behavior analysis.</p><p>2.10.5 Verifying the availability and completeness of documentation for key methods.</p><blockquote><em>✅</em> In this section, we have listed only the main tasks related to testing the RL agent itself as the primary RL component of our application.</blockquote><h3>3. Specification of a Hierarchical Reinforcement Learning Application Prototype for Demonstration in Google Colab</h3><p>We have outlined some RL testing tasks that we will explore together in this course. Now, let’s look at a brief overview of the complete architecture of our RL application for Next Best Action, integrated with Dynamics 365.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iOiopvwNn3BpL8wqTVmfA.png" /></figure><p>The architecture of the RL application we will develop together in this course implements the Next Best Action (NBA) task through computational components based on deep learning and data management. <strong>Process Model Service</strong> leverages Process-BERT to encode user action sequences into a latent space, where the context and temporal structure of the data are analyzed using attention mechanisms, enhancing the classification of behavioral patterns. <strong>KPI Prediction Service</strong>, built on a Decision Transformer, transforms sequences of states and actions into optimal metric predictions through inverse learning based on a utility maximization criterion, minimizing prediction errors for key business indicators.</p><p>The hierarchical RL agent in <strong>RL Optimization Service</strong> formalizes the decision-making process as a multi-level MDP, where upper levels address strategic tasks over large time intervals, and lower levels handle real-time operational tasks, optimizing a global objective function. <strong>Storage Service</strong> organizes data flow through distributed storage architectures with optimized indexing and caching, reducing latency for large-scale volumes. <strong>Monitoring System</strong> employs time series and deviation metrics for continuous monitoring of model errors and strategy convergence, automatically iterating parameters based on new data.</p><p>The integration of Process-BERT and Decision Transformer ensures a synergistic analysis of data, combining temporal dependencies and latent representations for unified prediction and optimization in a single computational cycle.</p><h3>3.1 Project Structure</h3><p><em>*For simplified demonstration purposes, we will implement the entire project in Google Colab.</em></p><h3>3.1.1 Archive Structure for Colab</h3><pre>hierarchical_rl.zip<br>  /src<br>    /models<br>      /process_bert<br>      /decision_transformer<br>    /services<br>      /process_model<br>      /kpi_prediction<br>      /rl_optimization<br>    /utils<br>      /monitoring<br>      /storage<br>    /tests<br>      /unit<br>      /integration<br>    /config<br>  /notebooks<br>    setup.ipynb<br>    train.ipynb<br>    evaluate.ipynb<br>  /data<br>    /processed<br>    /raw<br>  requirements.txt<br>  README.md</pre><h3>3.2 Core System Components</h3><h3>3.2.1 Process Model Service (/src/services/process_model/)</h3><h4>3.2.1.1 Main Files:</h4><ul><li>process_model_service.py - main service class</li><li>process_bert.py - Process-BERT implementation</li><li>validators.py - process validators</li><li>sqlite_storage.py - SQLite interaction</li></ul><h4>3.2.1.2 Key Classes:</h4><pre>class ProcessModelService:<br>    &quot;&quot;&quot;<br>    Main service for working with process models<br>    &quot;&quot;&quot;<br>    def __init__(self, db_path: str = &#39;:memory:&#39;):<br>        self.storage = SQLiteStorage(db_path)<br>        <br>    def extract_process_model(self, sequence_data: List[Dict]) -&gt; ProcessModel:<br>        &quot;&quot;&quot;Extract process model from a sequence&quot;&quot;&quot;<br>        pass<br>        <br>    def validate_sequence(self, sequence: List[str]) -&gt; bool:<br>        &quot;&quot;&quot;Validate a sequence of actions&quot;&quot;&quot;<br>        pass<br>        <br>    def predict_next_actions(self, current_state: Dict) -&gt; List[str]:<br>        &quot;&quot;&quot;Predict next actions&quot;&quot;&quot;<br>        pass<br>        <br>    def update_model(self, new_data: DataFrame) -&gt; None:<br>        &quot;&quot;&quot;Update the model with new data&quot;&quot;&quot;<br>        pass</pre><h3>3.2.2 KPI Prediction Service (/src/services/kpi_prediction/)</h3><h4>3.2.2.1 Main Files:</h4><ul><li>kpi_service.py - main service class</li><li>decision_transformer.py - Decision Transformer model</li><li>stream_processor.py - streaming data processor</li><li>in_memory_cache.py - in-memory caching</li></ul><h4>3.2.2.2 Key Classes:</h4><pre>class KPIPredictionService:<br>    &quot;&quot;&quot;<br>    KPI Prediction Service<br>    &quot;&quot;&quot;<br>    def __init__(self, cache_size: int = 1000):<br>        self.cache = InMemoryCache(cache_size)<br>        <br>    def predict_kpis(self, state: Dict, horizon: int) -&gt; List[Dict]:<br>        &quot;&quot;&quot;Predict KPIs for a given horizon&quot;&quot;&quot;<br>        pass<br>        <br>    def update_predictions(self, new_data: DataFrame) -&gt; None:<br>        &quot;&quot;&quot;Update predictions&quot;&quot;&quot;<br>        pass<br>        <br>    def get_real_time_metrics(self) -&gt; Dict[str, float]:<br>        &quot;&quot;&quot;Retrieve real-time metrics&quot;&quot;&quot;<br>        pass</pre><h3>3.2.3 RL Optimization Service (/src/services/rl_optimization/)</h3><h4>3.2.3.1 Main Files:</h4><ul><li>rl_service.py - main service class</li><li>hierarchical_agent.py - hierarchical RL agent</li><li>environment.py - OpenAI Gym environment</li><li>reward.py - reward system</li></ul><h4>3.2.3.2 Key Classes:</h4><pre>class HierarchicalRLAgent:<br>    &quot;&quot;&quot;<br>    Hierarchical RL Agent<br>    &quot;&quot;&quot;<br>    def __init__(self, checkpoint_dir: str = &#39;./checkpoints&#39;):<br>        self.checkpoint_dir = checkpoint_dir<br>        <br>    def select_action(self, state: Dict) -&gt; Tuple[str, float]:<br>        &quot;&quot;&quot;Select an action based on the current state&quot;&quot;&quot;<br>        pass<br>        <br>    def update_policy(self, experience: Experience) -&gt; Dict[str, float]:<br>        &quot;&quot;&quot;Update policy based on experience&quot;&quot;&quot;<br>        pass<br>        <br>    def save_checkpoint(self, path: str) -&gt; None:<br>        &quot;&quot;&quot;Save model checkpoint&quot;&quot;&quot;<br>        pass</pre><h3>3.3. Models and Algorithms</h3><h3>3.3.1 Process-BERT (/src/models/process_bert/)</h3><h4>3.3.1.1 Main Files:</h4><ul><li>model.py - model architecture</li><li>trainer.py - training logic</li><li>tokenizer.py - process tokenizer</li><li>config.py - model configuration</li></ul><h4>3.3.1.2 Key Classes:</h4><pre>class ProcessBERT(nn.Module):<br>    &quot;&quot;&quot;<br>    Transformer for process analysis (based on Hugging Face)<br>    &quot;&quot;&quot;<br>    def __init__(self, config: ProcessBERTConfig):<br>        super().__init__()<br>        self.bert = AutoModel.from_pretrained(&#39;bert-base-uncased&#39;)<br>        <br>    def forward(self, input_ids: torch.Tensor) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;Forward pass through the model&quot;&quot;&quot;<br>        pass<br>        <br>    def encode_sequence(self, sequence: List[str]) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;Encode a sequence&quot;&quot;&quot;<br>        pass</pre><h3>3.3.2 Decision Transformer (/src/models/decision_transformer/)</h3><h4>3.3.2.1 Main Files:</h4><ul><li>transformer.py - transformer architecture</li><li>memory.py - memory management</li><li>optimizer.py - optimizer</li><li>config.py - configuration</li></ul><h3>3.4 Integration Components</h3><h3>3.4.1 Storage Service (/src/services/storage/)</h3><h4>3.4.1.1 Main Files:</h4><ul><li>storage_service.py - main class</li><li>in_memory_cache.py - in-memory caching</li><li>sqlite_storage.py - SQLite storage</li><li>csv_handler.py - CSV file handler</li></ul><h4>3.4.1.2 Key Classes:</h4><pre>class StorageService:<br>    &quot;&quot;&quot;<br>    Data Storage Service<br>    &quot;&quot;&quot;<br>    def __init__(self, sqlite_path: str = &#39;:memory:&#39;, cache_size: int = 1000):<br>        self.db = SQLiteStorage(sqlite_path)<br>        self.cache = InMemoryCache(cache_size)<br>        <br>    def get_features(self, ids: List[str]) -&gt; Dict[str, np.ndarray]:<br>        &quot;&quot;&quot;Retrieve features&quot;&quot;&quot;<br>        pass<br>        <br>    def update_features(self, features: Dict[str, np.ndarray]) -&gt; None:<br>        &quot;&quot;&quot;Update features&quot;&quot;&quot;<br>        pass<br>        <br>    def batch_process(self, data: DataFrame) -&gt; None:<br>        &quot;&quot;&quot;Batch process data&quot;&quot;&quot;<br>        pass</pre><h3>3.5 Monitoring and Logging</h3><h3>3.5.1 Monitoring System (/src/utils/monitoring/)</h3><h4>3.5.1.1 Main Files:</h4><ul><li>metrics_collector.py - metric collection</li><li>visualization.py - visualization using matplotlib</li><li>logger.py - logging system</li><li>performance.py - performance monitoring</li></ul><h4>3.5.1.2 Key Classes:</h4><pre>class MetricsCollector:<br>    &quot;&quot;&quot;<br>    Metric Collection and Visualization<br>    &quot;&quot;&quot;<br>    def __init__(self, log_dir: str = &#39;./logs&#39;):<br>        self.log_dir = log_dir<br>        self.logger = setup_logger()<br>        <br>    def record_prediction(self, prediction: Dict) -&gt; None:<br>        &quot;&quot;&quot;Record a prediction&quot;&quot;&quot;<br>        pass<br>        <br>    def record_error(self, error: Exception) -&gt; None:<br>        &quot;&quot;&quot;Log an error&quot;&quot;&quot;<br>        pass<br>        <br>    def visualize_metrics(self) -&gt; None:<br>        &quot;&quot;&quot;Visualize metrics using matplotlib&quot;&quot;&quot;<br>        pass</pre><h3>4. Mapping of Testing Stack Components to Architecture Components</h3><p>🤗 And now we’ve reached our testing stack. After reviewing the stack, we’ll move on directly to the first development and testing task in accordance with the project’s planned architecture 🚀</p><h3>Core Testing Frameworks</h3><p><strong>1. pytest&gt;=6.2.5</strong><br> — Architecture Component: /tests/unit/ and /tests/integration/<br> 🛠️ testing task: Primary testing framework for all unit and integration tests across the project</p><p><strong>2. unittest</strong><br> — Architecture Component: /tests/unit/, especially TestProcessBERT and TestServiceIntegration classes<br> 🛠️ testing task: base testing functionality for all test classes in the project</p><p><strong>3. pytest-asyncio&gt;=0.16.0</strong><br> — Architecture Component: /src/services/process_model/process_model_service.py<br> 🛠️ testing task: testing async operations in ProcessModelService, especially predict_next_actions</p><p><strong>4. pytest-xdist&gt;=2.4.0</strong><br> — Architecture Component: all test directories (/tests/*)<br> 🛠️ testing task: parallel execution of test suites for faster testing cycles</p><p><strong>5. pytest-subtests&gt;=0.5.0</strong><br> — Architecture Component: /src/models/process_bert/model.py<br> 🛠️ testing task: detailed testing of Process-BERT’s individual layers and components</p><h3>ML Model Testing</h3><p><strong>6. torch&gt;=1.9.0</strong><br> — Architecture Component: /src/models/process_bert/model.py<br> 🛠️ testing task: testing PyTorch models, especially ProcessBERT implementation</p><p><strong>7. torch.testing</strong><br> — Architecture Component: /src/models/decision_transformer/transformer.py<br> 🛠️ testing task: testing tensor operations in Decision Transformer</p><p><strong>8. transformers&gt;=4.5.0</strong><br> — Architecture Component: /src/models/process_bert/<br> 🛠️ testing task: testing BERT model implementations and transformers architecture</p><p><strong>9. transformers.testing</strong><br> — Architecture Component: /src/models/process_bert/trainer.py<br> 🛠️ testing task: testing training loops and model behavior</p><p><strong>10. numpy&gt;=1.19.5</strong><br> — Architecture Component: /src/services/kpi_prediction/kpi_service.py<br> 🛠️ testing task: testing numerical computations in KPI predictions</p><p><strong>11. numpy.testing</strong><br> — Architecture Component: /src/services/rl_optimization/reward.py<br> 🛠️ testing task: testing reward calculations and numerical stability</p><p><strong>12. datasets&gt;=2.0.0</strong><br> — Architecture Component: /src/models/process_bert/tokenizer.py<br> 🛠️ testing task: testing dataset handling and preprocessing</p><p><strong>13. tokenizers&gt;=0.10.0</strong><br> — Architecture Component: /src/models/process_bert/tokenizer.py<br> 🛠️ testing task: testing custom tokenization for process sequences</p><h3>RL Components Testing</h3><p><strong>14. gym&gt;=0.18.0</strong><br> — Architecture Component: /src/services/rl_optimization/environment.py<br> 🛠️ testing task: testing RL environment implementation</p><p><strong>15. pytest-mock&gt;=3.6.1</strong><br> — Architecture Component: /src/services/rl_optimization/hierarchical_agent.py<br> 🛠️ testing task: mocking environment responses for RL agent testing</p><p><strong>16. stable-baselines3&gt;=1.3.0</strong><br> — Architecture Component: /src/services/rl_optimization/rl_service.py<br> 🛠️ testing task: testing baseline RL algorithms implementation</p><p><strong>17. gym-minigrid&gt;=1.0.0</strong><br> — Architecture Component: /src/services/rl_optimization/environment.py<br> 🛠️ testing task: creating test environments for RL agent validation</p><p><strong>18. sb3-contrib&gt;=1.5.0</strong><br> — Architecture Component: /src/services/rl_optimization/hierarchical_agent.py<br> 🛠️ testing task: testing advanced RL algorithms implementations</p><h3>Data Storage and Processing</h3><p><strong>19.</strong> <strong>pandas&gt;=1.3.0</strong><br> — Architecture Component: /src/services/storage/csv_handler.py<br> 🛠️ testing task: testing data frame operations and CSV handling</p><p><strong>20. pandas.testing</strong><br> — Architecture Component: /src/services/storage/storage_service.py<br> 🛠️ testing task: testing data storage and retrieval operations</p><p><strong>21. sqlite3</strong><br> — Architecture Component: /src/services/storage/sqlite_storage.py<br> 🛠️ testing task: testing SQLite database operations</p><p><strong>22. pytest-tempdir&gt;=2019.10.12</strong><br> — Architecture Component: /src/services/storage/sqlite_storage.py<br> 🛠️ testing task: testing temporary file handling in storage operations</p><h3>Performance Profiling</h3><p><strong>23. memory-profiler&gt;=0.58.0</strong><br> — Architecture Component: /src/utils/monitoring/performance.py<br> 🛠️ testing task: memory usage profiling of all services</p><p><strong>24. line-profiler&gt;=3.3.1</strong><br> — Architecture Component: /src/services/process_model/process_model_service.py<br> 🛠️ testing task: performance profiling of critical code paths</p><p><strong>25. py-spy&gt;=0.3.8</strong><br> — Architecture Component: /src/services/kpi_prediction/kpi_service.py<br> 🛠️ testing task: real-time performance monitoring</p><p><strong>26. scalene&gt;=1.3.16</strong><br> — Architecture Component: all services under /src/services/<br> 🛠️ testing task: CPU/GPU/memory profiling across services</p><h3>Monitoring and Logging</h3><p><strong>27. pytest-html&gt;=3.1.1</strong><br> — Architecture Component: /src/utils/monitoring/metrics_collector.py<br> 🛠️ testing task: generating HTML test reports</p><p><strong>28. pytest-cov&gt;=2.12.1</strong><br> — Architecture Component: All source code under /src/<br> 🛠️ testing task: code coverage reporting</p><p><strong>29. coverage&gt;=6.2</strong><br> — Architecture Component: All source code under /src/<br> 🛠️ testing task: detailed coverage analysis</p><p><strong>30. logging</strong><br> — Architecture Component: /src/utils/monitoring/logger.py<br> 🛠️ testing task: testing logging functionality</p><p><strong>31. pytest-timeout&gt;=2.0.2</strong><br> — Architecture Component: /src/services/kpi_prediction/stream_processor.py<br> 🛠️ testing task: testing timeout handling in stream processing</p><h3>Test Data Generation</h3><p><strong>32. hypothesis&gt;=6.75.3</strong><br> — Architecture Component: /src/services/process_model/validators.py<br> 🛠️ testing task: property-based testing of process validators</p><p><strong>33. faker&gt;=8.1.0</strong><br> — Architecture Component: /src/services/process_model/process_model_service.py<br> 🛠️ testing task: generating synthetic process data</p><p><strong>34. pytest-benchmark&gt;=3.4.1</strong><br> — Architecture Component: /src/models/decision_transformer/transformer.py<br> 🛠️ testing task: performance benchmarking of transformer operations</p><h3>Integration Testing</h3><p><strong>35. pytest-aiohttp&gt;=0.3.0</strong><br> — Architecture Component: /tests/integration/<br> 🛠️ testing task: testing async service communication</p><h3>Notebook Testing</h3><p><strong>36. nbconvert&gt;=6.3.0</strong><br> — Architecture Component: /notebooks/train.ipynb<br> 🛠️ testing task: testing notebook execution</p><p><strong>37. nbval&gt;=0.9.6</strong><br> — Architecture Component: /notebooks/evaluate.ipynb<br> 🛠️ testing task: validation of notebook outputs</p><p><strong>38. papermill&gt;=2.3.3</strong><br> — Architecture Component: /notebooks/setup.ipynb<br> 🛠️ testing task: parameterized notebook execution</p><p><strong>39. ipytest&gt;=0.12.0</strong><br> — Architecture Component: all notebooks under /notebooks/<br> 🛠️ testing task: in-notebook test execution</p><h3>Auxiliary Tools</h3><p><strong>40. pytest-repeat&gt;=0.9.1</strong><br> — Architecture Component: /src/services/rl_optimization/hierarchical_agent.py<br> 🛠️ testing task: repeated testing of stochastic RL behavior</p><p><strong>41. pytest-randomly&gt;=3.10.1</strong><br> — Architecture Component: all test suites<br> 🛠️ testing task: random order test execution</p><p><strong>42. pytest-sugar&gt;=0.9.4</strong><br> — Architecture Component: all test suites<br> 🛠️ testing task: enhanced test output formatting</p><p><strong>43. pytest-clarity&gt;=1.0.1</strong><br> — Architecture Component: all test suites<br> 🛠️ testing task: improved assertion failure reporting</p><p><strong>44. pytest-check&gt;=1.0.1</strong><br> — Architecture Component: /tests/integration/service_to_service<br> 🛠️ testing task: multiple assertion testing in integration tests</p><p><strong>45. pytest-testmon&gt;=1.1.1</strong><br> — Architecture Component: all test suites<br> 🛠️ testing task: selective test execution based on changes</p><p><strong>46. pytest-rerunfailures&gt;=10.2</strong><br> — Architecture Component: /tests/integration/<br> 🛠️ testing task: handling flaky integration tests</p><h3>Specific Tools for BERT and RL</h3><p><strong>47. torch-testing-utils&gt;=0.1.0</strong><br> — Architecture Component: /src/models/process_bert/model.py<br> 🛠️ testing task: testing PyTorch-specific BERT components</p><p><strong>48. deepdiff&gt;=5.5.0</strong><br> — Architecture Component: /src/services/rl_optimization/hierarchical_agent.py<br> 🛠️ testing task: testing complex state transitions in RL</p><p><strong>49. pytest-pytorch&gt;=0.2.0</strong><br> — Architecture Component: /src/models/decision_transformer/<br> 🛠️ testing task: PyTorch-specific fixtures and assertions</p><p><strong>50. pytest-ordering&gt;=0.6.0</strong><br> — Architecture Component: /tests/integration/end_to_end<br> 🛠️ testing task: managing test dependencies in end-to-end scenarios</p><h4>🎉Congratulations!</h4><p><em>The review of our course plan is complete — let’s move on to the first development and testing task.</em></p><p>In the next lesson, we will continue the development and testing of our Reinforcement Learning application for the <strong>Next Best Action</strong> task with integration to <a href="https://www.microsoft.com/en-us/dynamics-365">Dynamics 365</a>.</p><p>🎓<strong>For Complete individual RL development course for Dynamics 365 and for one-on-one tutoring on machine Reinforcement Learning topics, please, contact: </strong><a href="https://neuverso.ai/"><strong>https://neuverso.ai/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e83570b10fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching Dynamics 365 to Play “Frozen Market”: a Reinforcement Learning Approach to Business…]]></title>
            <link>https://medium.com/@serhii.barskyi/teaching-dynamics-365-to-play-frozen-market-a-reinforcement-learning-approach-to-business-746ec71c799e?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/746ec71c799e</guid>
            <category><![CDATA[serhii-barskyi]]></category>
            <category><![CDATA[complex-valued-q-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[neuverso]]></category>
            <category><![CDATA[dynamics-365]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 15:09:36 GMT</pubDate>
            <atom:updated>2026-05-02T07:33:39.473Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Teaching Dynamics 365 to Play “Frozen Market”: a Reinforcement Learning Approach to Business Decision Making</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l44i3daK5u1qDOIswAqb6Q.png" /></figure><p>*<em>This guide will help you make your ML projects for Dynamics 365 significantly more adaptable.</em></p><p>My Data Science Course <a href="https://preply.com/en/tutor/7756455">https://preply.com/en/tutor/7756455</a></p><h4>Microsoft Dynamics 365 is one of the most powerful platforms for managing business processes, combining CRM and ERP functionality.</h4><p>Through the integration of artificial intelligence tools such as Azure Machine Learning, Copilot, and Power BI, the platform provides users with extensive capabilities for data analysis, forecasting, and decision-making.</p><blockquote>Machine learning (ML) tools today are at the center of business process transformation.</blockquote><p>However, most solutions built into <a href="https://www.microsoft.com/en-us/dynamics-365">Dynamics 365</a> are based on Supervised and Unsupervised Learning methods, which are limited by existing data. Against this background, a natural question arises: is it possible to use Reinforcement Learning (RL) for dynamic forecasting and real-time decision-making, which is particularly relevant for managing complex processes such as supply chain management or personalizing customer experience?</p><h3>Table of Contents</h3><p>This article explores the potential of RL in the Dynamics 365 infrastructure, demonstrating an approach to system learning through the “Frozen Market” model — a simulation built on market data:</p><blockquote>1.Advantages of MDP for Management</blockquote><blockquote>2.“Frozen Market” Game</blockquote><blockquote>3.Integration of External RL Solutions with Dynamics 365 ML Infrastructure</blockquote><blockquote>4.Announcement of the next lesson:</blockquote><blockquote>— Dynamics 365 Interactions Simulator based on Django REST Framework</blockquote><blockquote>— Basic RL Models for Dynamics 365</blockquote><h4>Existing machine learning methods in Dynamics 365, based on supervised and unsupervised learning, are effective for static tasks but have limitations when working with dynamic decision-making processes that require dynamic adaptation under uncertainty.</h4><p>Integrating Reinforcement Learning (RL) methods into the Dynamics 365 ecosystem contributes to optimizing sequential business decisions. RL, based on the mathematical apparatus of Markov Decision Processes (MDP), allows intelligent agents to learn through interaction with the environment, which is potentially applicable to business process management tasks.</p><h3>RL-Uniqueness</h3><p>Reinforcement Learning (RL) represents a unique direction in machine learning, the only ML direction with a high-level formalism at its core — MDP, which can be viewed as management-oriented. Unlike methods focused on optimizing local metrics, RL, using MDP, focuses on achieving long-term goals, considering risks and adapting to environmental changes. <strong><em>This ability for adaptive learning and long-term optimization makes RL particularly promising for solving complex management tasks within Dynamics 365.</em></strong></p><h3>RL-Adaptivity</h3><p>The modeling of complex market processes, including customer interactions, pricing, and supply chain management, can be achieved through RL, enabling adaptation to changing conditions. When integrated into the Dynamics 365 ecosystem, it enhances decision-making quality, optimizes business processes, and boosts company competitiveness. <strong><em>Integrating RL into the Dynamics 365 platform opens new horizons for business decision automation, bringing process management to a qualitatively new level.</em></strong></p><h3>RL-Strategy</h3><p>We will present specific approaches to implementing RL in Dynamics 365 projects and demonstrate their effectiveness through a practical example. This article contains arguments and a strategy for developing RL infrastructure for Dynamics 365 projects, which will enable the RL community to intensify its work on Dynamics 365 tasks, enhance the potential of Dynamics 365, and increase customer satisfaction.</p><h3>1.Advantages of MDP for Management</h3><p>The priority of Reinforcement Learning in management is clearly discernible through the prism of MDP and management philosophy.</p><blockquote>Reinforcement Learning (RL), based on Markov Decision Processes (MDP), represents a mathematically rigorous approach that integrates key aspects of management philosophy: optimization, uncertainty analysis, and consideration of long-term perspective.</blockquote><p>This section provides a brief mathematical analysis of RL, revealing its advantages in strategic management. It also addresses adaptive and philosophical aspects of management, formalized using MDP.</p><h3>1.1 Mathematical Formalization of MDP</h3><p>A Markov Decision Process (MDP) is formally defined as a quintuple:</p><pre>M = (S, A, P, R, gamma)</pre><p>where:</p><ul><li>S: state space describing business parameters (S ⊆ ℝ^n)</li><li>A: action space representing management strategies</li><li>P(s&#39;|s,a): transition probability function (P: S × A × S → [0,1])</li><li>R(s,a): reward function (R: S × A → ℝ)</li><li>gamma ∈ [0,1]: discount factor accounting for the time value of future rewards</li></ul><p>The main objective of RL is to find the <strong>optimal policy</strong>:</p><pre>pi_star = argmax_pi E[sum(gamma**t * R(s_t, a_t) <br>                          for t in range(0, infinity)) <br>                      | s_0 = s, pi]</pre><h3>Explanation of the equation structure:</h3><p>pi_star = argmax_pi<br> This means we are searching for the policy <strong>π</strong> that maximizes the expression on the right.</p><p>E[...]<br> The expected value of the total reward.</p><p>sum(...)<br> The sum of discounted rewards over all steps <strong>t</strong>=0,1,2,…</p><p>gamma**t * R(s_t, a_t)<br> The reward at step<strong> t</strong>, discounted by the factor <strong>γ^t</strong>.</p><p>| s_0 = s, pi<br> The condition: the initial state is <strong>s0=s</strong>, and the policy being followed is <strong>π</strong>.</p><p>Markov Decision Process (MDP) forms the foundation for many Reinforcement Learning (RL) methods, as it formalizes the decision-making problem under uncertainty. RL studies how an agent, interacting with its environment, should choose a sequence of actions to maximize long-term cumulative reward. Within the MDP framework, this is achieved by constructing an optimal policy <strong>π*</strong>, which specifies which actions should be taken in each state.</p><h4>Relationship between RL and MDP</h4><p>Reinforcement Learning relies on MDP as a mathematical model of the environment in which the agent operates. The agent, interacting with the environment, uses reward signals to adjust its policy <strong>π</strong>. MDP provides a structure for this task by defining the transition rules between states, reward functions, and discounting factors, making it suitable for RL algorithms.</p><h4>Is the main goal of RL to find the optimal policy?</h4><p>The primary goal of RL is to learn to choose actions in a way that maximizes the expected cumulative reward. This is the search for the optimal policy <strong>π*</strong>. However, in practice, this is not always the sole goal. Sometimes RL is used to study the characteristics of the environment or the behavior of the agent, even if the resulting solution is not strictly optimal.</p><h3>1.2 Solving the Optimal Policy Equation</h3><pre>import numpy as np<br>import gym<br>import random<br>from typing import List, Tuple, Dict<br><br>class PolicyOptimization:<br>    def __init__(self, env: gym.Env, gamma: float = 0.99):<br>        &quot;&quot;&quot;<br>        Initialization of the policy optimization class.<br>        <br>        Parameters:<br>        - env: OpenAI Gym environment<br>        - gamma: discount factor (0 &lt; gamma &lt;= 1)<br>        &quot;&quot;&quot;<br>        self.env = env  # Reinforcement learning environment<br>        self.gamma = gamma  # Discount factor<br>        <br>        # Initialize the number of states and actions<br>        self.n_states = env.observation_space.n<br>        self.n_actions = env.action_space.n<br>        <br>        # Initialize a random initial policy<br>        self.policy = self.initialize_random_policy()<br>        <br>    def initialize_random_policy(self) -&gt; np.ndarray:<br>        &quot;&quot;&quot;<br>        Create a random stochastic policy.<br>        <br>        Returns:<br>        Numpy array with action probabilities for each state.<br>        &quot;&quot;&quot;<br>        # Create a policy with uniform probability distribution<br>        policy = np.ones((self.n_states, self.n_actions)) / self.n_actions<br>        return policy<br>    <br>    def compute_value_function(self, policy: np.ndarray) -&gt; np.ndarray:<br>        &quot;&quot;&quot;<br>        Compute the value function for a given policy.<br>        <br>        Parameters:<br>        - policy: the current policy<br>        <br>        Returns:<br>        Numpy array with values for each state.<br>        &quot;&quot;&quot;<br>        # Solve Bellman equation using iterative method<br>        values = np.zeros(self.n_states)<br>        <br>        for _ in range(100):  # Limit the number of iterations<br>            prev_values = values.copy()<br>            <br>            for state in range(self.n_states):<br>                action_values = []<br>                for action in range(self.n_actions):<br>                    # Transition probabilities and immediate reward<br>                    transitions = self.env.P[state][action]<br>                    <br>                    # Compute the expected value for each possible transition<br>                    action_value = sum(<br>                        prob * (reward + self.gamma * prev_values[next_state])<br>                        for prob, next_state, reward, _ in transitions<br>                    )<br>                    action_values.append(action_value)<br>                <br>                # Weight by the current policy<br>                values[state] = sum(<br>                    policy[state][action] * action_value <br>                    for action, action_value in enumerate(action_values)<br>                )<br>        <br>        return values<br>    <br>    def policy_improvement(self, values: np.ndarray) -&gt; np.ndarray:<br>        &quot;&quot;&quot;<br>        Improve the current policy based on the value function.<br>        <br>        Parameters:<br>        - values: the current value function<br>        <br>        Returns:<br>        Updated optimal policy.<br>        &quot;&quot;&quot;<br>        new_policy = np.zeros_like(self.policy)<br>        <br>        for state in range(self.n_states):<br>            action_values = []<br>            <br>            for action in range(self.n_actions):<br>                # Compute the value of each action<br>                transitions = self.env.P[state][action]<br>                action_value = sum(<br>                    prob * (reward + self.gamma * values[next_state])<br>                    for prob, next_state, reward, _ in transitions<br>                )<br>                action_values.append(action_value)<br>            <br>            # Select the action with the maximum value<br>            best_action = np.argmax(action_values)<br>            new_policy[state][best_action] = 1.0<br>        <br>        return new_policy<br>    <br>    def policy_iteration(self, max_iterations: int = 100) -&gt; np.ndarray:<br>        &quot;&quot;&quot;<br>        Main policy iteration algorithm.<br>        <br>        Parameters:<br>        - max_iterations: maximum number of iterations<br>        <br>        Returns:<br>        Optimal policy.<br>        &quot;&quot;&quot;<br>        for _ in range(max_iterations):<br>            # Compute the value function for the current policy<br>            values = self.compute_value_function(self.policy)<br>            <br>            # Improve the policy<br>            new_policy = self.policy_improvement(values)<br>            <br>            # Check for convergence<br>            if np.array_equal(self.policy, new_policy):<br>                break<br>            <br>            self.policy = new_policy<br>        <br>        return self.policy<br><br># Algorithm demonstration<br>def main():<br>    # Use a simple Gym environment (e.g., FrozenLake)<br>    env = gym.make(&#39;FrozenLake-v1&#39;)<br>    <br>    # Create an instance of the policy optimization class<br>    optimizer = PolicyOptimization(env, gamma=0.99)<br>    <br>    # Run policy iteration<br>    optimal_policy = optimizer.policy_iteration()<br>    <br>    print(&quot;Optimal policy found!&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Explanation of the provided code:</h4><p>The code performs a search for the optimal policy <strong>π*</strong> by:</p><ul><li><strong>Using arg⁡max⁡:</strong></li></ul><p>Selects actions that maximize the cumulative reward.</p><ul><li><strong>Iterating over expected rewards:</strong></li></ul><p>Applies the Bellman equation to compute V<strong>π(s)</strong> and subsequently selects the optimal actions.</p><ul><li><strong>Supporting Gym environments:</strong></li></ul><p>Can be applied to real RL tasks, such as<strong> FrozenLake</strong>.</p><h4>Possible improvements:</h4><ul><li><strong>Handling stochastic policies:</strong></li></ul><p>The code focuses on deterministic policies (in the final version, the policy chooses one action per state). To handle stochastic policies, modifications would be needed.</p><ul><li><strong>Efficiency:</strong></li></ul><p>For large state spaces, methods like Policy Iteration can become computationally expensive. Alternatives like Value Iteration or learning-based methods (e.g., Q-Learning or Actor-Critic) might be preferable.</p><ul><li><strong>Parameterized environments:</strong></li></ul><p>If tasks involve continuous state or action spaces, this approach would need to be adapted, for example, using neural networks (as in Deep RL).</p><h4>method: <strong>compute_value_function</strong></h4><p>This method computes state values for the current policy by solving the Bellman equation:</p><pre>V^π(s) = ∑_{a ∈ A} π(a|s) ∑_{s&#39;,r} P(s&#39;,r|s,a) [r + γV^π(s&#39;)]</pre><p>or equivalently:</p><pre>V^π(s) = ∑_{a ∈ A} π(a|s) [ ∑_{s&#39; ∈ S} ∑_{r ∈ R} P(s&#39;,r|s,a) (r + γV^π(s&#39;)) ]</pre><h4>How is this implemented in code?</h4><ul><li>For each state, the expected action values (action_value) are computed based on all possible transitions P[s][a] (probability, reward, and next state).</li><li>The state value is updated as a weighted sum of the expected action values, using probabilities from the current policy.</li></ul><h4>Goal:</h4><p>Approximate the value function through iterative refinement of state values.</p><h4>method: policy_improvement</h4><p>This method updates the current policy to make it greedy with respect to the value function:</p><pre>π&#39;(s) = argmax_{a ∈ A} [∑_{s&#39; ∈ S} ∑_{r ∈ R} P(s&#39;, r | s, a) * (r + γ * V^π(s&#39;))]</pre><p>or equivalently:</p><pre>π&#39;(s) = argmax_{a ∈ A} [∑_{s&#39; ∈ S} ∑_{r ∈ R} P(s&#39;, r | s, a) * (r + γ * V^π(s&#39;))]</pre><h4>How is this implemented in code?</h4><ul><li>For each state, the values of all actions (action_value) are computed based on the current value function.</li><li>The action with the highest value is selected, and the policy is updated to make this action deterministic.</li></ul><h4>Goal:</h4><p>Improve the policy to approximate the optimal one.</p><h4>method: policy_iteration</h4><p>This method combines the previous two steps:</p><ol><li>Computes the value function for the current policy.</li><li>Updates the policy based on the value function.</li><li>Checks for convergence (if the policy doesn’t change, the algorithm terminates).</li></ol><h4>Goal:</h4><p>Iteratively improve the policy until convergence.</p><h3>Mathematical Context for Bellman Equations</h3><h4>Value Function Computation:</h4><pre><br>def compute_value_function(policy, P, R, gamma, states, actions):<br>    # MATHEMATICAL INITIALIZATION: V(s) = 0 ∀s ∈ S<br>    # Initializing value function vector V ∈ ℝ^|S| where |S| is the cardinality of state space<br>    V = np.zeros(len(states))<br>    <br>    # CONVERGENCE PARAMETER: δ = ∞<br>    # Setting initial maximum difference to infinity for the first iteration of value iteration<br>    delta = float(&#39;inf&#39;)<br>    <br>    # BELLMAN ITERATION LOOP: Repeat until ||V_{k+1} - V_k||_{∞} &lt; 1e-6<br>    # Implementation of fixed-point iteration for solving V = T(V) where T is Bellman operator<br>    while delta &gt; 1e-6:<br>        # RESET CONVERGENCE METRIC: δ = 0<br>        # Initialize maximum norm of value function difference for current iteration<br>        delta = 0<br>        <br>        # STATE SPACE ITERATION: ∀s ∈ S<br>        # Iterate over each state to update its value using Bellman equation<br>        for s in states:<br>            # STORE CURRENT VALUE: v = V_k(s)<br>            # Cache current state value for convergence computation<br>            v = V[s]<br>            <br>            # BELLMAN UPDATE EQUATION: V_{k+1}(s) = ∑_a π(a|s) ∑_{s&#39;} P(s&#39;|s,a)[R(s,a,s&#39;) + γV_k(s&#39;)]<br>            # Compute expected value under policy π using transition dynamics P and rewards R<br>            V[s] = sum(<br>                policy[a][s] * sum(  # Σ_a π(a|s) × [...]<br>                    P[s, a, s_prime] * (R[s, a, s_prime] + gamma * V[s_prime])  # Σ_{s&#39;} P(s&#39;|s,a)[R + γV(s&#39;)]<br>                    for s_prime in states  # Integration over next state space S&#39;<br>                )<br>                for a in actions  # Integration over action space A<br>            )<br>            <br>            # SUPREMUM NORM UPDATE: δ = max(δ, |V_{k+1}(s) - V_k(s)|)<br>            # Update maximum absolute difference for convergence check using L∞ norm<br>            delta = max(delta, abs(v - V[s]))<br>    <br>    # RETURN CONVERGED VALUE FUNCTION: V* satisfying Bellman equation<br>    # Final value function satisfying ||T(V) - V||_{∞} &lt; 1e-6<br>    return V</pre><h4>Policy Improvement:</h4><pre>def policy_improvement(V, P, R, gamma, states, actions):<br>    # POLICY MATRIX INITIALIZATION: π(a|s) = 0 ∀(s,a) ∈ S × A<br>    # Creates a zero matrix π ∈ ℝ^{|A| × |S|} representing probability distribution over actions<br>    new_policy = np.zeros_like(policy)<br>    <br>    # STATE SPACE ITERATION: ∀s ∈ S<br>    # Iterate through state space to determine optimal actions using greedy policy improvement<br>    for s in states:<br>        # Q-FUNCTION COMPUTATION: Q(s,a) = ∑_{s&#39;} P(s&#39;|s,a)[R(s,a,s&#39;) + γV(s&#39;)]<br>        # Calculate action-value function Q(s,a) for all a ∈ A using current value function V<br>        action_values = [<br>            sum(P[s, a, s_prime] * (R[s, a, s_prime] + gamma * V[s_prime])  # Expected return E[R + γV(s&#39;)]<br>                for s_prime in states)  # Integration over next state space S&#39;<br>            for a in actions  # Evaluation for each action in action space A<br>        ]<br>        <br>        # OPTIMAL ACTION SELECTION: a* = argmax_a Q(s,a)<br>        # Determine optimal action by maximizing Q-value using supremum operator over action space<br>        best_action = np.argmax(action_values)<br>        <br>        # DETERMINISTIC POLICY UPDATE: π(a|s) = 1 if a = a*, 0 otherwise<br>        # Convert Q-function maximizer to deterministic policy by setting probability mass to 1<br>        new_policy[best_action][s] = 1<br>    <br>    # RETURN IMPROVED POLICY: π&#39;(a|s) that strictly improves value function unless optimal<br>    # Returns new deterministic policy satisfying V_{π&#39;}(s) ≥ V_π(s) ∀s ∈ S<br>    return new_policy</pre><h4>Policy Iteration:</h4><pre>def policy_iteration(P, R, gamma, states, actions):<br>   # INITIAL POLICY DISTRIBUTION: π_0(a|s) = 1/|A| ∀(s,a) ∈ S × A<br>   # Initialize stochastic policy matrix π ∈ ℝ^{|A| × |S|} with uniform distribution over actions<br>   # This ensures ∑_a π(a|s) = 1 ∀s ∈ S as required for valid policy<br>   policy = np.ones((len(actions), len(states))) / len(actions)<br>   <br>   while True:<br>       # POLICY EVALUATION PHASE: Compute V^π solving V = T^π V<br>       # Determines value function V^π(s) for current policy π by iteratively applying Bellman operator<br>       # V^π(s) = ∑_a π(a|s) ∑_{s&#39;} P(s&#39;|s,a)[R(s,a,s&#39;) + γV^π(s&#39;)]<br>       V = compute_value_function(policy, P, R, gamma, states, actions)<br>       <br>       # POLICY IMPROVEMENT PHASE: π_{k+1} = G(V^{π_k})<br>       # Computes improved policy using greedy operator G with respect to current value function<br>       # π_{k+1}(s) = argmax_a ∑_{s&#39;} P(s&#39;|s,a)[R(s,a,s&#39;) + γV^π(s&#39;)]<br>       new_policy = policy_improvement(V, P, R, gamma, states, actions)<br>       <br>       # CONVERGENCE TEST: ||π_{k+1} - π_k||_{∞} = 0<br>       # Checks if policy iteration has reached fixed point π* = G(V^π*)<br>       # Terminates when policy improvement no longer changes policy (Howard&#39;s policy iteration theorem)<br>       if np.all(policy == new_policy):<br>           break  # Fixed point reached: π* = G(V^π*)<br>       <br>       # POLICY UPDATE: π_k ← π_{k+1}<br>       # Updates policy for next iteration of policy evaluation-improvement loop<br>       policy = new_policy<br>   <br>   # RETURN OPTIMAL POLICY-VALUE PAIR: (π*, V^π*)<br>   # Returns converged optimal policy π* and its corresponding value function V^π*<br>   # Guarantees: V^π*(s) = max_π V^π(s) ∀s ∈ S<br>   return policy, V</pre><p>The equation for the optimal policy involves maximizing the expected cumulative reward.</p><p>The solution to this problem boils down to calculating the value of states and actions, which can be achieved using algorithms such as <strong>Value Iteration</strong>, <strong>Policy Iteration</strong>, or methods based on Q-function updates (e.g., <strong>Q-learning</strong>).</p><p>The code below illustrates three different approaches to finding the optimal policy in a reinforcement learning problem using the <em>GridWorld</em> environment as an example.</p><p>Here are the key points for each method:</p><h4>1. Value Iteration Method:</h4><ul><li>This method uses iterative updates of the value function for each state.</li><li>At each step, the maximum expected value of a state is calculated, considering all possible actions.</li><li>The process stops when changes in value estimates fall below a predefined threshold (threshold).</li><li>The final policy can be derived after the iterations are complete.</li></ul><p><strong>Goal</strong>: Optimize the value function for all states, making it easy to extract the optimal policy.</p><h4>2. Policy Iteration Method:</h4><ul><li>This method alternates between two phases:</li><li><strong>Policy Evaluation</strong>: computes the value function for the current policy.</li><li><strong>Policy Improvement</strong>: selects the optimal actions based on the updated value function.</li><li>The process repeats until the policy becomes stable, meaning it no longer changes.</li></ul><p><strong>Goal</strong>: Find the optimal policy by iteratively improving it.</p><h4>3. Q-Learning Method:</h4><ul><li>This is a model-free approach, meaning it does not require prior knowledge of transition probabilities P.</li><li>The agent learns through interaction with the environment:</li><li>Actions are chosen using the ε-greedy strategy (balancing exploration and exploitation).</li><li>Based on the received reward, the Q-value is updated, improving the agent’s behavior.</li><li>The final Q-values enable the derivation of the optimal policy by selecting actions with the highest Q-values.</li></ul><p><strong>Goal</strong>: Use interactive learning to evaluate action values without needing a model of the environment.</p><h3>Method Comparison:</h3><ol><li><strong>Value Iteration</strong> and <strong>Policy Iteration</strong> assume knowledge of the transition and reward functions. They require a complete model of the environment and provide exact solutions.</li><li><strong>Q-Learning</strong> is suitable for tasks where the environment model is unknown. While more flexible, it can sometimes be less efficient than model-based methods.</li></ol><p>Thus, the code demonstrates three distinct approaches (Model-based and Model-free) used to solve the reinforcement learning problem within the same environment:</p><p><strong>1.Environment Setup:</strong></p><pre>import numpy as np  # Import the NumPy library for numerical operations<br>import random  # Import the random module for random number generation<br><br># Define states for a 4x4 GridWorld<br># Each state is represented as a tuple (x, y) corresponding to the grid coordinates<br>states = [(x, y) for x in range(4) for y in range(4)]<br><br># Define possible actions an agent can take in the grid<br># Actions include moving &#39;up&#39;, &#39;down&#39;, &#39;left&#39;, and &#39;right&#39;<br>actions = [&#39;up&#39;, &#39;down&#39;, &#39;left&#39;, &#39;right&#39;]<br><br># Define the discount factor (gamma) used in reinforcement learning<br># Gamma determines the importance of future rewards (0 &lt; gamma ≤ 1)<br>gamma = 0.9</pre><p>This block sets up our GridWorld environment. The states represent coordinates in a 4x4 grid, with four possible movement actions. The gamma parameter (0.9) determines how much we value future rewards compared to immediate ones.</p><p><strong>2.Environment Dynamics:</strong></p><pre># Define the reward function R(s, a)<br># This function returns a scalar reward based on the current state (s) and action (a)<br>def R(s, a):<br>    goal_state = (3, 3)  # Define the goal state of the grid where the reward is highest<br>    if s == goal_state:  # Check if the current state is the goal state<br>        return 10  # Return a positive reward for reaching the goal<br>    return -1  # Return a negative reward for non-goal states<br><br># Define the transition probability function P(s_next, s, a)<br># This function calculates the probability of transitioning to state s_next <br># given the current state s and action a<br>def P(s_next, s, a):<br>    # Define an inner function to compute the next state based on the current state and action<br>    def get_next_state(s, a):<br>        x, y = s  # Extract the coordinates of the current state<br>        # Check if the action results in a valid movement within grid boundaries<br>        if a == &#39;up&#39; and y &gt; 0:  # Moving up decreases the y-coordinate<br>            return (x, y-1)<br>        elif a == &#39;down&#39; and y &lt; 3:  # Moving down increases the y-coordinate<br>            return (x, y+1)<br>        elif a == &#39;left&#39; and x &gt; 0:  # Moving left decreases the x-coordinate<br>            return (x-1, y)<br>        elif a == &#39;right&#39; and x &lt; 3:  # Moving right increases the x-coordinate<br>            return (x+1, y)<br>        return s  # If no valid movement, remain in the same state<br>    <br>    # Return 1.0 if the determined next state matches s_next, otherwise return 0.0<br>    return 1.0 if get_next_state(s, a) == s_next else 0.0</pre><p>These functions define how the environment behaves. R(<strong>s,a</strong>) is the reward function, giving +10 for reaching the goal and -1 for each move. P(<strong>s_next</strong>,<strong>s,a</strong>) defines transition probabilities between states given an action.</p><p><strong>3.Value and Policy Functions:</strong></p><pre># Define the optimal_policy function<br># This function determines the best action to take in a given state based on the value function V<br>def optimal_policy(V, state, actions):<br>    # Use the max function to find the action that maximizes the expected reward<br>    # The key function computes the value of each action<br>    return max(<br>        actions,  # Iterate over all possible actions<br>        key=lambda a: R(state, a) + gamma * sum(  # Calculate the expected value of each action<br>            P(s_next, state, a) * V.get(s_next, 0)  # Probability of transition * value of next state<br>            for s_next in states  # Iterate over all possible next states<br>        )<br>    )<br><br># Define the value_function function<br># This function calculates the maximum expected value for a given state based on actions and value function V<br>def value_function(V, state, actions):<br>    # Use the max function to find the maximum expected value over all actions<br>    return max(<br>        R(state, a) + gamma * sum(  # Compute the expected value for each action<br>            P(s_next, state, a) * V.get(s_next, 0)  # Probability of transition * value of next state<br>            for s_next in states  # Iterate over all possible next states<br>        )<br>        for a in actions  # Iterate over all possible actions<br>    )<br><br># Define the Q_value function<br># This function calculates the Q-value for a given state-action pair based on the value function V<br>def Q_value(state, action, V):<br>    # Compute the expected value of taking the action in the given state<br>    return R(state, action) + gamma * sum(  # Immediate reward + discounted future rewards<br>        P(s_next, state, action) * V.get(s_next, 0)  # Probability of transition * value of next state<br>        for s_next in states  # Iterate over all possible next states<br>    )</pre><p>These helper functions calculate optimal actions and state values. They’re used by all three main algorithms to determine the best actions and estimate how good each state is.</p><p><strong>4.Value and Policy Iteration:</strong></p><pre># Define the value_iteration function<br># This function performs the value iteration algorithm to compute the value function V<br># It iteratively updates the value function until convergence or until the maximum number of iterations<br>def value_iteration(states, actions, threshold=1e-6, max_iterations=100):<br>    V = {s: 0 for s in states}  # Initialize the value function with zeros for all states<br>    # Iterate up to max_iterations<br>    for _ in range(max_iterations):<br>        delta = 0  # Initialize the maximum change in value function<br>        V_temp = V.copy()  # Make a copy of the current value function to avoid in-place updates<br>        # Iterate over all states<br>        for s in states:<br>            v = V_temp[s]  # Save the current value of the state<br>            # Update the value function using the value_function for each state<br>            V[s] = value_function(V_temp, s, actions)<br>            # Update delta to track the maximum change<br>            delta = max(delta, abs(v - V[s]))<br>        # If the maximum change in value is smaller than the threshold, stop the iteration<br>        if delta &lt; threshold:<br>            break<br>    return V  # Return the final value function after convergence or max iterations<br><br># Define the policy_iteration function<br># This function performs the policy iteration algorithm to compute the optimal policy<br># It alternates between policy evaluation and policy improvement until convergence<br>def policy_iteration(states, actions, max_iterations=100):<br>    policy = {s: random.choice(actions) for s in states}  # Initialize the policy randomly for all states<br>    V = {s: 0 for s in states}  # Initialize the value function with zeros for all states<br>    <br>    # Iterate up to max_iterations<br>    for _ in range(max_iterations):<br>        # Policy evaluation phase: compute the value function for the current policy<br>        while True:<br>            delta = 0  # Initialize the maximum change in value function<br>            V_temp = V.copy()  # Make a copy of the current value function<br>            # Iterate over all states<br>            for s in states:<br>                v = V_temp[s]  # Save the current value of the state<br>                # Update the value function based on the current policy<br>                V[s] = R(s, policy[s]) + gamma * sum(P(s_next, s, policy[s]) * V_temp.get(s_next, 0) for s_next in states)<br>                # Update delta to track the maximum change<br>                delta = max(delta, abs(v - V[s]))<br>            # If the maximum change in value is smaller than the threshold, stop the evaluation loop<br>            if delta &lt; 1e-6:<br>                break<br>        <br>        stable = True  # Flag to check if the policy is stable<br>        # Policy improvement phase: update the policy based on the new value function<br>        for s in states:<br>            old_action = policy[s]  # Save the old action for comparison<br>            # Update the policy using the optimal action for the current state<br>            policy[s] = optimal_policy(V, s, actions)<br>            # If the policy changes, mark it as unstable<br>            if old_action != policy[s]:<br>                stable = False<br>        <br>        # If the policy has not changed, stop the iteration<br>        if stable:<br>            break<br>    <br>    return policy, V  # Return the final policy and value function after convergence</pre><p>These are two model-based approaches. Value iteration directly computes optimal state values, while policy iteration alternates between policy evaluation and improvement steps.</p><p><strong>5.Q-Learning Implementation:</strong></p><pre># Define the q_learning function<br># This function implements the Q-learning algorithm, an off-policy reinforcement learning algorithm<br># It learns the action-value function Q over multiple episodes<br>def q_learning(states, actions, episodes=1000, alpha=0.1, epsilon=0.1):<br>    # Initialize the Q-table with zeros for all state-action pairs<br>    Q = {(s, a): 0 for s in states for a in actions}<br>    <br>    # Iterate over a specified number of episodes<br>    for _ in range(episodes):<br>        state = random.choice(states)  # Start at a random state for each episode<br>        <br>        # Loop until the episode ends (when the agent reaches a terminal state or based on exploration)<br>        while True:<br>            # Epsilon-greedy action selection<br>            if random.random() &lt; epsilon:  # With probability epsilon, choose a random action (exploration)<br>                action = random.choice(actions)<br>            else:  # Otherwise, choose the action with the highest Q-value (exploitation)<br>                action = max((a for a in actions), key=lambda a: Q.get((state, a), 0))<br>            <br>            # Choose the next state based on the transition probabilities and random sampling<br>            s_next = random.choices(states, weights=[P(s_next, state, action) for s_next in states])[0]<br>            reward = R(state, action)  # Get the reward for taking the chosen action<br>            <br>            # Update the Q-value using the Q-learning update rule<br>            Q[(state, action)] += alpha * (  # Update Q-value using learning rate alpha<br>                reward + gamma * max(Q.get((s_next, a), 0) for a in actions) - Q[(state, action)]  # Bellman equation<br>            )<br>            <br>            # Move to the next state<br>            state = s_next<br>            <br>            # With a 10% probability, end the current episode (exploration termination condition)<br>            if random.random() &lt; 0.1:<br>                break<br>    <br>    return Q  # Return the learned Q-table after completing all episodes</pre><p>Q-learning is a model-free approach that learns directly from experience. It uses an epsilon-greedy strategy to balance exploration and exploitation, learning Q-values for state-action pairs through interaction with the environment. Unlike the previous methods, it doesn’t require complete knowledge of the environment’s dynamics.</p><h3>Why Optimal Policy Matters for Managers?</h3><p>To reveal the <strong>meaning of optimal policy</strong> in management, let’s consider an example where a manager makes decisions based on the current state of the system. Consider the inventory management problem, where the <strong>optimal policy</strong> determines how much product to order to minimize costs and ensure long-term benefits.</p><h3>Example: Inventory Management with Optimal Policy</h3><h4>Context</h4><p>The manager is responsible for warehouse management. At the end of each period:</p><ul><li>he observes the current inventory level s</li><li>he makes a decision a — how many items to order (for example, 0, 10, or 20 units).</li></ul><p>Costs include:</p><ul><li>Storage cost h * s</li><li>Shortage penalty p * max(0, d - s - a), where d is demand</li><li>Ordering cost c * a</li></ul><blockquote>Objective: Find the <strong>optimal policy </strong>π*(s) that minimizes total discounted costs over a time horizon T.</blockquote><h4>Mathematical Formulation</h4><p>Consider the classic <strong>dynamic programming problem</strong>:</p><ol><li><strong>State </strong>s: current inventory level.</li><li><strong>Action </strong>a: order size.</li><li><strong>Reward (negative costs):</strong></li></ol><pre>R(s, a) = -(h * s + p * max(0, d - s - a) + c * a)</pre><p>4. <strong>State transition:</strong> after placing the order and realizing demand:</p><pre>s&#39; = max(0, s + a - d)</pre><p>where d is the random demand.</p><p><strong>5. Objective function:</strong> The optimal value V*(s) is defined as:</p><pre>V*(s) = max_a [ R(s, a) + γ * E_d[V*(s&#39;)] ]</pre><p>where γ is the discount factor, and E_d is the expectation over the demand distribution d.</p><h4>Calculation Example</h4><p>Assume:</p><ul><li>h = 1, p = 5, c = 2</li><li>Possible inventory levels: s ∈ {0, 10, 20}</li><li>Possible actions: a ∈ {0, 10, 20}</li><li>Demand d is uniformly distributed over {0, 10, 20}</li><li>Discount factor γ = 0.9</li><li>Horizon T = 2</li></ul><h4>Algorithm Implementation</h4><pre>import numpy as np  <br><br># Problem Parameters<br>base_states = [0, 10, 20]  # Initial inventory levels, which represent possible starting states in the inventory management model. The inventory starts at 0, 10, or 20 units.<br>actions = [0, 10, 20]  # Possible order quantities, representing the different actions the decision-maker can take to replenish inventory. Actions can be 0 (no order), 10, or 20 units.<br>demands = [0, 10, 20]  # Possible customer demand levels, which describe the quantities of products the customers might want at each period. These can be 0, 10, or 20 units.<br>prob_demand = [1/3, 1/3, 1/3]  # The probabilities for each demand scenario. Here, the demand distribution is uniform, with each demand level having a probability of 1/3.<br><br># Cost Parameters<br>h, p, c = 1, 10, 1  # Holding cost (h = 1), penalty cost for shortage (p = 10), and ordering cost per unit (c = 1). These parameters will be used in the reward function.<br>gamma = 0.9  # Discount factor (γ = 0.9) reflects the relative importance of future rewards compared to immediate rewards. A value less than 1 discounts future costs.<br>T = 2  # Time horizon (T = 2) indicates the number of periods the decision-maker will plan for. In this case, there are two decision-making periods.<br>max_state = 20  # Maximum inventory level, representing the highest allowable state in the system. This caps the state to 20 units of inventory.<br><br># Reward Function<br>def reward(s, a, d):<br>    &quot;&quot;&quot;<br>    Computes the reward (which is the negative of total costs) based on the current state `s`, the action `a`, and the demand `d`.<br>    The reward consists of three components:<br>    - Holding cost: The cost of holding excess inventory, which is calculated as `h * max(s + a - d, 0)`, where `s + a - d` represents the inventory after ordering and satisfying demand.<br>    - Shortage cost: The penalty for failing to meet demand, which is calculated as `p * max(0, d - s - a)`, where `d - s - a` represents the unmet demand.<br>    - Order cost: The cost of placing an order, which is calculated as `c * a`.<br>    &quot;&quot;&quot;<br>    holding_cost = h * max(s + a - d, 0)  # If `s + a - d &gt; 0`, then holding cost is positive; otherwise, no holding cost.<br>    shortage_cost = p * max(0, d - s - a)  # If `d - s - a &gt; 0`, then shortage cost is positive; otherwise, no shortage cost.<br>    order_cost = c * a  # The cost of ordering `a` units.<br>    return -(holding_cost + shortage_cost + order_cost)  # The reward is the negative of the total cost (because we are minimizing cost, maximizing negative cost).<br><br># State Transition Function<br>def next_state(s, a, d):<br>    &quot;&quot;&quot;<br>    Computes the next inventory level (`s_next`) after taking action `a` in state `s` when demand `d` occurs.<br>    The inventory evolves as: `s_next = s + a - d`, but it is constrained between 0 and `max_state` to reflect the valid range of inventory levels.<br>    This function ensures that `s_next` is within [0, max_state], as negative or excessively large states are not valid.<br>    &quot;&quot;&quot;<br>    return max(0, min(max_state, s + a - d))  # Ensure that `s_next` is clamped between 0 and `max_state`.<br><br># State Space Generation<br>states = sorted(set(base_states + [next_state(s, a, d) for s in base_states for a in actions for d in demands]))<br>&quot;&quot;&quot;<br>Generates the set of all possible states that can result from any combination of base states, actions, and demands.<br>- For each combination of state `s`, action `a`, and demand `d`, we calculate the next state using the `next_state` function.<br>- This process ensures that all reachable states are captured, with each state being clamped within the range [0, max_state].<br>- The result is sorted and converted into a unique set, ensuring no duplicate states.<br>&quot;&quot;&quot;<br><br># Value Function and Policy Initialization<br>V = {t: {s: 0 for s in states} for t in range(T + 1)}  # Initialize the value function `V` for each time period `t` and each state `s`. Initially, all values are set to 0.<br>policy = {t: {s: None for s in states} for t in range(T)}  # Initialize the policy `policy` for each time period `t` and each state `s`. Initially, all policies are set to `None`.<br><br># Backward Induction Algorithm<br>for t in reversed(range(T)):  # Perform backward induction by iterating over periods in reverse order.<br>    for s in states:  # Iterate over all possible states.<br>        action_values = {}  # Dictionary to store expected values for each action.<br>        for a in actions:  # Iterate over all possible actions.<br>            if s + a &gt; max_state:  # Skip invalid actions that would result in a state exceeding the `max_state`.<br>                continue<br>            expected_value = 0  # Initialize the expected value for action `a`.<br>            for d, prob in zip(demands, prob_demand):  # Iterate over all possible demand levels `d` and their corresponding probabilities `prob`.<br>                s_next = next_state(s, a, d)  # Compute the next state after taking action `a` in state `s` with demand `d`.<br>                # Calculate the expected value of taking action `a` in state `s` at time `t`, considering the reward and the discounted future value.<br>                expected_value += prob * (reward(s, a, d) + gamma * V[t + 1][s_next])  # Add the expected reward plus the discounted future value of the next state.<br>            action_values[a] = expected_value  # Store the expected value for action `a`.<br><br>        if action_values:  # If there are valid actions to choose from.<br>            best_action = max(action_values, key=action_values.get)  # Select the action with the maximum expected value.<br>            V[t][s] = action_values[best_action]  # Update the value function `V` for state `s` at time `t` with the best expected value.<br>            policy[t][s] = best_action  # Store the best action in the policy for state `s` at time `t`.<br><br># Output Optimal Policy<br>print(&quot;Results&quot;)  # Output the results.<br>print(f&quot;\nFor T = {T}, the optimal policy could be as follows:\n&quot;)  # Inform the user of the optimal policy for `T = 2`.<br>for t in range(T):  # Iterate over each period.<br>    print(f&quot;At the beginning t = {t}:&quot;)  # Print the period.<br>    for s in sorted(policy[t].keys()):  # Iterate over all states at period `t`, sorted for clarity.<br>        action = policy[t][s]  # Retrieve the optimal action for state `s` at period `t`.<br>        if action is not None:  # If there is an optimal action (i.e., it&#39;s not `None`).<br>            print(f&quot;  If s = {s}, order a = {action}&quot;)  # Print the optimal order quantity for state `s` at period `t`.<br>    print()  # Print a newline for readability between periods.</pre><h4>Results</h4><p>For T = 2, the optimal policy could be as follows:</p><ol><li>At the beginning t = 0:</li></ol><ul><li>If s = 0, order a = 20</li><li>If s = 10, order a = 10</li><li>If s = 20, do not order a = 0</li></ul><p>2. In the next period t = 1, decisions depend on the inventory level s.</p><h4>Practical Significance of Optimal Policy for a Manager</h4><ul><li><strong>Cost optimization</strong>: the policy helps minimize shortage penalties and storage costs.</li><li><strong>Adaptation to uncertainty</strong>: the optimal policy accounts for demand probabilities.</li><li><strong>Long-term strategy</strong>: using discounting helps focus on long-term benefits.</li></ul><p>This <strong>optimal policy</strong> provides the manager with a <strong>clear rule of action</strong>, minimizing subjective errors and suboptimal decisions.</p><p>Markov Decision Processes (MDPs) hold significant historical and mathematical value in management. Historically, MDPs emerged at the crossroads of several mathematical disciplines. They draw from <strong>probability theory</strong>, including foundational work on Markov chains (1906–1907), <strong>dynamic programming</strong> developed by Bellman in the 1950s, <strong>optimal control theory</strong>, and <strong>game theory</strong>. This interdisciplinary origin highlights their versatility and depth.</p><blockquote>From a mathematical perspective, MDPs rely on key domains. Probability theory contributes concepts such as <strong>conditional probabilities</strong>, <strong>Markov processes</strong>, and <strong>stochastic processes</strong>. Mathematical analysis further strengthens the framework with tools from <strong>functional analysis</strong>, <strong>optimization theory</strong>, and <strong>differential equations</strong>. Together, these elements provide a comprehensive foundation for addressing decision-making challenges in uncertain environments.</blockquote><h3>1.3 Practical Value of MDPs</h3><p>MDPs offer significant practical benefits. First, they provide mathematical rigor by formalizing uncertainty, quantifying risks, and optimizing decision-making processes. Second, they exhibit model flexibility, allowing adaptation to various scales of management, accounting for multiple parameters, and enabling modifications for specific tasks. Finally, MDPs possess strong analytical potential, making it possible to predict consequences, evaluate alternatives, and optimize resource allocation.</p><h3>1.4 Modern Applications of MDPs</h3><p>In strategic planning, MDPs are used to evaluate long-term consequences, conduct scenario analyses, and manage risks. In operational management, they support process optimization, resource allocation, and inventory management. In financial planning, MDPs aid in investment decisions, portfolio management, and budgeting.</p><p>By providing a robust mathematical framework, MDPs enable the formalization and resolution of complex management challenges, balancing mathematical rigor with practical applicability across various domains.</p><p>We can also interpret the components of an MDP in the following way:</p><ul><li><strong>S (state space):</strong> provides a clear description of the current situation.</li><li><strong>A (action space):</strong> represents a catalog of possible decisions or actions.</li><li><strong>P (transition function):</strong> models the consequences of taking specific actions.</li><li><strong>R (reward function):</strong> evaluates the outcomes of decisions, offering a measure of success or benefit.</li><li><strong>γ (discount factor):</strong> accounts for time preference by balancing immediate and future rewards.</li></ul><h4>Optimization of Strategy</h4><p>The goal of an MDP is to find an optimal policy <strong>π∗</strong>​ defined as:</p><pre>import numpy as np<br><br>def optimal_policy(P, R, gamma, s_0):<br>    return np.argmax([np.sum([gamma**t * R[s_t, a_t] * P[s_t, a_t] for t in range(len(P))]) for a_t in A])</pre><p>Where the policy maximizes the expected long-term reward:</p><pre>from scipy import sum<br><br>def expected_return(P, R, gamma, s_0, pi):<br>    return sum([gamma**t * R[s_t, pi[s_t]] for t, s_t in enumerate(P)])</pre><p>This equation allows for:</p><ul><li>Maximizing long-term benefit</li><li>Considering uncertainty</li><li>Balancing short-term and long-term objectives</li></ul><h3>1.5 Optimal Value Equation</h3><p>The value function V(<strong>s</strong>), which represents the maximum expected reward, satisfies the Bellman equation:</p><pre>V_star(s) = max_a [R(s, a) + gamma * sum_s&#39; P(s&#39;|s, a) * V_star(s&#39;)]</pre><p>Similarly, the Q-function (action-value function) is defined as:</p><pre>Q_star(s, a) = R(s, a) + gamma * sum_s&#39; P(s&#39;|s, a) * max_a&#39; Q_star(s&#39;, a&#39;)</pre><p>These equations form the foundation of RL algorithms, embodying its philosophy of managing actions and their consequences in a multi-objective environment.</p><p><em>Let us analyze these equations in the context of managerial decision-making.</em></p><p>The equation for the optimal value in management can be expressed as:</p><pre>from scipy import sum, max<br><br>def optimal_value(V_star, R, P, gamma, s):<br>    return max([R[s, a] + gamma * sum(P[s, a, s_prime] * V_star[s_prime] for s_prime in P[s, a]) for a in R[s]])</pre><p>Where:</p><ul><li>V_star(s) is the maximum expected value (benefit) from being in <strong>a</strong> given state <strong>s.</strong></li><li>R(s, a) is the immediate reward (e.g., profit) from taking action <strong>a</strong> in state <strong>s.</strong></li><li>gamma (0&lt;γ&lt;1) is the discount factor for future rewards.</li><li>P(s&#39;|s, a) is the probability of transitioning to <strong>a</strong> new state<strong> s′</strong> after taking action <strong>a</strong>.</li><li>V_star(s&#39;) is the value of the new state <strong>s′</strong>.</li></ul><p>In practice, this means the optimal strategy considers:</p><ol><li>Immediate outcomes of the decision.</li><li>Long-term consequences with their probabilities.</li><li>A balance between short-term and long-term benefits.</li></ol><h4>Q-Function</h4><p>The Q-function generalizes this understanding:</p><pre>def q_function(Q_star, R, P, gamma, s, a):<br>    return R[s, a] + gamma * sum(P[s, a, s_prime] * max(Q_star[s_prime, a_prime] for a_prime in Q_star[s_prime]) for s_prime in P[s, a])</pre><p>Where:</p><p>Q_star(s, a) evaluates the value of a specific decision <strong>a</strong> in state <strong>s</strong>, considering:</p><ul><li>Immediate outcomes.</li><li>All possible consequences.</li><li>Optimal decisions in future states.</li></ul><p>The <strong>Q-function</strong> Q∗(s, a) generalizes the understanding of the value of a state V∗(s) by adding the context of a specific action a. This can be observed as follows:</p><ol><li>V∗(s) represents the maximum expected reward achievable starting from state s, assuming the optimal policy is used.</li><li>Q∗(s, a) not only considers the state s but also evaluates the expected reward for a specific action a, assuming this action is chosen.</li></ol><p>Formally, the relationship between V∗(s) and Q∗(s, a) is expressed as:</p><pre>V_star_s = max_a(Q_star_s_a)</pre><p>or:</p><pre>V_star_s = amax(Q_star_s_a)</pre><p>This generalization is crucial for control and decision-making because the <strong>Q-function</strong> allows the analysis of both the consequences of state selection and the evaluation of specific action outcomes.</p><h4>Mathematical Context</h4><p>The value function V∗(s) is defined as:</p><pre>V_star_s = max_a [R(s, a) + γ * Σ P(s&#39;|s, a) * V_star_s_prime]</pre><p>Here:</p><ul><li>R(s, a) is the reward for taking action a in state s.</li><li>γ is the discount factor.</li><li>P(s&#39;|s, a) is the probability of transitioning to state s&#39; from s after taking action a.</li></ul><p>Similarly, the Q-function is defined as:</p><pre>Q_star_s_a = R(s, a) + γ * Σ P(s&#39;|s, a) * max_a_prime Q_star_s_prime_a_prime</pre><h4>Interpretation in Control Systems</h4><ol><li>The <strong>state value</strong> V∗(s) focuses on the long-term reward potential of a state under the optimal policy.</li><li>The <strong>Q-function</strong> Q∗(s, a) refines this understanding by considering immediate rewards and potential future outcomes of specific actions.</li></ol><h4>Practical Significance:</h4><ul><li><strong>Decision Optimization</strong>: Q∗(s, a) allows choosing the best actions based on current and expected future outcomes.</li><li><strong>Granular Control</strong>: Enables fine-grained evaluation of specific decisions, facilitating better action planning in dynamic environments.</li></ul><h4>Applications in Management</h4><blockquote>These two equations mentioned above (the <strong>Optimal value function equation</strong> and the <strong>Q-function equation</strong>) help in:</blockquote><ol><li>Evaluating long-term consequences of decisions.</li><li>Accounting for future uncertainties.</li><li>Balancing risks and rewards.</li><li>Making more informed strategic decisions.</li></ol><p><strong>Example</strong>: <em>in evaluating an investment decision, these equations help consider not only immediate profits but also strategic advantages, future opportunities, and associated risks.</em></p><h3>1.6 Advantages of RL through a Mathematical Lens</h3><h3>1.6.1 Accounting for Uncertainty</h3><p>Management often deals with uncertainty, which can be quantified using the entropy of transition probabilities:</p><pre>H(s, a) = -sum_s&#39; P(s&#39;|s, a) * log(P(s&#39;|s, a))</pre><p>The entropy H(<strong>s,a</strong>) measures the risk associated with action <strong>a</strong> in state <strong>s</strong>, a critical factor in strategic planning.</p><h4>From a management perspective:</h4><p><strong>Entropy</strong> measures the uncertainty of the outcomes of managerial decisions. Higher entropy, H(<strong>s,a</strong>), indicates less predictable consequences of a chosen action <strong>a</strong> in the current state <strong>s</strong>.</p><h4>Practical Applications:</h4><ul><li><strong>Market Expansion Strategy:</strong> high entropy suggests high risk and unpredictability in outcomes.</li><li><strong>Project Management:</strong> helps assess the risks associated with different decisions at various stages.</li><li><strong>Financial Planning:</strong> quantifies the uncertainty of various investment decisions.</li></ul><h4>Connection to MDPs (Markov Decision Processes):</h4><ol><li>In MDPs, each state <strong>s</strong> and action <strong>a</strong> are linked to transition probabilities P(<strong>s′∣s,a</strong>) for moving to subsequent states <strong>s′</strong>.</li><li>The entropy formula relies on these transition probabilities to measure uncertainty.</li><li>MDPs model the sequence of managerial decisions, accounting for their long-term consequences.</li></ol><h4>Reinforcement Learning (RL):</h4><ol><li>An agent (e.g., a decision support system) learns an optimal strategy by interacting with the environment.</li><li>Entropy plays a key role in:</li></ol><ul><li><strong>Exploration: </strong>high entropy encourages exploring new strategies.</li><li><strong>Exploitation:</strong> low entropy highlights more reliable, established solutions.</li></ul><blockquote>Balancing <strong>exploration</strong> and <strong>exploitation</strong> is crucial for finding the optimal strategy.</blockquote><h4>Practical Example:</h4><p>Imagine managing a retail chain and deciding where to open a new store.</p><ul><li><strong>State s:</strong> the current market situation.</li><li><strong>Action a:</strong> selecting a location.</li><li><strong>P(s’|s,a):</strong> probabilities of various outcomes (success/failure).</li><li><strong>H(s,a):</strong> risk assessment for each location.</li></ul><p>Low entropy is associated with locations with predictable outcomes (e.g., a mall with steady foot traffic), while high entropy corresponds to riskier areas (e.g., a new neighborhood without established shopping patterns).</p><h3>1.6.2 Long-Term Optimization</h3><p>Unlike short-term optimization methods, RL maximizes the discounted sum of rewards:</p><pre>G_t = sum(gamma**k * R(s[t+k], a[t+k]) for k in range(0, max_steps))</pre><p>where:</p><ul><li>G_t is the total expected reward starting from time t.</li><li>gamma is the discount factor (0 ≤ gamma &lt; 1).</li><li>k is the time step into the future.</li><li>R(s, a) is the immediate reward for action a in state s.</li></ul><h4>Explanation:</h4><ul><li>For k = 0: R(s_t, a_t) is the immediate reward.</li><li>For k = 1: gamma^1 * R(s_{t+1}, a_{t+1}) is the reward after 1 step.</li><li>For k = 2: gamma^2 * R(s_{t+2}, a_{t+2}) is the reward after 2 steps.</li></ul><p>This formula calculates the total expected reward starting from time t, where each step is discounted by gamma. The sum may be taken over a finite (max_steps) or infinite number of steps depending on the scenario.</p><h4>Integration into MDP:</h4><ul><li>At each state s ∈ S, an action a ∈ A is chosen.</li><li>The immediate reward R(s, a) is received.</li><li>A transition to a new state s&#39; occurs with probability P(s&#39;|s, a).</li><li>The process repeats, forming a chain of rewards.</li></ul><h4>Example:</h4><p>In strategic planning, investing in innovation might yield higher G_t despite low R(s, a) in the short term.</p><h4>Application in Management:</h4><p>This mathematical model is particularly useful for the following managerial tasks:</p><p><strong>Strategic Planning:</strong></p><ul><li>gamma close to 1: Long-term projects with delayed benefits.</li><li>gamma close to 0: Short-term projects with quick returns.</li></ul><p><strong>Investment Decisions:</strong></p><p><em>Example</em></p><ul><li>Immediate reward R(s_t, a_t) = -1000 (investment in training).</li><li>Future rewards R(s_{t+k}, a_{t+k}) = +300 annually.</li><li>With gamma = 0.9, the project may be profitable in the long term.</li></ul><p><strong>Resource Management:</strong></p><ul><li>Balance between current exploitation (high R now).</li><li>And exploring new opportunities (potentially high R in the future).</li></ul><p><strong>Employee Development:</strong></p><ul><li>Training costs (negative R now).</li><li>Increased productivity (positive R in the future).</li></ul><h4>Practical Example:</h4><p>Suppose the company is deciding between:</p><ul><li>option <strong>a:</strong> Immediate asset sale (R = 100)</li><li>option <strong>b:</strong> Modernization and subsequent sale:</li></ul><p>Year 1: R = -50 (costs)</p><p>Year 2: R = 100</p><p>Year 3: R = 150</p><p>Discount factor:gamma = 0.9</p><p>In this example, we are considering a decision-making problem that accounts for the discounting of future revenues and costs. This is a typical situation for analyzing long-term benefits in the context of reinforcement learning, where strategy optimization considers <strong>future rewards</strong>.</p><h4>Explanation:</h4><p>There are two options (decisions):</p><ol><li><strong>Immediate sale of the asset</strong> with an immediate revenue: R = 100</li></ol><p>This is a simple option where the entire benefit is obtained immediately.</p><p>2.<strong> Asset upgrade followed by sale</strong>, which includes:</p><ul><li>Year 1: Costs: R = -50 (negative value, since it’s an investment).</li><li>Year 2: Revenue: R = 100</li><li>Year 3: Revenue: R = 150</li></ul><p>We choose a discount factor: gamma = 0.9 which reduces the value of rewards received in the future based on how far they are in time.</p><h4>Calculation</h4><p><strong>1. Option a (immediate sale):</strong></p><p>Reward:</p><pre>G_a = 100</pre><p>There is no need to account for discounting, as the revenue is received immediately.</p><p><strong>2. Option b (upgrade and sale):</strong></p><p>The total reward G_b is calculated by considering the discounted costs and revenues:</p><pre>G_b = R_1 + gamma * R_2 + gamma**2 * R_3</pre><p>Where:</p><ul><li>R_1 = -50</li><li>R_2 = 100</li><li>R_3 = 150</li></ul><p>Substituting values:</p><pre>G_b = -50 + 0.9 * 100 + 0.9**2 * 150</pre><p>Step-by-step calculations:</p><ol><li>0.9**2 = 0.81</li><li>0.9 * 100 = 90</li><li>0.81 * 150 = 121.5</li><li>G_b = -50 + 90 + 121.5 = 195.5</li></ol><h4>Analysis</h4><ul><li>G_a = 100 for immediate sale.</li><li>G_b = 195.5 for upgrade and sale.</li></ul><p>Although <strong>option b</strong> involves costs in the first year and takes time to generate revenue, it is more profitable in the long run, even with discounting.</p><h4>Conclusion</h4><p>This example illustrates:</p><ol><li><strong>Long-term optimization</strong>: comparing short-term and long-term benefits, taking discounting into account.</li><li><strong>Application of the discount factor </strong>gamma: shows how gamma influences decision-making. The higher gamma, the more significant the future rewards are.</li><li><strong>Real-world approach</strong>: such analysis is often used in strategic planning for companies when choosing between current and future benefits.</li></ol><p>This illustrates how long-term optimization can lead to better results, even if the short-term performance is worse.</p><p><em>This approach reflects how MDPs and</em><strong><em> discounted rewards</em></strong><em> are used in strategic management, providing an objective and mathematically grounded framework for decision-making.</em></p><h3>1.6.3 Adaptivity via Policy Gradient</h3><p>For continuous actions, policy optimization can be achieved using the policy gradient:</p><pre>nabla_theta J(theta) = E_pi_theta [nabla_theta log pi_theta(a|s) * Q_pi_theta(s, a)]</pre><p>where theta are the policy parameters.</p><p>The formula ∇_θ J(θ) = E_π_θ [∇_θ log π_θ(a|s) * Q_π_θ(s, a)] describes:</p><ul><li>∇_θ J(θ) - gradient of the objective function with respect to the policy parameters</li><li>π_θ(a|s) - probability of selecting action a in state s under parameters θ</li><li>Q_π_θ(s, a) - state-action value function</li><li>E_π_θ [...] - expected value under policy π_θ</li></ul><p>Let’s break down the formula:</p><ol><li>∇_θ log π_θ(a|s) indicates the direction of change in the parameters to increase the probability of an action.</li><li>Q_π_θ(s, a) defines &quot;how good&quot; the action is in the long-term perspective.</li><li>Their product indicates how to change the parameters to improve the policy.</li></ol><h4>In the context of an MDP (S, A, P, R, γ), the policy gradient:</h4><ul><li>Works with continuous action space A</li><li>Uses the reward function R to calculate Q_π_θ</li><li>Considers transition probabilities P when estimating long-term value</li><li>Optimizes parameters θ to maximize the expected reward</li></ul><h4>This mathematical model is especially useful for:</h4><p><strong>Adaptive Resource Management:</strong></p><ul><li>s: current resources, market conditions</li><li>a: resource allocation</li><li>Q_π_θ: assessment of the long-term effectiveness of decisions</li></ul><p><em>Example: </em>dynamic budget distribution among projects</p><p><strong>Pricing Policy:</strong></p><ul><li>s: market situation</li><li>a: price setting (continuous action)</li><li>Q_π_θ: long-term profit</li></ul><p><em>Example: </em>adaptive pricing based on demand</p><p><strong>Personnel Management:</strong></p><ul><li>s: team productivity</li><li>a: level of motivational payments</li><li>Q_π_θ: balance between costs and results<br> <em>Example:</em></li></ul><pre>Initial state: 70% productivity<br>Action: increase bonuses by 15%<br>Q-value: considers productivity growth and costs</pre><p><strong>Investment Strategies:</strong></p><ul><li>s: asset portfolio</li><li>a: percentage of investment allocation</li><li>Q_π_θ: long-term returns</li></ul><p><em>Example:</em></p><pre>State: high market volatility<br>Action: change the share of risky assets<br>Q-value: expected return considering risk</pre><h4>Practical Applications:</h4><p><strong>Business Process Optimization:</strong></p><pre>theta: process parameters<br>pi_theta: current management strategy<br>Q_pi_theta: process efficiency</pre><p><strong>Adaptive Planning:</strong></p><ul><li>Continuous adjustment of the strategy based on new data</li><li>Consideration of long-term consequences of decisions</li><li>Balancing exploration of new opportunities and using proven solutions</li></ul><p><strong>Risk Management:</strong></p><ul><li>Continuous adaptation to market changes</li><li>Optimizing the risk/return ratio</li><li>Dynamic hedging of risks</li></ul><p><em>Thus, the policy gradient provides the mathematical framework for creating adaptive management systems capable of optimizing long-term results in conditions of uncertainty and a changing environment.</em></p><h3>1.7 Metrics for Management Performance</h3><h3>1.7.1 Optimal Policy Efficiency</h3><p>The quality of management can be evaluated using the efficiency metric E:</p><pre>E = (1/T) * sum_{t=1}^T V_pi(s_t) / V_star(s_t)</pre><p>If 1E≈1, the system operates optimally.</p><p>Let’s break down each element:</p><ul><li>T - total time period</li><li>V_pi(s_t) - value of the current policy at state s at time t</li><li>V_star(s_t) - value of the optimal policy at state s at time t</li><li>The ratio V_pi / V_star shows how close the current policy is to the optimal one.</li></ul><p>When E ≈ 1, it means that:</p><ul><li>The current policy is almost as effective as the optimal policy</li><li>The system operates close to maximum efficiency</li><li>Management decisions are close to ideal</li></ul><h3>1.7.2 Adaptation Speed</h3><p>The rate of policy adjustment to new conditions can be formalized as:</p><pre>A = (1/delta_t) * |delta V_pi(s) / delta P(s&#39;|s, a)|</pre><p>where delta_t​ is the time interval of changes.</p><p>Here:</p><ul><li>Δt - time interval</li><li>ΔV_π(s) - change in policy value</li><li>ΔP(s&#39;|s,a) - change in transition probability to a new state</li><li>The modulus shows the absolute magnitude of changes.</li></ul><h4>Relationship with MDP (Markov Decision Process):</h4><p>These two metrics are based on fundamental concepts of MDP:</p><ul><li>the value function V_π(s) defines the expected long-term reward.</li><li>the optimal value function V*(s) shows the maximum possible reward.</li><li>transition probabilities P(s&#39;|s,a) describe the system&#39;s dynamics.</li></ul><h4>Practical Benefit for Management:</h4><p>The <strong>efficiency metric (E)</strong> allows:</p><ul><li>Evaluating the quality of decisions made.</li><li>Identifying areas for improvement.</li><li>Comparing the efficiency of different departments or periods.</li><li>Determining the need for strategy adjustments.</li></ul><p>The <strong>adaptation metric (A)</strong> helps:</p><ul><li>Measuring the organization’s response time to changes.</li><li>Assessing the flexibility of management processes.</li><li>Identifying barriers to rapid adaptation.</li><li>Optimizing decision-making processes.</li></ul><h4>Practical Applications:</h4><ul><li><em>Evaluation of managers’ performance.</em></li><li><em>Business process optimization.</em></li><li><em>Development of incentive systems.</em></li><li><em>Strategic planning.</em></li><li><em>Change management.</em></li></ul><h4>Benefits of Use:</h4><ul><li>Objective evaluation of management quality.</li><li>Quantitative justification of decisions.</li><li>Ability to forecast outcomes.</li><li>A systematic approach to process improvement.</li></ul><h4>These two metrics are especially useful for:</h4><ul><li>Large organizations with complex processes.</li><li>Rapidly changing markets.</li><li>Business transformation projects.</li><li>Evaluating the effectiveness of investments in process improvement.</li></ul><h3>1.8 Example: Investment Portfolio Optimization</h3><p>Consider a portfolio with two assets:</p><ul><li><strong>s</strong>: current portfolio state;</li><li><strong>a</strong>: allocation of investments to assets.</li></ul><p>The reward function is:</p><pre>R(s, a) = ROI(a) - lambda * Risk(a)</pre><p>where lambda is the risk aversion coefficient.</p><p><em>Let’s examine the application of Markov Decision Process (MDP) in the context of investment portfolio management.</em></p><p>In MDP terms, we have:</p><p><strong>1. States (S):</strong><br>- <strong>s</strong> represents the current portfolio state<br>- can include: current asset allocation, market conditions, asset prices<br>- for example, <strong>s₀</strong> = {60% stocks, 40% bonds}</p><p><strong>2. Actions (A):</strong><br>- <strong>a</strong> represents investment reallocation decisions<br>- for example, <strong>a₁</strong> = {increase stock share by 10%}<br>- each action changes the portfolio state</p><p><strong>3. Transition function P(s’|s,a):</strong><br>- probability of transitioning to new state <strong>s’</strong> from current state <strong>s</strong> when taking action <strong>a</strong><br>- reflects market uncertainty<br>- for example, P(<strong>s’|s,a</strong>) = 0.7 means 70% probability of achieving target state after rebalancing</p><p><strong>4. Reward function R(s,a):</strong><br>R(<strong>s,a</strong>) = ROI(<strong>a</strong>) —<strong> lambda</strong> * Risk(<strong>a</strong>), where:<br>- <strong>ROI(a)</strong> — expected return from action <strong>a</strong><br>- <strong>Risk(a) </strong>— risk associated with action <strong>a</strong><br>-<strong> lambda</strong> — risk aversion coefficient (higher means more conservative strategy)</p><p><strong>5. Policy π(s):</strong><br>- decision-making strategy<br>- determines which action <strong>a</strong> to choose in state <strong>s</strong><br>- optimal policy <strong>π* </strong>maximizes long-term reward</p><p><strong>6. Value function V(s):</strong><br>- evaluates the “quality” of state <strong>s</strong><br>- considers both immediate reward and future opportunities<br>- helps choose the best actions</p><p><em>Practical application:</em></p><p><strong>1. System constantly monitors:</strong><br>- current portfolio state<br>- market conditions<br>- risk metrics</p><p><strong>2. At each step:</strong><br>- evaluates possible rebalancing actions<br>- forecasts probable outcomes<br>- chooses action with optimal risk-return balance</p><p><strong>3. Learning:</strong><br>- system learns from historical data<br>- improves transition probability forecasts<br>- adapts strategy to market changes</p><p><em>This is an example of how MDP can be applied to create an intelligent portfolio management system capable of making informed decisions under uncertainty.</em></p><h3>1.9 Numerical Example</h3><p>Let:</p><pre>P(s&#39;|s, a) = <br>[[0.7, 0.3],<br> [0.4, 0.6]],<br><br>R(s, a) = <br>[[10, 5],<br> [8, 12]]</pre><p>The optimal policy <strong>pi_star</strong> is obtained by solving the Bellman equation:</p><pre>V_star(s) = max_a [R(s, a) + gamma * sum_s&#39; P(s&#39;|s, a) * V_star(s&#39;)]</pre><p>Let’s break down this numerical example step by step.</p><p>We have:</p><p><strong>1. Transition probability matrix P(s’|s, a):</strong><br>- <strong>P[0,0]</strong> = 0.7 means that being in state <strong>s</strong>=0 and choosing action <strong>a</strong>=0, the probability to remain in state <strong>s’</strong>=0 is 0.7<br>- <strong>P[0,1]</strong> = 0.3 is the probability to transition to state <strong>s’</strong>=1<br>- <strong>P[1,0]</strong> = 0.4 from state <strong>s</strong>=1 with action <strong>a</strong>=0, probability to transition to <strong>s’</strong>=0<br>- <strong>P[1,1] </strong>= 0.6 is the probability to remain in <strong>s’</strong>=1</p><p><strong>2. Reward matrix R(s,a):</strong><br>- <strong>R[0,0]</strong> = 10 — reward for choosing action <strong>a</strong>=0 in state <strong>s</strong>=0<br>- <strong>R[0,1]</strong> = 5 — reward for <strong>a</strong>=1 in <strong>s</strong>=0<br>- <strong>R[1,0] </strong>= 8 — reward for <strong>a</strong>=0 in <strong>s</strong>=1<br>- <strong>R[1,1]</strong> = 12 — reward for <strong>a</strong>=1 in <strong>s</strong>=1</p><p><strong>The Bellman equation states:</strong><br>The optimal state value V_star(s) equals the maximum over all actions<strong> a</strong> of:<br>[immediate reward R(<strong>s,a</strong>) + discount factor gamma × sum over all next states <strong>s’</strong> of the product of transition probability P(<strong>s’|s,a</strong>) and the next state value V_star(<strong>s’</strong>)]</p><p>By solving this equation, we will find the optimal V_star values for each state, and then we can determine the optimal policy <strong>pi_star</strong> — which action to choose in each state to maximize the total reward considering future transitions.</p><p>This is a classic example of a Markov Decision Process (MDP) problem, where we seek the optimal strategy of actions considering the probabilistic nature of transitions between states and the rewards received.</p><h3>1.10 Philosophical Dimensions of Management</h3><h3>1.10.1 Rational Decision Principles</h3><p>Management decisions follow the principle of maximizing expected utility:</p><pre>pi_rational(s) = argmax_a E[U(s, a)]</pre><p>where U(s,a) is the subjective utility function.</p><p>Let us delve into the mathematical framework in detail. The formula π_rational(s) = argmax_a E[U(s, a)] uses the expectation operator E, which accounts for all possible outcomes of action <strong>a</strong> in state <strong>s</strong>, weighted by their probabilities. The full expression can be written as:</p><pre>from scipy import sum<br><br>E_U = lambda s, a: sum(P(s_prime, s, a) * U(s, a, s_prime) for s_prime in S)</pre><p>Here, summation is over all possible next states <strong>s′</strong>. This directly relates to a Markov Decision Process (MDP), where we also deal with transition probabilities P(<strong>s′∣s,a</strong>) and rewards for these transitions.</p><p>The operator argmax in this context selects the action <strong>a</strong> that maximizes the expected utility E[U(<strong>s,a</strong>)]:</p><pre>import numpy as np<br><br>pi_rational = lambda s: np.argmax([E_U(s, a) for a in A])</pre><p>This means that the policy <strong>π</strong> maps each state<strong> s</strong> to the action <strong>a</strong> that provides the maximum expected utility. In classical MDPs, we typically use the value function V(<strong>s</strong>) or the Q-function Q(<strong>s,a</strong>), but here the utility function U(<strong>s,a</strong>) serves that purpose.</p><h4>Practical Implications for Management</h4><p>In real-world management scenarios, decision-makers must frequently make choices under uncertainty. Formalizing this process through expected utility allows for a structured and objective decision-making framework. For instance, in evaluating investment projects, the utility function may account for not only expected profit but also the company’s attitude toward risk, strategic advantages, and social factors.</p><blockquote>In the management context, the utility function U(s,a) is often subjective and reflects various organizational priorities. These may include financial indicators, reputational effects, long-term strategic benefits, or corporate social responsibility. The MDP framework enables a formal consideration of these factors and facilitates finding an optimal balance among the organization’s goals.</blockquote><h4>Value of MDP in Long-Term Strategic Decisions</h4><p>This approach is especially valuable in scenarios where decisions have long-term consequences and involve significant uncertainty. Examples include:</p><ul><li><strong>Developing a company’s growth strategy:</strong> determining the optimal course of action to balance risk and reward over time.</li><li><strong>Making major investment decisions:</strong> evaluating opportunities by incorporating strategic and financial dimensions.</li><li><strong>Reorganizing business processes:</strong> optimizing processes while considering both short-term and long-term impacts.</li></ul><p>The formal mathematical framework not only supports more rational decision-making but also provides a documented logic for decisions. This is crucial for corporate governance and training future managers.</p><h3>1.10.2 Modeling Human Factors</h3><p>Considering human factors, the reward function can be extended as:</p><pre>R&#39;(s, a) = R(s, a) + alpha * H(s, a) + beta * S(s, a)</pre><p>where:</p><ul><li>H(<strong>s,a</strong>): expertise factor;</li><li>S(<strong>s,a</strong>): social factor;</li><li>alpha,beta: weight coefficients.</li></ul><p>RL based on MDP is a powerful management tool that accounts for uncertainty, long-term perspectives, and adaptivity. Its mathematical formalism, integration with management philosophy, and real-world applicability make it a prioritized approach in modern business problem-solving.</p><h3>2. “Frozen Market” Game</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ozbz8gKEWCRPixqt7S17w.png" /></figure><p>We will use a custom implementation of the “Frozen Lake” game prototype to emulate the operation of external RL modules in the context of optimizing the Dynamics 365 ML infrastructure.</p><h3>2.1 Explanation of Custom Environment Adaptation</h3><h4>Simulating the “Frozen Lake” Environment</h4><p>The provided code simulates a grid-based environment inspired by “Frozen Lake.” In this environment, an agent navigates a grid to reach a goal, encountering “frozen” cells (safe paths) and “hole” cells (obstacles). Additionally, the environment includes slipping mechanics, where the agent’s intended action can randomly change.</p><p><em>While this custom implementation retains the simplicity of the original “Frozen Lake” concept, it is tailored for demonstrations and can be extended to mimic more complex scenarios.</em></p><p><strong>Real Scenarios in Dynamics 365:</strong></p><p>Dynamics 365 includes processes and data related to customer management (e.g., CRM scenarios), business process management, sales, etc.</p><p>An RL agent in this system could, for example:</p><ul><li>Automatically select optimal actions for customer interaction (e.g., sending an email, offering a discount, etc.).</li><li>Optimize business process flows based on historical data.</li></ul><p>It is important to note that every “environment” for RL involves the concept of states, actions, and rewards.</p><p><strong>Custom Environment Adaptation:</strong></p><p>To simulate realistic Dynamics 365 scenarios, we use a custom environment inspired by “Frozen Lake” but adapted to represent real-world business events and interactions.</p><ol><li><strong>State:</strong> represents the customer or the current stage of a business process.</li><li><strong>Actions:</strong> represents available decisions (e.g., offering a product, changing communication strategy).</li><li><strong>Reward:</strong> reflects the success of the interaction, such as increased sales or positive customer feedback.</li></ol><p><strong>Example of a Custom Environment:</strong><br>We aim to create a custom RL environment in Dynamics 365 to optimize customer interactions.</p><p><strong>Define States:</strong><br>States may include parameters such as the customer’s interaction history, the current deal status, customer interests, etc.</p><p><strong>Define Actions:</strong><br>Actions could include calling the customer, sending an email, offering a discount, or providing a special service.</p><p><strong>Define the Reward Function:</strong><br>The reward could measure how the agent influenced conversion rates (e.g., deal success) or customer satisfaction levels.</p><p><strong>Example of the “Frozen Lake” game:</strong></p><pre>import numpy as np<br>import random<br>import matplotlib.pyplot as plt<br>from IPython.display import clear_output<br>import time<br><br>class Dynamics365FrozenLake:<br>    &quot;&quot;&quot;<br>    Simulates a grid-based frozen lake environment with obstacles and slipping mechanics.<br>    The goal is to navigate from the top-left corner to the bottom-right corner while avoiding obstacles.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, grid_size=4, slip_probability=0.2):<br>        &quot;&quot;&quot;<br>        Initialize the environment.<br>        :param grid_size: Size of the grid (e.g., 4x4, but can be adjusted).<br>        :param slip_probability: Probability that the agent&#39;s intended action slips to a random one.<br>        &quot;&quot;&quot;<br>        self.grid_size = grid_size  # Dimensions of the square grid.<br>        self.slip_probability = slip_probability  # Chance of random unintended actions.<br>        self.goal_position = (grid_size - 1, grid_size - 1)  # Goal is at the bottom-right corner.<br>        self.state = (0, 0)  # Start position at the top-left corner.<br>        self.obstacles = [(1, 1), (2, 2), (3, 1)]  # Static obstacles representing hazards.<br><br>    def reset(self):<br>        &quot;&quot;&quot;<br>        Resets the environment to its initial state.<br>        :return: The starting state (0, 0).<br>        &quot;&quot;&quot;<br>        self.state = (0, 0)  # Reset the agent&#39;s position.<br>        return self.state<br><br>    def step(self, action):<br>        &quot;&quot;&quot;<br>        Executes an action in the environment and determines the next state, reward, and if the episode ends.<br>        :param action: Integer representing one of the four possible actions:<br>                       0 (up), 1 (right), 2 (down), 3 (left).<br>        :return: A tuple of (new_state, reward, done) where:<br>                 - new_state: The updated position of the agent.<br>                 - reward: The reward received after the action.<br>                 - done: Boolean indicating if the episode has ended.<br>        &quot;&quot;&quot;<br>        # Define possible moves corresponding to actions.<br>        moves = {<br>            0: (-1, 0),  # Move up.<br>            1: (0, 1),   # Move right.<br>            2: (1, 0),   # Move down.<br>            3: (0, -1)   # Move left.<br>        }<br><br>        # Simulate slipping, which may lead to a random unintended action.<br>        if random.random() &lt; self.slip_probability:<br>            action = random.choice([0, 1, 2, 3])<br><br>        # Calculate the new position based on the action.<br>        new_position = (<br>            self.state[0] + moves[action][0],<br>            self.state[1] + moves[action][1]<br>        )<br><br>        # Ensure the new position is within the grid bounds.<br>        if 0 &lt;= new_position[0] &lt; self.grid_size and 0 &lt;= new_position[1] &lt; self.grid_size:<br>            self.state = new_position  # Update state if within bounds.<br><br>        # Handle obstacle collisions or reaching the goal.<br>        if self.state in self.obstacles:<br>            return self.state, -10, True  # High penalty for hitting an obstacle.<br>        if self.state == self.goal_position:<br>            return self.state, 10, True   # High reward for reaching the goal.<br><br>        # Return a small penalty for regular movements to encourage efficiency.<br>        return self.state, -1, False<br><br>    def render(self):<br>        &quot;&quot;&quot;<br>        Prints a text-based visualization of the environment.<br>        &#39;O&#39;: Empty cells.<br>        &#39;X&#39;: Obstacles.<br>        &#39;G&#39;: Goal.<br>        &#39;A&#39;: Current position of the agent.<br>        &quot;&quot;&quot;<br>        # Create a grid representation.<br>        grid = [[&quot;O&quot; for _ in range(self.grid_size)] for _ in range(self.grid_size)]<br>        grid[self.goal_position[0]][self.goal_position[1]] = &quot;G&quot;  # Mark the goal.<br>        for obstacle in self.obstacles:<br>            grid[obstacle[0]][obstacle[1]] = &quot;X&quot;  # Mark obstacles.<br>        grid[self.state[0]][self.state[1]] = &quot;A&quot;  # Mark the agent&#39;s position.<br><br>        # Print the grid row by row.<br>        print(&quot;\n&quot;.join([&quot; &quot;.join(row) for row in grid]))<br>        print(&quot;\n&quot;)<br><br>class QLearningAgent:<br>    &quot;&quot;&quot;<br>    Implements a Q-learning agent to learn an optimal policy for navigating the environment.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, env, learning_rate=0.1, discount_factor=0.9, exploration_rate=1.0, exploration_decay=0.99):<br>        &quot;&quot;&quot;<br>        Initialize the Q-learning agent.<br>        :param env: The environment instance the agent will interact with.<br>        :param learning_rate: The step size for Q-value updates.<br>        :param discount_factor: Discount rate for future rewards.<br>        :param exploration_rate: Initial probability of choosing a random action.<br>        :param exploration_decay: Rate at which exploration probability decreases.<br>        &quot;&quot;&quot;<br>        self.env = env  # Environment the agent will interact with.<br>        self.learning_rate = learning_rate  # Learning rate for Q-value updates.<br>        self.discount_factor = discount_factor  # Discount factor for future rewards.<br>        self.exploration_rate = exploration_rate  # Initial exploration rate.<br>        self.exploration_decay = exploration_decay  # Decay factor for exploration.<br><br>        # Initialize the Q-table with zeros for all state-action pairs.<br>        self.q_table = {}<br>        self.initialize_q_table()<br><br>        # Metrics for tracking training progress.<br>        self.training_rewards = []  # Total rewards per episode.<br>        self.episode_lengths = []  # Steps taken per episode.<br>        self.success_rate = []  # Moving average success rate.<br>        self.window_size = 100  # Window size for moving averages.<br><br>    def initialize_q_table(self):<br>        &quot;&quot;&quot;<br>        Initializes the Q-table with zeros for each state-action pair.<br>        Each state has a list of 4 actions initialized to 0.<br>        &quot;&quot;&quot;<br>        for x in range(self.env.grid_size):<br>            for y in range(self.env.grid_size):<br>                self.q_table[(x, y)] = [0, 0, 0, 0]  # 4 actions per state.<br><br>    def choose_action(self, state):<br>        &quot;&quot;&quot;<br>        Chooses an action using an epsilon-greedy policy.<br>        :param state: The current state of the agent.<br>        :return: The chosen action (integer: 0, 1, 2, or 3).<br>        &quot;&quot;&quot;<br>        # Explore randomly with probability exploration_rate.<br>        if random.random() &lt; self.exploration_rate:<br>            return random.choice([0, 1, 2, 3])<br>        # Exploit by choosing the action with the highest Q-value.<br>        return np.argmax(self.q_table[state])<br><br>    def update_q_table(self, state, action, reward, next_state):<br>        &quot;&quot;&quot;<br>        Updates the Q-value for a given state-action pair using the Bellman equation.<br>        :param state: The current state.<br>        :param action: The action taken.<br>        :param reward: The reward received after the action.<br>        :param next_state: The resulting state after the action.<br>        &quot;&quot;&quot;<br>        best_next_action = np.max(self.q_table[next_state])  # Best Q-value for the next state.<br>        self.q_table[state][action] += self.learning_rate * (<br>            reward + self.discount_factor * best_next_action - self.q_table[state][action]<br>        )<br><br>    def train(self, episodes=1000, render_interval=100):<br>        &quot;&quot;&quot;<br>        Trains the agent using Q-learning over multiple episodes.<br>        :param episodes: Total number of training episodes.<br>        :param render_interval: Interval at which metrics are displayed and updated.<br>        &quot;&quot;&quot;<br>        success_count = 0  # Track successful episodes.<br><br>        for episode in range(episodes):<br>            state = self.env.reset()  # Reset environment at the start of each episode.<br>            total_reward = 0  # Total reward accumulated during the episode.<br>            steps = 0  # Count of steps taken in the episode.<br>            done = False  # Track if the episode has ended.<br><br>            while not done:<br>                action = self.choose_action(state)  # Choose action.<br>                next_state, reward, done = self.env.step(action)  # Take action and observe result.<br>                self.update_q_table(state, action, reward, next_state)  # Update Q-table.<br>                state = next_state  # Update state to the new state.<br>                total_reward += reward  # Accumulate reward.<br>                steps += 1  # Increment step counter.<br><br>                if steps &gt; 100:  # Prevent infinite episodes by limiting maximum steps.<br>                    done = True<br><br>            # Update exploration rate and metrics.<br>            self.exploration_rate *= self.exploration_decay<br>            self.training_rewards.append(total_reward)<br>            self.episode_lengths.append(steps)<br><br>            # Track success rate over a moving window.<br>            if total_reward &gt; 0:  # Successful episode if the goal is reached.<br>                success_count += 1<br><br>            if episode &gt;= self.window_size - 1:<br>                success = sum(1 for r in self.training_rewards[-self.window_size:] if r &gt; 0) / self.window_size<br>                self.success_rate.append(success)<br><br>            # Periodically display progress and metrics.<br>            if episode % render_interval == 0:<br>                clear_output(wait=True)<br>                print(f&quot;\nEpisode {episode}/{episodes}&quot;)<br>                print(f&quot;Exploration rate: {self.exploration_rate:.2f}&quot;)<br>                print(f&quot;Success rate: {success_count/(episode+1):.2%}&quot;)<br>                print(f&quot;Average reward: {np.mean(self.training_rewards[-render_interval:]):.2f}&quot;)<br>                print(f&quot;Average steps: {np.mean(self.episode_lengths[-100:]):.2f}&quot;)<br>                self.plot_metrics()<br>                plt.pause(0.1)<br><br>    def plot_metrics(self):<br>        &quot;&quot;&quot;<br>        Plots three key metrics collected during the training of an agent.<br>        &quot;&quot;&quot;<br>        # Set the size of the entire figure<br>        plt.figure(figsize=(15, 5))<br>        <br>        # Plotting total rewards per episode<br>        plt.subplot(131)  # Create a subplot in a 1x3 grid, first plot<br>        plt.plot(self.training_rewards)  # Plot training rewards over episodes<br>        plt.title(&#39;Total Rewards per Episode&#39;)  # Title of the first plot<br>        plt.xlabel(&#39;Episode&#39;)  # Label for the x-axis<br>        plt.ylabel(&#39;Total Reward&#39;)  # Label for the y-axis<br>        <br>        # Plotting episode lengths (steps taken per episode)<br>        plt.subplot(132)  # Create a subplot in a 1x3 grid, second plot<br>        plt.plot(self.episode_lengths)  # Plot the lengths of episodes<br>        plt.title(&#39;Episode Length&#39;)  # Title of the second plot<br>        plt.xlabel(&#39;Episode&#39;)  # Label for the x-axis<br>        plt.ylabel(&#39;Steps&#39;)  # Label for the y-axis<br>        <br>        # Plotting the success rate as a moving average (if data exists)<br>        if self.success_rate:  # Check if the success rate data is available<br>            plt.subplot(133)  # Create a subplot in a 1x3 grid, third plot<br>            plt.plot(self.success_rate)  # Plot the success rate<br>            plt.title(&#39;Success Rate (Moving Average)&#39;)  # Title of the third plot<br>            plt.xlabel(&#39;Episode&#39;)  # Label for the x-axis<br>            plt.ylabel(&#39;Success Rate&#39;)  # Label for the y-axis<br>        <br>        # Adjust layout to prevent overlapping of plots and titles<br>        plt.tight_layout()<br><br><br>def visualize_path(env, agent):<br>    &quot;&quot;&quot;<br>    Visualizes the path taken by the agent in the environment.<br>    <br>    Parameters:<br>    - env: The environment in which the agent operates.<br>    - agent: The agent being visualized (implements a choose_action method).<br>    <br>    Returns:<br>    - path: A list of actions taken by the agent during the visualization.<br>    &quot;&quot;&quot;<br>    state = env.reset()  # Reset the environment and get the initial state<br>    env.render()  # Render the environment&#39;s initial state<br>    done = False  # Initialize the termination flag<br>    path = []  # List to store actions taken by the agent<br>    <br>    while not done:  # Loop until the episode is complete<br>        action = agent.choose_action(state)  # Agent selects an action<br>        path.append(action)  # Store the action in the path<br>        state, _, done = env.step(action)  # Take a step in the environment<br>        <br>        # Introduce a delay to slow down visualization for better clarity<br>        time.sleep(0.5)<br>        <br>        # Clear the previous output to refresh the rendered environment<br>        clear_output(wait=True)<br>        <br>        # Render the updated environment state<br>        env.render()<br>    <br>    return path  # Return the sequence of actions taken<br><br><br>def test_agent(env, agent, episodes=100):<br>    &quot;&quot;&quot;<br>    Tests the agent&#39;s performance over multiple episodes.<br>    <br>    Parameters:<br>    - env: The environment to test in<br>    - agent: The trained agent to test<br>    - episodes: Number of test episodes (default: 100)<br>    <br>    Returns:<br>    - Dictionary containing test metrics (success rate, average reward, average steps)<br>    &quot;&quot;&quot;<br>    successes = 0<br>    total_rewards = []<br>    total_steps = []<br>    <br>    for episode in range(episodes):<br>        state = env.reset()<br>        episode_reward = 0<br>        steps = 0<br>        done = False<br>        <br>        while not done and steps &lt; 100:  # Limit steps to prevent infinite loops<br>            action = agent.choose_action(state)<br>            state, reward, done = env.step(action)<br>            episode_reward += reward<br>            steps += 1<br>            <br>        if episode_reward &gt; 0:  # Consider episode successful if reward is positive<br>            successes += 1<br>            <br>        total_rewards.append(episode_reward)<br>        total_steps.append(steps)<br>    <br>    return {<br>        &#39;success_rate&#39;: successes / episodes,<br>        &#39;average_reward&#39;: np.mean(total_rewards),<br>        &#39;average_steps&#39;: np.mean(total_steps)<br>    }<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    # Initialize the environment<br>    env = Dynamics365FrozenLake()<br>    <br>    # Initialize a Q-learning agent for the environment<br>    agent = QLearningAgent(env)<br>    <br>    # Train the agent and periodically display metrics<br>    print(&quot;Training the agent...&quot;)<br>    agent.train(episodes=1000, render_interval=50)  # Render every 50 episodes<br>    <br>    # Test the agent and visualize its path in the environment<br>    print(&quot;\nTesting the agent...&quot;)<br>    print(&quot;Path visualization:&quot;)<br>    path = visualize_path(env, agent)<br>    <br>    # Test the agent&#39;s performance over 100 episodes and display results<br>    test_results = test_agent(env, agent)  # Now this function is defined<br>    print(f&quot;\nTest Results (over 100 episodes):&quot;)<br>    print(f&quot;Success Rate: {test_results[&#39;success_rate&#39;]:.2%}&quot;)  # Percentage of successful episodes<br>    print(f&quot;Average Reward: {test_results[&#39;average_reward&#39;]:.2f}&quot;)  # Average reward per episode<br>    print(f&quot;Average Steps: {test_results[&#39;average_steps&#39;]:.2f}&quot;)  # Average steps per episode    </pre><p>We created the code above to demonstrate the features of the “Frozen Lake” game, which we plan to modify slightly and use to emulate the interaction of RL with Dynamics 365. We will attempt to adapt Dynamics 365 data to align with the logic of “Frozen Lake.”</p><h3>Data Examples from Dynamics 365 for “Frozen Lake”-based Modeling:</h3><p><strong>States and Customer Interaction Stages:</strong></p><ul><li>In “Frozen Lake,” the agent moves across cells with various properties (frozen tiles, holes, goal).</li><li>In Dynamics 365, this can be modeled using customer lifecycle stages (e.g., “initial contact,” “product offer,” “negotiation,” “deal closure”).</li><li>Frozen tiles represent more complex or blocked stages of customer interaction requiring special attention.</li><li>Holes (e.g., “action failure”) represent unsuccessful interactions, such as losing a customer.</li></ul><p><strong>Customer Interaction Actions:</strong></p><ul><li>In “Frozen Lake,” the agent can move in different directions, with each action leading to different consequences.</li><li>In Dynamics 365, actions may include various types of communication with customers, such as:</li><li>“Send an email”</li><li>“Call the customer”</li><li>“Schedule a meeting”</li><li>“Offer a discount”</li></ul><p><em>These actions may either improve customer relationships (moving closer to the goal) or worsen them (e.g., if the customer is uninterested).</em></p><p><strong>Rewards and Penalties:</strong></p><ul><li>In “Frozen Lake,” the agent earns a reward for reaching the goal and a penalty for falling into a hole.</li><li>In Dynamics 365, rewards could include successfully closing a deal or receiving positive customer feedback. Penalties might include losing a customer or a service rejection.</li></ul><p><strong>Data for Environment Setup:</strong></p><ul><li><strong>Customer Interaction History:</strong> previous interaction data is used to model the probabilities of success/failure for various actions.</li><li><strong>Customer Parameters:</strong> customer segmentation (e.g., by age, interests, past behavior) will be used as states.</li><li><strong>Success Metrics:</strong> metrics such as conversion rates, total closed deals, or profitability will be used as rewards.</li></ul><h3>Example of “Frozen Lake” Correspondence to Dynamics 365 Data:</h3><p><strong>Frozen Lake Grid Cells:</strong> each cell can represent a specific customer state or sales funnel stage.</p><p>For example:</p><ul><li>The starting cell represents a “new customer.”</li><li>Frozen tiles represent “customer hesitation.”</li><li>Holes represent “customer refusal.”</li><li>The goal cell represents “successfully closing the deal.”</li></ul><p><strong>Agent Actions:</strong> movements (right, left, up, down) correspond to specific customer interaction actions.</p><p><strong>Slipping Probability:</strong> the “slipping” probability in “Frozen Lake” symbolizes the risk of errors or unpredictable customer responses.</p><h3>Simplified Data for Modeling:</h3><ul><li><strong>Customer Profiles:</strong> arrays describing customers, e.g., {&quot;activity&quot;: 0.7, &quot;loyalty&quot;: 0.4, &quot;past response&quot;: 0.1}.</li><li><strong>Interaction History:</strong> a dictionary with outcomes (success or failure) affecting the likelihood of progressing to the next stage.</li><li><strong>Transition Probabilities:</strong> success probabilities for each action, such as the likelihood of closing a deal after a call or offering a discount.</li></ul><p>Thus, in the code above, we can identify a model where the agent “moves” through various customer states, aiming to reach a goal (e.g., closing a deal), encountering obstacles, and adjusting its interaction strategies based on learning.</p><h3><strong>2.2 Training an RL Agent based on Dynamics 365 Data: from Frozen Lake to Frozen Market</strong></h3><blockquote><strong>Conceptual Transformation of the Game Environment into a Business Context</strong><br> To understand how the classical Frozen Lake environment transforms into the business context of Frozen Market, it is necessary to deeply analyze the analogies between game mechanics and real business processes in a CRM system. In the classical version of Frozen Lake, the agent moves across a frozen lake, trying to reach the goal while avoiding falling through the ice. This mechanic surprisingly closely mirrors the process of working with customers in a CRM system, where the manager (or automated agent) attempts to guide the customer through the sales funnel, avoiding their loss at each stage.</blockquote><p>In our adaptation, each cell of the game board represents a specific customer state. Let’s examine this transformation at a deeper level. The starting cell (S) in Frozen Lake becomes the state of a new customer (NEW) in Frozen Market. This makes sense: just as the agent begins their journey from a specific point, so too does customer engagement start with the first contact. Frozen cells (F) transform into states of interested customers (INTERESTED) — these are safe states where work can continue, but caution and the right strategy are required.</p><p>The transformation of slippery cells is especially interesting. In Frozen Lake, on these cells, the agent might “slip” and end up somewhere unintended. In the CRM context, this perfectly models customer behavior uncertainty (UNCERTAIN). Even if we choose the correct action, the customer may react unpredictably — this is reflected in the code by the parameter slip_prob = 0.3, meaning a 30% chance of &quot;slipping&quot; in an unpredictable direction.</p><p>Falls through the ice (H) in our adaptation become lost customers (LOST). Just as in the game, a fall means having to start over, so too does losing a customer require returning to work with new leads. Finally, the goal cell (G) transforms into the state of a successfully converted customer (CONVERTED) — this is the ultimate goal that our agent strives to achieve.</p><h3><strong>2.3 Technical Implementation of the Frozen Market Environment</strong></h3><p>The implementation of the Frozen Market environment represents a complex system of classes and methods, each playing an important role in modeling business processes. Let’s begin by examining the CustomerState class, which defines all possible customer states in the system.</p><p>In the CustomerState class, we define six basic states, each corresponding to a specific stage of working with a customer. The state NEW (0) represents new customers who have just entered the system. INTERESTED (1) denotes customers who have shown initial interest in a product or service. NEGOTIATING (2) corresponds to the stage of active negotiations. UNCERTAIN (3) reflects an uncertain state where customer behavior is hard to predict. LOST (4) marks lost customers, while CONVERTED (5) represents successfully converted ones.</p><blockquote>The main environment logic is implemented in the DynamicsFrozenMarket class. This class contains methods for generating synthetic data, creating and managing environment states, and processing agent actions. The generate_synthetic_customer method creates realistic customer profiles, including parameters such as engagement level and potential budget. This allows the agent to work with data that is as close to real as possible.</blockquote><p>Particularly important is the generate_market_grid method, which creates the game board—a matrix of customer states. This method doesn’t just randomly distribute states: it follows a specific logic to ensure balance between different cell types. The starting position is always in the upper-left corner (NEW), and the goal is in the lower-right (CONVERTED). Between them are states INTERESTED, UNCERTAIN, and LOST, with their number and placement determined by the size parameter and probabilistic characteristics.</p><p><strong>Architecture and logic of the RL agent’s work</strong><br> The agent in our system is implemented using the Deep Q-Learning (DQN) algorithm, which allows it to efficiently learn in a complex state space. The architecture of the neural network is represented by the QNetwork class, which has three fully connected layers: the input layer with the number of states, a hidden layer of 64 neurons, and the output layer corresponding to the number of possible actions.</p><blockquote>The DQNAgent class implements all the logic for learning and decision-making. The method act is particularly interesting, as it implements the epsilon-greedy strategy. This strategy is especially important in the context of working with clients: at the initial stages of learning, the agent experiments more (high epsilon value), trying different approaches to clients, but gradually starts relying more on accumulated experience (epsilon decreases to epsilon_min).<br> The learning mechanism is implemented through the replay method, which uses the experience of past interactions to improve the strategy. This method randomly selects a batch of memories from memory and uses them to update the weights of the neural network. It is important to note that the memory size is limited (maxlen=2000), which prevents overfitting on outdated data.</blockquote><p><strong>Practical application in the context of Dynamics 365</strong><br> In the context of the real CRM system Dynamics 365, our model can be integrated as follows. Client states naturally correspond to the stages of the sales funnel in Dynamics 365:</p><blockquote>NEW — corresponds to new leads,</blockquote><blockquote>INTERESTED — potential opportunities,</blockquote><blockquote>NEGOTIATING — active negotiations,</blockquote><blockquote>UNCERTAIN — stalled deals,</blockquote><blockquote>LOST — lost opportunities,</blockquote><blockquote>CONVERTED — successfully closed deals.</blockquote><p>The agent’s actions (moving left, right, up, down) can be transformed into real actions for working with the client. For example, moving left may correspond to sending an email campaign, right — a phone call, up — scheduling a personal meeting, and down — sending a special offer.<br> The reward system also has clear analogies with real business metrics. A small negative reward for each step (-0.01) reflects the resource costs for each action with the client. A large negative reward for losing a client (-1) corresponds to real losses from losing a client, and a positive reward for conversion (+1) corresponds to profits from a successful deal.</p><pre># Required libraries<br>!pip install faker<br>import numpy as np<br>import random<br>from faker import Faker<br>from collections import deque<br>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torch.nn.functional as F<br>import heapq<br><br>class CustomerState:<br>    &quot;&quot;&quot;Customer states in CRM&quot;&quot;&quot;<br>    NEW = 0<br>    INTERESTED = 1<br>    NEGOTIATING = 2<br>    UNCERTAIN = 3  # &quot;slippery&quot; cell<br>    LOST = 4      # &quot;hole&quot;<br>    CONVERTED = 5  # target<br><br>class PrioritizedReplayBuffer:<br>    def __init__(self, maxlen=10000):<br>        self.memory = []<br>        self.priorities = []<br>        self.maxlen = maxlen<br>        <br>    def add(self, state, action, reward, next_state, done):<br>        max_priority = max(self.priorities) if self.priorities else 1.0<br>        <br>        if len(self.memory) &gt;= self.maxlen:<br>            self.memory.pop(0)<br>            self.priorities.pop(0)<br>            <br>        self.memory.append((state, action, reward, next_state, done))<br>        self.priorities.append(max_priority)<br>        <br>    def sample(self, batch_size, alpha=0.6, beta=0.4):<br>        if len(self.memory) &lt; batch_size:<br>            return None<br>            <br>        priorities = np.array(self.priorities) ** alpha<br>        probs = priorities / priorities.sum()<br>        <br>        indices = np.random.choice(len(self.memory), batch_size, p=probs)<br>        samples = [self.memory[idx] for idx in indices]<br>        <br>        total = len(self.memory)<br>        weights = (total * probs[indices]) ** (-beta)<br>        weights /= weights.max()<br>        <br>        return samples, indices, weights<br>        <br>    def update_priorities(self, indices, priorities):<br>        for idx, priority in zip(indices, priorities):<br>            self.priorities[idx] = priority + 1e-5<br><br>class DynamicsFrozenMarket:<br>    def __init__(self, size=4):<br>        self.size = size<br>        self.reset()<br>        <br>    def generate_market_grid(self):<br>        grid = np.ones((self.size, self.size)) * CustomerState.INTERESTED<br>        <br>        # Starting position<br>        grid[0][0] = CustomerState.NEW<br>        <br>        # Target position<br>        grid[-1][-1] = CustomerState.CONVERTED<br>        <br>        # Add fewer holes and uncertain cells<br>        n_holes = max(1, self.size - 2)<br>        n_uncertain = max(1, self.size - 2)<br>        <br>        # Create a path to goal<br>        path = [(i, i) for i in range(self.size)]<br>        <br>        # Add holes avoiding the path<br>        holes = 0<br>        attempts = 0<br>        while holes &lt; n_holes and attempts &lt; 100:<br>            i, j = random.randint(0, self.size-1), random.randint(0, self.size-1)<br>            if (i, j) not in path and grid[i][j] == CustomerState.INTERESTED:<br>                grid[i][j] = CustomerState.LOST<br>                holes += 1<br>            attempts += 1<br>            <br>        # Add uncertain cells avoiding the path and holes<br>        uncertain = 0<br>        attempts = 0<br>        while uncertain &lt; n_uncertain and attempts &lt; 100:<br>            i, j = random.randint(0, self.size-1), random.randint(0, self.size-1)<br>            if (i, j) not in path and grid[i][j] == CustomerState.INTERESTED:<br>                grid[i][j] = CustomerState.UNCERTAIN<br>                uncertain += 1<br>            attempts += 1<br>                <br>        return grid<br>    <br>    def reset(self):<br>        self.grid = self.generate_market_grid()<br>        self.current_pos = (0, 0)<br>        self.steps_taken = 0<br>        return self._get_state()<br>    <br>    def _get_state(self):<br>        state = np.zeros(self.size * self.size * 2)  # Include position and cell type<br>        pos_idx = self.current_pos[0] * self.size + self.current_pos[1]<br>        state[pos_idx] = 1  # One-hot position<br>        state[self.size * self.size + int(self.grid[self.current_pos])] = 1  # One-hot cell type<br>        return state<br>    <br>    def step(self, action):<br>        self.steps_taken += 1<br>        directions = [(0, -1), (1, 0), (0, 1), (-1, 0)]<br>        <br>        prev_pos = self.current_pos<br>        slip_prob = 0.3 if self.grid[self.current_pos] == CustomerState.UNCERTAIN else 0.0<br>        <br>        if random.random() &lt; slip_prob:<br>            action = random.randint(0, 3)<br>            <br>        new_pos = (<br>            self.current_pos[0] + directions[action][0],<br>            self.current_pos[1] + directions[action][1]<br>        )<br>        <br>        # Check boundaries<br>        if 0 &lt;= new_pos[0] &lt; self.size and 0 &lt;= new_pos[1] &lt; self.size:<br>            self.current_pos = new_pos<br>            <br>        current_cell = self.grid[self.current_pos]<br>        <br>        # Enhanced reward structure<br>        done = False<br>        reward = -0.01  # Small step penalty<br>        <br>        # Distance-based reward<br>        goal_pos = (self.size-1, self.size-1)<br>        prev_dist = abs(prev_pos[0] - goal_pos[0]) + abs(prev_pos[1] - goal_pos[1])<br>        curr_dist = abs(self.current_pos[0] - goal_pos[0]) + abs(self.current_pos[1] - goal_pos[1])<br>        <br>        if curr_dist &lt; prev_dist:<br>            reward += 0.1<br>        <br>        # State-based rewards<br>        if current_cell == CustomerState.LOST:<br>            reward = -1<br>            done = True<br>        elif current_cell == CustomerState.CONVERTED:<br>            reward = 2 + max(0, (50 - self.steps_taken) * 0.02)  # Bonus for quick completion<br>            done = True<br>        elif self.steps_taken &gt;= 50:  # Maximum steps reached<br>            done = True<br>            reward = -0.5<br>            <br>        return self._get_state(), reward, done, {}<br><br>class QNetwork(nn.Module):<br>    def __init__(self, state_size, action_size):<br>        super(QNetwork, self).__init__()<br>        <br>        self.fc1 = nn.Linear(state_size, 128)<br>        self.fc2 = nn.Linear(128, 128)<br>        self.fc3 = nn.Linear(128, action_size)<br>        <br>        # Initialize weights<br>        for m in self.modules():<br>            if isinstance(m, nn.Linear):<br>                nn.init.kaiming_normal_(m.weight)<br>                nn.init.constant_(m.bias, 0)<br>    <br>    def forward(self, x):<br>        x = F.relu(self.fc1(x))<br>        x = F.relu(self.fc2(x))<br>        return self.fc3(x)<br><br>class DQNAgent:<br>    def __init__(self, state_size, action_size):<br>        self.state_size = state_size<br>        self.action_size = action_size<br>        <br>        self.gamma = 0.99<br>        self.epsilon = 1.0<br>        self.epsilon_min = 0.1<br>        self.epsilon_decay = 0.997<br>        self.learning_rate = 0.0005<br>        self.tau = 0.001  # For soft update of target network<br>        <br>        self.device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>        <br>        # Q Networks (online and target)<br>        self.online_network = QNetwork(state_size, action_size).to(self.device)<br>        self.target_network = QNetwork(state_size, action_size).to(self.device)<br>        self.target_network.load_state_dict(self.online_network.state_dict())<br>        <br>        self.optimizer = optim.Adam(self.online_network.parameters(), lr=self.learning_rate)<br>        <br>        # Prioritized Experience Replay<br>        self.memory = PrioritizedReplayBuffer(maxlen=50000)<br>        <br>    def act(self, state, training=True):<br>        if training and random.random() &lt; self.epsilon:<br>            return random.randrange(self.action_size)<br>            <br>        with torch.no_grad():<br>            state = torch.FloatTensor(state).unsqueeze(0).to(self.device)<br>            action_values = self.online_network(state)<br>            return torch.argmax(action_values).item()<br>            <br>    def remember(self, state, action, reward, next_state, done):<br>        self.memory.add(state, action, reward, next_state, done)<br>        <br>    def replay(self, batch_size):<br>        result = self.memory.sample(batch_size)<br>        if result is None:<br>            return<br>            <br>        samples, indices, weights = result<br>        states, actions, rewards, next_states, dones = zip(*samples)<br>        <br>        states = torch.FloatTensor(np.array(states)).to(self.device)<br>        actions = torch.LongTensor(actions).to(self.device)<br>        rewards = torch.FloatTensor(rewards).to(self.device)<br>        next_states = torch.FloatTensor(np.array(next_states)).to(self.device)<br>        dones = torch.FloatTensor(dones).to(self.device)<br>        weights = torch.FloatTensor(weights).to(self.device)<br>        <br>        # Get current Q values<br>        current_q_values = self.online_network(states).gather(1, actions.unsqueeze(1))<br>        <br>        # Get next Q values from target network<br>        with torch.no_grad():<br>            next_q_values = self.target_network(next_states).max(1)[0]<br>            target_q_values = rewards + (1 - dones) * self.gamma * next_q_values<br>            <br>        # Compute loss and update priorities<br>        td_errors = torch.abs(current_q_values.squeeze() - target_q_values).detach().cpu().numpy()<br>        self.memory.update_priorities(indices, td_errors)<br>        <br>        # Compute weighted loss<br>        losses = F.mse_loss(current_q_values.squeeze(), target_q_values, reduction=&#39;none&#39;)<br>        loss = (losses * weights).mean()<br>        <br>        self.optimizer.zero_grad()<br>        loss.backward()<br>        torch.nn.utils.clip_grad_norm_(self.online_network.parameters(), 1.0)<br>        self.optimizer.step()<br>        <br>        # Soft update target network<br>        for target_param, online_param in zip(self.target_network.parameters(), self.online_network.parameters()):<br>            target_param.data.copy_(self.tau * online_param.data + (1.0 - self.tau) * target_param.data)<br>        <br>        # Update epsilon<br>        if self.epsilon &gt; self.epsilon_min:<br>            self.epsilon *= self.epsilon_decay<br>            <br>        return loss.item()<br><br>def train_agent():<br>    env = DynamicsFrozenMarket(size=4)<br>    state_size = env.size * env.size * 2  # Position and cell type<br>    action_size = 4<br>    agent = DQNAgent(state_size, action_size)<br>    <br>    n_episodes = 1000<br>    batch_size = 32  <br>    <br>    rewards_history = []<br>    success_history = []<br>    loss_history = []<br>    <br>    for episode in range(n_episodes):<br>        state = env.reset()<br>        total_reward = 0<br>        episode_loss = []<br>        <br>        while True:<br>            action = agent.act(state)<br>            next_state, reward, done, _ = env.step(action)<br>            <br>            agent.remember(state, action, reward, next_state, done)<br>            <br>            if len(agent.memory.memory) &gt; batch_size:<br>                loss = agent.replay(batch_size)<br>                if loss is not None:<br>                    episode_loss.append(loss)<br>                    <br>            state = next_state<br>            total_reward += reward<br>            <br>            if done:<br>                break<br>        <br>        rewards_history.append(total_reward)<br>        success_history.append(1 if total_reward &gt;= 1 else 0)<br>        if episode_loss:<br>            loss_history.append(np.mean(episode_loss))<br>        <br>        if episode % 100 == 0:<br>            success_rate = np.mean(success_history[-100:]) if success_history else 0<br>            avg_reward = np.mean(rewards_history[-100:])<br>            avg_loss = np.mean(loss_history[-100:]) if loss_history else 0<br>            print(f&quot;Episode: {episode}&quot;)<br>            print(f&quot;Average Reward (last 100): {avg_reward:.2f}&quot;)<br>            print(f&quot;Success Rate (last 100): {success_rate:.2%}&quot;)<br>            print(f&quot;Average Loss: {avg_loss:.4f}&quot;)<br>            print(f&quot;Epsilon: {agent.epsilon:.2f}&quot;)<br>            print(&quot;------------------------&quot;)<br>            <br>    return agent, env<br><br>if __name__ == &quot;__main__&quot;:<br>    agent, env = train_agent()</pre><p><strong>Features of implementation and technical details</strong><br> Special attention deserves the implementation of “uncertainty” in the system. In the step method of the DynamicsFrozenMarket class, we see how the agent&#39;s actions are processed considering the probability of &quot;slipping.&quot; If the client is in the UNCERTAIN state, there is a 30% chance that the result of the action will be random, regardless of the selected action. This perfectly models a real situation when the client&#39;s reaction can be unpredictable.</p><blockquote>The agent&#39;s learning process takes place over 1000 episodes, each limited to 200 steps. This limitation is important: it prevents situations where the agent &quot;gets stuck&quot; in suboptimal behavior. Using batches of size 32 for training represents a compromise between training speed and stability: the batches are large enough to ensure stable gradient descent, but small enough for effective learning.</blockquote><p><strong>Prospects for development and optimization</strong><br> The current implementation can be improved in several ways. First, the state space can be expanded to include additional parameters from Dynamics 365, such as the history of interactions with the client, time intervals between actions, engagement metrics, and other metrics.<br> Second, the architecture of the neural network can be enhanced by adding a prioritized experience mechanism (Prioritized Experience Replay), which will allow the agent to learn more from important and rare events. Also, the implementation of Double DQN looks promising to reduce the overestimation of Q-values.<br> <em>Finally, more complex business metrics can be integrated into the system, such as ROI of different actions, customer acquisition cost (CAC), and customer lifetime value (LTV). This will allow the agent to make decisions considering a broader context and long-term perspective.</em></p><p><strong>Conclusion</strong><br>The transformation of the classic Frozen Lake environment into a business-oriented Frozen Market environment demonstrates how Reinforcement Learning principles can be applied to real business problems. Our implementation shows that even a relatively simple architecture can model complex customer interaction processes, and the integration with Dynamics 365 opens up wide opportunities for automating and optimizing sales processes.</p><h3>3.Integration of External RL Solutions with Dynamics 365 ML Infrastructure</h3><p>Integration of Reinforcement Learning (RL) solutions with Dynamics 365 is possible not only through <strong>Power Platform</strong> but also using other tools. Let’s examine the alternatives and their features:</p><h4>3.1. Using Power Platform</h4><p><strong>Power Automate:</strong> creating automated workflows for data transfer between Dynamics 365 and RL model. This is convenient if your model requires periodic data updates or two-way integration.<br><strong>Power Apps:</strong> creating customized applications for users to display RL results or manage model-based actions.<br><strong>Power BI:</strong> visualizing RL data and tracking solution effectiveness in real-time.<br><em>Power Platform provides a user-friendly graphical interface and a wide range of ready-made connectors, simplifying the integration process. However, this approach may be limited in performance and complex scenarios.</em></p><h4>3.2. Direct Integration through Dataverse and API</h4><p>Dynamics 365 uses <strong>Dataverse</strong>, which allows working with data via REST API or OData. You can:<br>- <em>Transfer data from Dynamics 365 to your RL model using REST API.<br>- Return RL calculation results back to Dynamics 365.<br>- Organize asynchronous processes for computationally intensive tasks.</em><br>This is a flexible approach that doesn’t require Power Platform but needs programming skills for API work.</p><h4>3.3. Cloud Services and Azure Machine Learning</h4><p>If the RL model is hosted in the cloud (e.g., Azure Machine Learning), integration with Dynamics 365 can be organized through:<br><strong>Azure Logic Apps: </strong>an alternative to Power Automate for creating workflows.<br><strong>Custom Connectors: </strong>setting up custom connectors for interaction with external services.<br><strong>Direct Azure Services: </strong>using Azure Data Factory or Azure Functions to automate data transfer between RL and Dynamics 365.</p><h4>3.4. Direct Use of Django REST Framework as Middleware</h4><blockquote>If you’re already using <strong>Django REST Framework </strong>as a middleware layer, you can configure it as follows:<br><strong>Webhooks:</strong> Dynamics 365 can send data to Django REST Framework via webhooks, which then pass it to the RL model.<br><strong>REST API: </strong>Django REST Framework provides API for managing Dynamics 365 data and processing it in RL.<br><strong>WebSockets:</strong> for real-time data transmission.<br>This approach provides maximum flexibility but requires significant effort for infrastructure setup and maintenance.</blockquote><h4>3.5. Third-Party Platforms</h4><p>If Power Platform isn’t the preferred option, you can use integration tools such as: <strong>Zapier </strong>or<strong> Integromat</strong>: for simplified integration with RL model.<br><strong>Apache Kafka</strong> or <strong>RabbitMQ</strong>: for streaming data processing and event transmission between Dynamics 365 and RL.</p><p><strong>Conclusion</strong><br><em>While Power Platform is convenient for rapid solution development and integration, it’s not the only way. For complex scenarios, it’s better to use direct API integration, cloud hosting, or custom middleware like </em><strong><em>Django REST Framework</em></strong><em>. Your choice depends on requirements for flexibility, performance, and scale.</em></p><h3>4.Announcement of the next lesson</h3><blockquote>In the next lesson of this guide, we will cover two practical topics — these are real mathematical frameworks and RL model code for Dynamics 365, as well as an implementation example of a simulator based on Google Colab and Django Rest Framework for simulating RL models’ interaction with Dynamics 365.</blockquote><h3>4.1 Dynamics 365 Interactions Simulator based on Django REST Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bb_juTs0sMkPbdr-XD1XEA.jpeg" /></figure><p>In today’s world of artificial intelligence and machine learning development, there is a need to create effective tools for testing and deploying RL algorithms in corporate environments. This is especially true for complex ecosystems like Microsoft Dynamics 365, where error costs can run into millions of dollars, and access to real data is significantly limited.</p><p><strong>4.1.1 Problems and Solution</strong><br>RL algorithm developers face serious constraints when working with the real Dynamics 365 environment. High licensing costs, complexity in setting up test environments, and risks associated with experimenting on live data create significant barriers to innovation.</p><blockquote>A simulator based on Django REST Framework in Google Colab offers a possible solution to this problem, however, it has several significant limitations. The main limitations of Google Colab include the temporary nature of sessions with disconnection after several hours of inactivity, lack of permanent IP address and domain, inconsistency of computational resources, restrictions on process execution duration, and the need for periodic reconnection. In the context of Django REST Framework in Colab, there are difficulties in maintaining a permanent web server, issues with state preservation between sessions, limited asynchronous processing capabilities, and excessive functionality for simulation tasks.</blockquote><p>Nevertheless, the simulator remains a useful tool for prototyping RL solutions, training specialists, testing basic algorithms, and conducting short-term experiments.</p><p>Data engineers often face the problem of real Dynamics 365 data volumes being unavailable in the analytical environment. The developed simulator provides the ability to generate synthetic datasets taking into account seasonality, business process interference, and noise components. It is particularly important that the simulator can reproduce data at the level of individual company departments, including marketing, sales, and HR, making the analysis as close to reality as possible.</p><h4>4.1.2 Technical Architecture of the Simulator</h4><p>Considering platform limitations, the simulator’s architecture must be optimized. The API Layer is implemented as a lightweight version of Django REST Framework with minimal use of long-living processes, in-memory state caching, and periodic data saving to Google Drive. Each endpoint supports standard HTTP methods and complies with Microsoft documentation.</p><p><strong>Simulation Core</strong> represents a central Python module optimized for working in the limited Colab environment. It uses lightweight libraries and has a modular structure for quick state recovery. It includes a Generator Module for creating realistic time series, Process Simulator with checkpoint capabilities, and State Manager with backup functionality.</p><blockquote><strong>RL Environment </strong>is built on Gymnasium (formerly OpenAI Gym), providing a standard interface for training RL agents. It supports customizable state and action spaces, optimized reward functions, and capabilities for saving and loading environment states.</blockquote><p><strong>Data Generation Layer</strong> uses Faker and optimized data generators to create realistic business data, including customer profiles, transactions, logistics operations, and marketing campaigns. It supports caching of frequently used templates and incremental data generation.</p><h4>4.1.3 Required Infrastructure Components</h4><p><strong>1. Storage System:</strong><br> — Google Drive for state persistence<br> — Local caching in Colab memory<br> — Periodic backups of critical data</p><p><strong>2. Resource Management:</strong><br> — Memory usage monitoring<br> — Automatic release of unused resources<br> — Graceful degradation when limits are reached</p><p><strong>3. Fault Tolerance:</strong><br> — Automatic recovery after failures<br> — Intermediate results preservation<br> — Critical operations logging</p><h4>4.1.4 Economic Justification</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*UcNWnpJ7kT-XH1Lnb0axaA.jpeg" /></figure><p>The economic efficiency of the solution must consider platform limitations. With an average Dynamics 365 license cost of $100 per user per month, an organization with 50 engineers can save $60,000 annually on licensing alone. Development time reduction is 20–30% instead of the claimed 40% ($40,000–60,000 per year with an average developer salary of $100,000). Additional savings come from reduced prototyping risks and failed implementation (average $150,000 per project), as well as faster training of new specialists (savings of about $20,000 per specialist).</p><p>Additional costs for maintaining operability in Colab, periodic session restoration, and data backup must be considered.</p><h4>4.1.5 Technical Implementation Details in Google Colab</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-2nGBEBr2FM6BySwSI95Q.jpeg" /></figure><p><em>For stable operation in Colab, the following is required:</em></p><p><strong>1. Session Management:</strong><br> — Automatic reconnection<br> — State preservation between sessions<br> — Interrupt handling</p><p><strong>2. Resource Optimization:</strong><br> — Efficient RAM utilization<br> — GPU usage control<br> — Computational load management</p><p><strong>3. Google Drive Integration:</strong><br> — Automatic synchronization<br> — Data versioning<br> — Access rights management</p><h4>Integration Capabilities</h4><p><em>The simulator provides extensive integration capabilities with existing systems. Considering platform limitations, the following are implemented:</em></p><p><strong>1. API Integration:</strong><br> — REST API with OAuth 2.0 support<br> — Simplified authentication<br> — Basic HTTP methods<br> — Limited number of simultaneous connections<br> — Webhook interfaces for real-time notifications</p><p><strong>2. Data Export/Import:</strong><br> — Support for JSON, CSV, Excel formats<br> — Incremental processing<br> — Data integrity control</p><h4>4.1.6 Development Prospects</h4><p><em>Potential improvement directions include:</em></p><p><strong>1. Performance Optimization:</strong><br> — Improved caching mechanisms<br> — Memory usage optimization<br> — Data generation acceleration</p><blockquote><strong>2. Functionality Extension:</strong><br> — Adding new simulation types<br> — Improving generated data quality<br> — Expanding API capabilities<br> — Adding microservice architecture support<br> — Azure ML integration for advanced analytics<br> — Implementation of federated learning</blockquote><p><strong>3. Stability Improvements:</strong><br> — Recovery mechanism enhancement<br> — Monitoring improvements<br> — Data storage optimization</p><h4>4.1.7 Potential Benefits for Microsoft</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dij_Ngu3-mAj2ufwkvBdbA.jpeg" /></figure><p>Microsoft shows particular interest in initiatives that contribute to expanding the Dynamics 365 ecosystem. Increasing the developer base through educational and prototyping platforms like Google Colab makes Dynamics 365 more attractive for integration with modern machine learning algorithms.</p><blockquote>Particularly important is the development of capabilities for creating RL models that consider intersubjective data, such as customer feedback and behavioral patterns. This can significantly enhance the innovation potential of the Dynamics 365 platform and expand its range of solvable tasks. Microsoft may be interested in such developments to expand the developer community, simplify the learning process, and test new integration approaches.</blockquote><h3>4.1.8 Description of Tasks for Simulator</h3><p><strong>RL Algorithm Prototyping</strong><br>- Testing reinforcement learning (RL) strategies in an environment simulating Dynamics 365 business logic<br>- Training agents to make decisions in a simulated corporate environment with high risks and complex dependencies<br>- Testing new ideas without risk to the real Dynamics 365 system<br>- Implementing decision-making scenarios for company departments<br>- Analyzing business process management strategies</p><p><strong>Training and Research</strong><br>- Training specialists in working with RL algorithms and Dynamics 365 API<br>- Providing a safe platform for experiments, avoiding risks associated with real data</p><blockquote><strong>Corporate Process Simulation</strong><br>- Generating synthetic data for marketing, HR, logistics, and sales departments<br>- Modeling business scenarios considering seasonality, noise, and process interference<br>- Generating synthetic data for testing RL algorithms<br>- Simulating events such as campaigns, price changes, supply delays</blockquote><p><strong>Hypothesis Testing</strong><br>- Verifying how changes in business strategy can affect company metrics<br>- Analyzing effects of different strategies on KPI indicators</p><p><strong>Interpretability and Control, Analytics and Monitoring</strong><br>- Logging and analyzing RL agents’ work in the simulated environment<br>- Data interpretation and ensuring decision transparency through Explainable AI (XAI)</p><h3>4.1.9 Simulator Technology Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XoKUqU2EDdnxbxP2YaxMQ.jpeg" /></figure><p><em>13 main components</em></p><p><strong>1. Google Colab</strong><br>Main development, testing, and execution environment for the simulator.<br>Cloud platform with free GPU/TPU access for computation acceleration.</p><p><em>Benefits:<br>- Accessibility: free resource usage<br>- Convenience: easy setup and integration with Python and libraries<br>- Google Drive integration: easy data storage access</em></p><p><strong>2. Django REST Framework (DRF)</strong><br>- Implementation of API layer for RL agents’ interaction with simulated environment<br>- Providing standardized interface for data and simulation interaction</p><p><em>Benefits:<br>- Flexibility: easy route and endpoint configuration<br>- Extensibility: ability to add new methods without significant architecture changes<br>- Documentation: OpenAPI/Swagger support for documentation generation<br>- Integration convenience: easy work with other Python libraries</em></p><p><strong>3. Faker</strong><br>- Generation of synthetic data such as customer profiles, transactions, marketing campaigns</p><p><em>Role in simulator:<br>- Creating realistic data simulating Dynamics 365 corporate environment<br>- Used for initial simulator database population</em></p><p><strong>4. Gymnasium (OpenAI Gym)</strong><br>Environment for training RL agents, providing interface for working with simulated states and actions.</p><p><em>Role in simulator:<br>- Support for RL agents with customizable action and state spaces<br>- Business process simulation through reward functions and scenarios</em></p><p><strong>5. Generator Module</strong><br>Central component for generating time series and data simulating activity in Dynamics 365.</p><p><em>Functions:<br>- Data generation considering seasonality, parameter correlation, and noise<br>- Support for trends and anomalies in data</em></p><p><strong>Generator Module Architectural Features</strong></p><blockquote>Modular Structure with Separate Generators for Different Data Types:<br>- TimeSeriesGenerator: for time series<br>- EventGenerator: for discrete events<br>- NoiseGenerator: for adding realistic noise<br>- TrendGenerator: for creating long-term trends</blockquote><p>Generator Composition System:<br>- BaseGenerator base class with common interface<br>- Composite pattern for combining different generators<br>- Processing chain for sequential transformation application</p><p>Parameterization:<br>- YAML configuration files for parameter settings<br>- Dynamic parameter loading during execution<br>- Ability to save and load generator states</p><p><em>Technical Details<br>- Using NumPy for basic distribution generation<br>- Pandas for time series processing<br>- SciPy for special distributions and statistical functions<br>- Built-in validation of generated data<br>- Caching intermediate results in memory<br>- Multi-threaded data generation through concurrent.futures</em></p><p><strong>6. State Manager</strong><br>Environment state management, simulation progress saving, crash recovery, simulation state management, and progress saving in Google Drive.</p><p><em>Role in the simulator:<br> — Saving current state of RL-agents and simulation data<br> — Backup of data to Google Drive to prevent progress loss</em></p><p><strong>State Manager Architectural features</strong></p><blockquote>Persistence system:<br> — State serialization in JSON/pickle format<br> — Incremental change saving<br> — State versioning</blockquote><p>Recovery mechanism:<br> — Automatic checkpoint creation<br> — State change logging<br> — System for rolling back to previous states</p><p>Google Drive integration:<br> — Asynchronous data synchronization<br> — Write operation queue<br> — Conflict resolution mechanism</p><p><em>Technical details<br>- Using PyDrive for Google Drive API interactions<br>- Async IO for asynchronous operations<br>- Pickle protocol for complex object serialization<br>- LRU caching for access optimization<br>- Lock system for concurrent access</em></p><p><strong>7. Google Drive</strong><br>Cloud storage for saving simulation data and RL training results</p><p><em>Role in the simulator:<br> — Continuous saving of states, data, and logs<br> — Storage of data versions for experiment reproducibility</em></p><p><strong>8. Process Simulator</strong><br>Modeling various scenarios of Dynamics 365 department operations, including marketing, sales, and HR.</p><p><em>Functions:<br> — Event simulation, such as campaigns, price changes, and supply delays<br> — Implementation of business logic through customizable processes</em></p><p><strong>Process Simulator Architectural features</strong></p><blockquote>Event system:<br> — Priority-based event queue<br> — Time-stamped event scheduler<br> — Event handlers for different process types</blockquote><p>Process modeling:<br> — Finite state machines for business process representation<br> — Process dependency system<br> — Change propagation mechanism</p><p>Scenario management:<br> — Loading scenarios from YAML configurations<br> — Process behavior parameterization<br> — Trigger and condition system</p><p><em>Technical details<br>- Using PyYAML for configurations<br>- Transitions for finite state machine implementation<br>- APScheduler for event scheduling<br>- NetworkX for dependency modeling<br>- Built-in performance metrics</em></p><p><strong>9. Data Generation Layer</strong><br>Generation of synthetic business data considering relationships and constraints, such as customer profiles, financial reports, and transactions.</p><p><em>Functions:<br> — Caching frequently used templates<br> — Real-time incremental data generation</em></p><p><strong>Data Generation Layer Architectural features</strong></p><blockquote>Template system:<br> — Library of predefined data templates<br> — Template inheritance and extension mechanism<br> — Generated data validation</blockquote><p>Caching:<br> — Multi-level caching system<br> — Pre-generation of frequently used data<br> — Cache lifecycle management</p><p>Real-time generation:<br> — Stream data generation<br> — Buffering system<br> — Generation rate control mechanism</p><p><em>Technical details<br>- Faker for basic data generation<br>- Pandas for data structuring<br>- NumPy for mathematical operations<br>- joblib for parallel generation<br>- Built-in performance profiling system</em></p><p><strong>10. RL Agent Framework</strong><br>Management of RL agents learning from simulation data.<br><em>Role in the simulator:<br> — Support for algorithms such as Q-Learning, PPO, DDPG<br> — Optimization of solutions based on simulated environment</em></p><p><strong>11. Asynchronous Tasks</strong><br>Tools: Django Celery + Redis<br>Purpose:<br> — Processing background tasks such as data generation, logging, and long-running calculations</p><p><strong>12. Logging</strong><br>Tools: Python logging + Sentry<br>Purpose:<br> — Error tracking, task execution logging, simulator state monitoring</p><p><strong>13. Explainable AI (XAI)</strong><br>Interpretation of RL agents’ operation, analysis of decision-making strategies</p><h4>Component Interaction</h4><p>1. Generator Module provides base data for Process Simulator<br>2. Process Simulator uses State Manager to save states<br>3. Data Generation Layer uses Generator Module to create related data<br>4. State Manager coordinates states of all components</p><p>Google Colab Optimization<br>- Efficient memory usage through stream processing<br>- Automatic saving to Google Drive when threshold values are reached<br>- Distribution of computational load<br>- Fault tolerance systems for environment restarts</p><p><em>This stack provides a reliable architecture for the initial stages of prototyping and development while remaining flexible and accessible.</em></p><h3>4.1.10 Simplified Example of using Synthetic Data</h3><p>Without interaction simulation.</p><h3>Implementation Steps</h3><h4>1. Setting Up the Environment in Colab</h4><p>1.Install the required libraries:</p><pre>!pip install gymnasium faker torch torchvision matplotlib</pre><p>2.Connect Google Drive:</p><pre>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)</pre><h4>2. Creating a Data Generator</h4><p>Use Faker to generate data such as customer profiles, transactions, and events:</p><pre>from faker import Faker<br>import pandas as pd<br><br>fake = Faker()<br><br>def generate_customer_data(n):<br>    data = [{<br>        &#39;customer_id&#39;: i,<br>        &#39;name&#39;: fake.name(),<br>        &#39;email&#39;: fake.email(),<br>        &#39;country&#39;: fake.country(),<br>        &#39;signup_date&#39;: fake.date_this_decade()<br>    } for i in range(n)]<br>    return pd.DataFrame(data)<br><br>customer_data = generate_customer_data(100)<br>print(customer_data.head())</pre><h4>3. Developing the RL Environment</h4><p>Create a custom environment using Gymnasium:</p><pre>import gymnasium as gym<br>from gymnasium import spaces<br>import numpy as np<br><br>class DynamicsSimEnv(gym.Env):<br>    def __init__(self):<br>        super(DynamicsSimEnv, self).__init__()<br>        # State and action spaces<br>        self.observation_space = spaces.Box(low=0, high=1, shape=(5,))<br>        self.action_space = spaces.Discrete(3)  # For example: 0 - decrease price, 1 - maintain, 2 - increase<br><br>    def reset(self):<br>        # Initial state<br>        self.state = np.random.rand(5)<br>        return self.state<br><br>    def step(self, action):<br>        # State transition logic and reward calculation<br>        reward = np.random.random()  # Example: random reward<br>        self.state = np.random.rand(5)<br>        done = False  # Or True if the episode ends<br>        return self.state, reward, done, {}</pre><h4>4. Implementing an RL Agent</h4><p>Use PyTorch to implement the DQN algorithm:</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br><br>class DQNAgent(nn.Module):<br>    def __init__(self, input_dim, output_dim):<br>        super(DQNAgent, self).__init__()<br>        self.fc = nn.Sequential(<br>            nn.Linear(input_dim, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, output_dim)<br>        )<br><br>    def forward(self, x):<br>        return self.fc(x)<br><br>env = DynamicsSimEnv()<br>agent = DQNAgent(input_dim=5, output_dim=3)<br>optimizer = optim.Adam(agent.parameters(), lr=0.001)<br>criterion = nn.MSELoss()<br><br># Example training loop<br>for episode in range(100):<br>    state = torch.FloatTensor(env.reset())<br>    done = False<br>    while not done:<br>        action = torch.argmax(agent(state)).item()<br>        next_state, reward, done, _ = env.step(action)<br>        next_state = torch.FloatTensor(next_state)<br>        # Model training<br>        target = reward + 0.99 * torch.max(agent(next_state)).item()<br>        output = agent(state)[action]<br>        loss = criterion(output, torch.tensor(target))<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br>        state = next_state</pre><h4>5. Logging and Visualization</h4><p>Use Matplotlib to analyze results:</p><pre>import matplotlib.pyplot as plt<br><br>rewards = [np.random.random() for _ in range(100)]  # Example data<br>plt.plot(rewards)<br>plt.xlabel(&#39;Episode&#39;)<br>plt.ylabel(&#39;Total Reward&#39;)<br>plt.show()</pre><h4>6. Saving Data and Models</h4><p>Save the trained model to Google Drive:</p><pre>torch.save(agent.state_dict(), &#39;/content/drive/MyDrive/dynamics_agent.pth&#39;)</pre><h3>4.1.11 Next Steps</h3><ol><li>Add complex business logic to the simulation, such as seasonal changes or inter-departmental dependencies.</li><li>Integrate Explainable AI to analyze RL agent actions.</li><li>Optimize training performance using TPUs in Colab.</li></ol><p>This architecture enables the development and testing of RL agents in a simulated environment, using free tools.</p><h3>4.1.12 What can we test for RL projects on synthetic data?</h3><h4>1. RL Agent Algorithms</h4><ul><li>Evaluate agents’ decision-making in business environments:</li><li>Optimize marketing campaigns.</li><li>Manage inventory and logistics.</li><li>Improve sales conversions.</li><li>Test adaptability to dynamic changes like:</li><li>Seasonal demand fluctuations.</li><li>Customer behavior shifts.</li><li>Internal and external events.</li></ul><h4>2. Simulation of Complex Business Logic</h4><ul><li>Analyze how management strategy changes impact KPIs.</li><li>Evaluate the effectiveness of decisions.</li></ul><h4>3. Data Generation and Analysis</h4><p>Test algorithms for processing and interpreting data to analyze how environmental parameters (e.g., price reduction, increased marketing budget) affect system behavior.</p><h4>4. Hypothesis Reproducibility</h4><p>For example, test how discounts influence long-term profitability in scenarios mimicking Dynamics 365 data dynamics.</p><h3>4.1.13 Simulating Dynamics 365 Data</h3><p>We do not have direct access to Dynamics 365 data, but we:</p><p><strong>Simulate typical Dynamics 365 data and processes</strong>, including:</p><ul><li>Customer profiles (Faker generates demographic data).</li><li>Transaction history (create time series reflecting customer purchases).</li><li>Marketing campaigns (generate marketing-related event data).</li><li>KPIs used in Dynamics 365 (e.g., profit, customer retention).</li></ul><p><strong>Implement Scenarios</strong>:</p><ul><li>Example: An agent learns to allocate ad budgets across channels (similar to the Marketing module in Dynamics 365).</li><li>Example: Simulate warehouse management, where the agent optimizes inventory (similar to the Supply Chain Management module).</li></ul><p><strong>Use Synthetic Data</strong>:</p><p>Synthetic data mimics Dynamics 365 system behavior, enabling RL algorithm testing in realistic conditions.</p><h3>4.1.14 Example Test Scenario</h3><h4>Scenario 1: managing Marketing Budgets</h4><p><strong>Data</strong>:</p><ul><li>Synthetic customer database with attributes: age, income, geography.</li><li>Historical data on marketing campaigns (e.g., budget and results).</li></ul><p><strong>RL Task</strong>:</p><p>The agent allocates the budget across campaigns to maximize revenue and customer retention.</p><p><strong>Outcome</strong>:</p><p>Analyze how the agent optimizes the strategy: which customers/channels it prioritizes and how it adapts to dynamics.</p><h3>4.1.15 Why Is This Useful?</h3><p><strong>Learning and Prototyping</strong>:</p><p>Test advanced RL algorithms in simulated corporate processes without needing real system access.</p><p><strong>Risk-Free Experimentation</strong>:</p><p>Develop strategies and hypotheses in an isolated environment.</p><p><strong>Preparation for Deployment in Dynamics 365</strong>:</p><p>Algorithms validated in the simulator can be adapted for real-world use with Dynamics 365.</p><p><strong>In the next lesson we will detail a practical example of simulating the interaction between an RL agent and Dynamics 365 using the Django Rest Framework.</strong></p><h4>Conclusion</h4><blockquote>Developing a Dynamics 365 simulator based on Django REST Framework in Google Colab environment represents a compromise solution for prototyping and training. Despite significant platform limitations, with proper architecture and consideration of runtime environment characteristics, such a simulator can be a useful tool for developers and researchers, especially in the initial stages of working with RL algorithms in the context of Dynamics 365. Cost-effectiveness, technological flexibility, and broad integration capabilities make this solution attractive for a wide range of specialists and organizations, provided there is understanding and consideration of the platform’s existing limitations.</blockquote><h3>4.2 Basic RL Models for Dynamics 365</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJKeuGjKYjUIUcgBV-4tMw.png" /></figure><p><em>Target Dynamics 365 Components for RL Expansions.</em></p><h3><em>4.2.1 </em>Analysis of Reinforcement Learning (RL) Applications for Dynamics 365 Tasks</h3><p><em>Brief analysis for the next lesson.</em></p><p><strong>1.Lead Scoring</strong><br>The task is typically a classification problem. RL is not necessary, and simpler models like logistic regression, SVM, or gradient boosting are more effective. No real-time operation is required unless optimizing strategies based on lead interactions over time.<br><strong>Components: </strong><em>Dynamics 365 Sales Insights, AI Builder.</em></p><p><strong>2. Sales Forecasting</strong><br>RL can be applied for time series forecasting when there are complex dependencies, such as seasonality or external factors. However, simpler methods like ARIMA or Prophet are often more effective for well-defined problems. Real-time operation is possible, depending on the model complexity.<br><strong>Components</strong>: <em>Dynamics 365 Sales Insights, Power BI.</em></p><p><strong>3. Customer Lifetime Value Prediction</strong><br>This is a regression task, where classical methods are often more optimal. However, RL is well-suited for optimizing long-term customer value, considering delayed rewards and adapting strategies dynamically over time. The mathematical framework involves MDPs with delayed rewards, enabling continuous adaptation of customer interaction strategies and temporal behavior modeling.<br><strong>Components</strong>: <em>Dynamics 365 Customer Insights, Power BI.</em></p><p><strong>4. Churn Prediction</strong><br>RL can optimize retention strategies through sequential decision-making by detecting early signs of churn and determining the best timing for personalized interventions. The mathematical structure supports early warning detection and personalized intervention timing, with state transitions representing customer behavior evolution, involves adapting to customer behavior and optimizing actions over time to minimize churn.<br><strong>Components</strong>: <em>Dynamics 365 Customer Insights, AI Builder.</em></p><p><strong>5. Sentiment Analysis</strong><br>Sentiment analysis is a text classification task typically solved with NLP models like CNNs or RNNs. However, RL can enhance sentiment analysis by optimizing response strategies and adapting the model in dynamic environments with feedback loops. This can improve the system’s ability to respond effectively to changing user sentiments and interactions.<br><strong>Components</strong>: <em>Dynamics 365 Customer Voice, AI Builder.</em></p><p><strong>6. Next Best Action</strong><br>RL is essential for optimizing customer interactions through sequential decision-making in a dynamic environment. Approaches like Q-learning and SARSA can optimize actions based on real-time customer data. Real-time operation is critical for adapting strategies dynamically as new customer behavior data becomes available.<br><strong>Components</strong>: <em>Dynamics 365 Sales Insights, AI Builder.</em></p><p><strong>7. Recommendation Engine</strong><br>RL is essential for decision-making in dynamic environments, optimizing recommendations based on user feedback, such as through Bandit algorithms. Real-time operation is crucial for adapting recommendations as new user interactions are received.<br><strong>Components</strong>: <em>Dynamics 365 Commerce, AI Builder.</em></p><p><strong>8. Customer Feedback Analysis</strong><br>RL can enhance text analysis by optimizing response strategies, enabling dynamic categorization, and supporting active learning in feedback processing, allowing for continuous adaptation based on incoming customer feedback.<br><strong>Components</strong>: <em>Dynamics 365 Customer Voice, AI Builder.</em></p><p><strong>9. Relationship Analytics</strong><br>RL optimizes interaction strategies and personalizes communications by modeling long-term relationship dynamics. Markov Decision Processes (MDPs) model state transitions, making RL ideal for long-term relationship value optimization and adaptation to evolving customer behaviors.<br><strong>Components</strong>: <em>Dynamics 365 Sales Insights.</em></p><p><strong>10. Routing Optimization</strong><br>RL is needed to find optimal routes in a dynamic environment, considering various real-time factors. Methods like Deep Q-Networks (DQN) are effective for large and complex routing tasks, with real-time operation possible.<br><strong>Components</strong>: <em>Dynamics 365 Field Service, AI Builder.</em></p><p><strong>11. Predictive Stock Management</strong><br>RL can apply to time series forecasting tasks with complex dependencies, such as inventory management, but traditional methods like ARIMA or Prophet often provide better results for predictable patterns. RL is more useful for dynamic optimization and real-time decision-making.<br><strong>Components</strong>: <em>Dynamics 365 Supply Chain Management, Power BI.</em></p><p><strong>12. Fraud Detection for Transactions</strong><br>RL can adapt to fraudster strategies in real-time, but simpler models like decision trees, logistic regression, or ensemble methods are usually more effective in fraud detection. RL can be useful for long-term adaptation to new fraud strategies and dynamic decision-making.<br><strong>Components</strong>: <em>Dynamics 365 Fraud Protection, AI Builder.</em></p><p><strong>13. Credit Scoring</strong><br>While simpler models like logistic regression are typically more effective, RL can be applied when temporal dependencies exist, and long-term credit strategy optimization is needed. The mathematical structure involves sequential decision-making with delayed feedback (actual loan repayment), making it suitable for RL’s value function optimization and policy learning.<br><strong>Components</strong>: <em>Dynamics 365 Finance, AI Builder.</em></p><p><strong>14. Predictive Loan Default</strong><br>The classification task can be solved using other methods. But RL is particularly suitable due to the temporal nature of loan default prediction. The mathematical framework involves sequential risk assessment with delayed rewards, where the model can learn optimal policies for default prevention through continuous state-action-reward cycles.<br><strong>Components</strong>: <em>Dynamics 365 Finance, AI Builder.</em></p><p><strong>15. Anomaly Detection in Financial Reports</strong><br>RL is generally not the best choice for anomaly detection in financial reports. Statistical methods, autoencoders, or clustering algorithms tend to work better for this task. Real-time operation is possible with the appropriate methods.<br><strong>Components</strong>: <em>Dynamics 365 Finance, Power BI.</em></p><p><strong>16. Cash Flow Forecasting</strong><br>RL can be useful for forecasting when there are complex dependencies and decisions affect future cash flow, but ARIMA or Prophet methods are more commonly used for time series forecasting. Real-time operation is possible with appropriate methods.<br><strong>Components</strong>: <em>Dynamics 365 Finance, Power BI.</em></p><p><strong>17. Employee Retention Prediction</strong><br>Logistic regression or decision trees are more effective for initial prediction tasks. However, RL can optimize retention strategies through sequential decision-making. The mathematical structure supports learning from temporal patterns in employee behavior and optimizing intervention timing, making it effective for dynamic retention strategy adaptation.<br><strong>Components</strong>: <em>Dynamics 365 Human Resources, AI Builder.</em></p><p><strong>18. Predictive Employee Performance</strong><br>Linear regression or gradient boosting works better for performance prediction. However, RL is applicable for optimizing employee development trajectories. The mathematical framework involves continuous state spaces and action selection for performance optimization, supporting adaptive learning paths and dynamic KPI adjustments.<br><strong>Components</strong>: <em>Dynamics 365 Human Resources, AI Builder.</em></p><p><strong>19.Insider Threat Prediction</strong><br>Traditional machine learning methods, such as anomaly detection and classification, are more effective for insider threat prediction. RL is highly effective for complex classification tasks in security, can adapt to changing threat patterns, handle temporal dependencies, and optimize threat detection strategies. Additionally, modern RL systems can operate in real-time, enabling online monitoring of suspicious activities and immediate adaptation to new threats.<br><strong>Components</strong>: <em>Dynamics 365 Human Resources, AI Builder.</em></p><p><strong>20. Trust and Compliance Analytics </strong><br>RL can enhance monitoring strategies and compliance control. The mathematical structure supports sequential decision-making in risk detection and prevention, with state transitions representing compliance status changes over time.<br><strong>Components: </strong><em>Microsoft Compliance Manager, Azure Machine Learning, Power BI (for data visualization and analysis).</em></p><p><strong>21. Predictive Maintenance</strong><br>RL optimizes maintenance by balancing cost minimization and maximizing uptime. Methods like Contextual Bandits and DQN can be applied for decision-making in dynamic environments. Real-time operation is feasible.<br><strong>Components</strong>: <em>Dynamics 365 Supply Chain Management, AI Builder.</em></p><p><strong>22.Intelligent Order Management</strong><br>RL optimizes order fulfillment in real-time, taking into account dynamic changes in demand and resource constraints.<br><strong>Components</strong>: <em>Dynamics 365 Intelligent Order Management, AI Builder.</em></p><p><strong>23. Asset Management</strong><br>RL helps optimize predictive maintenance, minimizing downtime and improving efficiency. Real-time operation is possible.<br><strong>Components</strong>: <em>Dynamics 365 Supply Chain Management, AI Builder.</em></p><p><strong>24. Warehouse Management</strong><br>RL optimizes warehouse processes like product placement, routing, and order picking.<br><strong>Components</strong>: <em>Dynamics 365 Supply Chain Management, AI Builder.</em></p><p><strong>25. Expense Management</strong><br>RL optimizes budget allocation and predicts future expenses based on historical data. However, for detecting suspicious transactions, anomaly detection and classification models are more appropriate.<br><strong>Components</strong>: <em>Dynamics 365 Finance, AI Builder.</em></p><p><strong>26. Workforce Analytics</strong><br>RL can optimize team performance and predict workforce demand by adapting to changing conditions. However, employee efficiency analysis is typically handled better by regression and classification models.<br><strong>Components</strong>: <em>Dynamics 365 Human Resources, Power BI.</em></p><p><strong>27. Time and Attendance</strong><br>RL can optimize work schedules and detect attendance anomalies, but for workload prediction, simpler models like time series forecasting or regression might be more effective.<br><strong>Components</strong>: <em>Dynamics 365 Human Resources.</em></p><p><strong>28. Guides</strong><br>RL personalizes training materials by adapting content complexity and optimizing learning paths based on the learner’s progress and engagement.<br><strong>Components</strong>: <em>Dynamics 365 Guides.</em></p><p><strong>29. Remote Assist</strong><br>RL optimizes request routing, predicts required resources, and improves support quality by analyzing historical data and real-time interactions.<br><strong>Components</strong>: <em>Dynamics 365 Remote Assist.</em></p><p><strong>30. Customer Voice</strong><br>RL optimizes feedback collection, analyzes sentiments, and personalizes surveys by dynamically adjusting to customer responses and preferences.<br><strong>Components</strong>: <em>Dynamics 365 Customer Voice.</em></p><p><strong>31. IoT Intelligence</strong><br>RL applies to IoT data analysis, optimizing management, predictive maintenance, and real-time decision-making based on IoT device data.<br><strong>Components</strong>: <em>Dynamics 365 Supply Chain Management, Power BI.</em></p><p><strong>32. Marketing Optimization</strong><br>RL optimizes marketing campaigns, personalization, and targeting to maximize ROI in real-time, adapting to changing customer behaviors and campaign performance.<br><strong>Components</strong>: <em>Dynamics 365 Marketing, AI Builder.</em></p><p><strong>33. Omnichannel Personalization</strong><br>RL personalizes interactions across channels in real-time, adapting to customer preferences and behavior, optimizing engagement strategies.<br><strong>Components</strong>: <em>Dynamics 365 Omnichannel for Customer Service.</em></p><p><strong>34. Project Operations</strong><br>RL optimizes resource allocation, predicts risks and delays, and enables adaptive planning, improving project execution.<br><strong>Components</strong>: <em>Dynamics 365 Project Operations.</em></p><blockquote>Of course, the use of RL for Dynamics 365 projects must be carefully justified. Even in cases where RL could theoretically improve performance, its implementation and training complexity may outweigh the potential benefits.</blockquote><h3>4.2.2 RL Solutions Efficiency Metrics</h3><h4>4.2.2.1 RL Business Metrics:</h4><p><strong>CAGR (Compound Annual Growth Rate):</strong><br> — Analysis of company revenue growth after RL implementation.<br> — Shows RL impact on company competitiveness.<br> — Used for long-term investment planning.</p><p><strong>CLV (Customer Lifetime Value):</strong><br> — Evaluates RL contribution to customer retention.<br> — Enables building long-term customer interaction strategies.<br> — Helps assess the effectiveness of personalized offers.</p><p><strong>ROI (Return on Investment):</strong><br> — Compares the cost of developing RL solutions and their benefits.<br> — Used to justify further investments in ML technologies.<br> — Analyzed to identify the most effective implementations.</p><h4>4.2.2.2 RL Technical Metrics:</h4><p><strong>Total Reward:</strong><br> — Demonstrates agent success in completing tasks.<br> — Helps determine the effectiveness of RL model training.<br> — Serves as a basis for comparing different RL strategies.</p><p><strong>Average Episode Duration:</strong><br> — Allows evaluation of how quickly the agent achieves goals.<br> — Used for diagnosing possible RL model problems.<br> — Decrease in episode duration indicates model improvement.</p><h3>4.2.3 Specifics of the ML Infrastructure in Dynamics 365:</h3><p>*<em>The complexity level indicates how much technical work and expertise will be required from the team to implement ML functionality in a specific Dynamics 365 module.</em></p><p><strong>4.2.3.1 Modules with Built-in ML Models (complexity level: Low):</strong></p><p>ML functionality is an integral part of the module, with pre-trained models available “out of the box.” No significant customization or model development is required from the user. These modules provide immediate value with minimal setup.</p><p><strong>4.2.3.2 Modules with Built-in Analytics and ML Extensibility (Hybrid Approach, complexity level: Medium):</strong></p><p>The module provides basic analytics and/or simple ML algorithms. Functionality can be extended through integration of custom models, typically via AI Builder or Azure ML. Power Automate and Power Apps can be used for automation and custom interface creation. This approach allows for balanced customization while leveraging existing capabilities.</p><p><strong>4.2.3.3 Modules with ML Integration Capability via Azure, Power Platform, or Third-party Solutions (complexity level: High):</strong></p><p>ML functionality is not available by default. Significant custom development and model deployment is required using Azure ML, Power Platform (Power Automate, Power Apps, Power BI), or third-party ML platforms. This approach offers maximum flexibility but requires substantial expertise.</p><p>Imagine your Dynamics 365 could independently learn optimal pricing strategies, demand forecasting, or inventory management, adapting to constantly changing market conditions. This becomes possible through the application of reinforcement learning (RL), a promising machine learning direction that allows systems to learn through interaction with the environment.</p><p>Implementing RL in Dynamics 365 projects is not just the next step in platform development. It’s an opportunity for Dynamics 365 users to gain a competitive advantage by expanding the potential of intellectualizing their business.</p><p>Reinforcement Learning (RL), based on Markov Decision Processes (MDP), offers an approach that perfectly combines management philosophy and formal methods of stochastic optimization.</p><blockquote>In the <a href="https://medium.com/@serhii.barskyi/testing-methods-in-reinforcement-learning-projects-for-dynamics-365-6e83570b10fd">next lesson</a>, we will also examine one of the examples of integrating an RL model with the Dynamics infrastructure.</blockquote><p><strong>For Complete individual RL development course for </strong><a href="https://www.microsoft.com/en-us/dynamics-365"><strong>Dynamics 365</strong></a><strong> and for one-on-one tutoring on machine Reinforcement Learning topics, please, contact: </strong><a href="https://neuverso.ai/"><strong>https://neuverso.ai/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=746ec71c799e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aizenberg Neuron (MVN) in Complex-Valued Reinforcement Learning Tasks]]></title>
            <link>https://medium.com/@serhii.barskyi/aisenberg-neuron-in-complex-valued-reinforcement-learning-tasks-dc4a8f53cc1d?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc4a8f53cc1d</guid>
            <category><![CDATA[neuverso]]></category>
            <category><![CDATA[aizenberg-neuron]]></category>
            <category><![CDATA[complex-valued-q-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[serhii-barskyi]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 22:38:15 GMT</pubDate>
            <atom:updated>2026-05-02T07:34:36.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YY01oiZ8CQWXlpDnYgV9g.png" /></figure><p>My Data Science Course <a href="https://preply.com/en/tutor/7756455">https://preply.com/en/tutor/7756455</a></p><p>Aizenberg’s multi-valued neuron model (MVN) generalizes threshold activation using multi-valued logic and complex numbers to represent inputs, weights, and outputs. In complex-valued reinforcement learning (RL), this neuron leverages phase characteristics to adapt to changing environmental conditions, enabling the agent to make decisions based on complex representations of state.</p><h3>1. Aizenberg Neuron Inputs</h3><p>The neuron’s input values are represented as complex numbers on the unit circle of the complex plane:</p><pre>x_k = e**(i * phi_k),    # k = 1, 2, ..., n</pre><p>where phi_k is the phase of the input signal, and i is the imaginary unit. The input magnitude |x_k| equals 1, as inputs lie on the unit circle.</p><p>In RL tasks, complex inputs can encode the agent’s states or actions, with the phase angle phi_k representing the current state or action. This allows Aizenberg’s neuron to process phase characteristics within the RL context, emphasizing key signal features.</p><h3>2. Weighted Sum</h3><p>Each input signal x_k is multiplied by a complex weight w_k, represented as:</p><pre>w_k = |w_k| * e**(i * theta_k),</pre><p>where |w_k| is the weight&#39;s magnitude and theta_k is its phase.</p><p>The weighted sum of all inputs is calculated as:</p><pre>z = sum(w_k * x_k for k in range(1, n+1)) = sum(|w_k| * e**(i * (theta_k + phi_k)) for k in range(1, n+1))</pre><p>The resulting value z is a complex number. In polar form, it is represented as:</p><pre>z = R * e**(i * psi),</pre><p>where:</p><pre>R = |z| = sqrt((sum(|w_k| * cos(theta_k + phi_k) for k in range(1, n+1))**2) + (sum(|w_k| * sin(theta_k + phi_k) for k in range(1, n+1))**2))</pre><p>and</p><pre>psi = arg(z) = atan2(sum(|w_k| * sin(theta_k + phi_k) for k in range(1, n+1)), sum(|w_k| * cos(theta_k + phi_k) for k in range(1, n+1)))</pre><p>The Aizenberg neuron’s activation is based on the phase psi, which determines the neuron&#39;s response. The magnitude R, depending on the task, can serve as an indicator of signal strength and be used for additional amplitude information.</p><h3>3. Activation Function</h3><p>Aizenberg’s multi-valued neuron activation function divides the complex plane into k sectors, using the k-th roots of unity:</p><pre>epsilon_j = e**(2 * pi * i * j / k),    # j = 0, 1, ..., k-1</pre><p>These values are evenly distributed on the unit circle.</p><p>The activation function determines which sector the weighted sum z falls into, based on its argument psi. If psi falls within the sector corresponding to the j-th root of k, the neuron output y is defined as:</p><pre>y = epsilon_j = e**(2 * pi * i * j / k),    # if (2 * pi * j / k) &lt;= psi &lt; (2 * pi * (j + 1) / k)</pre><p>Thus, the neuron’s output is always one of the k-th roots of unity, making this model particularly flexible for complex representations.</p><h3>Example of MVN-CVRL for UAV Control</h3><p>In unmanned aerial vehicle (UAV) control, precise maneuvering and dynamic forecasting require hybrid approaches that can account for complex states and uncertainties in the environment. The combination of Aizenberg’s Multi-Valued Neuron Model (MVN) with complex-valued reinforcement learning (CVRL) extends classical approaches through phase coding of data. Complex-valued states, represented as amplitudes and phases, provide greater information capacity, improving the accuracy of current and future state estimations for UAVs. This allows Aizenberg’s neuron to utilize sectoral phase coding, supporting robust control in a changing environment.</p><blockquote>Additionally, the phase representation facilitates the classification of states and transitions, enabling the model to effectively account for errors and adjust its course. With the help of phase information, the MVN-CVRL method adapts complex weights for control, reducing the need for additional sensors and enhancing maneuvering precision. In turn, the complex-valued Q-function allows for modeling stochastic transitions between states by accumulating phase shifts, thus more accurately considering the long-term consequences of actions.</blockquote><h3>1. Description of the Control System</h3><h3>1.1 Dynamic Model of UAV</h3><h4>1.1.1 Motion Equations in State Space</h4><p>The control system is described by the following equation in state space:</p><pre>dx_dt = f(x, u)</pre><p>where:</p><ul><li>x = [x, y, z, phi, theta, psi, dx, dy, dz, p, q, r] - state vector:</li><li>[x, y, z] - position in space.</li><li>[phi, theta, psi] - Euler angles (roll, pitch, yaw).</li><li>[dx, dy, dz] - linear velocities.</li><li>[p, q, r] - angular velocities.</li><li>u = [u1, u2, u3, u4] - control vector:</li><li>u1 - total thrust.</li><li>u2, u3, u4 - moments around roll, pitch, and yaw axes.</li></ul><p>The state equations describe the motion of the UAV based on the control vector and current state, which is the basis for predicting its behavior. The state vector [x, y, z, phi, theta, psi, dx, dy, dz, p, q, r] specifies the key parameters that characterize the position, orientation, and speeds of the UAV. The control system uses input signals u = [u1, u2, u3, u4] to adjust the state, allowing for control over the position and orientation of the UAV. The motion equations represent a nonlinear dynamic system that accounts for the interaction of all components in the state vector. The main goal of control is to maintain stable motion of the UAV along a given trajectory with minimal deviations from the target state.</p><h4>1.1.2 Explicit Motion Equations</h4><p><strong>Translational Motion:</strong></p><pre>ddx = u1 / m * (cos(phi) * sin(theta) * cos(psi) + sin(phi) * sin(psi))<br>ddy = u1 / m * (cos(phi) * sin(theta) * sin(psi) - sin(phi) * cos(psi))<br>ddz = u1 / m * cos(phi) * cos(theta) - g</pre><p>where:</p><ul><li>m - mass of the UAV,</li><li>g - acceleration due to gravity.</li></ul><pre>dp = (I_yy - I_zz) / I_xx * q * r + u2 / I_xx<br>dq = (I_zz - I_xx) / I_yy * p * r + u3 / I_yy<br>dr = (I_xx - I_yy) / I_zz * p * q + u4 / I_zz</pre><p>where:</p><ul><li>I_xx, I_yy, I_zz - moments of inertia of the UAV around the respective axes.</li></ul><p>The translational motion equations determine the trajectory of the UAV based on its orientation and the effect of total thrust. The rotational motion equations describe turning movements, considering moments of inertia and control moments around the axes. The mass of the UAV m and moments of inertia I_xx, I_yy, I_zz play a key role in modeling, as they affect accelerations and rotational speeds. The nonlinear structure of the equations requires numerical methods for solutions, adding complexity to the control. This model allows for accurate calculations of changes in linear and angular velocities given the known forces and moments acting on the UAV.</p><h3>1.2 Aizenberg’s Neuron (MVN)</h3><h4>1.2.1 Representation of Inputs</h4><pre>def state_to_complex(state):<br>    &quot;&quot;&quot;Transform physical state to complex representation&quot;&quot;&quot;<br>    # Normalize state to range [0, 2π]<br>    phi = normalize_angle(state)<br>    # Representation on the unit circle<br>    return exp(1j * phi)<br><br>def normalize_inputs(x):<br>    &quot;&quot;&quot;Normalize inputs to the unit circle&quot;&quot;&quot;<br>    return [x_i / abs(x_i) for x_i in x]</pre><p>Transforming the state into a complex representation ensures compatibility with the MVN algorithm, which works with phase data. Normalizing the state to the range [0, 2π] allows all input values to be represented as phase angles. Simplifying input through normalization helps avoid numerical errors and increases the model’s stability. The transformation onto the unit circle ensures that all data are presented as complex numbers with a modulus of 1, stabilizing the algorithm. This approach allows for effective use of phase information in controlling the UAV’s state.</p><h4>1.2.2 Structure of Weight Coefficients</h4><pre>def initialize_complex_weights(n):<br>    &quot;&quot;&quot;Initialize complex weights&quot;&quot;&quot;<br>    return [exp(1j * random.uniform(0, 2 * pi)) for _ in range(n)]</pre><p>Complex weights are initialized with random phase values to provide initial diversity in the system. Using phases uniformly distributed in the range [0, 2π] aids in exploring a large solution space. Weights represent complex numbers that can be interpreted as rotations on the unit circle. Random weight initialization helps avoid symmetry issues that can arise in symmetric systems. This approach improves the system’s ability to generalize since it starts with a broad range of possible reactions.</p><h4>1.2.3 Activation Function</h4><pre>def mvn_activate(z, k):<br>    &quot;&quot;&quot;Sector activation MVN&quot;&quot;&quot;<br>    # Calculate phase of the weighted sum<br>    psi = arg(z)<br>    # Determine the sector<br>    sector = floor(k * psi / (2 * pi))<br>    # Return the k-th root of unity<br>    return exp(2 * pi * 1j * sector / k)</pre><p>The MVN activation function divides the phase space into sectors to represent different states. Calculating the phase of the weighted sum allows for determining the current phase state of the network. Dividing into k sectors helps improve the accuracy of state classification, contributing to more precise control. Choosing a sector is a discretization of the phase space, simplifying the action selection problem. This function is used to activate the network and select further actions based on the phase representation of the state.</p><h4>1.2.4 MVN Learning Rule</h4><pre>def update_mvn_weights(w_k, x_k, y, d, eta):<br>    &quot;&quot;&quot;Update MVN weights&quot;&quot;&quot;<br>    delta_w_k = eta * (d - y) * conj(x_k)<br>    return (w_k + delta_w_k) / abs(w_k + delta_w_k)</pre><p>The MVN learning rule is based on adjusting weights according to the error between the expected and current output. The complex contribution of the error (d - y) * conj(x_k) allows for considering phase errors. The parameter eta regulates the learning rate, determining how quickly the network adapts to changes. Normalizing weights after updates helps avoid error accumulation and maintains learning stability. This formula ensures gradual learning of the system, improving its ability to respond correctly to new inputs.</p><h3>1.3 Complex-Valued Reinforcement Learning (CVRL)</h3><h4>1.3.1 Definition of States and Actions</h4><pre>class ComplexState:<br>    def __init__(self, position, velocity, angular_velocity, error):<br>        self.position = position  # [x, y, z]<br>        self.velocity = velocity  # [dx, dy, dz]<br>        self.angular_velocity = angular_velocity  # [p, q, r]<br>        self.error = error  # [e_x, e_y, e_z]<br>        <br>    def to_complex(self):<br>        &quot;&quot;&quot;Convert state to complex representation&quot;&quot;&quot;<br>        return [state_to_complex(val) for val in self.flatten()]</pre><p>The ComplexState class represents the UAV state, including position, velocity, angular velocity, and error in the current position. Position, linear, and angular velocities are modeled as separate vectors, simplifying the manipulation of these quantities. Class fields allow for easy addition of new state parameters, such as errors, which can enhance learning accuracy. The to_complex method converts each numerical state value into a complex form, enabling its use in complex-valued learning algorithms. This complex representation of the state facilitates phase-based learning, where each state can be encoded as a phase on the unit circle, improving the system’s response to changes.</p><h4>1.3.2 Complex Q-Function</h4><pre>class ComplexQFunction:<br>    def __init__(self):<br>        self.q_table = {}<br>        <br>    def get_value(self, state, action):<br>        &quot;&quot;&quot;Retrieve complex Q-value&quot;&quot;&quot;<br>        if (state, action) not in self.q_table:<br>            self.q_table[(state, action)] = 0 + 0j<br>        return self.q_table[(state, action)]<br>    <br>    def update(self, state, action, reward, next_state, alpha, gamma):<br>        &quot;&quot;&quot;Update Q-value&quot;&quot;&quot;<br>        current_q = self.get_value(state, action)<br>        max_next_q = max(self.get_value(next_state, a) for a in self.get_actions(next_state))<br>        self.q_table[(state, action)] += alpha * (reward + gamma * max_next_q - current_q)</pre><p>The ComplexQFunction class represents an implementation of a complex Q-function that stores Q-values for state-action pairs. The get_value method returns the current Q-value for a specific pair, initializing it as 0 + 0j if no entry exists yet. Q-values are updated using the update method, which considers the reward for the current action as well as the maximum expected value in the next state. The alpha parameter regulates the learning rate, while gamma adjusts the consideration of future rewards, allowing for tuning the balance between short-term and long-term gains. Complex Q-values enable phase information to be encoded, enhancing the system’s response in the complex state space and providing more accurate control.</p><h3>1.4 Hybrid MVN-CVRL Architecture</h3><h4>1.4.1 Structure of the Hybrid System</h4><pre>class HybridMVNCVRL:<br>    def __init__(self, k_sectors, state_dim, action_dim):<br>        self.k = k_sectors<br>        self.mvn = MVNLayer(state_dim)<br>        self.q_function = ComplexQFunction()<br>        <br>    def process_state(self, state):<br>        &quot;&quot;&quot;Process state through MVN&quot;&quot;&quot;<br>        x = state.to_complex()<br>        x_norm = normalize_inputs(x)<br>        z = self.mvn.forward(x_norm)<br>        return mvn_activate(z, self.k)<br>    <br>    def select_action(self, mvn_output, state):<br>        &quot;&quot;&quot;Select action based on MVN output and Q-values&quot;&quot;&quot;<br>        sector = arg(mvn_output) * self.k / (2 * pi)<br>        return self.q_function.get_best_action(state, sector)</pre><p>The hybrid system HybridMVNCVRL combines MVN and complex Q-function to process the phase representation of the state and select actions based on it. The process_state method processes the input state using MVN, converting it into a phase representation suitable for action selection. MVN allows the phase space to be divided into sectors corresponding to different states and activation levels, simplifying the decision-making process. The select_action method uses the MVN output and current Q-values to select an action, optimizing it according to the phase information. The hybrid architecture integrates phase activation with reinforcement learning, providing more precise and robust UAV control.</p><h4>2.4 Pseudocode of the Algorithm</h4><pre>class HybridControl:<br>    def __init__(self, k_sectors, state_dim, action_dim):<br>        self.hybrid_system = HybridMVNCVRL(k_sectors, state_dim, action_dim)<br>        self.safety_checker = SafetyChecker()<br>        <br>    def run(self, initial_state, goal_position):<br>        state = initial_state<br>        <br>        while not self.goal_reached(state, goal_position):<br>            # Safety check<br>            if not self.safety_checker.is_safe(state):<br>                self.execute_safety_protocol()<br>                continue<br>            <br>            # State transformation<br>            complex_state = state.to_complex()<br>            <br>            # Getting MVN output<br>            mvn_output = self.hybrid_system.process_state(complex_state)<br>            <br>            # Action selection<br>            action = self.hybrid_system.select_action(mvn_output, state)<br>            <br>            # Applying action<br>            next_state = self.apply_action(state, action)<br>            <br>            # Getting reward<br>            reward = self.compute_reward(next_state, goal_position)<br>            <br>            # Updating systems<br>            self.hybrid_system.update(state, action, reward, next_state)<br>            <br>            # Transition to the next state<br>            state = next_state</pre><p>HybridControl represents a complex control system that combines phase transformations of MVN with reinforcement learning. The run method creates a control loop that continues until the current state approaches the goal position, facilitating the achievement of the specified goal. SafetyChecker verifies the safety of the current state, and if it is not safe, the safety protocol is triggered. After transforming the state into a complex representation, MVN activation helps determine the optimal action based on phase information. This approach ensures smooth execution of the specified path, adjusting each action according to the current state and reward received for previous actions.</p><h3>3.1 Control Under Uncertainty</h3><h4>3.1.1 Adaptive Phase Weight Update</h4><pre>def adapt_phase_weights(weights, error, sensitivity):<br>    &quot;&quot;&quot;Adapt phase weights based on error&quot;&quot;&quot;<br>    phase_correction = sensitivity * error<br>    return [w * exp(1j * phase_correction) for w in weights]</pre><p>The adapt_phase_weights function regulates phase weights depending on the error to improve control accuracy under uncertainty. error is the deviation of the current state from the target, helping to assess the need for adjusting phase weights. sensitivity controls how much the weight will be adjusted based on the magnitude of the error. Modifying the weight through phase rotation (multiplying by the exponential with an imaginary value) accounts for the current phase of the state and minimizes deviation. Dynamic adaptation of phase weights enables the system to respond more quickly to changing conditions while maintaining stability and accuracy.</p><h3>3.2 Trajectory Correction</h3><h4>3.2.1 Error Compensation Algorithm</h4><pre>def compute_correction(current_state, desired_state, params):<br>    &quot;&quot;&quot;Compute correction vector&quot;&quot;&quot;<br>    position_error = desired_state.position - current_state.position<br>    velocity_error = desired_state.velocity - current_state.velocity<br>    <br>    return {<br>        &#39;position&#39;: params.beta * position_error,<br>        &#39;velocity&#39;: params.gamma * velocity_error,<br>        &#39;phase&#39;: compute_phase_correction(current_state, desired_state)<br>    }</pre><p>The compute_correction function calculates necessary adjustments for the current trajectory, focusing on deviation from the desired state. position_error determines how much the current position differs from the target, helping the system correct the trajectory. Parameters beta and gamma control the degree of correction for position and velocity, allowing flexible adjustment of control. phase is computed separately, considering the need for phase correction, which enhances accuracy in the complex space. This approach ensures a rapid system response to deviations, maintaining stable movement along the designated trajectory.</p><h4>4.1 Performance Criteria</h4><pre>class PerformanceMetrics:<br>    def __init__(self):<br>        self.trajectory_error = 0.0<br>        self.energy_consumption = 0.0<br>        self.stability_measure = 0.0<br>        <br>    def update(self, state, action, desired_state):<br>        &quot;&quot;&quot;Update performance metrics&quot;&quot;&quot;<br>        self.trajectory_error += norm(state.position - desired_state.position)<br>        self.energy_consumption += norm(action)<br>        self.stability_measure = compute_stability(state)</pre><p>PerformanceMetrics collects and updates key indicators such as trajectory error, energy consumption, and stability measure to evaluate control effectiveness. trajectory_error computes the distance between the current and target positions, allowing assessment of trajectory execution accuracy. energy_consumption measures energy costs associated with the chosen action, helping to analyze control efficiency.stability_measure serves as an indicator of flight stability, providing an assessment of smoothness and stability of movement. These metrics allow the system to adapt to current conditions, improving control parameters to minimize errors and energy consumption.</p><h4>4.2 Tuning Parameters</h4><pre>class SystemParameters:<br>    def __init__(self):<br>        # Learning parameters<br>        self.alpha = 0.1  # Learning rate for the Q-function<br>        self.gamma = 0.99  # Discount factor<br>        self.eta = 0.01  # Learning rate for MVN<br>        <br>        # Reward weights<br>        self.w_position = 0.5<br>        self.w_velocity = 0.3<br>        self.w_energy = 0.2<br>        <br>    def adapt(self, performance_metrics):<br>        &quot;&quot;&quot;Adapt parameters based on metrics&quot;&quot;&quot;<br>        self.adjust_learning_rates(performance_metrics)<br>        self.adjust_reward_weights(performance_metrics)</pre><p>The SystemParameters class defines key learning parameters such as alpha, gamma, and eta, affecting the reinforcement learning process and MVN. w_position, w_velocity, and w_energy determine the contribution of position, velocity, and energy consumption to the overall reward, allowing for more precise tuning of target metrics. The adapt method adjusts parameters based on performance metric values, helping to achieve optimal system behavior. Adapting reward coefficients and learning rates enables the system to respond more quickly to changing conditions and reach set goals. This class provides flexibility in tuning the system, optimizing its behavior for better performance and stability in control.</p><h3>Conclusion</h3><p>The hybrid architecture MVN-CVRL for UAV control demonstrates the advantages of using complex-valued states and phase representation of data. During modeling, Aizenberg’s multivalued neuron effectively decomposes complex states and actions into phase sectors, optimizing the response to external disturbances. The application of a complex Q-function, capable of adapting to phase shifts, enhances the learning process and minimizes errors by accumulating complex information. By considering phase shifts between states, complex reinforcement learning offers a method for minimizing stochastic errors and allows for more accurate modeling of the UAV’s motion dynamics. As a result, complex-valued metrics, such as phase error and amplitude deviation, enable dynamic evaluation and adjustment of control, ensuring safer and more reliable maneuvering.</p><p>In the next lesson, we will examine in more detail how the complex-valued representation and the use of the Aizenberg neuron help solve the “curse of dimensionality” in drone navigation tasks:</p><blockquote>- Complex-valued representation enables the Aizenberg neuron to learn non-linearly separable tasks in the original space without needing to create higher-degree inputs or transition to a higher-dimensional space;</blockquote><blockquote>- Complex numbers can compactly encode the position, orientation, and velocity of a drone in three-dimensional space;</blockquote><blockquote>- The angles of rotation and movement direction of the drone are naturally represented in complex form.</blockquote><p><strong>For one-on-one tutoring on machine Reinforcement Learning topics, please, contact: </strong><a href="https://neuverso.ai/"><strong>https://neuverso.ai/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc4a8f53cc1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex-Valued Magic and the Mystery of the Emerald Adit]]></title>
            <link>https://medium.com/@serhii.barskyi/complex-valued-magic-and-the-mystery-of-the-emerald-adit-e594277c7b71?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/e594277c7b71</guid>
            <category><![CDATA[complex-valued-q-learning]]></category>
            <category><![CDATA[neuverso]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[aizenberg-neuron]]></category>
            <category><![CDATA[serhii-barskyi]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 10:56:24 GMT</pubDate>
            <atom:updated>2026-05-02T07:35:03.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvMHq7KLMR1zMDR8kyOAvw.jpeg" /></figure><p>Halloween is approaching, and it’s time for tales and mysterious stories. This time, the RL Studio at the <a href="https://neuverso.ai/">Neuverso Academy</a> is excited to present a lesson in the format of “Math-Fiction Fairy Tales for Junior Data Scientists” with some unusual test challenges. The theme of the lesson is aimed at fans of <a href="https://medium.com/@serhii.barskyi/aisenberg-neuron-in-complex-valued-reinforcement-learning-tasks-dc4a8f53cc1d">Derivative-Free Complex Valued Reinforcement Learning</a>, lovers of complex numbers, and the theory of functions of a complex variable.</p><p>My Data Science Course <a href="https://preply.com/en/tutor/7756455">https://preply.com/en/tutor/7756455</a></p><h3>Why Complex Numbers for RL?</h3><p>Given the ability of complex-valued reinforcement learning to effectively handle periodic processes and cyclic dependencies, such an approach, like derivative-free complex-valued reinforcement learning, can significantly improve decision-making quality in tasks with a cyclical nature, such as robotics and quantum computing. As quantum technologies advance and dynamic system control tasks become more complex, using complex representations of states and actions could become a standard approach, especially in areas requiring <a href="https://medium.com/aimonks/exploring-the-frontier-complex-numbers-in-deep-learning-enhancements-challenges-and-future-8fb4aebd415b">phase characteristics and multidimensional interactions.</a></p><p>1. The use of complex numbers on the unit circle enables efficient encoding of an agent’s states and actions through phase angles, naturally representing cyclic and periodic processes.</p><p>2. The phase characteristics of complex signals make it possible to evenly partition the solution space into an arbitrary number of classes using k-th roots of unity.</p><p>3. Updating weights in complex form eliminates the need for computing derivatives of the activation function, simplifying and accelerating the learning process.</p><p>4. Complex-valued representation on the unit circle with normalized inputs (|x_k| = 1) ensures stable signal processing focused on phase characteristics, while the magnitude of weighted sum (R) can serve as an additional indicator of signal strength when needed.</p><p>5. Minimizing phase error in the complex plane provides more accurate agent adaptation to the current situation compared to traditional methods based solely on real numbers.</p><blockquote>*All the 5 points listed above concern only complex-valued reinforcement learning on the <a href="https://medium.com/@serhii.barskyi/aisenberg-neuron-in-complex-valued-reinforcement-learning-tasks-dc4a8f53cc1d">Aizenberg neuron</a>.</blockquote><h3>About the Lesson Format</h3><p>Lewis Carroll (Charles Lutwidge Dodgson) wrote mathematical tales woven with themes of logic, set theory, and geometry. His works often explore questions about infinity, paradoxes, and logical puzzles. For instance, in “Alice’s Adventures in Wonderland” and its sequel “Through the Looking-Glass”, paradoxes and references to logical and mathematical principles are subtly embedded. These stories not only entertain but also prompt readers to ponder complex concepts like sequence, reality and relativity.</p><p>Now, it’s time for Junior Data Scientists to embark on their own mathematical adventure, where the key to the mystery lies in complex numbers and their interactions. Here, special attention is given to operations like addition and multiplication of complex numbers, along with their unique properties, as the imaginary and real parts combine in fascinating ways.</p><p><a href="https://blog.keithmcnulty.org/the-era-of-the-mathematician-has-arrived-bc2d59b95245">The era of the mathematician has arrived</a>, so developing mathematical intuition is one of the primary goals of Neuverso Academy’s <a href="https://neuverso.ai/courses/">individual Data Science courses</a>.</p><p><a href="https://www.researchgate.net/publication/238557755_THE_NATURE_OF_MATHEMATICS_AS_VIEWED_FROM_COGNITIVE_SCIENCE">Epistemological</a> and <a href="https://philarchive.org/archive/LAWABI-4">phenomenological</a> approaches in pedagogy present mathematical constructs as phenomena that reflect not only quantitative relations but also qualitative aspects of our conscious experience. Thus, mathematics is not just a set of formulas, but tools for <a href="https://harvest.usask.ca/server/api/core/bitstreams/c9d138b3-05a7-4965-a7b4-b142d526b2e2/content"><strong>organizing our thinking and structuring perception</strong></a><strong>.</strong></p><p>At the same time, incorporating game elements into mathematical learning materials encourages more creative and deeper observation of the processes that shape our understanding of reality. It helps learners focus on the quality of awareness and interpretation of the world around them.</p><p>From the perspective of cognitive neurobiology, using metaphors and stories can activate various brain areas and aid in the integration of logical and creative thinking.</p><p>Metaphors:<br>- Often appeal to sensory memory, engaging emotional centers in the brain, such as the amygdala.<br>- Create richer associative connections in memory and often require students to formulate their own interpretations, leading to deeper understanding.</p><p>The ability to generate and comprehend metaphors is associated with various cognitive skills, including fluid and crystallized intelligence, as well as the capacity for broad information retrieval, which enhances both memory retention and the application of information across different contexts.</p><p>Before diving into the tale, you need to be familiar with the architecture of the <a href="https://medium.com/@serhii.barskyi/aisenberg-neuron-in-complex-valued-reinforcement-learning-tasks-dc4a8f53cc1d">Aizenberg neuron</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfyxSpuJPmszRizdd3n6ig.jpeg" /></figure><h3>Complex-Valued Magic and the Mystery of the Emerald Adit</h3><p>In a deep underground dungeon, where the walls shimmered with emerald light, there lived a dwarf named Cardano. He was the most skillful gem collector in all the kingdom of subterranean dwellers. Cardano knew all the secret formulas and spells that allowed him to find emeralds in the most inaccessible parts of the mines.</p><p>One day, the dwarf king gave Cardano a special task: to find three magical emeralds which, when gathered together, could grant any wish. The sages of the kingdom handed Cardano an ancient spell for finding the stones, written on parchment in mysterious runes:</p><p>“When you cube what you have found, add twenty, and subtract twenty-one times the found, you will get zero.”</p><pre><br># Cubic Equation<br><br><br>x^3 + 20*x - 21 = 0<br><br><br># To find the roots of a general cubic equation of the form ax^3 + bx^2 + cx + d = 0, <br># we use Cardano&#39;s method, which includes steps to find complex roots.<br><br>Introducing auxiliary variables:<br>Let Δ = Q^3 + R^2, where:<br>Q = (3ac - b^2) / (9a^2)<br>R = (9abc - 27a^2d - 2b^3) / (54a^3)<br><br>Formula for roots depending on Δ &gt; 0, Δ &lt; 0, and Δ = 0:<br>Root x = u + v - b / (3a), where u and v are the cube roots of R ± √(Δ).<br><br></pre><p>Cardano was confident in his craft. He knew the special rule for finding gems — the “three roots formula,” as the dwarves called it. But when he tried to apply the spell, something strange happened — the formula pointed into the void, as if the emeralds existed in another dimension.</p><pre><br># Solution for the Roots of a Depressed Cubic Equation<br><br><br>x = 2^(1/3) * (q/2 + (q^2/4 + p^3/27)^(1/2))^(1/3) + 2^(1/3) * (q/2 - (q^2/4 + p^3/27)^(1/2))^(1/3)<br><br><br># This formula represents one of the real roots of a depressed cubic equation of the form:<br>t^3 + pt + q = 0<br><br>Steps for solving the equation using complex numbers:<br>Step 1: Introduce discriminant Δ = (q/2)^2 + (p/3)^3, which determines the nature of the roots.<br>Step 2: If Δ &gt; 0, one real root and two complex conjugate roots exist.<br>Step 3: Define cube roots u and v as:<br>     u = (q/2 + √(Δ))^(1/3)<br>     v = (q/2 - √(Δ))^(1/3)<br>Step 4: Then the root is expressed as:<br>     x = u + v<br>When Δ &lt; 0, the roots include complex numbers with imaginary components.</pre><p>This void was special — it shimmered with reflections of non-existent crystals, like the mirror-like surface of an underground lake, reflecting treasures that were not on the shore. In this void lived the shadows of emeralds — transparent and elusive, like morning mist, but capable of pointing the way to real treasures.</p><p>Cardano noticed that when he passed his hand through these ghostly crystals, they began to spin, like the hands of a magical compass, always pointing toward real gems. It seemed that the very mine itself created this mysterious space, where crystal-guides dwelled — not quite real, yet not entirely illusory.</p><pre><br># Complex Number Representation<br><br><br>z = x + y * i<br><br><br># A complex number z is represented as z = x + yi, where:<br>  - x is the real part, Re(z) = x<br>  - y is the imaginary part, Im(z) = y<br>  - i is the imaginary unit, with the property i^2 = -1<br><br># Operations involving complex numbers:<br> 1. Magnitude (or modulus) of z: |z| = √(x^2 + y^2)<br> 2. Argument (or phase) of z: θ = arctan(y / x)<br> 3. Complex conjugate of z: z* = x - yi<br><br># Complex numbers are often solved in polar form:<br> z = |z|(cos θ + i sin θ), which can also be written as |z| * e^(iθ)</pre><pre><br>In the context of the Aizenberg neuron and complex-valued reinforcement <br>learning, the model uses complex inputs, weights, and a weighted sum z <br>represented in polar or exponential form.<br>This model emphasizes phase characteristics to classify inputs <br>effectively and guide reinforcement learning.<br><br>The formula z = x + y*i (where z is a complex number with real part x and <br>imaginary part y) illustrates the decomposition into real and imaginary <br>components, essential for phase-based operations.<br><br># Key aspects affected by this representation:<br><br># 1. Output sector determination:<br>    - The phase ψ = arg(z) = atan2(y, x) determines the sector <br>into which the Aizenberg neuron&#39;s output falls.<br>    - The Aizenberg neuron’s activation corresponds to one of the k roots <br>of unity based on the computed phase, allowing for k-class separation.<br><br># 2. Weight adjustment during training:<br>    - The error is computed as the difference between the desired <br>and current output in complex form.<br>    - The conjugate of the input is used for weight updates, maintaining <br>the phase alignment.<br>    - No derivatives are needed, as phase difference alone guides <br>the learning, making it derivative-free.<br><br>Thus, representing z in complex form enables effective partitioning of <br>the space into sectors and allows training of the Aizenberg neuron without <br>using derivatives, a key advantage of this model.<br><br># 1. Output sector determination:<br><br>Assume we have 4 classes (k=4), dividing the complex plane into 4 <br>sectors of 90° each:<br># Roots of the 4th degree of unity (possible outputs):<br>epsilon_0 = 1 + 0j      # phase 0° (sector 0° - 90°)<br>epsilon_1 = 0 + 1j      # phase 90° (sector 90° - 180°)<br>epsilon_2 = -1 + 0j     # phase 180° (sector 180° - 270°)<br>epsilon_3 = 0 - 1j      # phase 270° (sector 270° - 360°)<br><br># Example 1:<br>z1 = 2 + 2j             # complex number<br>psi1 = atan2(2, 2)      # phase (in radians)<br># The angle is approximately 45°, placing it in the sector 0°-90°<br>output1 = epsilon_0     # corresponding root of unity for this phase<br><br># Example 2:<br>z2 = -1 + 3j            # complex number<br>psi2 = atan2(3, -1)     # phase (in radians)<br># The angle is approximately 108°, placing it in the sector 90°-180°<br>output2 = epsilon_1     # corresponding root of unity for this phase<br><br># 2. Weight adjustment during training:<br># Let us assume:<br>x = 1 + 2j              # input<br>w = 0.5 + 0.5j          # current weight<br>d = 1                   # desired output (epsilon_0, first root of unity)<br>y = 1j                  # current output (epsilon_1, second root of unity)<br>eta = 0.1               # learning rate<br><br># Weight update step:<br># 1. Compute the error, aiming to reduce phase difference<br>e = d - y     # complex error, representing the phase adjustment needed<br>e = (1 + 0j) - (0 + 1j) = 1 - 1j<br><br># 2. Find the conjugate of the input<br>x_conjugate = 1 - 2j    # conjugate of the input<br><br># 3. Update the weight with the error correction<br>Phase (ψ) adjustment affects the weight through the error <br>and conjugate of the input:<br>w_new = w + eta * e * x_conjugate<br># Detailed calculation:<br># Step 1: Multiply error by conjugate input<br>         (1 - 1j) * (1 - 2j) = 1 - 2j - 1j + 2j^2<br># Step 2: Substitute j^2 = -1:<br>         = 1 - 2j - 1j - 2 = -1 - 3j<br># Step 3: Scale by learning rate:<br>         eta * (-1 - 3j) = -0.1 - 0.3j<br># Step 4: Add to the current weight:<br>         w_new = (0.5 + 0.5j) + (-0.1 - 0.3j) = 0.4 + 0.2j<br><br># Result:<br>w_new = 0.4 + 0.2j<br><br># Advantages of this approach with Aizenberg neuron:<br> 1. No need to compute derivatives of the activation function.<br> 2. Weight updates are computed in complex form, accounting <br>for both magnitude and phase.<br> 3. Adjustments align weights to reduce phase error, improving <br>the model&#39;s response.<br><br> In reinforcement learning, this process is repeated for each agent <br>state and action, where:<br> - States and actions are encoded as complex numbers.<br> - The reward influences the desired output.<br> - Phase error guides strategy adjustments, supporting robust <br>and adaptive learning.<br><br><br></pre><p>The ancient magic of the dungeon seemed to weave an invisible web of force lines, where each phantom gem was connected to a real one by the strongest bonds of sorcery. These bonds were fed by the very essence of the mountain rocks, by their eternal striving for order and symmetry, by their ability to give rise to astonishing crystalline lattices in their depths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBHsQ9HYRv0SBXihUPg6Ng.jpeg" /></figure><p>The dwarf understood that he had entered a special place where the laws of the ordinary world intertwined with the laws of the shadow world, where every real emerald had its ghostly counterpart-guide.</p><pre><br># Addition of Complex Numbers<br><br><br>(a + b*i) + (c + d*i) = (a + c) + (b + d)*i<br><br><br># This formula represents the addition of two complex numbers:<br>   - z1 = a + bi<br>   - z2 = c + di<br># The result of adding these two complex numbers is also a complex number.<br><br># Steps for the addition:<br># Step 1: Identify the real parts and imaginary parts of both complex numbers:<br>   - Real part of z1: a<br>   - Imaginary part of z1: b<br>   - Real part of z2: c<br>   - Imaginary part of z2: d<br><br># Step 2: Add the real parts together:<br>   Real part of the result: Re(z) = a + c<br><br># Step 3: Add the imaginary parts together:<br>   Imaginary part of the result: Im(z) = b + d<br><br># Step 4: Combine the results to form the new complex number:<br>   z_result = (a + c) + (b + d)i</pre><pre><br>In the context of the Aizenberg neuron, the formula for addition of <br>complex numbers addition = (a + b*i) + (c + d*i) = (a + c) + (b + d)*i <br>is important for two key operations:<br><br># 1. Calculation of the weighted sum of inputs:<br># Example:<br>input_1 = 1 + 2j         # first input<br>weight_1 = 0.5 + 1j      # first weight<br>product_1 = weight_1 * input_1<br>product_1 = (0.5 + 1j) * (1 + 2j) = 0.5 + 2.5j<br><br>input_2 = 2 + 1j         # second input<br>weight_2 = 1 + 0.5j      # second weight<br>product_2 = weight_2 * input_2<br>product_2 = (1 + 0.5j) * (2 + 1j) = 1.5 + 2.5j<br><br># Weighted sum<br>z = product_1 + product_2<br>z = (0.5 + 2.5j) + (1.5 + 2.5j)<br>  = 2 + 5j  # This sum determines which sector the output will fall into<br><br># 2. Accumulation of error during training:<br># If we have several training examples:<br>error_1 = 0.5 + 1j         # error for the first example<br>error_2 = 1.5 + 0.5j       # error for the second example<br><br>total_error = error_1 + error_2<br>total_error = (0.5 + 1j) + (1.5 + 0.5j)<br>            = 2 + 1.5j     # Weights are adjusted based on this sum<br><br># Thus, correct addition of complex numbers is critical for:<br> - Determining the activation sector of the neuron<br> - Proper weight adjustment during training<br> - Accumulating the overall error across all examples</pre><p>These counterparts were like vague dreams of the stones, their own dreams about themselves, and yet they obeyed the strict rules of underground magic.</p><pre><br># Multiplication of Complex Numbers<br><br><br>(a + b*i) * (c + d*i) = (a*c - b*d) + (a*d + b*c)*i<br><br><br># This formula represents the multiplication of two complex numbers:<br>   - z1 = a + bi<br>   - z2 = c + di<br># The result of multiplying these two complex numbers is also a complex number.<br><br># Steps for the multiplication:<br># Step 1: Apply the distributive property (FOIL method):<br>   z1 * z2 = (a + bi)(c + di)<br>   = a*c + a*di + b*i*c + b*i*di<br><br># Step 2: Simplify the expression:<br>   Remember that i^2 = -1:<br>   = a*c + adi + bci + b*d*(-1)<br>   = (a*c - b*d) + (a*d + b*c)*i<br><br># Step 3: Identify the real part and the imaginary part:<br>   - Real part: Re(z) = a*c - b*d<br>   - Imaginary part: Im(z) = a*d + b*c<br><br># Step 4: Combine the results to form the new complex number:<br>   z_result = (a*c - b*d) + (a*d + b*c)*i</pre><pre><br># 1. Inputs and weights in the Aizenberg model are defined as:<br># Inputs on the unit circle:<br>x_k = exp(I * φ_k)   # |x_k| = 1<br><br># Weights:<br>w_k = |w_k| * exp(I * θ_k)<br><br># 2. Weighted sum according to the model:<br>z = Σ(w_k * x_k) = Σ(|w_k| * exp(I * θ_k) * exp(I * φ_k)) <br>  = Σ(|w_k| * exp(I * (θ_k + φ_k)))<br><br># 3. Weight update rule:<br>w_k_new = w_k_old + η * (d - y) * x_k_conjugate<br><br># In the Aizenberg model, multiplication of complex numbers is used:<br><br># 1. When calculating the weighted sum:<br># For each input k:<br>product_k = w_k * x_k <br>product_k = |w_k| * exp(I * θ_k) * exp(I * φ_k) <br>          = |w_k| * exp(I * (θ_k + φ_k))<br><br># 2. When updating weights:<br># Correction for each weight k:<br>w_k_new = w_k_old + η * (d - y) * x_k_conjugate<br><br># Where:<br> d - target output (one of the k-th roots of unity)<br> y - current output of the neuron (also one of the k-th roots)<br> x_k_conjugate - complex conjugate of the input<br> η - learning rate<br><br>Thus, the multiplication of complex numbers in the Aizenberg model <br>is used strictly for:<br><br>1. Multiplying weights by inputs when calculating the weighted sum<br>2. Computing weight adjustments during training through the <br>product of the error (d - y) and the complex conjugate input</pre><p>Deep inside, Cardano felt that this void was not just an absence of something, but a special state of the mine, when it revealed its deepest secrets. And the longer he stared into this shimmering void, the more he understood: it existed because, without it, it was impossible to find the path to the most mysterious treasures of the underground kingdom.</p><p>“How can this be?” Cardano wondered. “My calculations suggest I need to dig in a non-existent direction, as if in the mirror image of the mine! But I know for sure that the emeralds are here — when I randomly explore the tunnels, I find them: one stone in the first tunnel, four in the next, and five in the last, but marked by the sign of darkness.”</p><pre><br># Magical Crystals Sum Representation<br><br><br>z = 1 + 4 + (-5)*i<br><br><br># This formula represents a complex number in the form:<br>   z = a + bi<br># Where:<br>   - a is the real part of the complex number<br>   - b is the imaginary part of the complex number<br>   - i is the imaginary unit, defined as i^2 = -1<br><br># Steps for evaluating the expression:<br># Step 1: Identify the real part:<br>   - Real part (Re(z)): 1 + 4 = 5<br><br># Step 2: Identify the imaginary part:<br>   - Imaginary part (Im(z)): -5<br><br># Step 3: Combine the parts to express the complex number:<br>   z = 5 - 5i<br><br># The final representation of the complex number is:<br>   z = 5 - 5i</pre><p>In the underground kingdom, the “sign of darkness” was a special magical seal that could transform the normal light of crystals into a mysterious dark glow. When the dwarves placed the sign of darkness on an emerald, its glow didn’t simply fade — it seemed to turn inside out, starting to emit a strange anti-light.</p><pre><br># Multiplication of Negative Numbers<br><br><br>result = (-1) * (-1)<br><br><br># This formula illustrates the multiplication of two negative numbers:<br># When multiplying two negative numbers, the result is positive.<br># Mathematically, this is expressed as:<br>     (-a) * (-b) = ab, where a and b are positive numbers.<br><br># Steps for evaluating the expression:<br># Step 1: Identify the values being multiplied:<br># In this case, a = 1, so we have:<br>     (-1) * (-1)<br><br># Step 2: Apply the multiplication rule for negative numbers:<br># Since both numbers are negative:<br>     (-1) * (-1) = 1<br><br># Therefore, the final result is:<br>   result = 1</pre><p>If a normal emerald illuminated the mine with green light, then an emerald with the sign of darkness created an area of deep, velvety darkness around it, in which, however, a faint flicker could be seen. The remarkable property of the sign of darkness was that two dark emeralds, when brought together, began to shine with regular light!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WT-i_t69CT1NhvAqlAAFQ.jpeg" /></figure><p>It was like two mirrors placed opposite each other, creating an infinite corridor of reflections — only here, darkness multiplied by darkness gave birth to light. Cardano called this the “rule of double negation of darkness.”</p><p>When the dwarf tried to multiply a regular crystal with a dark one, the result was a new dark stone, as if the darkness infected the glowing emerald with its mysterious nature.</p><pre><br># Distributive Property for Negation of Complex Numbers<br><br><br>(-1) * (a + b*i) = -a - b*i<br><br><br># This formula demonstrates the application of the distributive property<br># to negate a complex number. Given a complex number:<br>   z = a + bi, where a is the real part and b is the imaginary part.<br><br># Steps for applying the negation:<br># Step 1: Identify the complex number:<br>   z = a + bi<br><br># Step 2: Multiply the complex number by -1:<br>   (-1) * (a + bi)<br><br># Step 3: Apply the distributive property:<br>   = (-1) * a + (-1) * bi<br><br># Step 4: Simplify the expression:<br>   = -a - bi<br><br># Therefore, the result of negating the complex number is:<br>   z_negated = -a - bi</pre><p>However, if he added a light and dark crystal together, they didn’t cancel each other out but continued to exist side by side, like day and night, without blending yet without conflicting.</p><p>The signs of darkness had a particularly strange effect on the guide-crystals from the mirror dimension. When such a ghostly crystal received the seal of darkness, it began to spin in the opposite direction, pointing to the dark versions of real emeralds.</p><pre><br># Negation of a Complex Number<br><br># Formula<br>(x + y*i) * (-1) = -x - y*i<br><br># Solution Method with Formulas<br># This formula illustrates the negation of a complex number by multiplying<br># it by -1. Given a complex number:<br>   z = x + yi, where x is the real part and y is the imaginary part.<br><br># Steps for negating the complex number:<br># Step 1: Identify the complex number:<br>   z = x + yi<br><br># Step 2: Multiply the complex number by -1:<br>   (-1) * (x + yi)<br><br># Step 3: Apply the distributive property:<br>   = (-1) * x + (-1) * yi<br><br># Step 4: Simplify the expression:<br>   = -x - yi<br><br># Therefore, the result of negating the complex number is:<br>   z_negated = -x - yi</pre><p>Yet the guide-crystals remained just as elusive and transparent, only their shimmer took on a faint violet hue.</p><p>Another dwarf named Bombelli discovered that it was possible to create complex chains of light and dark guides, which, interacting with each other according to special rules, led unerringly to hidden treasures.</p><pre>(x + y*I) * (c + d*I) = (x*c - y*d) + (x*d + y*c)*I</pre><p>These chains resembled an intricate dance of light and darkness, where every movement was precisely calibrated by the ancient magic of the mines.</p><p>The mathematician dwarves created special maps where light and dark guide crystals were marked with different runes, and their interactions were described by special magical formulas.</p><pre><br># Multiplication of Complex Numbers in Polar Form<br><br><br>z1 * z2 = r1 * r2 * [cos(θ1 + θ2) + I*sin(θ1 + θ2)]<br><br><br># This formula represents the multiplication of two complex numbers in their polar form. <br># Given two complex numbers:<br>   - z1 = r1 * (cos(θ1) + I*sin(θ1)) <br>   - z2 = r2 * (cos(θ2) + I*sin(θ2))<br><br># Steps for multiplying two complex numbers in polar form:<br># Step 1: Identify the magnitudes and angles of the complex numbers:<br>   - r1 = magnitude of z1<br>   - θ1 = argument (angle) of z1<br>   - r2 = magnitude of z2<br>   - θ2 = argument (angle) of z2<br><br># Step 2: Use the multiplication formula:<br>   - When multiplying z1 and z2, the magnitudes multiply, and the angles add:<br>   - Magnitude: r1 * r2<br>   - Angle: θ1 + θ2<br><br># Step 3: Write the result in polar form:<br>   Result: z = r1 * r2 * (cos(θ1 + θ2) + I*sin(θ1 + θ2))<br><br># Step 4: To convert the result back to rectangular form:<br>   z = r1 * r2 * cos(θ1 + θ2) + I * (r1 * r2 * sin(θ1 + θ2))<br><br># This multiplication method simplifies calculations involving complex numbers, particularly in <br># fields such as electrical engineering and physics, where complex numbers often represent <br># quantities like impedance and wave functions.</pre><p>These maps allowed them to predict where real emeralds would appear if the chains of light and dark guides were connected correctly.</p><p>Gradually, the signs of darkness transformed from simple magical seals into a powerful treasure-hunting tool, enabling the dwarves to explore the most mysterious corners of their underground kingdom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dV0G1NoPs9TcuTgfvhNQg.jpeg" /></figure><p>Fortunately, at the moment when Cardano was struggling to understand the meaning of the seal of darkness, his friend, the wizard dwarf Bombelli, came to visit. He studied the strange indications of the formula for a long time and suddenly exclaimed:</p><p>“What if these indications are not nonsense? What if there is a mirror dimension of the mine where we can find intermediate crystals? They won’t be quite real — let’s say, imaginary — but if we work with them correctly, they will lead us to the real emeralds!”</p><pre><br># Definition of the Imaginary Unit<br><br><br>i**2 = -1<br><br><br># This formula defines the imaginary unit &#39;i&#39;, which is fundamental in complex number theory. <br># The imaginary unit is used to extend the real number system to include solutions <br># to equations that do not have real solutions, such as x^2 + 1 = 0.<br><br># Steps for understanding the concept:<br># Step 1: Recognize that in the real number system, there is no real number whose square <br># is negative. Therefore, to solve equations like x^2 + 1 = 0, we introduce the concept of &#39;i&#39;.<br><br># Step 2: By defining i such that:<br>   i = √(-1), we can express the square of i as:<br>   i**2 = -1<br><br># Step 3: This definition allows us to represent any complex number in the form:<br>   z = a + bi<br># where &#39;a&#39; is the real part, and &#39;b&#39; is the imaginary part.<br><br># Step 4: Understanding this fundamental concept enables the manipulation of complex numbers <br># and helps in solving a wide range of mathematical problems, particularly in engineering, <br># physics, and applied mathematics.<br><br># Example: <br> - The equation x^2 + 1 = 0 can be solved as:<br>   - x^2 = -1<br>   - x = ±i</pre><p>“But how do we work with imaginary crystals?” Cardano doubted. “They don’t exist in our world!”</p><p>“Let’s give it a try!” Bombelli suggested. “We will treat them just like regular stones — add, multiply, extract roots. Just remember that they are from a mirror world where everything is reversed.”</p><pre><br># Square of a Complex Number<br><br><br>(a + b*I)**2 = a**2 + 2*a*b*I - b**2<br><br><br># This formula represents the square of a complex number expressed in rectangular form, <br># where &#39;a&#39; is the real part and &#39;b&#39; is the imaginary part.<br><br># Steps for squaring a complex number:<br># Step 1: Start with the complex number in the form:<br>   z = a + b*I<br><br># Step 2: Apply the square operation:<br>   z^2 = (a + b*I)^2<br><br># Step 3: Expand the expression using the distributive property (FOIL method):<br>   z^2 = (a + b*I) * (a + b*I)<br>   z^2 = a*a + a*(b*I) + (b*I)*a + (b*I)*(b*I)<br><br># Step 4: Simplify each term:<br>   = a^2 + ab*I + ab*I + b^2*I^2<br>   = a^2 + 2ab*I + b^2*(-1)  (since I^2 = -1)<br><br># Step 5: Combine the terms:<br>   z^2 = a^2 - b^2 + 2ab*I<br><br># Final Expression:<br># Thus, the square of the complex number can be expressed as:<br>   (a + b*I)^2 = (a^2 - b^2) + (2*a*b)*I<br><br># Understanding this formula is crucial for performing operations on complex numbers,<br># particularly in fields like electrical engineering and signal processing, where<br># complex numbers are used to represent waveforms and phasors.</pre><p>Thus, Cardano and Bombelli began their amazing experiments with imaginary crystals. At first, the other dwarves twisted their fingers at their temples — how could one seriously work with non-existent stones? But gradually it became clear that these strange calculations consistently led to real emeralds!</p><p>Years passed. A new sage came to the underground kingdom — the gnome Vessel. He studied the writings of Cardano and Bombelli for a long time and one day made an astonishing discovery:</p><p>“My friends!” he declared at the gnomes’ council. “Imaginary crystals exist! We were just looking for them in the wrong place. They are not in the mirror world, but in a special dimension of our mine — not just forward and backward along the tunnel, but also up and down! If we start marking the mine with not one ruler, but two — a regular one and a magical one, perpendicular to it — we can find any crystal, even an imaginary one!”</p><pre><br># Polar Form of a Complex Number<br><br><br>z = r * (cos(theta) + I*sin(theta))<br><br><br># This formula represents a complex number in its polar form, where:<br>   - z is the complex number,<br>   - r is the magnitude (modulus) of the complex number,<br>   - theta (θ) is the argument (angle) of the complex number in radians.<br><br># Steps for converting a complex number to polar form:<br># Step 1: Identify the complex number in rectangular form:<br>   z = a + bi, where a is the real part and b is the imaginary part.<br><br># Step 2: Calculate the magnitude (r):<br>   r = √(a^2 + b^2)<br><br># Step 3: Calculate the argument (θ):<br>   θ = atan2(b, a)<br>   This function takes into account the signs of a and b to determine the correct quadrant for θ.<br><br># Step 4: Substitute r and θ into the polar form formula:<br>   z = r * (cos(theta) + I*sin(theta))<br><br># Step 5: To convert back to rectangular form, use:<br>   a = r * cos(theta)<br>   b = r * sin(theta)<br><br># This polar representation is useful for multiplication and division of complex numbers, <br># as well as for finding powers and roots of complex numbers using De Moivre&#39;s Theorem.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GH_HOCmaNgoxqO9dubFUXQ.jpeg" /></figure><p>This discovery revolutionized gnome mathematics. Now every crystal could be described by two numbers — how far it is along the regular ruler and how far it is along the magical one.</p><p>All the strange rules for working with imaginary crystals suddenly gained a simple geometric meaning!</p><p>Since then, the gnomes were no longer afraid of imaginary numbers. They learned to use them for creating magical maps of the dungeon, calculating the strength of bridges and tunnels, and even predicting the behavior of underground waters.</p><p>And all of this happened because one day the brave gnome Cardano dared to trust the strange formula that pointed the way to nowhere:</p><pre><br># Cubic Equation<br><br><br>x**3 - 21*x + 20 = 0<br><br><br># This formula represents a cubic equation in the standard form:<br>   ax^3 + bx^2 + cx + d = 0<br># Where:<br>   - a = 1 (coefficient of x^3)<br>   - b = 0 (coefficient of x^2, which is absent)<br>   - c = -21 (coefficient of x)<br>   - d = 20 (constant term)<br><br># Steps for solving the cubic equation:<br># Step 1: Identify the coefficients:<br>   a = 1, b = 0, c = -21, d = 20<br><br># Step 2: Use the Rational Root Theorem to find possible rational roots:<br>   Possible rational roots can be factors of the constant term (±1, ±2, ±4, ±5, ±10, ±20)<br><br># Step 3: Test the possible roots to find at least one root:<br># Substitute each possible rational root into the equation to find a valid root (e.g., testing x = 1):<br>     1^3 - 21*1 + 20 = 1 - 21 + 20 = 0 (x = 1 is a root)<br><br># Step 4: Perform synthetic division or polynomial long division using the found root to factor the cubic equation:<br>   (x - 1)(x^2 + x - 20) = 0<br><br># Step 5: Solve the resulting quadratic equation:<br>   - x^2 + x - 20 = 0<br>   - Use the quadratic formula: x = (-b ± √(b^2 - 4ac)) / (2a)<br>   - In this case, a = 1, b = 1, c = -20<br><br># Step 6: Calculate the roots:<br>   x = (-1 ± √(1^2 - 4*1*(-20))) / (2*1)<br>   x = (-1 ± √(1 + 80)) / 2<br>   x = (-1 ± √81) / 2<br>   x = (-1 ± 9) / 2<br><br># The final solutions will include:<br>   x = 1 (from the rational root found)<br>   x = 4 (from (-1 + 9)/2)<br>   x = -5 (from (-1 - 9)/2)</pre><p>And it is said that somewhere in the deepest mines, the very first formula, with which everything began, is still kept, along with three magical emeralds: one, four, and minus five…</p><pre>x1 = 1<br>x2 = 4<br>x3 = -5</pre><p>After the metaphorical introduction, let’s move on directly to testing your knowledge in the field of Derivative-Free Complex Valued Reinforcement Learning. You will encounter 13 magical stories-riddles.</p><p>Read each story carefully. Try to guess which aspect of complex number theory is being discussed. Use the hints provided. At the end of this article, you’ll find the full answers to each story-puzzle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Nv8fdnqm5Lh6xGQMkFocw.jpeg" /></figure><h3>1.The Unified Light of Two Gemstones</h3><p>Once upon a time, there lived a wise dwarf named Cardano, renowned for his knowledge in the magic of numbers and symmetries. One day, while exploring ancient mines, he stumbled upon two remarkable stones. One glowed with a bright, steady green light, clearly pinpointing its location in the world, like a pure number on a line. The other stone emitted a cold and profound light, full of mystery, yet its glow was just as clear as the first, though its nature remained enigmatic.</p><p>Cardano soon realized that these stones were not mere ornaments. Their light was deeply connected, even though the stones existed in different realms. When he placed them side by side, they didn’t rotate, change shape, or depend on angles. Instead, their light merged in one direction, like a line that starts on Earth and extends into another, unseen world.</p><blockquote>The dwarf pondered: why did these stones differ so much from other magical artifacts he had seen before? Typically, magic required angles, rotations, and arcs — like the movements of stars, planets, and circular orbits. But here, everything was different. No rotations, no angles. The stones seemed to exist in a flat, linear world where arcs and circles had no part. Their power lay in simple addition: one stone added its light, and the other its mysterious depth, together creating a new, unfamiliar light, more powerful than either alone.</blockquote><p>Cardano understood: these were no ordinary magical stones. They embodied a more fundamental principle — linearity. These stones didn’t rely on angles or radii, as many other magical objects did; instead, they adhered to the laws of straight lines and simple addition.</p><p>And so, having grasped all this, the dwarf Cardano posed a riddle to his students:<br>“Before you are two stones. They do not rotate or follow angles, as stars and planets do. Each of them exists along its own line, and their light never touches circles. Instead, their power lies in simple addition, without angles or phases. What are they? What unites them?”</p><h3>Hints</h3><p><strong>1.Algebraic Notes</strong></p><p>“It seems these two stones follow a strange law. When one of them lies on the axis, the light of the other adds its depth to it, and they merge into one line. Something like this:”</p><pre>def merge_light(a, b):<br>    result = a + b<br>    return result</pre><p><em>Think about it: there are no angles or rotations here, just addition. One line and simple summation.</em></p><p><strong>2.Symbols of the Stones</strong></p><p>“One of these stones, the green one, resembles a number, but the other… its light is so strange. I will denote them as:”</p><pre>Emerald: R<br>Purple: iB</pre><p><em>It’s interesting how combining their light results in something new, where one symbol adds simplicity, and the other — depth.</em></p><p><strong>3.Experiment with the Stones</strong></p><p>“I tried to sum their light, and discovered something strange. Instead of the light of angles I expected, they created a single ray, but only in one direction:”</p><pre>emerald_stone = 3   # can be represented as the number R<br>purple_stone = 4j   # the mysterious light of the second stone, B<br>unified_light = emerald_stone + purple_stone<br>print(unified_light)</pre><p><em>Remember, my students, there are no rotations here. We are simply connecting the light of one world with another, creating something new that exists on a single line.</em></p><p><strong>4.A Simple Line, Not a Circle</strong></p><p>“The power of these stones lies in their linearity. No angles are needed for their connection, and their light moves forward without deviation. Perhaps this is the key?”</p><pre>Let X = a + b, <br>where a is the direct light of the first stone, <br>and b is its mysterious companion that sees no angles.</pre><p><em>Only simple addition! Who can name this light that lives on the edge of two worlds?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zm0c0sqbbvfRqEz08GEXVg.jpeg" /></figure><h3>2.The Compass of Eternal Rotation</h3><p>Once, the dwarf Cardano found a mysterious moonlit compass that seemed to know the answers to all questions. This compass didn’t just show the way; it was infused with a mystical power of rotation, guiding one’s steps toward the goal without the need to draw lines or circles. The compass needle didn’t remain still; its glow constantly shifted, depending on the direction, as if someone had predetermined its angle.</p><blockquote>Every movement of the compass held a rhythm, as if it rotated around an invisible center, indicating not only the path but also the strength with which one should proceed. Cardano noticed that the flickering light of the needle grew brighter and more powerful when he followed its guidance, as if it held the harmony of ancient numbers like e, i, and π, linking the past and the future in a single simple equation. When he fully trusted the compass, following not only the direction but also the strength it prescribed, the path to the treasure revealed itself. What mystery was hidden in this flickering, guiding light that combined rotation and harmony?</blockquote><h3>Hints</h3><p><strong>1.Exploring the Compass</strong></p><p>“When I first held the moon compass, its light was strangely captivating. The compass didn’t point north but always rotated with a constant force. I thought: what if its secret lies in a circle, but not an ordinary one? In every direction, it displays one of two powers, real and imaginary, but merges them into one whole:”</p><pre>import cmath<br>compass_rotation = cmath.exp(1j * cmath.pi)  # a mysterious mechanism based on circular motion<br>print(compass_rotation)</pre><p><em>It seems that the movement of the compass defies conventional linear explanations. At its core is something fundamentally cyclical, eternal…</em></p><p><strong>2.Angular Harmony</strong></p><p>“I noticed the compass repeats itself with every full rotation. Its light grows stronger when I trust it, but the angle at which it shines is always predetermined. Perhaps this is related to those numbers known only to sages: e, π, and the mysterious power I’ll call ‘imagination:’”</p><pre>emerald_power = cmath.exp(1j * cmath.pi) + 1  # a hint at the deep connection between numbers<br>print(emerald_power)</pre><p><em>It seems the compass directs me to the idea that the harmony of numbers is tied to an infinite circle.</em></p><p><strong>3.Following the Rhythm</strong></p><p>“The rotation of the compass draws me to follow it; even as its needle changes directions, I remain on a path that feels unchanging. As if each angle at which it shines is just a new turn that brings me back to the start, but on a new level.”</p><pre>def follow_compass(angle):<br>    step = cmath.exp(1j * angle)  # moving along the circle<br>    return step</pre><p><em>Each new movement guides me forward again, as if rotation and power are tied by a secret equation.</em></p><p><strong>4.A Closed Circle</strong></p><p>“The invisible circle of the compass isn’t just motion, but a complete return to the beginning with every full turn. Perhaps this gives it that mysterious power, for by combining the real and the imaginary, the compass seems to encapsulate the harmony of the world.”</p><pre>The Compass’s Guiding Force:<br>W = e^{i \cdot \pi} + 1 = 0</pre><p><em>Here, the compass’s power becomes a single whole, where two beginnings close in one step, on the edge of the real and the imaginary.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MASjvT8_Lbq4qz5T1Lgldw.jpeg" /></figure><h3>3.The Dance of Light and Shadow in the Dungeon</h3><p>Cardano was walking through an ancient tunnel when he saw light and shadow begin to dance before him in a strange rhythm. Light pierced through a tiny crack in the wall and moved in a circle, creating a magical figure, as if someone were drawing invisible lines in the air. The shadow followed the light but always lagged slightly behind, mimicking its every move. The dwarf noticed that the dance of light was precise, while the shadow smoothly followed every curve, as if it knew where the light would move in advance. Cardano’s path twisted left and right, yet the circular movement of the light remained constant, as if defying the laws of time.</p><p>Then Cardano began to understand: the dance of light and shadow was no coincidence but a clue. Emeralds occasionally flickered in the depths of the dungeon, and he noticed they always lay along the path of the light. But what was astonishing was that nearby, crystals of remarkable hues — blue and violet with a faint glow — sparkled. These crystals appeared precisely where light and shadow moved together, merging into a single flow, as one. At times, light and shadow would unite, and Cardano felt a special secret hidden in that moment.</p><p>“Well,” he thought, “if I can figure out how they move, I might find the path to the treasure.” He paused for a moment, listening to the rhythm: the light made one full circle, then moved away, with the shadow following, a step behind. This endless repetition held a pattern, as though the dungeon itself wanted to reveal its secret. With each step, the dance of light unveiled more: crystals and emeralds sparkled in rhythm, enchanting the dwarf.</p><p>Another step, and Cardano approached a place where light and shadow met for a moment, creating a flash, like a ripple of light in a pond. Before him lay a crystal, shimmering like an evening sky. Cardano realized that here, light and shadow had reached their full harmony, and the crystal was a reward for this magical balance. The further he went, the more he saw these magical unions guiding him along hidden paths of the dungeon.</p><blockquote>Every crystal that sparkled in the light’s flow was like a sign — follow the dance, and the path to the emeralds and blue and violet stones would open. Watching the intricate dance, Cardano understood: the circular spiral of light, sometimes merging with the shadow, was his guiding star. He went deeper, and the dance grew faster, as if inviting him to go all the way to the end. There was only one thing left to do: trust this magical movement and listen to the music of light and shadow, which led him to the heart of the dungeon, where countless emeralds and crystals of every hue lay.</blockquote><h3>Hints</h3><p><strong>1.The Magic of Circular Motion</strong></p><p>“The dance of light traces a circle, but the shadow lags for a moment, as if nature itself dictated its rhythm. Light and shadow seem to follow the same trajectory, yet always with a slight delay. The path of light describes a figure, as if ancient laws known only to those who understand the harmony of numbers and angles are embedded in its movements:”</p><pre>import math<br>angle = 0<br>light = math.cos(angle)<br>shadow = math.sin(angle)<br>print(f&quot;Light: {light}, Shadow: {shadow}&quot;)</pre><p><em>It seems as if the dance describes a closed circle, where light and shadow echo each other in eternal motion.</em></p><p><strong>2.The Path of Light and Shadow</strong></p><p>“I noticed that light was always slightly ahead, and shadow followed closely behind. In this movement was an astonishing coordination, as if their rhythm was preordained by a number that obeys the law of circles. Perhaps behind every curve of light lie hidden angles that dictate the movement. Every position of light is reflected on the crystals, while the shadow seems to send it a signal, as if their movements are something greater than mere play:”</p><pre>def trajectory_of_movement(angle):<br>    light = math.cos(angle)  # movement of light in a circle<br>    shadow = math.sin(angle + math.pi / 2)  # shadow lagging a quarter circle<br>    return light, shadow</pre><p><em>Light is always ahead, as if it knows the way, while the shadow follows like a faithful companion.</em></p><p><strong>3.The Rhythm of Light and Shadow</strong></p><p>“One of the crystals shimmered strangely, repeating the cycle of light and shadow. It seemed that the crystal, light, and shadow were connected by the same frequency. When the light completed a full rotation, the shadow lagged, but their paths crossed at certain points, and then a flash occurred — a momentary merging, as if something within them closed this cycle:”</p><pre>from math import pi, cos, sin<br>full_rotation = 2 * pi<br><br>for angle in [0, pi/2, pi, 3*pi/2, full_rotation]:<br>    light = cos(angle)<br>    shadow = sin(angle)<br>    if light == shadow:<br>        print(f&quot;Merging of light and shadow at angle {angle}&quot;)</pre><p><em>Their intersections are rare, but within them lies the harmony of eternal circular motion.</em></p><p><strong>4.Harmony and the Hidden Key</strong></p><p>“It seems that light and shadow create a pattern, as if with each new point it becomes deeper. I begin to see a regularity in their encounters — they seem to be part of a larger picture, where one movement accounts for light and the other for its reflection. It’s like an incantation, where two movements converge in one harmony, like a unified whole despite their differences:”</p><pre>Light: cos(θ)<br>Shadow: sin(θ + π/2)</pre><p><em>This dance of light and shadow is a mystery that repeats in the harmony of an infinite circle, like the equation of motion.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUWJrt_0rYdXw_B4aUi5iw.jpeg" /></figure><h3>4.The Star of Two Forces</h3><p>In the emerald dungeons beneath the mountain, where every stone held an ancient secret, the dwarf Cardano once noticed something extraordinary: a bright star had appeared on the ceiling of the tunnel, pulsating with a mysterious light. It shifted its colors, alternating green and purple flashes, as if conveying a silent message through its radiant display. Bombelli, Cardano’s old friend, quietly approached and, smiling thoughtfully, whispered, “This is Euler’s Star. They say it unites two forces of light into a single stream, merging opposites into one.”</p><blockquote>Cardano gazed at the star, which seemed to move in a circle, leaving behind glowing trails as if to remind them that every circle holds its own path, where two forces move together. These forces were like day and night, closely linked yet distinct. Watching carefully, Cardano realized that the star’s green light reflected off all the emerald crystals around him as if they were a part of it. Meanwhile, the purple light playfully danced through blue and violet stones, making them flicker in response.</blockquote><p>Bombelli sighed and said, “One of these forces makes the crystals move like the flow of a river, while the other circles around the star, following an unseen law. Together, they create a rhythm that drives everything around.” Cardano waved his hand in the air near the star and noticed its light grew brighter with his slightest movement. “This star senses us — it’s almost alive with us,” he whispered, awestruck by its unusual shimmering.</p><p>“It’s the heart of the dungeon, its breath,” Bombelli mused. “And what is it telling us?” Cardano asked softly. “Perhaps it’s hinting that these two forces are always near, and one cannot exist without the other?” Bombelli pondered aloud. “The green light is ever-present, like a foundation. But what if the purple light is its shadow, its reverse? Could it be that they transform into each other?”</p><p>Cardano closed his eyes, feeling the star’s light as though it enveloped him. He suddenly understood that its pulsing followed an invisible rhythm, like a magical spell controlling both movement and stillness in the earth’s depths. “There’s something eternal within it, yet ever-changing,” he murmured. “It cannot be just light; there’s a hidden mystery, an unseen part that spans the entire underworld like a web.”</p><p>“Perhaps its light is just the tip, and its roots go deep underground?” Cardano speculated. “If we could see it entirely, we might understand how all forces connect, how the world moves, how day turns to night.” The dwarves stood there for a long time under the mysterious star, trying to grasp its magical rhythm, feeling that somewhere within that rhythm lay the law that governed their world.</p><p>They sensed that this star connected everything they knew and had seen, merging it all into a single whole. Light and darkness, stillness and motion — all intertwined in its dance. The star, like an endless circle, reflected them in its every movement.</p><h3>Hints</h3><p><strong>1.Eternal Circular Path of the Star</strong></p><p>“The star seems to trace a circle, blending green and violet colors, as if it orbits around an invisible center. This circle reminds me of an ancient formula, where circular movement occurs in perfect rhythm, like a dance of two forces:”</p><pre>import math<br>angle = 0<br>euler_star = complex(math.cos(angle), math.sin(angle))  # complex representation of the star<br>print(f&quot;Star: {euler_star}&quot;)</pre><p><em>Two forces, like day and night, green and violet light, intertwine to form a perfect circular pattern.</em></p><p><strong>2.Unity of Two Opposites</strong></p><p>“When the green light was replaced by violet, I felt they were inseparably connected. As if someone had embedded a formula into their movements, where e^iθ=cos⁡(θ)+isin⁡(θ), creating a single, unified essence. They move but are never separated:”</p><pre>def star_movement(angle):<br>    star = complex(math.cos(angle), math.sin(angle))  # e^(i*angle)<br>    return star</pre><p><em>The star’s movement reflects continuity, like the harmony of two opposites that cannot exist apart.</em></p><p><strong>3.Rhythm Embedded in Nature</strong></p><p>“When the star reached certain angles, the green and violet lights merged, creating flashes. These points are like the roots of deep symmetry, where light and shadow connect at the crossing of the circle:”</p><pre>from cmath import exp, pi<br><br>for angle in [0, pi/2, pi, 3*pi/2, 2*pi]:<br>    star = exp(1j * angle)  # e^(i*angle)<br>    print(f&quot;Star at angle {angle}: {star.real} + {star.imag}j&quot;)</pre><p><em>These moments of union between the two colors symbolize how complete unity can be found even in separation.</em></p><p><strong>4.Eternal Mystery Hidden in the Glow</strong></p><p>“As the star circles around, I begin to understand: its light is not only brightness but a hidden mystery that unites the visible and invisible, material and spiritual, as if they are two sides of the same number:”</p><pre>Star: e^(iθ) = cos(θ) + i*sin(θ)</pre><p><em>Each flash of the star hints at the eternal movement, where opposing forces merge within the circle.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWymbGkHNjWPaqMQH0ZOzA.jpeg" /></figure><h3>5.Mirror Stars — Guardians of Balance</h3><p>In an emerald dungeon, Cardano saw an enchanted circle at the center of which spun blue stars, like tiny mirrors reflecting one another. They glowed with a mystical light that felt as ancient as the earth itself. As Cardano stepped closer, the stars began moving faster, mirroring his every step, yet their light remained constant, as if each star followed an ancient rhythm from which it could not stray.</p><blockquote>“Look at how these lights spin,” said Bombelli, his wise companion. “Their glow remains steady no matter how fast they move. They seem to dance in a circle, always returning to the same point as calmly as day follows night.” Cardano noticed that the stars seemed to travel along invisible paths bound by a special harmony, as though an unseen composer orchestrated their eternal rhythm.</blockquote><p>The lights grew brighter or dimmer depending on the angle from which they were viewed, only to return to their original glow, leaving an impression of unseen equilibrium. Cardano realized that each star, having completed its circle, reappeared in the same place, shining with the same intensity. “These stars obey an eternal law that binds their light and path,” said Bombelli. “They seem to follow the earth’s breath, repeating each turn, never deviating from their course.”</p><p>And Cardano, holding his breath, understood that these stars moved not only in circles but wove together, expressing a music of equality and balance that no earthly being could disturb.</p><h3>Hints</h3><p><strong>1.Magic of Mirror Reflection</strong></p><p>“Stars, like living beings, reflect light, and something greater hides within this reflection. Every turn of their movement creates waves that return to the beginning, as if nature itself grants them this rhythm. Their light is not just a glow; it’s an expression of the laws governed by cycles. In each moment that a star traces its path, a mystery is contained within its light:”</p><pre>def mirror(angle):<br>    light = math.cos(angle)  # star&#39;s light<br>    reflection = light       # reflection equal to the light<br>    return light, reflection</pre><p><em>Each star preserves equilibrium, reflecting itself, as if wisdom of eternity is hidden in this reflection.</em></p><p><strong>2.Invisible Paths</strong></p><p>“I noticed that stars not only rotate but create patterns that reach beyond the circle. Every turn leads to a new pattern that repeats, always with slight variations, as if these changes create harmony. They reflect each other, and I see how their movements are connected to what surrounds them. Their light is music, and their movements are notes that compose the melody of infinity:”</p><pre>for angle in range(0, 360, 30):  # movement of stars in a circle<br>    light, reflection = mirror(math.radians(angle))<br>    print(f&quot;Angle: {angle}°, Light: {light}, Reflection: {reflection}&quot;)</pre><p><em>Each angle becomes a new possibility, and each reflection — a new sound in the symphony of light.</em></p><p><strong>3.Eternal Rhythm</strong></p><p>“These stars seem connected to an invisible source that sets their rhythm. They spin with such speed that it seems time and space lose their boundaries. I felt their movement tie me to this circle, and within this circle, I found my own rhythm. Each crossing of their paths creates a flash of light, as if they strive to show that their movements are not random but governed by an ancient harmony:”</p><pre>import matplotlib.pyplot as plt<br><br>angles = range(0, 360, 10)<br>light = [math.cos(math.radians(angle)) for angle in angles]<br>reflection = [math.cos(math.radians(angle)) for angle in angles]<br><br>plt.plot(angles, light, label=&#39;Light&#39;)<br>plt.plot(angles, reflection, label=&#39;Reflection&#39;)<br>plt.xlabel(&#39;Angle (degrees)&#39;)<br>plt.ylabel(&#39;Light Intensity&#39;)<br>plt.title(&#39;Light and Its Reflection&#39;)<br>plt.legend()<br>plt.grid()<br>plt.show()</pre><p><em>Each flash is a moment when stars come together to create a unified whole, where every movement forms a new reality.</em></p><p><strong>4.Mystery of Balance</strong></p><p>“Each star, like a guardian, carefully preserves its light, and I see how they work together, creating a unique balance. Their movements are an endless dance where light and shadow, day and night, merge into one. I begin to understand that true power lies hidden in this balance. It’s as if they hint that to maintain harmony, respect for both sides is necessary, in life and in science:”</p><pre>Light: cos(θ)<br>Reflection: cos(θ)<br>Balance: {Light + Reflection = Constant Force}</pre><p><em>This harmony is an invisible thread connecting each movement in the dance of eternal balance, reflecting philosophy and mathematics as one.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7klwYmnHfVsrzGHgtbd3g.jpeg" /></figure><h3>6.The Mystery of the Complete Circle</h3><p>In the emerald cavern where bright blue and purple crystals lay hidden, the dwarf Cardano discovered a secret angle that led toward the light. One day, he noticed an unusual pattern: a crystal would shine just as it had at the start when he circled back exactly to where he began. “Curious,” thought Cardano, “could light return to where it started, simply by following its path and returning to the same angle?” That night, he began his secret experiment, navigating every corner of the cave and eventually coming back to where the first crystal stood.</p><p>With each step, Cardano touched a new crystal, shifting its light in various directions, yet when he completed the full circle, the light returned to its starting point. Cardano was astonished; it wasn’t just a circle — it was a return to the very beginning, to the original state. It was as though none of the crystals had moved, even as each turned and cast its light in an ever-expanding perspective.</p><blockquote>“To return to the start is to preserve all strength and find oneself,” he mused, gazing at the radiant circle. But what amazed him even more was that no matter how many circles he made, the first light remained unchanged. Every complete turn brought Cardano back to where he began, showing that a full circle held the power of return, closing upon itself, preserving strength, path, and light.</blockquote><p>Now, Cardano pondered how the power of light and movement could lead to such a magical return. He imagined each light coming back to a unified glow, if only it completed the full circle. In the depths of the dungeon, he decided that each crystal remembered the entire path, and every full circle returned them to the beginning. Leaving his thoughts behind, he posed a riddle for future generations: “How does light return to its starting point after the great circle? In that lies both the power and the completion.”</p><h3>Hints</h3><p><strong>1.The Path to Light and Its Return</strong></p><p>“Each step I took felt like part of a grand plan. I began my journey at the first crystal, and after traversing the entire space, I returned to it. This reminded me of how a complex number describing a circle can return to its starting point after a full rotation, where everything begins anew:”</p><pre>import math<br><br>angle = 2 * math.pi  # full circle<br>crystal = complex(math.cos(angle), math.sin(angle))  # return to the start<br>print(f&quot;Crystal: {crystal}&quot;)</pre><p><em>A full circle is not just movement but a return to the beginning, where everything remains the same.</em></p><p><strong>2.The Power of Return</strong></p><p>“Each time I touched the crystal, it glowed anew, but returning to the starting point after a full circle always yielded the same light. This reminded me of how e^i⋅2π=1, when a complex number returns to its beginning, retaining its inner power:”</p><pre>def crystal_return(angle):<br>    return complex(math.cos(angle), math.sin(angle))  # return to unity<br><br>crystal = crystal_return(2 * math.pi)</pre><p><em>Each return is a reminder that the power of light remains, despite the angle’s change.</em></p><p><strong>3.Memory of Crystals</strong></p><p>“Each crystal, though its light changed, remembered its path. It was as if each circle left an imprint on its heart, creating a rhythm that always led back. As if in each angle lay its history, like the argument of a complex number guiding it back to its original state:”</p><pre>from cmath import exp<br><br>for n in range(5):<br>    crystal = exp(1j * n * 2 * math.pi)  # each full rotation<br>    print(f&quot;Crystal at angle {n * 2 * math.pi}: {crystal}&quot;)</pre><p><em>Each full rotation, like each flash, is part of the shared path back to the beginning.</em></p><p><strong>4.Completion as a New Beginning</strong></p><p>“Finally, I realized that each full circle not only brought me back to the beginning but also created a new understanding of the light. This light, which I saw over and over, remained unchanged, as if all changes were merely an illusion of motion, hiding the eternal truth of the argument that always returns to the same value:”</p><pre>Return: e^(i * θ) = cos(θ) + i*sin(θ) at θ = 2π</pre><p><em>Each return to the starting point is an opportunity to see the light differently, leaving traces in the memory of all crystals.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FU28y0qhgM29DQrSLtd0IA.jpeg" /></figure><h3>7.The Riddle of Reflected Twins</h3><p>Far in the realm of Emerald and Violet Crystals, there was a mirror that didn’t reflect colors or shapes, but instead transformed the very space it looked into. Legends claimed that this artifact could reveal to each dweller their true twin — a mirror image equal in size but facing an opposite direction.</p><blockquote>The emerald crystals gazed into the mirror, but it remained still. “We don’t know what you are,” said one old emerald, “but it seems you’re meant for someone else, not us.” Then came the Violet and Blue Crystals — strange beings who couldn’t fully be seen, as they always seemed to be part of something greater.</blockquote><p>When a single Violet Crystal looked into the mirror, it filled with light. “Now you have a twin,” the mirror murmured, “one just as large, yet moving in another direction.” And the more violet crystals approached, the more twins appeared, each one holding true to its reflection despite the strange reversal in direction.</p><p>The Violet and Blue Crystals pondered the mystery: “Why can’t we draw closer, yet remain connected? Why does none of us change in size, even though the mirror shows us the other side?”</p><p>Then the mirror replied, “Each of you is a strange twin, and I am merely the reflection of your opposite. Together, you create something new, something real, leaving behind both light and shadow.”</p><h3>Hints</h3><p><strong>1.Mirror of the Inner World</strong></p><p>“When I look into the mirror, I see not just my reflection but my opposite. This strange artifact, like a complex number, shows that the real and imaginary parts are in eternal harmony. I feel my double becoming a part of me, as though we are connected by an invisible thread:”</p><pre>def conjugate(crystal):<br>    # Complex conjugation<br>    return complex(crystal.real, -crystal.imag)<br><br>violet_crystal = complex(2, 3)  # Example complex number<br>reflection = conjugate(violet_crystal)<br>print(f&quot;Reflection of the violet crystal: {reflection}&quot;)</pre><p><em>The mirror unveils a secret where doubles are joined but move in opposite directions, like conjugate complex numbers.</em></p><p><strong>2.Duality and Unity</strong></p><p>“I noticed how the violet crystals, when facing the mirror, created strange figures. Their true doubles were not just reflections but part of a unified whole. It’s wonderful that two numbers — one real, the other imaginary — can create something new and amazing, just like us looking in the mirror:”</p><pre>violet_crystals = [complex(1, 1), complex(2, 2), complex(3, 3)]<br>for crystal in violet_crystals:<br>    reflection = conjugate(crystal)<br>    print(f&quot;Crystal: {crystal}, Double: {reflection}&quot;)</pre><p><em>In every reflection lies duality, and within it, the depth and meaning of existence.</em></p><p><strong>3.Entry Three: Merging and Division</strong></p><p>“When we look into the mirror, we realize that even though our reflection changes direction, we don’t lose our essence. We are like complex numbers, where the real part remains constant, and the imaginary part is like a shadow, capable of changing shape but not substance:”</p><pre>def show_doubles(crystals):<br>    doubles = [conjugate(crystal) for crystal in crystals]<br>    return doubles<br><br>doubles = show_doubles(violet_crystals)<br>print(f&quot;Doubles: {doubles}&quot;)</pre><p><em>The mirror points to the connection that exists between each pair, reminding us that each shadow has its essence.</em></p><p><strong>4.Entry Four: The Eternal Dance of Light and Shadow</strong></p><p>“When the light of the violet crystals meets the shadow of their doubles, a magical moment of unity arises. I see how everything returns to the beginning, as if each number is manifesting its essence over and over. This movement creates an endless cycle, where no part is lost:”</p><pre>Mirror: z and its double z* = conjugate(z)<br>Essence: Each complex number has its reflection, but in the mirror, we see only part of a broader picture.</pre><p><em>And in this eternal dance, light and shadow come together in a unified surge, creating harmony that always brings us back to ourselves.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rj_2HDjPoXZAUn6EriAcww.jpeg" /></figure><h3>8.The Golden Scroll of Truth</h3><p>One day, the dwarf Cardano, exploring ancient mines, stumbled upon a scroll illuminated by a strange golden light. In the text of this scroll, every word appeared doubled, and as he looked at it, Cardano felt as if he could see both the text and its reflection simultaneously. Each symbol seemed to have a mirrored twin — slightly shifted and turned to the side.</p><p>“What magic lies within this double light?” wondered Cardano. But as he tilted the scroll slightly, some of the reflected symbols suddenly vanished, leaving only the clear and bright words. These lines pointed toward the emeralds hidden deep within the mines, though their secret remained elusive.</p><p>“Only what remains after uniting,” whispered an ancient voice from the scroll, “is true and real. All that is unnecessary will disappear, and what was complex will become simple. You will encounter two opposites — a number and its twin, facing the other way, yet their power will be one.”</p><blockquote>Cardano pondered deeply. He didn’t yet realize that this riddle would reveal the secret of separating the real from the ephemeral, from the imaginary. He continued to gaze at the glowing lines and understood that their glow was not mere doubling but a way to distinguish the true from the hidden. Shadows vanished when he combined symbols with their reflections, leaving only the golden truth that guided him in the right direction.</blockquote><p>Thus, he discovered how to use the scroll. In every symbol of the scroll lived part of the power hidden in its mirror. This duality was inseparable and revealed only what was true if viewed from the right angle. Where opposites met, all that was unnecessary vanished, leaving only what had meaning and weight in this world.</p><p>In this way, Cardano found the path to the emeralds, following the light that revealed each symbol in its pure essence, undistorted by shadows. The shadows dissolved, and all excess faded away as he uncovered each line like a number and its reflection, leaving only the essence on the thin boundary between reality and imagination.</p><h3>Hints</h3><p><strong>1.The Mystery of the Golden Glow</strong></p><p>“The scroll glowed as if lit from within by two suns, one facing right and the other left. I sensed that each symbol on the scroll had a reflection, as if half of it was directed towards another world. When I tilted the scroll slightly, part of this mysterious light faded, leaving only distinct lines, something unchanging in an eternal opposition:”</p><pre>import cmath<br><br>θ = 0  # initial angle of light<br>symbol = cmath.rect(1, θ)  # symbol glowing at the start<br>print(f&quot;Initial light: {symbol}&quot;)</pre><p><em>The symbols appeared and disappeared, leaving behind only the true markings.</em></p><p><strong>2.Vanishing Symbols</strong></p><p>“Each time I tilted the scroll, one half of the reflection vanished, leaving only the clear trace of the other. It resembled a magical process that seemed to preserve only the authentic part, free from excess. There was strength in this phenomenon, as if the scroll itself was showing me what was truth and what was illusion:”</p><pre>real_symbol = symbol.real  # keeping only the true marking<br>print(f&quot;Light of the true symbol: {real_symbol}&quot;)</pre><p><em>Each disappearance revealed the truth, as if the scroll itself was guiding what to see.</em></p><p><strong>3.Duality of Symbols</strong></p><p>“I saw the symbols as if doubled, as though one part was reaching into another world. They seemed to look at each other like reflections in a mirror, but each had its own light. When the two images came together, their light became one, leaving only what held strength and meaning:”</p><pre>reflection = symbol.conjugate()  # reflected symbol<br>true_symbol = (symbol + reflection) / 2  # merging to keep unified light<br>print(f&quot;Unified light of the symbol: {true_symbol}&quot;)</pre><p><em>The light remained whole when opposites came together.</em></p><p><strong>4.Light Remaining at the Boundary</strong></p><p>“Each symbol, reflected in the scroll’s light, held something immutable within, as if all excess disappeared in a single glance. When I saw a symbol and its double merging, they became something whole, illuminating my path into the mine. This light was more than just visibility; it was pure truth:”</p><pre>truth = abs(true_symbol)  # preserving the strength of the symbol<br>print(f&quot;Pure strength of the symbol: {truth}&quot;)</pre><p><em>Thus, the symbols opened the path ahead, guiding the way with light in its purest form.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Wa2GS3yK5wfngIthr7zQw.jpeg" /></figure><h3>9.The Gem of Invisible Vibrations</h3><p>Once, while exploring the depths of a magical mine, Cardano discovered an ancient stone that seemed to glow from within. The light was no longer golden and even, as before; it flickered and held a mysterious quality, as if it emanated from a distant, misty expanse. More importantly, this light did not remain still — it moved, as if propelled by an invisible force hidden within the stone itself. Cardano noticed that the light spread in various directions, and the closer he approached, the more he sensed something elusive — as if the stone itself were vibrating, though these vibrations were unseen.</p><blockquote>Cardano understood that the secret of the stone lay in perceiving its essence through the distinction between what is and what is reflected. He took a second, mirror-smooth stone and held it up to the first. Both reflected each other, but in their difference, in the space between them, a force emerged that seemed elusive, like a spirit of water swirling in a whirlpool.</blockquote><p>“Only through separation can one capture what is hidden in motion,” a voice spoke in his head. “The force of rotation lives in that which gazes in two opposite directions, leaving its mark only on one of the axes. Where there are neither axes nor boundaries, everything disappears, but what remains is pure energy that guides.”</p><p>Thus, Cardano learned to see the invisible, noticing only the movements of light, and found the path to the most intimate illusion that existed between the stone and its reflection. The light could fade, disappear, and reemerge, but within its very shadow, in the interaction with the reflection, a force was born — one that no straight line could touch, yet which he could use to unlock previously unseen depths.</p><h3>Hints</h3><p><strong>1.The Mysterious Light in Motion</strong></p><p>“The stone glowed with a soft, flickering light that seemed distant and fluid. As I approached, I felt the light shimmering, yet it felt as though it was slightly displaced, driven by an unseen force. It seemed the stone itself was emitting this motion, as if it was hidden within its very essence:”</p><pre>import cmath<br>import math<br><br>amplitude = 1<br>angle = math.pi / 4  # initial angle<br>oscillation = cmath.rect(amplitude, angle * 1j)  # imaginary oscillation<br>print(f&quot;Oscillating light: {oscillation}&quot;)</pre><p><em>The light within the stone was alive, concealing a constant motion within.</em></p><p><strong>2.Separation and Reflection</strong></p><p>“I decided to bring a mirror-smooth stone close to it, to see what was hidden in this light. When both stones met, a hidden energy was revealed in their reflection, something that could not be seen directly. I realized that the power of this stone lived in its opposite — it appeared only through the separation into two lights:”</p><pre>stone = cmath.rect(amplitude, angle * 1j)<br>stone_reflection = cmath.rect(amplitude, -angle * 1j)<br>separation = stone - stone_reflection  # difference of oscillations<br>print(f&quot;Hidden energy: {separation}&quot;)</pre><p><em>Thus, the light revealed its power, born in the difference between two reflections.</em></p><p><strong>3.Circular Motion</strong></p><p>“I noticed that the movement of this light resembled a swirling water ripple. The strength was not in the direct light but in how it rotated between the two stones. This motion had no beginning or end, as if it was rotating around an invisible axis extending into the depth of the stone itself:”</p><pre>rotation = cmath.exp(1j * angle)  # rotation of the light<br>rotational_energy = rotation * separation<br>print(f&quot;Rotational energy: {rotational_energy}&quot;)</pre><p>The mesmerizing light was itself a circular motion, pulsing in the depth.</p><p><strong>4.Power on the Verge of Disappearance</strong></p><p>“When the light was fully absorbed by the reflection, everything disappeared, leaving only a hint of oscillation. In this void lived pure energy, guiding me deeper into the mine’s mysteries. This was a light that couldn’t be held, yet it pointed me to a path hidden behind an imaginary boundary:”</p><pre>pure_energy = abs(rotational_energy)  # remaining strength in oscillation<br>print(f&quot;Pure energy: {pure_energy}&quot;)</pre><p><em>Thus, the stone left its mark, revealing the path to depths hidden within the essence of light itself.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccbI60JFsDroXKYhxl9dwg.jpeg" /></figure><h3>10.The Unchanging Dance of the Blue Star</h3><p>In an emerald underground, Cardano saw an enchanted circle at the center of which spun a blue star, like a small mirror reflecting an ancient mystery. It glowed with a magical light that seemed eternal, like the earth itself. As Cardano approached, the star began to move faster, yet its light remained unchanged, as if it followed an ancient rhythm from which it could not deviate.</p><p>“Look at how this little light moves,” said Bombelli, his wise companion. “Its glow stays constant, no matter how fast it spins. The star dances in a circle, and the distance from the center is always the same, unchanging, like the unity of day and night.”</p><blockquote>Cardano noticed that the star moved along an invisible path, linked to a special harmony, as if an unseen composer orchestrated its eternal dance. Remarkably, wherever the star moved along the circle, regardless of the angle it traversed, the distance from it to the center remained constant, as if tethered by an invisible thread of a fixed length.</blockquote><p>“This star is subject to one eternal law,” said Bombelli. “It can be in any point of the circle, it can traverse any angle of the path, but it will never approach the center or move away from it. Its path is a perfect circle, and the distance from the center is always equal to one.”</p><p>And Cardano, holding his breath, realized that this star expressed a special magic of numbers — how one could move in a circle while maintaining a constant distance from the center, no matter the angle traversed.</p><h3>Hints</h3><p><strong>1.The Mystery of the Unchanging Path</strong></p><p>“I watched as the blue star moved in a circle, but something in that movement remained stable and unbreakable. Its path was circular, and the distance to the center was constant, no matter how fast its dance. It was as if it was bound by an invisible thread, keeping it at the same distance from the center, without the slightest deviation:”</p><pre>import cmath<br>import math<br><br>angle = math.pi / 3  # angle traversed by the star<br>star = cmath.rect(1, angle)  # modulus is always equal to one<br>print(f&quot;Star&#39;s position: {star}&quot;)</pre><p><em>Its circular motion remained perfect, no matter how its position changed.</em></p><p><strong>2.The Laws of the Circle</strong></p><p>“I noticed that no matter the angle the star traveled along the circle, its distance to the center always remained one. It seemed to follow a particular law without question. In every moment of its shine, it retained a constant value, just like the movement itself:”</p><pre>star_modulus = abs(star)  # check modulus<br>print(f&quot;Star&#39;s modulus: {star_modulus}&quot;)</pre><p><em>Thus, the star showed me that its shine did not depend on the angle — its magic was in the constancy of distance.</em></p><p><strong>3.The Harmony of Angles</strong></p><p>“The blue star, as if obeying the melody of angles, could be at any point on the circle, but each time its distance to the center remained the same. It was as if each angle brought it to a new position, yet didn’t alter its true essence. It moved like notes in a song, but its distance from the center was always one:”</p><pre>for i in range(6):<br>    angle = i * math.pi / 3<br>    star = cmath.rect(1, angle)<br>    print(f&quot;Star at angle {angle}: {star}&quot;)</pre><p><em>Each angle revealed a new position, yet the path always kept the same unchanging length.</em></p><p><strong>4.Eternal Unity</strong></p><p>“I realized the star contained an eternal truth — its light always returned to the same value, neither coming closer nor moving away from the center. This circular path was its eternal essence, its unchanging magic, showing how it could move while remaining at one distance from the center, no matter the angle:”</p><pre>circle_motion = cmath.rect(1, 2 * math.pi)  # full rotation, return to start<br>print(f&quot;Star after full circle: {circle_motion}&quot;)</pre><p><em>Thus, the star returned to the beginning, completing a full circle but retaining its untouchable essence.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7umJ_VwLjapM35WPZS18g.jpeg" /></figure><h3>11.The Song of the United Crystals</h3><p>In an ancient emerald underground, full of secrets and wonders, lived a wise gnome named Cardano. Cardano was known for his ability to find hidden paths among the magical crystals — blue and purple — that mysteriously glowed on the walls of his subterranean home. One day, Cardano discovered an ancient scroll that read: “Crystals, separate in space, can be united if one follows the circle of light.” Intrigued, the gnome decided to test the power of this strange knowledge.</p><p>Approaching one of the blue crystals, Cardano turned it to direct its light eastward and said, “Now you are the first sign.” Then, traveling along the circumference, Cardano found a purple crystal and turned its light northward. “Now you are the second sign,” the gnome said, and the light from both crystals merged, creating a dazzling third light. This light was neither blue nor purple; it sparkled with a whole spectrum of colors, reminding the gnome of a simple rule: “The sum of the paths determines the overall direction.”</p><blockquote>Cardano realized that the light emanating from each crystal acted as a pointer to its secret direction. When the crystals united, their beams combined, creating a new direction on the circle. “Interesting,” the gnome pondered, “it doesn’t matter in what order I turn the crystals. If I first connect the first and second, and then the third, the result will be the same.” He tried again, connecting different crystals in various combinations, and each time the light found its way to the same shimmering beam.</blockquote><p>Then Cardano understood: “There is neither beginning nor end here. Each light is a continuation of another.” He realized that by uniting the light of different crystals, he was traveling along the same circumference, returning to where it all began. “So each of them guides me to a new part of the circle, no matter how far I go,” exclaimed Cardano, filled with joy at his discovery.</p><p>“It’s not just addition, not just rotation, but something more — a union,” he said, watching as the shimmering light now filled the entire underground. And so he left his riddle for future generations: “How can one unite light so that every time the path remains on the circle, always returning to itself?”</p><h3>Hints</h3><p><strong>1.Light Rotation</strong></p><p>“I noticed that by turning the crystal, I can direct its light in any direction. This light becomes a pointer, and the crystal acts as a landmark on my map. It’s as if in each turn, I find a point on the circle, and as soon as it lights up, I get closer to unraveling an ancient design:”</p><pre>import math<br><br>def direct_light(angle):<br>    # Coordinates of light on the unit circle<br>    x = math.cos(angle)<br>    y = math.sin(angle)<br>    return (x, y)<br><br>rotation_angle = math.radians(45)  # Rotate 45 degrees<br>light_position = direct_light(rotation_angle)<br>print(f&quot;Light directed to point: {light_position}&quot;)</pre><p><em>Each new direction of light paves the way to unexplored heights, where crystals gain their secret connection.</em></p><p><strong>2.The Path of Duality</strong></p><p>“How strange! Two crystals, illuminating different sides of the circle, seem to lead to the same goal, but from different paths. They are like opposite points on the circumference, whose rays meet somewhere on the distant horizon, creating a unified light:”</p><pre>def opposite_angle(angle):<br>    # Transition to the opposite point on the circle<br>    return (angle + math.pi) % (2 * math.pi)<br><br>main_crystal_angle = math.radians(30)<br>twin_angle = opposite_angle(main_crystal_angle)<br>print(f&quot;Crystal directed at angle: {main_crystal_angle}, Twin: {twin_angle}&quot;)</pre><p><em>Each turn seems to point to an infinite multitude of paths intersecting on the circle of light, like two crystals, separated but eternally connected.</em></p><p><strong>3.Movement Around the Source</strong></p><p>“The more I turn the crystals, the clearer it becomes: each turn preserves distance but alters the angle, as if the circle itself dictates the path. Every time, starting from a new direction, I return to the same light, as if the circle has no beginning and no end:”</p><pre>def path_on_circle(start_angle, steps):<br>    positions = []<br>    angle = start_angle<br>    for _ in range(steps):<br>        positions.append(direct_light(angle))<br>        angle = (angle + math.radians(30)) % (2 * math.pi)  # Step around the circle<br>    return positions<br><br>light_positions = path_on_circle(main_crystal_angle, 4)<br>print(f&quot;Light positions on the circle: {light_positions}&quot;)</pre><p><em>Each crystal points to eternal return, where the path repeats, but each turn reveals a new facet of light.</em></p><p><strong>4.The Unity of Circles’ Sequence</strong></p><p>“All the crystals, connected by light, seem to form a single pattern on the circle, where each light leads to another. The eternal cycle connects them in an infinite sequence, as if each light returns to itself when its path is completed:”</p><pre>Crystal: angle θ and its opposing angle θ + π<br>Unity: each turn brings us back to the beginning, but on a new path.</pre><p><em>In this sequence of circles, light moves endlessly, forming a pattern of eternal return, where each step on the circle finds its reflection.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-FE1PCySQJChS3CR2G9tg.jpeg" /></figure><h3>12.The Thirteen Crystals of Power</h3><p>In an ancient emerald underground filled with mysterious corridors and halls, there lived a gnome named Cardano, known for his rare ability to shape crystal light into intricate patterns. One night, wandering among the blue and purple crystals, Cardano stumbled upon a peculiar circle of thirteen crystals, shining more brightly than usual. Every time he touched one of the crystals, he noticed it changed its glow and began shining in a new direction, guiding him deeper into the underground. Before long, Cardano realized that if he touched the same crystal multiple times, it would glow brighter, and its beam would point further, as though its light was traveling farther around the circle.</p><p>Amazed, Cardano began to study exactly how each crystal’s direction shifted with repeated touches. With one touch, the beam pointed east. With two, it turned southeast, and each time, the light shifted further, tracing a path around the circle. Cardano noticed that with each new touch, the beam turned faster, moving the light along the same course but ever further around the circle. “So, each touch multiplies its force, pushing it further,” Cardano mused.</p><blockquote>Again and again, he tried counting how many touches would bring the light back to its original position, and he discovered that after a certain number of touches, the beam returned to its starting point. Now, Cardano understood: each crystal held a secret cycle in which its light repeated its path when multiplied enough times. This force, he realized, carried the crystals beyond a single movement but still completed a circle, returning them to the beginning.</blockquote><p>“So even endless light knows where it came from,” Cardano said with reverence, “and each crystal holds the strength of countless rotations.” As he ventured further into the depths, he left a riddle for the crystals: “What force brings light back to the start, no matter how many times it circles?” And the mystery remained unsolved in the underground, where the crystals continued to shine, sending their light further and further around.</p><h3>Hints</h3><p><strong>1.The First Touch of Light</strong></p><p>“When I first touched one of the crystals, its light suddenly came alive, aiming directly east. I felt that this was just the beginning of its journey and realized that this direction was like a starting point on the circle, where light only begins its infinite road:”</p><pre>import math<br><br>def light_direction(steps):<br>    # Calculate the position of light on the unit circle<br>    angle = steps * (2 * math.pi / 13)<br>    x = math.cos(angle)<br>    y = math.sin(angle)<br>    return (x, y)<br><br>first_touch_position = light_direction(1)<br>print(f&quot;Position of light at first touch: {first_touch_position}&quot;)</pre><p><em>Like in every touch, the path of light, starting from the east, calls it beyond the visible, promising new discoveries.</em></p><p><strong>2.Amplifying the Light</strong></p><p>“The second touch awakened an unknown power within the crystal. Its light turned, delving deeper into the underground, and each new step intensified it, as if the force of light was increasing, moving it further around the circle. It seemed that each time the light spun faster, drawing me along with it:”</p><pre>steps = 2<br>second_touch_position = light_direction(steps)<br>print(f&quot;Position of light at second touch: {second_touch_position}&quot;)</pre><p><em>Each turn seems to unveil a new facet, where the intensified light creates a pattern and directs further along the infinite circle.</em></p><p><strong>3.The Secret Circle of Return</strong></p><p>“The more I touched the crystal, the clearer I saw how its light moved in a circle, exploring uncharted directions, yet always remaining on its path. Each time, the light returned to its original position, as if it knew where its home was, despite its growing power:”</p><pre>steps = 13<br>full_cycle_position = light_direction(steps)<br>print(f&quot;Position of light after a full circle of touches: {full_cycle_position}&quot;)</pre><p><em>The light of the crystal completed the circle, and each of its turns, each intensified flash, points back to the beginning, to the point of rest.</em></p><p><strong>4.The Great Dance of Power</strong></p><p>“I realized that each crystal could carry light around, again and again, without fatigue and with increasing strength. Each turn, amplifying the light, leaves a path behind, yet none of them goes beyond the circle. As if the force of light itself were part of that very circle, returning to itself with each step:”</p><pre>Crystal: the power of light after n touches<br>Path: each turn carries light further but returns to the source.</pre><p><em>The strength of each touch gives the light a new direction, but as it curves around the circle, it always returns, as if preserving the ancient covenant of returning to the beginning.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpcQDOCx-l1a53roHaZRIw.jpeg" /></figure><h3>13.Return to the Origin</h3><p>In an emerald underground where vibrant blue and purple crystals lay hidden, the gnome Cardano knew a secret angle that led to the light. One day, he noticed a strange pattern: a crystal would begin to shine just as it had at the start of his journey when he circled back exactly one full round. “Curious,” thought Cardano, “can the light return to where it began simply by traveling the path and reaching the same angle?” That night, he began a secret experiment, visiting every corner of the underground and returning to where the first crystal stood.</p><blockquote>With each step, Cardano touched a new crystal, each time shifting its light in different directions, yet once he completed the circle, the light returned to its starting point. Cardano was amazed: this was not just a circle — it was a return to the very beginning, to a pristine state. As though none of the crystals had moved, each remained in place while casting light into a new, far-reaching perspective.</blockquote><p>“To return to the beginning,” mused the gnome, gazing at the shining circle, “means preserving all strength and finding oneself.” The most astonishing thing, he realized later, was that no matter how many circles he completed, the first light remained unchanged. Every full circuit brought Cardano back to where he had started, revealing that a complete circle contained a power of return, closing upon itself and preserving both strength and path.</p><p>Now, the gnome pondered how light’s force and movement could lead to such a magical return. He imagined that any light could return to its singular brilliance, simply by completing a full circle. Deep within the underground, Cardano decided that each crystal remembered the entire path, and every complete circle brought them back to the beginning. Leaving his musings behind, he left a riddle for future generations: “How will the light return to its origin after the great circle? In this lies both strength and completion.”</p><h3>Hints</h3><p><strong>1.First Step Around the Circle</strong></p><p>“Taking the first step, I felt the crystal’s light move in a certain direction, as if obeying an invisible force. This step was the beginning of the path, and it seemed that with every new move, I was getting closer to uncovering how the light could find its origin, following a circle:”</p><pre>import math<br><br>def light_path(angle):<br>    # Light&#39;s position on the circle at a given angle<br>    x = math.cos(angle)<br>    y = math.sin(angle)<br>    return (x, y)<br><br>starting_angle = 0<br>starting_position = light_path(starting_angle)<br>print(f&quot;The light starts at position: {starting_position}&quot;)</pre><p><em>Every new step opens a path for the light, leading it further but preserving its connection to the origin.</em></p><p><strong>2.The Light’s Trail</strong></p><p>“After taking several steps, the light began circling around, as if pointing to the place where it would return. Every new angle revealed a new direction, but I felt the light held an invisible connection to the first step, as if it would return to it once more:”</p><pre>steps = 3<br>angle = steps * (2 * math.pi / 12)<br>trail_position = light_path(angle)<br>print(f&quot;Position of the light after several steps: {trail_position}&quot;)</pre><p><em>The light follows its path, but the circle holds it, guiding it to the point of origin.</em></p><p><strong>3.Turning and Returning</strong></p><p>“When I completed the entire circle, the light was suddenly at the exact point where it all began. No matter how many times I went around, the crystal always brought the light back to the original position. It was a mysterious closed path, where each full circle brought everything back to where it belonged:”</p><pre>full_rotation = 12<br>position_after_rotation = light_path(full_rotation * (2 * math.pi / 12))<br>print(f&quot;Position of the light after a full circle: {position_after_rotation}&quot;)</pre><p><em>Each loop was a new step, but the complete return of light always preserved its constancy.</em></p><p><strong>4.The Eternal Return of Light</strong></p><p>“Now I knew: no matter how many circles I completed, the light would always return to its original point, retaining its nature. Every full rotation was a path to the beginning, as if each light held within it the memory of its first step, bringing everything back to the prime position.”</p><pre>Light: path around the circle<br>Return: each rotation completes the path and returns the light to its origin.</pre><h3>Answers to riddles — in the context of using the Aizenberg neuron</h3><p>Below are the answers to the 13 story-puzzles. Check your solutions. For more detailed information about the features of the <a href="https://medium.com/@serhii.barskyi/aisenberg-neuron-in-complex-valued-reinforcement-learning-tasks-dc4a8f53cc1d">Aizenberg neuron</a>, see <a href="https://medium.com/@serhii.barskyi/aisenberg-neuron-in-complex-valued-reinforcement-learning-tasks-dc4a8f53cc1d">this lesson</a>. Please post any questions in the article discussion.</p><pre><br>1.The Unified Light of Two Gemstones<br><br><br># 1. Algebraic form of complex number <br>z = a + b * sp.I<br><br>&quot;&quot;&quot;<br>In complex-reinforcement learning, each state or action can <br>be represented in algebraic form as z = a + bi, where a and b are <br>the real and imaginary parts.<br>&quot;&quot;&quot;<br><br># State representation<br>z1 = 3 + 4 * sp.I<br><br>&quot;&quot;&quot;<br>For example, if an agent is in state z1 = 3 + 4i, this might <br>mean that the real state is characterized by the value a = 3, while <br>the imaginary part is b = 4.<br>&quot;&quot;&quot;<br><br># Weight coefficients<br>w = c + d * sp.I<br><br>&quot;&quot;&quot;<br>Weight coefficients w can also be represented as w = c + di, where <br>c and d are analogous components.<br>&quot;&quot;&quot;<br><br># Weighted summation<br>z_sum = (a + c) + (b + d) * sp.I<br><br>&quot;&quot;&quot;<br>In the process of weighted summation, the agent will sum <br>inputs and weights in algebraic form: z_sum = (a1 + c1) + (b1 + d1)i.<br>&quot;&quot;&quot;<br><br># Error calculation<br>e = (a_d - a_y) + (b_d - b_y) * sp.I<br><br>&quot;&quot;&quot;<br>The complex value of the error e between the desired and current <br>neuron output can be calculated in <br>algebraic form: e = (ad - ay) + (bd - by)i, where indices d and y <br>denote the target and current outputs.<br>&quot;&quot;&quot;<br><br># Weight adjustment<br>w_new = w_old + eta * e * sp.conjugate(x)<br><br>&quot;&quot;&quot;<br>Weight adjustment in training can also occur by adding a complex <br>number to the weight: w_new = w_old + eta * e * x*, where e and x are <br>represented in algebraic form.<br>&quot;&quot;&quot;<br><br># Example with specific values for e and x<br>e_example = 1 + 2 * sp.I<br>x_example = 2 + 3 * sp.I<br>w_example = 0.5 + 0.5 * sp.I<br>w_new_example = w_example + 0.1 * e_example * sp.conjugate(x_example)<br><br>&quot;&quot;&quot;<br>For instance, if e = 1 + 2i and x = 2 + 3i, the weight <br>update w = 0.5 + 0.5i could look <br>like w_new = (0.5 + 0.5i) + 0.1 * (1 + 2i)(2 - 3i).<br>&quot;&quot;&quot;<br><br># Final formula<br>z_final = sp.Sum(a + b * sp.I, (a, 0, 1)) + eta * (a_d + b_d * sp.I)<br><br>&quot;&quot;&quot;<br>The final formula that integrates this in the context <br>of learning is z = ∑(ak + bk i) + eta * (ae + be i).<br>&quot;&quot;&quot;<br><br></pre><pre><br>2.The Compass of Eternal Rotation<br><br><br># 2. Exponential form of a complex number<br>z_exponential = r * sp.exp(phi * sp.I)<br><br>&quot;&quot;&quot;<br>The exponential form is convenient for representing phase <br>characteristics, where r is the modulus and φ is the phase.<br>&quot;&quot;&quot;<br><br># Interpretation in reinforcement learning<br>signal_strength = r<br>phase_direction = phi<br><br>&quot;&quot;&quot;<br>In reinforcement learning tasks, r can interpret the strength <br>of the signal, while φ represents the direction or phase of the action.<br>&quot;&quot;&quot;<br><br># Example state in exponential form<br>z1_exponential = 2 * sp.exp(sp.pi / 3 * sp.I)<br><br>&quot;&quot;&quot;<br>For example, for the state z1 = 2e^(iπ/3), r = 2 and φ = π/3, which <br>can be interpreted as an action with strength 2 and phase π/3.<br>&quot;&quot;&quot;<br><br># Weighted sum in exponential form<br>weighted_sum = sp.Sum(r * sp.exp(phi * sp.I), (r, 1, sp.symbols(&#39;n&#39;)))<br><br>&quot;&quot;&quot;<br>The weighted sum during training can also be expressed through <br>the exponential form: z = ∑(rk e^(iφk)).<br>&quot;&quot;&quot;<br><br># Multiplication of state and weight in exponential form<br>w_exponential = s * sp.exp(theta * sp.I)<br>product = z_exponential * w_exponential<br><br>&quot;&quot;&quot;<br>For weighing the state and weight, z = re^(iφ) and w = se^(iθ), their <br>product will be zw = rs e^(i(φ + θ)), preserving phase relationships.<br>&quot;&quot;&quot;<br><br># Phase adjustment during learning<br>new_weight_phase_adjustment = r * sp.exp((theta + delta_phi) * sp.I)<br><br>&quot;&quot;&quot;<br>In reinforcement learning, it&#39;s important to adjust the phase of the <br>neuron&#39;s output, which can be done by changing the phase angle in the <br>exponential form.<br>&quot;&quot;&quot;<br><br># Example of phase error adjustment<br>w_new_phase_adjustment = r * sp.exp((theta + delta_phi) * sp.I)<br><br>&quot;&quot;&quot;<br>For instance, if the phase error is Δφ = φd - φy, the new weight is <br>adjusted through the phase: w_new = r e^(i(θ + Δφ)).<br>&quot;&quot;&quot;<br><br># Update weight based on error<br>e_exponential = r * sp.exp(delta_phi * sp.I)<br>w_new_weight_update = w_exponential + sp.symbols(&#39;eta&#39;) * e_exponential * sp.conjugate(x)<br><br>&quot;&quot;&quot;<br>To update the weight based on the error e = re^(iΔφ), one can <br>multiply by the input signal in exponential <br>form: w_new = w_old + ηr e^(i(Δφ)) x*.<br>&quot;&quot;&quot;<br><br># Final note on exponential form utility<br>&quot;&quot;&quot;<br>The exponential form provides a convenient representation for <br>analyzing phase characteristics and controlling rotation on the complex plane.<br>&quot;&quot;&quot;</pre><pre><br>3.The Dance of Light and Shadow in the Dungeon<br><br><br># 3. Trigonometric form of a complex number<br>z_trigonometric = r * (sp.cos(phi) + sp.I * sp.sin(phi))<br><br>&quot;&quot;&quot;<br>In triangular problems, phase characteristics can be conveniently <br>expressed in trigonometric form through z = r (cos φ + i sin φ).<br>&quot;&quot;&quot;<br><br># Example action of an agent in trigonometric form<br>z_agent_action = 2 * (sp.cos(sp.pi / 4) + sp.I * sp.sin(sp.pi / 4))<br><br>&quot;&quot;&quot;<br>For example, the agent&#39;s action can be <br>represented as z = 2 (cos(π/4) + i sin(π/4)), which has an <br>angle of π/4 and a length of 2.<br>&quot;&quot;&quot;<br><br># Importance of maintaining phase proportionality<br>&quot;&quot;&quot;<br>In learning processes, it is important to maintain the <br>phase proportionality between the phases of input signals and weights.<br>&quot;&quot;&quot;<br><br># New action phase for the agent<br>new_action_phase = sp.pi / 6<br><br>&quot;&quot;&quot;<br>If the agent receives a new action with phase φ = π/6, the <br>trigonometric form provides a clear representation of motion on <br>the complex plane.<br>&quot;&quot;&quot;<br><br># Weighted sum in trigonometric form<br>weighted_sum_trigonometric = sp.Sum(r * (sp.cos(phi) + sp.I * sp.sin(phi)), (r, 1, sp.symbols(&#39;n&#39;)))<br><br>&quot;&quot;&quot;<br>In the context of the weighted sum, z = ∑rk (cos(φk) + i sin(φk)) is <br>used to find the resulting amplitude and direction of the action.<br>&quot;&quot;&quot;<br><br># Reinforcement learning adjustment of angle<br>&quot;&quot;&quot;<br>Reinforcement learning can take into account the angle φ, adjusting <br>it to minimize the error, for instance, through weight adjustments in <br>trigonometric form.<br>&quot;&quot;&quot;<br><br># Example error in trigonometric form<br>error_trigonometric = 1 * (sp.cos(sp.pi / 6) + sp.I * sp.sin(sp.pi / 6))<br><br>&quot;&quot;&quot;<br>For example, if the error e = 1 (cos(π/6) + i sin(π/6)), the weights <br>are updated considering these trigonometric components.<br>&quot;&quot;&quot;<br><br># Adjustment based on real and imaginary components<br>&quot;&quot;&quot;<br>Since e includes both real and imaginary parts, the phase adjustment <br>in the neuron depends on these values.<br>&quot;&quot;&quot;<br><br># Visualization of rotations and phase corrections<br>&quot;&quot;&quot;<br>The trigonometric form helps visualize rotations and phase corrections <br>in training, minimizing error.<br>&quot;&quot;&quot;<br><br># Final equation for weight adjustment<br>w_new_adjustment = r * (sp.cos(theta + delta_phi) + sp.I * sp.sin(theta + delta_phi))<br><br>&quot;&quot;&quot;<br>The final equation for weight adjustment can be written <br>as w_new = r (cos(θ + Δφ) + i sin(θ + Δφ)).<br>&quot;&quot;&quot;</pre><pre><br>4.The Star of Two Forces<br><br># 4. Euler&#39;s formula<br>euler_formula = sp.exp(sp.I * phi)<br><br>&quot;&quot;&quot;<br>Euler&#39;s formula is used to connect the exponential and <br>trigonometric forms of complex numbers.<br>&quot;&quot;&quot;<br><br># Agent action phase<br>agent_action_phase = sp.pi / 3<br><br>&quot;&quot;&quot;<br>If the agent&#39;s action has a phase φ = π/3, its representation <br>can be directly computed as e^(iπ/3) = cos(π/3) + i sin(π/3).<br>&quot;&quot;&quot;<br><br># Converting between forms<br>trigonometric_representation = sp.cos(agent_action_phase) + sp.I * sp.sin(agent_action_phase)<br><br>&quot;&quot;&quot;<br>Euler&#39;s formula allows easy switching between phase representation <br>and trigonometric structure.<br>&quot;&quot;&quot;<br><br># Weight adjustment using Euler&#39;s formula<br>w = 2 * sp.exp(sp.I * sp.pi / 4)<br><br>&quot;&quot;&quot;<br>In the learning process, the agent can change its weights using <br>this formula for calculating phase adjustments.<br>&quot;&quot;&quot;<br><br># Converting weight to trigonometric form<br>trigonometric_weight = 2 * (sp.cos(sp.pi / 4) + sp.I * sp.sin(sp.pi / 4))<br><br>&quot;&quot;&quot;<br>For example, if weight w = 2e^(iπ/4), it can be transformed into <br>trigonometric form 2(cos(π/4) + i sin(π/4)) for calculating changes.<br>&quot;&quot;&quot;<br><br># Simplifying calculations using Euler&#39;s formula<br>&quot;&quot;&quot;<br>Euler&#39;s formula also simplifies calculations when multiplying complex <br>numbers, preserving phase components.<br>&quot;&quot;&quot;<br><br># Weighing input signals with Euler&#39;s formula<br>&quot;&quot;&quot;<br>When weighing input signals, the formula helps reduce computations <br>to simple angle addition.<br>&quot;&quot;&quot;<br><br># Updating weight based on error<br>error_weight_update = sp.exp(sp.I * (theta + delta_phi))<br><br>&quot;&quot;&quot;<br>In the weight update process based on error, Euler&#39;s formula can <br>be used to minimize phase deviations.<br>&quot;&quot;&quot;<br><br># Expressing weight update compactly<br>compact_weight_update = sp.exp(sp.I * (theta + delta_phi))<br><br>&quot;&quot;&quot;<br>Using e^(i(θ + Δφ)), the weight update can be expressed in a compact <br>form, making this formula key for learning.<br>&quot;&quot;&quot;</pre><pre><br>5.Mirror Stars — Guardians of Balance<br><br><br># 5. Modulus of a complex number<br>modulus = sp.sqrt(a**2 + b**2)<br><br>&quot;&quot;&quot;<br>The modulus |z| defines the length of the complex number <br>on the plane, which can interpret the strength of the signal in RL.<br>&quot;&quot;&quot;<br><br># Example state<br>z_example = 3 + 4 * sp.I<br><br>&quot;&quot;&quot;<br>For the state z = 3 + 4i, the modulus is |z| = √(3² + 4²) = 5, <br>which can express the strength of the action.<br>&quot;&quot;&quot;<br><br># Modulus role in weighting<br>&quot;&quot;&quot;<br>In the process of weighting states and actions, the modulus <br>plays an important role, determining the contribution of each <br>signal to the final decision.<br>&quot;&quot;&quot;<br><br># Updating weights dependence on modulus<br>&quot;&quot;&quot;<br>Weight updates also depend on the modulus of the complex number, as <br>errors are often related to the distance on the complex plane.<br>&quot;&quot;&quot;<br><br># Normalizing signals using modulus<br>&quot;&quot;&quot;<br>The modulus can be used to normalize signals, especially when <br>comparing inputs with different amplitudes.<br>&quot;&quot;&quot;<br><br># Example weight<br>w_example = 1 + 2 * sp.I<br><br>&quot;&quot;&quot;<br>If the weight w = 1 + 2i, the modulus will be |w| = √(1² + 2²) = √5, and <br>this can be taken into account during adjustment.<br>&quot;&quot;&quot;<br><br># Weight update assessment<br>&quot;&quot;&quot;<br>During weight updates, the modulus can be used to assess how strongly <br>each complex number needs to be changed.<br>&quot;&quot;&quot;<br><br># Error correction example<br>error_example = 1 + 2 * sp.I<br><br>&quot;&quot;&quot;<br>For instance, when adjusting the weight based on the error e = 1 + 2i, the <br>modulus of the error |e| will help adjust the strength of the impact.<br>&quot;&quot;&quot;<br><br># Considering both modulus and phase for weight updates<br>&quot;&quot;&quot;<br>For weight updates, one can consider both the modulus and the phase of <br>the complex number.<br>&quot;&quot;&quot;<br><br># Modulus interpretation in RL<br>&quot;&quot;&quot;<br>In RL, the modulus is often interpreted as the degree of impact of an <br>action on the outcome, making it important in phase computations.<br>&quot;&quot;&quot;</pre><pre><br>6.The Mystery of the Complete Circle<br><br><br># 6. Argument of a complex number<br>argument = sp.atan(b/a)<br><br>&quot;&quot;&quot;<br>The argument arg(z) defines the angle between the complex <br>number and the real axis, which is important for determining the phase in RL.<br>&quot;&quot;&quot;<br><br># Example state<br>z_example = 1 + sp.I<br><br>&quot;&quot;&quot;<br>For the state z = 1 + i, the argument <br>will be arg(z) = arctg(1/1) = π/4.<br>&quot;&quot;&quot;<br><br># Argument role in phase error computation<br>&quot;&quot;&quot;<br>The argument helps to compute phase errors, for instance, the <br>difference between the current state and the target: Δφ = arg(d) - arg(y).<br>&quot;&quot;&quot;<br><br># Weight adjustment using the argument<br>&quot;&quot;&quot;<br>When adjusting weights, the argument helps to calculate <br>the angle needed to shift the phase to reduce the error.<br>&quot;&quot;&quot;<br><br># Phase error example<br>&quot;&quot;&quot;<br>If the error is phase-related, the difference in <br>angles Δφ = φ_d - φ_y is computed, allowing the agent to <br>reduce phase deviation.<br>&quot;&quot;&quot;<br><br># Considering arguments during input weighting<br>&quot;&quot;&quot;<br>When weighting inputs, it&#39;s essential to consider the <br>arguments of all input signals for proper phase distribution.<br>&quot;&quot;&quot;<br><br># Example of computing resultant phase<br>z1 = sp.exp(sp.I * sp.pi / 6)<br>z2 = sp.exp(sp.I * sp.pi / 3)<br><br>&quot;&quot;&quot;<br>For example, if z_1 = e^(iπ/6) and z_2 = e^(iπ/3), their <br>arguments will help the agent compute the resultant phase.<br>&quot;&quot;&quot;<br><br># Argument in multi-class classification<br>&quot;&quot;&quot;<br>The argument is also used to select the correct sector on the <br>complex plane in multi-class classification.<br>&quot;&quot;&quot;<br><br># Example sector classification<br>&quot;&quot;&quot;<br>For instance, if arg(z) is between 0 and π/2, the output of the <br>neuron might be assigned to the first class.<br>&quot;&quot;&quot;<br><br># Summary of argument&#39;s importance<br>&quot;&quot;&quot;<br>Thus, the argument is a key tool in phase computations for weight <br>adjustment and phase control.<br>&quot;&quot;&quot;</pre><pre><br>7.The Riddle of Reflected Twins<br><br><br># 7. Complex Conjugate<br>z_conjugate = a - sp.I * b<br><br>&quot;&quot;&quot;<br>The complex conjugate z̅ = a - bi represents the reflection <br>of the complex number across the real axis on the complex plane.<br>&quot;&quot;&quot;<br><br># Example in reinforcement learning with Aizenberg neuron<br>&quot;&quot;&quot;<br>In complex reinforcement learning on the Aizenberg neuron, conjugation <br>is useful for computing weight adjustments: in the weight update formula <br>w_k^new = w_k^old + η (d - y) x_k*, the conjugate value of <br>the input x_k* is used.<br>&quot;&quot;&quot;<br><br># Example of input and its conjugate<br>x_k = 2 + 3 * sp.I<br>x_k_conjugate = 2 - 3 * sp.I<br><br>&quot;&quot;&quot;<br>For example, if x_k = 2 + 3i, then x_k* = 2 - 3i, which allows <br>for effective use of phase and amplitude differences to adjust weights.<br>&quot;&quot;&quot;<br><br># Role of conjugation in phase adjustment<br>&quot;&quot;&quot;<br>Conjugation helps the neuron account for phases opposite to that <br>of the input signal, which is important for adapting weights and <br>minimizing phase errors.<br>&quot;&quot;&quot;<br><br># Weight update using conjugate input<br>w_k = 1 + sp.I<br>w_k_new = w_k + sp.Symbol(&#39;eta&#39;) * (1 + sp.I) * x_k_conjugate<br><br>&quot;&quot;&quot;<br>If the weight w_k = 1 + i and the input x_k = 2 + 3i, the weight <br>update uses the conjugate of the input x_k* = 2 - 3i: <br>w_k^new = (1 + i) + η (1 + i)(2 - 3i).<br>&quot;&quot;&quot;<br><br># Calculating the norm using conjugate<br>norm = x_k * x_k_conjugate<br><br>&quot;&quot;&quot;<br>This allows for consideration of phase differences between input <br>signals and target values, improving weight adjustment at each <br>iteration of learning.<br>&quot;&quot;&quot;<br><br># Example of normalization<br>&quot;&quot;&quot;<br>The complex conjugate is also important for calculating the norm <br>of the complex number: |x_k|^2 = x_k x_k* = (2 + 3i)(2 - 3i) = 13,<br>which is used for normalizing input signals.<br>&quot;&quot;&quot;<br><br># Importance of normalization for stability<br>&quot;&quot;&quot;<br>Normalization based on the conjugate helps ensure the stability of <br>the Aizenberg neuron during training, especially when working with <br>phase data.<br>&quot;&quot;&quot;<br><br># Example with exponential input signal<br>x_k_exp = sp.exp(sp.I * sp.pi / 4)<br>x_k_conjugate_exp = sp.exp(-sp.I * sp.pi / 4)<br><br>&quot;&quot;&quot;<br>For instance, if the input signal x_k = e^(iπ/4), <br>its conjugate x_k* = e^(-iπ/4) is used to find the new weight <br>considering the phase.<br>&quot;&quot;&quot;<br><br># Summary of the importance of complex conjugation<br>&quot;&quot;&quot;<br>Thus, the complex conjugate is a key tool for working with <br>phase characteristics and adjusting weights in the Aizenberg neuron.<br>&quot;&quot;&quot;</pre><pre><br>8.The Golden Scroll of Truth<br><br><br># 8. Real Part<br>real_part = (z + (a - sp.I * b)) / 2<br><br>&quot;&quot;&quot;<br>The real part of the complex number z = a + bi is <br>defined as Re(z) = (z + z̅) / 2 = a.<br>&quot;&quot;&quot;<br><br># Interpretation in reinforcement learning<br>&quot;&quot;&quot;<br>In complex reinforcement learning, the real part can <br>interpret the real component of the agent&#39;s state or action.<br>&quot;&quot;&quot;<br><br># Example of weighted sum<br>example_z = 2 + 3 * sp.I<br>real_part_example = (example_z + (2 - 3 * sp.I)) / 2<br><br>&quot;&quot;&quot;<br>For example, for the weighted sum z = 2 + 3i, the real <br>part will be Re(z) = ((2 + 3i) + (2 - 3i)) / 2 = 2,<br>which may mean the contribution to the real axis on the complex plane.<br>&quot;&quot;&quot;<br><br># Usefulness of real part in separating components<br>&quot;&quot;&quot;<br>Using the real part is useful for separating real and <br>imaginary components in learning, simplifying the interpretation <br>of input signals and weighted sums.<br>&quot;&quot;&quot;<br><br># Weighted sum example<br>w1 = 1 + 2 * sp.I<br>x1 = 3 + 4 * sp.I<br>weighted_sum = w1 * x1<br>real_part_weighted_sum = (weighted_sum + (1 - 2 * sp.I) * (3 - 4 * sp.I)) / 2<br><br>&quot;&quot;&quot;<br>For example, in the weighted sum z = w1 x1, the data scientist <br>can compute the real part of the final sum to control the amplitude <br>of the signal.<br>&quot;&quot;&quot;<br><br># Real part for error evaluation<br>d = 1 + 0 * sp.I<br>y = 0 + sp.I<br>real_error = sp.re(d - y)<br><br>&quot;&quot;&quot;<br>If the weight w = 1 + 2i and the input x = 3 + 4i, then the real <br>part of their product z = w x = -5 + 10i will be Re(z) = -5.<br>&quot;&quot;&quot;<br><br># Importance of real part for interpreting errors<br>&quot;&quot;&quot;<br>The real part is also used to assess the impact of real values on phase error. <br>If d = 1 + 0i and y = 0 + i, the real error will be Re(d - y) = 1.<br>&quot;&quot;&quot;<br><br># Better interpretation of errors<br>&quot;&quot;&quot;<br>This allows the neuron to better interpret errors associated with <br>the real axis and adjust weights to minimize this error.<br>&quot;&quot;&quot;<br><br># Example of desired action<br>&quot;&quot;&quot;<br>For instance, if in reinforcement learning the desired action has <br>a phase close to 0, it is important to use the real part of the <br>weighted sum for proper control of the neuron output.<br>&quot;&quot;&quot;<br><br># Summary of the usefulness of the real part<br>&quot;&quot;&quot;<br>Thus, the real part helps analyze and control the real contribution <br>of input signals and weights in the complex learning model.<br>&quot;&quot;&quot;</pre><pre><br>9.The Gem of Invisible Vibrations<br><br><br># 9. Imaginary Part<br>imaginary_part = (z - (a - sp.I * b)) / (2 * sp.I)<br><br>&quot;&quot;&quot;<br>The imaginary part of the complex number z = a + bi is <br>defined as Im(z) = (z - z̅) / (2i) = b.<br>&quot;&quot;&quot;<br><br># Role of imaginary part in reinforcement learning<br>&quot;&quot;&quot;<br>In complex reinforcement learning, the imaginary part plays <br>a key role in managing the phase characteristics of the agent&#39;s <br>state or action.<br>&quot;&quot;&quot;<br><br># Example of weighted sum<br>example_z = 2 + 3 * sp.I<br>imaginary_part_example = (example_z - (2 - 3 * sp.I)) / (2 * sp.I)<br><br>&quot;&quot;&quot;<br>For example, for the weighted sum z = 2 + 3i, the imaginary <br>part will be Im(z) = ((2 + 3i) - (2 - 3i)) / (2i) = 3,<br>which encodes the phase component.<br>&quot;&quot;&quot;<br><br># Efficiency of imaginary part in phase data processing<br>&quot;&quot;&quot;<br>The imaginary part allows efficient processing of phase data, which <br>is crucial for managing multi-class classification in the Aizenberg neuron.<br>&quot;&quot;&quot;<br><br># Weighted product example<br>w = 1 + 2 * sp.I<br>x = 3 + 4 * sp.I<br>weighted_product = w * x<br>imaginary_part_weighted_product = sp.im(weighted_product)<br><br>&quot;&quot;&quot;<br>For instance, if the weight w = 1 + 2i and the input x = 3 + 4i, the <br>imaginary part of their product z = w x = -5 + 10i will be Im(z) = 10.<br>&quot;&quot;&quot;<br><br># Use of imaginary part in error correction<br>d = 0 + 1 * sp.I<br>y = 1 + 0 * sp.I<br>imaginary_error = sp.im(d - y)<br><br>&quot;&quot;&quot;<br>In reinforcement learning, the imaginary part of the error is used <br>to adjust the phase: if the desired output d = i and the current output y = 1,<br>the imaginary error will be Im(d - y) = 1.<br>&quot;&quot;&quot;<br><br># Correction of weights based on imaginary part<br>&quot;&quot;&quot;<br>Adjusting weights based on the imaginary part allows for minimizing <br>phase error, which is particularly important for models working with <br>the phases of input signals.<br>&quot;&quot;&quot;<br><br># Example with weighted sum of exponentials<br>weighted_sum_example = sp.exp(sp.I * sp.pi / 3) + sp.exp(sp.I * sp.pi / 4)<br>imaginary_part_final = sp.im(weighted_sum_example)<br><br>&quot;&quot;&quot;<br>For example, if the weighted sum z = e^{iπ/3} + e^{iπ/4}, the imaginary <br>part of the final value helps determine the phase sector for <br>neuron activation.<br>&quot;&quot;&quot;<br><br># Importance of imaginary part in learning<br>&quot;&quot;&quot;<br>During training, the imaginary part of the weighted sum or error <br>helps control and minimize phase deviations, ensuring the accuracy <br>of the output signal.<br>&quot;&quot;&quot;<br><br># Summary of the importance of the imaginary part<br>&quot;&quot;&quot;<br>Thus, the imaginary part serves as an essential tool for working <br>with phase characteristics in complex reinforcement learning, allowing <br>for more accurate weight adjustments and minimizing phase errors.<br>&quot;&quot;&quot;</pre><pre><br>10.The Unchanging Dance of the Blue Star<br><br><br># 10. Magnitude on the unit circle<br>magnitude_unit_circle = sp.Abs(sp.exp(sp.I * phi))<br><br>&quot;&quot;&quot;<br>The property of the unit circle is used to ensure that all complex <br>inputs x_k and weights w_k of the Aizenberg neuron have a magnitude of 1.<br>&quot;&quot;&quot;<br><br># Magnitude on the unit circle is always 1<br>magnitude_always_one = magnitude_unit_circle.simplify()<br><br>&quot;&quot;&quot;<br>The magnitude of a complex number on the unit circle is always <br>equal to 1, ensuring the stability of computations.<br>&quot;&quot;&quot;<br><br># Simplification for data scientists<br>&quot;&quot;&quot;<br>For the data scientist, this simplifies working with the phases of <br>inputs and weights, as there is no need to account for changes in <br>amplitudes, only phase shifts.<br>&quot;&quot;&quot;<br><br># Example of a complex input<br>example_x1 = sp.exp(sp.I * sp.pi / 4)<br>magnitude_x1 = sp.Abs(example_x1)<br><br>&quot;&quot;&quot;<br>For example, if x_1 = e^{iπ/4}, then its magnitude |x_1| = 1.<br>&quot;&quot;&quot;<br><br># Magnitude of the weighted sum<br>weighted_sum = sp.Sum(sp.symbols(&#39;w_k&#39;) * sp.symbols(&#39;x_k&#39;), (sp.symbols(&#39;k&#39;), 1, sp.symbols(&#39;n&#39;)))<br>magnitude_weighted_sum = sp.Abs(weighted_sum)<br><br>&quot;&quot;&quot;<br>The magnitude of the weighted sum z = Σ w_k x_k will also depend <br>only on the phase shifts between the components.<br>&quot;&quot;&quot;<br><br># Working directly with phase error<br>&quot;&quot;&quot;<br>In reinforcement learning, this allows for direct manipulation <br>of phase error without worrying about scaling values.<br>&quot;&quot;&quot;<br><br># Example with weighted sum<br>weighted_sum_example = sp.exp(sp.I * sp.pi / 3)<br>magnitude_example_sum = sp.Abs(weighted_sum_example)<br><br>&quot;&quot;&quot;<br>For example, let the weighted sum z = e^{iπ/3}, then |z| = 1, which <br>preserves the simplicity of calculations.<br>&quot;&quot;&quot;<br><br># Minimizing amplitude-related errors<br>&quot;&quot;&quot;<br>When training the agent based on complex values, this property minimizes <br>errors related to amplitude fluctuations.<br>&quot;&quot;&quot;<br><br># Importance of phases<br>&quot;&quot;&quot;<br>It is important that the phases of the signals remain key in the <br>learning process and are independent of their magnitude.<br>&quot;&quot;&quot;<br><br># Focus on phase characteristics<br>&quot;&quot;&quot;<br>Thus, the data scientist can focus on phase characteristics, which <br>is a fundamental aspect of working with complex numbers <br>in the Aizenberg neuron.<br>&quot;&quot;&quot;</pre><pre><br>11.The Song of the United Crystals<br><br><br># 11. Multiplication rule on the unit circle<br>multiplication_rule = sp.exp(sp.I * phi1) * sp.exp(sp.I * phi2)<br><br>&quot;&quot;&quot;<br>This rule is used to compute the weighted sum of inputs <br>of the Aizenberg neuron.<br>&quot;&quot;&quot;<br><br># Product of input and weight<br>product = sp.exp(sp.I * theta1) * sp.exp(sp.I * phi1)<br>simplified_product = product.simplify()<br><br>&quot;&quot;&quot;<br>If the input x_1 = e^{iφ₁} and the weight w_1 = e^{iθ₁}, then <br>their product w_1 x_1 = e^{i(θ₁ + φ₁)}.<br>&quot;&quot;&quot;<br><br># Reinforcement learning interaction<br>&quot;&quot;&quot;<br>In reinforcement tasks, multiplying phases allows for modeling the <br>interaction between the agent&#39;s state and action.<br>&quot;&quot;&quot;<br><br># Example with specific phases<br>example_phi1 = sp.pi / 4<br>example_theta1 = sp.pi / 6<br>example_product = sp.exp(sp.I * example_phi1) * sp.exp(sp.I * example_theta1)<br>simplified_example = example_product.simplify()<br><br>&quot;&quot;&quot;<br>For example, if φ₁ = π/4 and θ₁ = π/6, <br>then w_1 x_1 = e^{i(π/4 + π/6)} = e^{i 5π/12}.<br>&quot;&quot;&quot;<br><br># Weighted sum<br>weighted_sum = sp.Sum(sp.symbols(&#39;w_k&#39;) * sp.symbols(&#39;x_k&#39;), (sp.symbols(&#39;k&#39;), 1, sp.symbols(&#39;n&#39;)))<br>final_phase = sp.Add(sp.symbols(&#39;theta_k&#39;) + sp.symbols(&#39;phi_k&#39;), (sp.symbols(&#39;k&#39;), 1, sp.symbols(&#39;n&#39;)))<br><br>&quot;&quot;&quot;<br>For the weighted sum z = Σ w_k x_k, the phases of all <br>inputs and weights are summed, affecting the final phase.<br>&quot;&quot;&quot;<br><br># Efficient consideration of inputs<br>&quot;&quot;&quot;<br>This property allows for efficient consideration of the <br>influence of various inputs and weights in complex-valued learning.<br>&quot;&quot;&quot;<br><br># Updating weights<br>&quot;&quot;&quot;<br>When updating weights in reinforcement learning models, this <br>helps adjust the phase of the output signal.<br>&quot;&quot;&quot;<br><br># Weight adjustment based on error<br>error = sp.symbols(&#39;d&#39;) - sp.symbols(&#39;y&#39;)<br>phase_adjustment = sp.arg(error)<br><br>&quot;&quot;&quot;<br>For example, adjusting weights based on the error e = d - y will <br>also depend on the sum of the phases of the error and input signals.<br>&quot;&quot;&quot;<br><br># Importance in optimization methods<br>&quot;&quot;&quot;<br>This rule is also important when calculating gradient and non-gradient <br>optimization methods in phase space.<br>&quot;&quot;&quot;<br><br># Agent&#39;s action adjustment<br>&quot;&quot;&quot;<br>As a result, the agent is able to adjust its actions based on <br>phase changes in the environment.<br>&quot;&quot;&quot;</pre><pre><br>12.The Thirteen Crystals of Power<br><br><br># 12. Exponentiation rule on the unit circle<br>exponentiation_rule = (sp.exp(sp.I * phi))**n<br><br>&quot;&quot;&quot;<br>This rule is useful for modeling sequential phase shifts <br>during agent training.<br>&quot;&quot;&quot;<br><br># Cumulative phase modeling<br>cumulative_phase = sp.exp(sp.I * n * phi)<br><br>&quot;&quot;&quot;<br>If the agent repeats an action n times, the cumulative phase <br>can be modeled as (e^{iφ})^n = e^{inφ}.<br>&quot;&quot;&quot;<br><br># Example with specific values<br>example_phi = sp.pi / 3<br>example_n = 3<br>example_result = (sp.exp(sp.I * example_phi))**example_n<br><br>&quot;&quot;&quot;<br>For example, if φ = π/3 and n = 3, the <br>result is (e^{i π/3})^3 = e^{i π} = -1.<br>&quot;&quot;&quot;<br><br># Importance in reinforcement learning<br>&quot;&quot;&quot;<br>This is useful in reinforcement learning for accounting for <br>repeated actions and their impact on state phase.<br>&quot;&quot;&quot;<br><br># Agent&#39;s current state<br>&quot;&quot;&quot;<br>If the agent performs an action n times, its current state <br>will reflect the accumulated phase, which can be adjusted in training.<br>&quot;&quot;&quot;<br><br># Modeling behavioral inertia<br>&quot;&quot;&quot;<br>This also helps model the agent&#39;s behavioral inertia, where <br>the state phase changes over time.<br>&quot;&quot;&quot;<br><br># Example of phase shift<br>example_shift = sp.pi / 4<br>cumulative_shift_phase = example_shift * example_n<br><br>&quot;&quot;&quot;<br>For example, if each action shifts the phase by π/4, after n = 4 steps, <br>the state phase will be π.<br>&quot;&quot;&quot;<br><br># Phase response in Aizenberg neuron model<br>&quot;&quot;&quot;<br>In the Aizenberg neuron model, this property is used to compute <br>the phase response to repeated input signals.<br>&quot;&quot;&quot;<br><br># Control over phase dynamics<br>&quot;&quot;&quot;<br>For data scientists, this means the ability to control phase <br>dynamics at higher levels of abstraction.<br>&quot;&quot;&quot;<br><br># Optimization of agent behavior<br>&quot;&quot;&quot;<br>This helps optimize agent behavior in complex environments where <br>repeated actions can be critical.<br>&quot;&quot;&quot;</pre><pre><br>13.Return to the Origin <br><br><br># 13. Full rotation property<br>full_rotation_property = sp.exp(2 * sp.pi * sp.I)<br><br>&quot;&quot;&quot;<br>This property indicates that any complex number returns <br>to its original point on the unit circle after a full rotation.<br>&quot;&quot;&quot;<br><br># Application in reinforcement learning<br>&quot;&quot;&quot;<br>In reinforcement learning, this is used to account for <br>periodic phase changes in tasks with repeated states.<br>&quot;&quot;&quot;<br><br># Example of phase change<br>example_phase_change = 2 * sp.pi<br><br>&quot;&quot;&quot;<br>For example, if the phase of a state changes by 2π, the agent <br>returns to the initial state, which is important for cyclical tasks.<br>&quot;&quot;&quot;<br><br># Simplification for data scientists<br>&quot;&quot;&quot;<br>For data scientists, this means that phase changes can be <br>constrained to values from 0 to 2π, simplifying calculations.<br>&quot;&quot;&quot;<br><br># State after multiple actions<br>multiple_action_shift = 4 * sp.pi<br>new_state_equivalence = multiple_action_shift % (2 * sp.pi)<br><br>&quot;&quot;&quot;<br>For example, if the agent&#39;s state shifts by 4π after a series of <br>actions, its new state will be equivalent to 0.<br>&quot;&quot;&quot;<br><br># Importance in periodic feedback training<br>&quot;&quot;&quot;<br>This rule is also important when training with periodic feedback, <br>where the state returns to the initial one after a certain cycle.<br>&quot;&quot;&quot;<br><br># Cyclical actions effect<br>&quot;&quot;&quot;<br>If the agent performs cyclical actions, its phase state will <br>periodically return to the initial value.<br>&quot;&quot;&quot;<br><br># Modeling stable cyclic processes<br>&quot;&quot;&quot;<br>This allows modeling stable cyclic processes, such as circular <br>motions or repetitive tasks.<br>&quot;&quot;&quot;<br><br># Optimization of agent behavior<br>&quot;&quot;&quot;<br>For optimizing agent behavior, this helps account for recurring <br>phase changes and adjust neuron weights accordingly.<br>&quot;&quot;&quot;<br><br># Minimizing phase error<br>&quot;&quot;&quot;<br>Thus, full rotations help consider the periodicity of phases <br>in reinforcement learning, minimizing phase error.<br>&quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0jdeBMVgygLwzx8-WS4Uw.jpeg" /></figure><p>Deepen your knowledge in Derivative-Free Complex Valued Reinforcement Learning on the <a href="https://medium.com/@serhii.barskyi/aisenberg-neuron-in-complex-valued-reinforcement-learning-tasks-dc4a8f53cc1d">Aizenberg neuron</a> and have fun. Stay tuned for publications from the <a href="https://medium.com/@serhii.barskyi">Neuverso Academy</a> — a new issue from the series “Math-Fiction Fairy Tales for Junior Data Scientists” is coming your way.</p><p><strong>For one-on-one tutoring on machine Reinforcement Learning topics, please, contact: </strong><a href="https://neuverso.ai/"><strong>https://neuverso.ai/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e594277c7b71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex Valued Q-learning. Car problem.]]></title>
            <link>https://medium.com/@serhii.barskyi/complex-valued-q-learning-car-problem-393a25026520?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/393a25026520</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[serhii-barskyi]]></category>
            <category><![CDATA[complex-valued-q-learning]]></category>
            <category><![CDATA[q-learning-algorithm]]></category>
            <category><![CDATA[neuverso]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 02:06:38 GMT</pubDate>
            <atom:updated>2026-05-02T07:36:05.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXL2MI5yWKhpPsUhW6YnSQ.png" /></figure><p>The creative RL-modeling studio of the <a href="https://neuverso.ai/">Neuverso Academy</a> is pleased to welcome you to the next lesson of the <a href="https://medium.com/@serhii.barskyi/complex-valued-reinforcement-learning-course-cfeb937bedc5">Complex Valued Reinforcement Learning course</a>.</p><p>My Data Science Course <a href="https://preply.com/en/tutor/7756455">https://preply.com/en/tutor/7756455</a></p><p><strong>The full code of the lesson can be downloaded </strong><a href="https://github.com/Serhii-Barskyi/Complex-Valued-Reinforcement-Learning-course/blob/main/Complex_valued_Q_learning_Car_problem.ipynb"><strong>here</strong></a>.</p><p>Complex-valued reinforcement learning (in this case, Complex-Valued Q-learning) represents an exciting direction in artificial intelligence that expands traditional approaches to learning using complex numbers. In this lesson, we will explore how the application of complex numbers enables more effective modeling of complex systems, such as vehicle control on various road surfaces. Unlike standard reinforcement learning, where states and actions are represented by real numbers, we will use complex numbers, allowing for better consideration of the relationships between vehicle state parameters, such as speed and direction.</p><blockquote>The importance of this approach lies in the fact that each vehicle state can be described by a complex number, where the real part represents speed, and the imaginary part represents the steering angle. Thus, the agent will be able to make more informed decisions based on rich information about the current state. For instance, when driving on wet or icy roads, not only the basic motion parameters are taken into account, but also the impact of road conditions on traction.</blockquote><blockquote>During training, our agent will interact with the environment, receiving rewards for correct actions and penalties for deviations from optimal motion parameters. We will examine how to use complex values to represent states and actions, as well as how to update Q-values according to phase components. The phase information used in updating Q-values will allow the agent to adapt more precisely to changing road conditions.</blockquote><p>A key element of our study will be examining the role of the phase function, which will adjust Q-values based on the state of the environment. We will also analyze how actions are selected based on the complex representation, ensuring higher efficiency and stability in learning. This lesson aims to deepen the understanding of how complex-valued representation can enhance the learning and decision-making processes in complex situations, such as driving a vehicle in various road conditions.</p><h3><strong>Car Control with Complex States and Actions</strong></h3><p>We will consider car control in various road conditions, such as dry, wet, and icy roads. The task is to teach the car to respond appropriately to changes in road situations by using complex numbers to describe the car’s state and its actions.</p><p><strong>What is the state in the car control task?</strong></p><p>The state of the car can be represented as a complex number. The real part of this number will represent the car’s speed, while the imaginary part will represent its direction of movement. This allows for a more accurate understanding of how the car behaves on different surfaces.</p><p><strong>Complex Representation of the Car State</strong></p><p>The real part of the complex number describes the car’s speed (e.g., 60 km/h), while the imaginary part indicates the angle at which it is moving (e.g., 15 degrees). An example of the state can be expressed as:</p><pre>state = speed + 1j * angle</pre><p><strong>What is the action in the car control task?</strong></p><p>The car’s actions are also modeled using complex numbers. Changes in the real part of the number correspond to changes in speed, while changes in the imaginary part correspond to changes in the steering angle. This helps us flexibly manage the car’s behavior.</p><p><strong>How do actions change the state?</strong></p><p>When the car performs an action, its state changes. For example, the new speed can be calculated as:</p><pre>new_speed = old_speed + action.real</pre><p>and the new angle as:</p><pre>new_angle = old_angle + action.imag</pre><p>This allows the car to adapt to changing road conditions.</p><h3>Class ComplexEnvironment - Defining the Environment</h3><p>We will create a class named ComplexEnvironment to model the environment in which an agent controls a car.</p><pre>import numpy as np<br><br>class ComplexEnvironment:<br>    def __init__(self):<br>        self.max_speed = 120  # Maximum speed of the car in km/h<br>        self.max_angle = np.pi / 4  # Maximum turning angle in radians<br>        self.road_conditions = [&#39;dry&#39;, &#39;wet&#39;, &#39;icy&#39;]  # Possible road conditions<br>        self.reset()  # Initialize the environment&#39;s state</pre><ul><li><strong>Creating the Class</strong>: We define a class ComplexEnvironment to encapsulate the environment&#39;s properties and behaviors.</li><li><strong>__init__ Method</strong>: This method initializes the environment&#39;s parameters:</li><li>max_speed: The maximum speed of the car is set to 120 km/h.</li><li>max_angle: The maximum turning angle is set to ±π/4 radians.</li><li>road_conditions: A list of possible road conditions: dry, wet, and icy.</li><li>reset(): This method initializes the environment&#39;s state, setting speed, angle, and road conditions.</li></ul><p>Make sure to implement the reset() method to set the initial state of the environment!</p><h3><strong>Speed and Angle Constraints for the Car</strong></h3><p>The speed of the car is limited to a range from 0 to 120 km/h. This means that the car cannot go faster than 120 km/h or slower than 0 km/h (which corresponds to a complete stop).<br>The steering angle of the car is restricted to values between -np.pi/4 and np.pi/4. This indicates that the car can only turn within a 45-degree range in either direction.</p><p><strong>Objective of the Task — Optimizing Car Movement</strong></p><p>The agent’s task is to learn how to control the car in such a way as to minimize the deviation from optimal speed and angle values. This means that the agent should aim to keep the speed close to the ideal value (e.g., 60 km/h) and the steering angle close to zero (moving straight).</p><p><strong>Agent’s Learning Task</strong></p><p>The agent will use reinforcement learning to solve its task. This means that it will receive rewards or penalties depending on how well it controls the car. The closer it gets to the optimal values, the more rewards it will receive.</p><p><strong>Environment Parameters</strong></p><p>The environment consists of three different road surface states: dry, wet, and icy. Each of these states affects how the car behaves on the road, particularly its slip coefficient.</p><p><strong>Importance of the Slip Coefficient</strong></p><p>The imaginary part of the state accounts for how the car slips on different surfaces. The slip coefficient depends on the road condition; for example, it will be high on ice, making car control more challenging, while it will be low on dry asphalt.</p><p><strong>Function of reset() — How the Agent Starts an Episode</strong></p><p>The reset() function is called at the beginning of each episode. It randomly initializes the car&#39;s speed, steering angle, and road conditions. This enables the agent to train in various scenarios and adapt to different driving conditions.</p><h3>Method reset - Initializing the Initial State</h3><p>We will define the reset method to initialize the car&#39;s initial state in the environment.</p><pre>def reset(self):<br>    self.speed = np.random.uniform(30, 90)  # Initial speed closer to 60 km/h<br>    self.angle = np.random.uniform(-np.pi/8, np.pi/8)  # Initial angle closer to 0 radians<br>    self.road_condition = np.random.choice(self.road_conditions)  # Randomly choose road condition<br>    return self.get_complex_state()  # Return the complex state of the car</pre><ul><li><strong>Defining the </strong><strong>reset Method</strong>: This method initializes the car&#39;s state every time it&#39;s called.</li><li><strong>Speed Initialization</strong>: The speed is set randomly between 30 and 90 km/h, ensuring it starts closer to 60 km/h on average.</li><li><strong>Angle Initialization</strong>: The angle is selected randomly within the range of [-π/8, π/8] radians, allowing for a slight deviation from straight driving.</li><li><strong>Road Condition Selection</strong>: A random road condition is chosen from the available options: dry, wet, or icy.</li><li><strong>Returning Complex State</strong>: The method calls get_complex_state() to return the current complex state of the car, which likely includes speed, angle, and road condition.</li></ul><h3><strong>Method get_complex_state()</strong></h3><p>This method transforms the physical state of the car, represented by speed and angle, into a complex representation. The speed will be the real part of the complex number, while the angle will be the imaginary part. For example, if the speed is 80 km/h and the angle is 15 degrees, the complex state will look like:</p><pre>complex_state = 80 + 15j</pre><p>This allows for a more efficient representation of the car’s state in the context of complex-valued learning.</p><p><strong>Method step() — How do the agent’s actions change the state?</strong></p><p>The step() method manages the change in the car&#39;s state based on the agent&#39;s action. The action is represented as a complex number: the real part corresponds to the change in speed, while the imaginary part corresponds to the change in angle. When the agent performs an action, the speed and angle are updated as follows:</p><pre>new_speed = current_speed + action.real<br>new_angle = current_angle + action.imag</pre><p>This allows the agent to change the car’s state, taking both speed and angle into account in a single action.</p><p><strong>Method calculate_reward() — How does the agent receive a reward?</strong></p><p>The reward that the agent receives depends on the current speed, angle, and skid coefficient. The optimal speed is set at 60 km/h, and the optimal angle is 0. The reward is calculated with penalties for deviations from these values:</p><ul><li><strong>Penalty for Speed:</strong></li></ul><pre>speed_reward = 1 - abs(speed - 60) / 60</pre><p>This value will be close to 1 if the speed is near 60, and it will approach 0 if the speed deviates significantly from 60.</p><ul><li><strong>Penalty for Angle:</strong></li></ul><pre>angle_reward = 1 - abs(angle) / (π / 4)</pre><p>This penalty will also be high if the angle is close to 0 and will decrease as the angle increases.</p><p><strong>Penalty for the Car’s Skid</strong></p><p>The skid coefficient is introduced as an additional component in the reward calculation. It accounts for how road conditions affect car control. For example, the skid penalty can be calculated as follows:</p><pre>skid_penalty = - (action.imag / action.real)</pre><p>This means that with a high skid coefficient, the agent will receive fewer rewards, encouraging it to avoid situations where skidding significantly impacts control.</p><p><strong>Complex-Valued Q-Learning: How is the complex representation of states and actions used?</strong></p><p>In this approach, each state and action now has a complex Q-value. This allows for efficient management of complex dynamic systems. The Q-table will contain values that are complex numbers, where the real part corresponds to the expected reward value, while the imaginary part can reflect additional information, such as uncertainty or the influence of external factors. Thus, the agent can learn more accurately and make decisions based on a complex assessment of its actions and states.</p><h3>Method get_complex_state - Transforming State into Complex Form</h3><p>We will define the get_complex_state method to represent the car&#39;s state as a complex number.</p><pre>def get_complex_state(self):<br>    if self.road_condition == &#39;dry&#39;:<br>        skid_factor = np.random.uniform(0, 0.1)  # Minimal skid factor for dry road<br>    elif self.road_condition == &#39;wet&#39;:<br>        skid_factor = np.random.uniform(0.1, 0.5)  # Medium skid factor for wet road<br>    else:  # icy<br>        skid_factor = np.random.uniform(0.5, 1.0)  # High skid factor for icy road<br>    <br>    # Represent the state as a complex number<br>    return complex(self.speed * np.cos(self.angle), self.speed * np.sin(self.angle)) * (1 + 1j * skid_factor)</pre><p><strong>Defining the </strong><strong>get_complex_state Method</strong>: This method converts the car&#39;s physical state into a complex number format.</p><p><strong>Skid Factor Calculation</strong>: The skid factor varies based on the road condition:</p><ul><li><strong>Dry Road</strong>: A skid factor close to 0 indicates minimal slipping.</li><li><strong>Wet Road</strong>: A moderate skid factor models the increased risk of slipping.</li><li><strong>Icy Road</strong>: A high skid factor represents significant slipping potential.</li></ul><p><strong>Complex Number Representation</strong>: The state is represented as a complex number:</p><ul><li>The <strong>real part</strong> corresponds to the car’s speed and direction, calculated using cosine for the x-component.</li><li>The <strong>imaginary part</strong> incorporates the speed’s sine for the y-component and the skid factor, representing the impact of the road condition on the car’s handling.</li></ul><p><strong>Returning the Complex State</strong>: The method returns the complex state that accounts for both the car’s movement and the effects of skidding.</p><h3><strong>Structure of the Q-Table for Complex-Valued Q-Learning</strong></h3><p>The Q-table stores complex Q-values for each “state-action” pair. Each element of the Q-table represents a complex number that reflects the expected reward for performing a specific action in a given state. The structure of the Q-table can be represented as:</p><pre>Q(s, a) = r + action.imag</pre><p>Complex values allow for the consideration of both real and imaginary parts, which helps in complex situations involving uncertainty.</p><p><strong>Updating the Q-Table Considering Phase Information</strong></p><p>When updating the Q-table, it is important to consider not only the received reward but also the phase information that may influence the expected reward in the future. The phase in this context adds an additional component that allows the agent to better adapt to changing conditions, such as alterations in road conditions or time of day.</p><p><strong>Phase Shift as an Additional Learning Component</strong></p><p>A phase function is introduced that adjusts the Q-values based on road conditions and time:</p><pre>phase_adjustment = exp(1j * θ)</pre><p>The parameter θ depends on time and road state, allowing for the consideration of the dynamic influence of these factors on the agent’s behavior.</p><p><strong>Why Use a Phase Function?</strong></p><p>The phase adds additional information about state changes, helping the agent make more informed decisions under uncertainty. This is particularly useful in situations where road conditions can change rapidly (e.g., changes in road surface conditions), and the agent needs to adapt quickly.</p><p><strong>Standard Q-Learning: Basic Formula for Updating Q-Values</strong></p><p>In standard Q-learning, the update of Q-values is carried out using the following formula:</p><pre>Q(s, a) = (1 - α) * Q(s, a) + α * (r + γ * max(Q(s&#39;, a&#39;)))</pre><p>Here, α is the learning rate, γ is the discount factor, and r is the reward received by the agent for performing the action.</p><p><strong>Complex-Valued Q-Learning: How Are Complex Q-Values Updated?</strong></p><p>In complex-valued Q-learning, a similar update formula is used, but with the addition of the phase component:</p><pre>Q(s, a) = (1 - α) * Q(s, a) + α * (r + γ * max(Q(s&#39;, a&#39;)) * phase_adjustment)</pre><p>This allows for updating Q-values while considering both the real part (reward) and the imaginary part (phase), making the system more adaptive.</p><p><strong>Difference in Updating Q-Values: Standard vs. Complex-Valued Q-Learning</strong></p><p>In standard Q-learning, only real values are used, which limits learning capabilities under uncertainty. In complex-valued Q-learning, the phase adjusts the Q-values by adding the imaginary part, expanding the learning and adaptation capabilities of the agent to dynamic changes in the environment.</p><h3>Method step - Changing State in Response to Agent&#39;s Action</h3><p>We will define the step method to update the car&#39;s state based on the agent&#39;s action.</p><pre>def step(self, action):<br>    # Action is now a complex number, with the real part as speed change and the imaginary part as angle change<br>    self.speed += action.real  # Update speed using the real part of the action<br>    self.angle += action.imag  # Update angle using the imaginary part of the action<br><br>    # Clipping values to stay within limits<br>    self.speed = np.clip(self.speed, 0, self.max_speed)  # Ensure speed doesn&#39;t exceed max_speed<br>    self.angle = np.clip(self.angle, -self.max_angle, self.max_angle)  # Ensure angle is within bounds<br><br>    # Calculate reward<br>    reward = self.calculate_reward()  # Calculate reward based on the new state<br><br>    return self.get_complex_state(), reward  # Return the new state and the reward</pre><p><strong>Defining the </strong><strong>step Method</strong>: This method processes the agent&#39;s action to modify the car&#39;s state within the environment.</p><p><strong>Action as a Complex Number</strong>: The action is represented as a complex number:</p><ul><li>The <strong>real part</strong> represents the change in speed.</li><li>The <strong>imaginary part</strong> represents the change in the turning angle.</li></ul><p><strong>Updating State</strong>: The car’s speed and angle are updated based on the action provided by the agent.</p><p><strong>Clipping Values</strong>: The updated speed and angle are constrained:</p><ul><li>np.clip ensures the speed remains between 0 and the maximum speed.</li><li>It also constrains the angle within the defined maximum turning angle.</li></ul><p><strong>Calculating Reward</strong>: The method computes the reward by calling calculate_reward(), which evaluates the current state.</p><p><strong>Returning New State and Reward</strong>: The method returns the new complex state of the car and the computed reward, allowing the agent to assess its performance.</p><h3><strong>How Action Is Selected in Standard Q-Learning</strong></h3><p>In standard Q-learning, the agent selects the action with the highest Q-value for the current state:</p><pre>a* = argmax_a(Q(s, a))</pre><p>This means that the agent focuses on the action that maximizes the expected reward based on the values in the Q-table.</p><p><strong>How Action Is Selected in Complex-Valued Q-Learning</strong></p><p>In complex-valued Q-learning, the action selection is based on phase consistency:</p><pre>a* = argmax_a(Re(Q(s, a) * phase_adjustment))</pre><p>Here, the agent chooses the action with the highest real part of the complex Q-value multiplied by the phase function, allowing for consideration of dynamic changes in the state of the environment.</p><p><strong>Mathematical Difference: Working with Phase in Complex-Valued Q-Learning</strong></p><p>In standard Q-learning, only the numerical Q value is considered:</p><pre>Q(s, a) ∈ R</pre><p>In complex-valued Q-learning, both the modulus and the phase of the complex number are considered:</p><pre>Q(s, a) ∈ C</pre><p>This enables the agent to adapt to various situations by taking into account not only the magnitude of the Q-values but also their phase.</p><p><strong>How the Phase Function Acts in Complex-Valued Q-Learning</strong></p><p>The phase function adjusts the action selection based on road conditions:</p><ul><li>A specific phase is used for dry roads.</li><li>A different phase is used for wet roads.</li><li>A third phase is used for icy roads.</li></ul><p>This allows the agent to make more accurate decisions depending on the conditions.</p><p><strong>Method choose_action() — How the Agent Selects an Action with Phase Information</strong></p><p>The agent selects the action that is most consistent with the phase of the current state:</p><pre>a* = argmax_a(Re(Q(s, a) * phase_adjustment))</pre><p>This considers both the magnitude of the expected reward and the phase information, making the selection process more robust to changes in the environment.</p><p><strong>How the Agent Updates the Phase</strong></p><p>The phase is updated at each step based on time and road conditions:</p><pre>R_t = (1 / N) * ∑ Q(s, a) * phase_adjustment</pre><p>Here, N is the number of actions being considered by the agent, and Rt​ represents the average reward taking the phase function into account.</p><p><strong>Mathematical Structure of the Phase Function</strong></p><p>The phase function is based on the exponential representation of complex numbers:</p><pre>phase_adjustment = exp(1j * θ)</pre><p>The parameter θ depends on road conditions and time, allowing the agent to adapt to changing conditions on the road.</p><h3>Method calculate_reward - Reward Calculation</h3><p>We will define the calculate_reward method to evaluate the reward based on the car&#39;s current state.</p><pre>def calculate_reward(self):<br>    state = self.get_complex_state()  # Get the current complex state<br>    speed = np.abs(state)  # Calculate speed as the magnitude of the complex number<br>    angle = np.angle(state)  # Extract the angle from the complex number<br>    real_part = np.real(state)  # Get the real part representing speed<br>    imag_part = np.imag(state)  # Get the imaginary part representing angle and skid<br><br>    # Calculate skid factor<br>    if abs(real_part) &lt; 1e-5:<br>        skid_factor = 0  # No skid if speed is close to zero<br>    else:<br>        skid_factor = imag_part / real_part  # Determine the skid factor<br><br>    # Optimal speed and angle rewards<br>    speed_reward = 1 - abs(speed - 60) / 60  # Normalized reward for speed<br>    angle_reward = 1 - abs(angle) / (np.pi / 4)  # Reward for minimizing angle deviation<br>    skid_penalty = -skid_factor  # Penalty for skidding<br><br>    # Total reward calculation<br>    total_reward = speed_reward + angle_reward + skid_penalty<br><br>    return total_reward  # Return the total reward</pre><p><strong>Defining the </strong><strong>calculate_reward Method</strong>: This method calculates the reward based on the car&#39;s current state.</p><p><strong>Current State Retrieval</strong>: It calls get_complex_state() to retrieve the current state of the car as a complex number.</p><p><strong>Calculating Speed and Angle</strong>:</p><ul><li><strong>Speed</strong>: The magnitude of the complex number represents the speed of the car.</li><li><strong>Angle</strong>: The angle is extracted from the complex number representation.</li><li>The real part corresponds to speed, while the imaginary part is linked to the angle and skid factor.</li></ul><p><strong>Skid Factor Calculation</strong>: The skid factor is computed to determine the impact of the road condition:</p><ul><li>If the speed is near zero, the skid factor is set to 0.</li><li>Otherwise, it is calculated as the ratio of the imaginary part (angle and skid) to the real part (speed).</li></ul><p><strong>Reward Components</strong>:</p><ul><li><strong>Speed Reward</strong>: Encourages maintaining a speed close to the optimal value of 60 km/h.</li><li><strong>Angle Reward</strong>: Rewards minimal deviation from straight driving (angle of 0).</li><li><strong>Skid Penalty</strong>: Applies a penalty based on the skid factor, discouraging skidding.</li></ul><p><strong>Total Reward Calculation</strong>: The total reward is the sum of the speed reward, angle reward, and skid penalty.</p><p><strong>Returning Total Reward</strong>: The method returns the calculated total reward, which the agent will use to adjust its actions.</p><h3><strong>Example of Phase Function for Dry Road</strong></h3><p>For a dry road, the phase shift can be minimal, as the grip on the road is good:</p><pre>phase_adjustment = exp(1j * (π / 6) * t)</pre><p>This value allows the agent to make decisions with minimal adjustments, corresponding to conditions of good traction.</p><p><strong>Example of Phase Function for Wet Road</strong></p><p>For a wet road, the phase shift increases due to reduced grip:</p><pre>phase_adjustment = exp(1j * (π / 4) * t)</pre><p>The increased shift allows the agent to consider the possibility of slipping and adapt its actions accordingly.</p><p><strong>Example of Phase Function for Icy Road</strong></p><p>For an icy road, the maximum phase shift is used, as the grip is extremely low:</p><pre>phase_adjustment = exp(1j * (π / 3) * t)</pre><p>This value helps the agent adapt more accurately to conditions where controlling the vehicle becomes challenging.</p><p><strong>How the Agent Learns</strong></p><p>The agent updates the Q-values at each step, taking into account both the reward for actions and the phase information:</p><pre>Q(s, a) ← (1 - α) * Q(s, a) + α * (r + γ * max_a Q(s&#39;, a&#39;) * phase_adjustment)</pre><p><strong>Method update_q_value() — How the Agent Updates Q-Values?</strong></p><p>Updating Q-values occurs while considering phase information and the reward obtained for actions. The update formula includes the phase component, allowing adjustments based on road conditions.</p><p><strong>Analysis of Phase Correction Component in Q-Values</strong></p><p>The phase adds an additional level of information that influences the choice of optimal action. It adjusts the agent’s strategy, enabling it to consider not only the magnitude of Q-values but also their phase, which is especially important in uncertain conditions.</p><p><strong>Implementation of State Discretization</strong></p><p>In the method discretize_state(), the state of the vehicle is transformed into indices for the Q-table to simplify handling continuous values:</p><pre>index = round(speed / 10) + round(angle / (π / 4)) * max_speed_index</pre><p>This organizes access to the Q-table values.</p><p><strong>Implementation of Action Discretization</strong></p><p>The method discretize_action() is used to convert an action into indices for the Q-table, allowing the agent to select actions from a finite set:</p><pre>action_index = round(change_speed / 10) + round(change_angle / (π / 8)) * max_action_index</pre><p><strong>Learning Parameters: Learning Rate and Discount Factor</strong></p><p>The parameters α and γ play an important role in the learning process:</p><ul><li>α (learning rate) determines how quickly the agent updates its Q-values based on new data.</li><li>γ (discount factor) determines how much the agent values future rewards compared to immediate ones.</li></ul><p><strong>Heuristic for Choosing Parameters for the Vehicle Task</strong></p><p>Justification for choosing parameters α=0.1 and γ=0.9 for this task:</p><ul><li>A low value of α (0.1) allows the agent to cautiously adapt to changes, which is particularly important in situations where an action may have a long-term impact.</li><li>A high value of γ (0.9) indicates that the agent values future rewards, which is important for achieving long-term goals such as safe and efficient vehicle control.</li></ul><h3>Class ComplexQLearning - Main Agent with Complex Q-Values</h3><p>We will define the ComplexQLearning class, which implements a Q-learning agent using complex values.</p><pre>class ComplexQLearning:<br>    def __init__(self, state_dim, action_dim, learning_rate=0.1, discount_factor=0.9):<br>        self.state_dim = state_dim  # Number of dimensions for the state space<br>        self.action_dim = action_dim  # Number of dimensions for the action space<br>        self.learning_rate = learning_rate  # Learning rate for the Q-learning algorithm<br>        self.discount_factor = discount_factor  # Discount factor for future rewards<br>        self.q_table = np.zeros(state_dim + action_dim, dtype=complex)  # Q-table initialized with complex numbers<br>        self.R_t = complex(1, 0)  # Initial value for R_t, representing a phase component</pre><p><strong>Defining the </strong><strong>ComplexQLearning Class</strong>: This class represents the Q-learning agent that utilizes complex Q-values for learning.</p><p><strong>Constructor Parameters</strong>:</p><ul><li>state_dim: Defines the dimensions of the state space, determining how many unique states the agent can encounter.</li><li>action_dim: Defines the dimensions of the action space, determining how many unique actions the agent can take.</li><li>learning_rate: A parameter that controls how much new information overrides the old information in the Q-table.</li><li>discount_factor: This parameter represents the importance of future rewards; it influences how much the agent values immediate rewards versus future rewards.</li></ul><p><strong>Q-Table Initialization</strong>: The Q-table is initialized with complex zeros, allowing the agent to store complex Q-values for each state-action pair.</p><p><strong>R_t Initialization</strong>: R_t is initialized as a complex number (1 + 0j), representing the phase component that will be updated during the learning process.</p><h3><strong>Exploration Strategy: ϵ-Greedy Method</strong></h3><p>The ϵ-greedy method is a strategy used by the agent to explore the environment, allowing it to balance between exploring new actions and exploiting known ones.</p><p><strong>Using the ϵ-Greedy Method to Explore the Environment</strong></p><p>In the ϵ-greedy strategy, the agent randomly selects an action with a probability of ϵ (exploration) and selects the action with the highest Q-value with a probability of 1−ϵ(exploitation). This helps to avoid local minima and promotes finding the optimal strategy.</p><p><strong>Value of the ϵ Parameter for Exploring the Environment</strong></p><p>The initial value of ϵ can be set high to ensure significant exploration during the early stages of learning. As the agent learns, the probability of taking random actions should decrease, allowing a focus on exploitation actions.</p><p><strong>Smooth Decay of ϵ</strong></p><p>Mathematical formula for decay:</p><pre>ϵ = ϵ_start × ϵ_decay^t</pre><p>Here, ϵ_start​ is the initial value of ϵ, ϵ_decay​ is the decay factor (less than 1), and t is the current episode number. This allows the agent to gradually reduce the level of randomness in its actions.</p><p><strong>How Decay of ϵ Affects Learning?</strong></p><p>Decay of ϵ affects the balance between exploration and exploitation. At the beginning of training, the agent actively explores the environment, but as knowledge accumulates, it begins to select more optimal actions, enhancing its efficiency.</p><p><strong>Method train_agent() — How Does the Training Process Work?</strong></p><p>The training process includes a loop where the agent interacts with the environment, selects actions, receives rewards, and updates its Q-values:</p><p>For each episode:</p><ul><li>The state is initialized.</li><li>Inside the loop:</li></ul><p>- An action is chosen considering the ϵ-greedy method.</p><p>- The action is executed, and a new reward is obtained.</p><p>- The Q-values are updated, taking phase information into account.</p><ul><li>The final reward for the episode is recorded.</li></ul><p><strong>Training Episodes and Rewards</strong></p><p>The final reward for each episode is calculated as the sum of all rewards obtained by the agent throughout that episode. This allows for assessing how successfully the agent acted in that situation.</p><p><strong>Method visualize_q_values() — Visualization of Q-Values</strong></p><p>Graphical representation of complex Q-values allows for analyzing the learning process. Graphs can be plotted to show changes in amplitude and phase of Q-values as the agent learns.</p><p><strong>Analysis of Q-Values: Magnitude and Phase</strong></p><p>Visualizing the amplitude and phase of Q-values for different states helps understand how the agent evaluates its actions in various conditions. The phase plays an important role in adjusting the agent’s strategy, especially under uncertainty, as it helps the agent adapt to changing conditions.</p><p><strong>Importance of Phase Analysis in Q-Values</strong></p><p>Analyzing the phase allows the agent to make more informed decisions. For instance, if the phase indicates high risk, the agent may opt for safer actions, even if they lead to lower rewards.</p><h3>Method phase_function - Impact of Road Conditions on Phase</h3><p>We will define the phase_function method to calculate the phase based on road conditions and time.</p><pre>def phase_function(self, t, road_condition):<br>    if road_condition == &#39;dry&#39;:<br>        return np.exp(1j * (np.pi / 6 * t + np.sin(t / 10)))  # Phase function for dry conditions<br>    elif road_condition == &#39;wet&#39;:<br>        return np.exp(1j * (np.pi / 4 * t + np.sin(t / 8)))  # Phase function for wet conditions<br>    else:  # icy<br>        return np.exp(1j * (np.pi / 3 * t + np.sin(t / 6)))  # Phase function for icy conditions</pre><p><strong>Defining the </strong><strong>phase_function Method</strong>: This method calculates the phase based on the road conditions and time.</p><p><strong>Parameters</strong>:</p><ul><li>t: Represents time, which influences the phase calculation.</li><li>road_condition: Indicates the current condition of the road (e.g., &#39;dry&#39;, &#39;wet&#39;, &#39;icy&#39;).</li></ul><p><strong>Phase Calculation</strong>:</p><ul><li><strong>Dry Condition</strong>: For dry roads, the phase function is calculated with a lower angular frequency, resulting in less phase shift.</li><li><strong>Wet Condition</strong>: For wet roads, the angular frequency is slightly higher, resulting in a moderate phase shift.</li><li><strong>Icy Condition</strong>: For icy roads, the phase shift is greater due to a higher angular frequency, representing the more challenging driving conditions.</li></ul><p><strong>Return Value</strong>: The method returns the calculated phase as a complex exponential, which incorporates both the time-dependent and road condition-dependent components, used to adjust the Q-values based on road conditions.</p><h3><strong>Visualization of Phase Coherence</strong></h3><p>Graphical representation of phase coherence allows understanding how synchronized the phases of various actions are for a given state. This can aid in visualizing the relationship between the state of the vehicle and the selected actions.</p><p><strong>Method analyze_phase_coherence() — How is Phase Coherence Analyzed?</strong></p><p>In this method, the agent calculates phase coherence using a formula to determine how aligned the phases of various actions are with each other and with the state. This is important for identifying preferred actions that consider both the state and the reality of the environment.</p><p><strong>How is Phase Coherence Calculated and Why is it Important for Complex Q-Learning?</strong></p><p>Phase coherence is computed using the formula:</p><pre>phase_coherence = |(1/N) * Σ exp(i × (θ - mean_phase))|</pre><p>Here, N is the number of actions, and mean_phase is the average phase for the given state. The significance lies in the fact that high coherence indicates the alignment of actions, allowing the agent to make more optimal choices.</p><p><strong>How Does Phase Coherence Affect Action Selection?</strong></p><p>The agent selects actions that have high phase coherence with the current state, enabling it to avoid suboptimal or risky actions.</p><p><strong>Example of Phase Coherence Output for a Specific State</strong></p><p>Analyzing phase coherence for a selected state helps determine how well the actions align with the phase. For instance, if coherence is low, it may indicate that the agent is facing uncertainty, which necessitates more cautious action selection.</p><p><strong>Importance of Complex Numbers in Car Control Tasks</strong></p><p>The use of complex numbers allows for more effective modeling of complex states, such as the speed and steering angle of the car, by combining them into a single complex representation.</p><p><strong>Why is the Imaginary Part of the State Important?</strong></p><p>The imaginary part of the state can reflect parameters such as slip or inertia, which are critical for training the agent in various road conditions and help better manage the vehicle’s dynamics.</p><h3><strong>Advantages of CVQ-learning over regular Q-learning</strong></h3><p><strong>Consideration of complex states</strong>:</p><p>CVQ-learning can effectively represent complex states, such as the speed and steering angle of a car, as complex numbers. This allows for a more accurate modeling of the interactions between parameters, which is crucial for tasks related to vehicle control on various road surfaces. In regular Q-learning, such aspects are represented only through real numbers, which may limit the understanding of the relationships between parameters.</p><p><strong>Better representation of uncertainty</strong>:</p><p>complex numbers allow for a better consideration of uncertainty associated with changing road conditions (e.g., wet or icy roads). The imaginary part can reflect additional parameters, such as the friction coefficient, providing the agent with a more complete view of the state. In regular Q-learning, this information may be overlooked.</p><p><strong>Phase information</strong>:</p><p>in CVQ-learning, the use of phase information enables the agent to adjust its actions based on the environmental state. For example, depending on the phase shift, the agent can adapt its strategy if road conditions change. Regular Q-learning lacks a similar mechanism, making it less flexible in dynamic conditions.</p><p><strong>Improved action sampling</strong>:</p><p>in CVQ-learning, the agent selects actions based not only on the magnitude of Q-values but also on their phase characteristics. This allows for consideration of how the state influences the action in the context of current conditions. In regular Q-learning, action selection is based solely on maximizing the real value, which can lead to ineffective decisions in complex situations.</p><p><strong>On-the-fly strategy adjustment</strong>:</p><p>phase information in CVQ-learning allows the agent to adapt to changes in the environment in real time. For example, if the road becomes slippery, the agent can adjust its actions based on the phase shift, improving its ability to handle various situations. Regular Q-learning does not offer such a level of adaptation.</p><p><strong>Deeper state analysis</strong>:</p><p>the use of complex numbers allows for more complex mathematical operations on states and actions, potentially leading to more efficient updates of Q-values. For instance, phase coherence can be used to analyze the consistency of actions and states, which can enhance the overall strategy of the agent. In regular Q-learning, such analysis is limited and does not account for similar interactions.</p><p><strong>Overall learning efficiency</strong>:</p><p>as a result of all these factors, CVQ-learning can provide higher learning efficiency in vehicle control tasks. Agents utilizing complex representation can adapt more quickly to changing conditions and make more informed decisions, enhancing their ability to tackle real-world challenges. Regular Q-learning methods may struggle in similar situations, as they do not account for the complexity of parameter interactions.</p><p>These advantages make CVQ-learning particularly beneficial for tasks involving dynamic and complex environments, where the interaction between various parameters is critical for success.</p><p><strong>The full code of the lesson can be downloaded </strong><a href="https://github.com/Serhii-Barskyi/Complex-Valued-Reinforcement-Learning-course/blob/main/Complex_valued_Q_learning_Car_problem.ipynb"><strong>here</strong></a>.</p><p>In the next lesson, we’ll walk through a CVQ-learning code example for a maze problem with an efficient solution to the perceptual aliasing problem.</p><p><strong>For one-on-one tutoring on machine Reinforcement Learning topics, please, contact: </strong><a href="https://neuverso.ai/"><strong>https://neuverso.ai/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=393a25026520" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex-valued gradients in Reinforcement Learning]]></title>
            <link>https://medium.com/@serhii.barskyi/complex-valued-gradients-in-reinforcement-learning-560379a978ab?source=rss-6960a7e8ad52------2</link>
            <guid isPermaLink="false">https://medium.com/p/560379a978ab</guid>
            <category><![CDATA[neuverso]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[serhii-barskyi]]></category>
            <category><![CDATA[complex-valued-gradients]]></category>
            <category><![CDATA[deep-q-learning]]></category>
            <dc:creator><![CDATA[Serhii Barskyi]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 20:43:46 GMT</pubDate>
            <atom:updated>2026-05-02T07:36:50.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XFIUeyvNf_3O2Eyah7l-g.png" /></figure><p>My Data Science Course <a href="https://preply.com/en/tutor/7756455">https://preply.com/en/tutor/7756455</a></p><h3>Lesson 11: Complex-valued gradients in Reinforcement Learning</h3><h3>The Concept of Gradient in Complex Space</h3><p>The gradient is a vector that indicates the direction of the greatest change of a function. In complex space, unlike in real space, a function depends on two parts: the real and the imaginary. This expands the concept of the gradient to cases where the function takes and returns complex values. In real-world tasks, such as quantum physics, signal processing, and optimization, complex-valued functions play a key role. The complex gradient helps find the extrema of such functions and analyze their behavior.</p><p><strong>Complex Space</strong></p><p>In complex space, each variable is represented as a sum of real and imaginary parts. This space can be described using a pair of independent variables: z_real (the real part) and z_imag (the imaginary part). The gradient of a function in this space is computed considering the derivatives with respect to each of these variables. For example, the variable z can be expressed as:</p><pre>z = sp.Symbol(&#39;z&#39;)<br>z_real = sp.Symbol(&#39;z_real&#39;)<br>z_imag = sp.Symbol(&#39;z_imag&#39;)<br>z_eq = sp.Eq(z, z_real + sp.I * z_imag)<br>z_eq</pre><p>This expression shows that a complex number has two independent components, which are used in gradient computation. Thus, the gradient of a complex function depends on the derivatives with respect to both components.</p><p><strong>Functions in Complex Space</strong></p><p>Functions that depend on complex variables can also be divided into real and imaginary parts. The function f(z) can be represented as the sum of these two parts, simplifying the analysis of its derivatives. For example:</p><pre>f = sp.Function(&#39;f&#39;)(z)<br>f_real = sp.Function(&#39;f_real&#39;)(z_real, z_imag)<br>f_imag = sp.Function(&#39;f_imag&#39;)(z_real, z_imag)<br>f_complex = sp.Eq(f, f_real + sp.I * f_imag)<br>f_complex</pre><p>Here, f_real and f_imag are the components of the function that depend on the real and imaginary parts of the variable z. When analyzing functions in complex space, it is important to consider their separation into these two parts, as the derivatives will be calculated separately for each.</p><p><strong>Partial Derivatives with Respect to Real and Imaginary Parts</strong></p><p>To compute the gradient of a complex function, it is necessary to find its partial derivatives with respect to z_real and z_imag. This is done considering that each part of the function may depend differently on these variables. The derivative with respect to z_real expresses the change of the function along the real axis, while that with respect to z_imag does so along the imaginary axis:</p><pre>df_dz_real = sp.diff(f_real, z_real) + sp.I * sp.diff(f_imag, z_real)<br>df_dz_real<br><br>df_dz_imag = sp.diff(f_real, z_imag) + sp.I * sp.diff(f_imag, z_imag)<br>df_dz_imag</pre><p>These partial derivatives express how the function changes with respect to each component of the complex variable. They are the fundamental building blocks for computing the complex gradient.</p><p><strong>Gradient in Complex Space</strong></p><p>The gradient in complex space is a vector that combines the partial derivatives with respect to the real and imaginary parts of the variable z. This vector indicates the direction of the greatest change of the function in the complex number space. For a complex function f(z), the gradient is expressed as:</p><pre>grad_f = sp.Matrix([df_dz_real, df_dz_imag])<br>grad_f</pre><p>In this form, the gradient is a two-dimensional vector that reflects the change of the function along the two axes: z_real and z_imag. This is a key concept in analyzing functions in complex spaces, allowing exploration of their behavior as variables change.</p><p><strong>Complex-Conjugate Derivatives</strong></p><p>When working with functions dependent on complex variables, there arises a need to use complex-conjugate variables and derivatives. The complex conjugate of the variable z is denoted as z_conj, and its derivatives play an important role in analyzing functions. The complex-conjugate variable is defined as:</p><pre>z_conj = sp.conjugate(z)<br>z_conj</pre><p>The derivatives with respect to the complex-conjugate variable also influence the gradient and must be considered in the analysis:</p><pre>df_dz_conj = sp.diff(f_real, z_real) - sp.I * sp.diff(f_imag, z_real)<br>df_dz_conj</pre><p>Using conjugate variables and their derivatives is necessary for the correct calculation of the gradient and finding the extrema of complex functions.</p><p><strong>Example: Complex Function</strong></p><p>Let’s consider a specific example of a complex function f(z), where the function has the form:</p><pre>f_example = z**2 + sp.I * z<br>f_example</pre><p>For this function, we can compute the partial derivatives with respect to the real and imaginary parts:</p><pre>df_real_example = sp.diff(f_example, z_real)<br>df_imag_example = sp.diff(f_example, z_imag)<br>grad_example = sp.Matrix([df_real_example, df_imag_example])<br>grad_example</pre><p>This example illustrates how to compute the gradient of a function in complex space for a specific case. It is important to understand that such calculations help find the extrema of the function by analyzing its changes along the real and imaginary axes.</p><p><strong>Calculating the Magnitude of the Gradient</strong></p><p>The magnitude of the gradient in complex space is useful for optimization and analysis tasks. The gradient magnitude shows how significantly the function changes in a given direction. It can be computed as:</p><pre>grad_magnitude = sp.sqrt(df_real_example**2 + df_imag_example**2)<br>grad_magnitude</pre><p>The gradient magnitude is important for understanding the rate of change of the function and serves as a foundation for gradient descent methods in complex space.</p><p><strong>Task:</strong> Reinforcement learning in an environment with complex states, where agents utilize complex gradients to optimize their policies.</p><pre>import numpy as np<br><br># Complex agent weights<br>weights = np.array([0.5 + 1j, 0.3 - 0.4j])<br><br># Input state of the environment represented as a complex number<br>state = np.array([np.exp(1j * np.pi / 4), np.exp(1j * np.pi / 6)])<br><br># Weighted sum for decision-making<br>z = np.dot(weights, state)<br><br># Agent&#39;s activation function based on phase<br>action = np.angle(z)<br><br># Complex error gradient (with respect to weights)<br>error_gradient = np.conjugate(state) * (1 - action)<br><br># Updating agent weights based on complex gradient<br>learning_rate = 0.1<br>weights_new = weights + learning_rate * error_gradient<br><br>print(f&quot;Updated weights: {weights_new}&quot;)</pre><p>The gradient in complex space incorporates both the real and imaginary parts, expanding the agent’s ability to account for temporal and spatial changes. An important feature is the computation of derivatives with respect to complex variables, which is associated with the concept of complex analytic continuation.</p><p>The complex gradient is computed as the derivative of a function concerning a complex variable, which includes partial derivatives concerning both the real and imaginary parts. The gradient in complex space directs the change of model parameters towards the greatest increase of the loss function, but this increase can encompass changes in both phase and amplitude.</p><p>In complex space, the gradient can be computed through the complex derivative, which is based on the notion of holomorphicity. The concept of holomorphicity plays a crucial role in the theory of complex functions and imposes additional constraints on the form of functions, making the use of gradients more specific.</p><p>Unlike the real gradient, which focuses solely on the magnitude of the error, the complex gradient incorporates changes in both amplitude and phase. Learning in an environment with complex states allows for the consideration of the dynamics of temporal changes through phase and the influence of signal strength through amplitude.</p><p>Utilizing complex gradients enables agents to adjust not only the magnitude of the error but also its direction in a temporal or spatial context. In reinforcement learning, the complex gradient accounts for uncertainties encoded in phase.</p><p>In tasks involving cyclic processes, such as periodic changes in the environment, complex gradients may better adapt to phase shifts. The complex gradient also considers the direction of changes, which is important in tasks related to physical processes (e.g., movement in space).</p><p>Agents learning in environments with high temporal dependencies can use complex gradients for a better understanding of sequential actions. Interaction with phase in the complex gradient helps the agent to better comprehend changes in the environment that are not captured by ordinary numerical values.</p><p>The complex gradient can manage not only the magnitude but also the direction of changes, making it a flexible tool in optimization tasks. Real and complex gradients differ in that the latter can account for multidimensional dependencies, which is useful in tasks with multidimensional data.</p><p>In the complex plane, the gradient aims to reduce error in terms of both modulus and phase, enabling agents to adapt more accurately to changes. The notion of complex gradient is linked to the potential for exploring more complex dynamic processes involving temporal and cyclic dependencies.</p><p>Phase changes in reinforcement learning may be better accounted for using complex gradients, improving the accuracy of models. The complex gradient provides the opportunity to optimize not only the model’s error but also its temporal adaptability through phase shifts.</p><h3>Differences Between Complex Gradients and Real Gradients</h3><p>Complex gradients and real gradients are used to analyze functions, but their differences have significant implications for optimization methods and computations. It is important to note that with the correct representation of data, complex gradients can offer deeper insights and improved results. These differences are rooted in the structure of complex numbers and the characteristics of functions dependent on real and imaginary components. In this lesson, we will explore the main differences between complex and real gradients, highlighting the advantages of complex approaches.</p><p><strong>Space and Independent Variables</strong></p><p>In real space, functions depend on one or more real variables. For example, a function f(x, y) may depend on two real variables. In contrast, complex functions depend on complex variables, allowing for more efficient modeling of data and interactions. For instance, representing a variable z as z = x + iy opens new horizons for analysis. Thus, the gradient of a complex function can be expressed as:</p><pre>z = sp.Symbol(&#39;z&#39;)<br>f_complex = sp.Function(&#39;f_complex&#39;)(z)<br>grad_complex = sp.Matrix([sp.diff(f_complex, z.real), sp.diff(f_complex, z.imag)])<br>grad_complex</pre><p>This structure allows for better consideration of relationships between variables and can lead to more effective solutions in optimization problems.</p><p><strong>Complexity and Structure of the Gradient</strong></p><p>Complex gradients possess a more intricate structure as they account for the interaction between the real and imaginary parts. This means that changes in one part (real or imaginary) can influence the other, allowing for finer model adjustments. For example:</p><pre>f = z**2 + sp.I * z<br>df_dz_real = sp.diff(f, z.real)<br>df_dz_imag = sp.diff(f, z.imag)</pre><p>Comparing this to real gradients shows that, in the latter, changes in one variable do not affect the other. This makes the analysis more complex in complex space, but also more useful for tasks that require consideration of intricate dependencies.</p><p><strong>Complex Conjugate and Gradients</strong></p><p>When working with complex gradients, it is important to consider the complex conjugate. This allows for the analysis of functions and their derivatives while accounting for the influence of the imaginary part on the results. For example, if z is a complex number, its conjugate is denoted as z_conj, and its influence on the gradient can be written as:</p><pre>z_conj = sp.conjugate(z)<br>df_dz_conj = sp.diff(f, z_conj)</pre><p>This characteristic helps to more comprehensively account for the behavior of functions and their gradients. Unlike in real space, where derivatives depend only on real values, the complex conjugate allows for a more accurate modeling of complex systems.</p><p><strong>Optimization and Application of Gradients</strong></p><p>In the context of optimization, complex gradients often prove to be more effective as they allow for the consideration of more information about interactions between variables. When dealing with tasks where functions may take complex values, using complex gradients can lead to more accurate and faster algorithms. For example:</p><pre>f_example = sp.exp(z)<br>grad_example = sp.Matrix([sp.diff(f_example, z.real), sp.diff(f_example, z.imag)])</pre><p>Unlike real gradients, which have a more predictable nature, complex gradients require greater attention to the function’s structure. This can result in the creation of more complex models that can solve problems more efficiently.</p><p><strong>Continuity and Differentiability</strong></p><p>Complex functions impose special requirements on continuity and differentiability conditions. For the analyticity of functions dependent on complex variables, the Cauchy-Riemann conditions must be satisfied. This requires that the partial derivatives with respect to the real and imaginary parts are related in a specific way:</p><pre>u = sp.Function(&#39;u&#39;)(z.real, z.imag)<br>v = sp.Function(&#39;v&#39;)(z.real, z.imag)<br>Cauchy_Riemann = sp.Eq(sp.diff(u, z.real), sp.diff(v, z.imag)) &amp; sp.Eq(sp.diff(u, z.imag), -sp.diff(v, z.real))<br>Cauchy_Riemann</pre><p>In real space, such conditions are not required, making function analysis simpler but less flexible. For tasks where it is important to consider complex interactions, the Cauchy-Riemann conditions allow for the construction of more sophisticated models.</p><p>Understanding the differences between complex and real gradients opens new horizons for the analysis and optimization of functions in various fields of science and engineering. Complex gradients, when properly represented, can be more effective in solving problems due to their ability to account for complex dependencies between variables. Considering the interactions between real and imaginary parts, along with the conditions for analyticity, makes the analysis of complex functions more rigorous and profound. These differences are crucial for practical applications in optimization and data analysis, allowing for the use of complex approaches to achieve better results.</p><p><strong>Task:</strong> Controlling a robot’s movement in an environment using complex gradients to account for spatial and temporal changes.</p><pre># Complex signals representing the robot&#39;s movement<br>robot_position = np.array([1.0 + 0.5j, 0.8 + 0.6j])<br><br># Complex weights for controlling movement<br>weights = np.array([0.7 + 0.3j, 0.5 + 0.2j])<br><br># Weighted sum to compute the direction of movement<br>z = np.dot(weights, robot_position)<br><br># Complex error gradient<br>error_gradient = np.conjugate(robot_position) * (1 - np.abs(z))<br><br># Updating weights based on the complex gradient<br>learning_rate = 0.05<br>weights_new = weights + learning_rate * error_gradient<br><br>print(f&quot;Updated robot weights: {weights_new}&quot;)</pre><p>The main distinction between complex gradients and real gradients is that complex gradients take into account both real and imaginary components, expanding the optimization space. They work with both phase and amplitude simultaneously, while real gradients focus solely on magnitude.</p><p>Complex gradients are more sensitive to temporal changes because phase is directly linked to time dependencies. In robotics, they allow for considering changes in the robot’s movement caused by phase shifts and correcting direction.</p><h4>Features of Complex Gradients</h4><blockquote>- Capable of changing both amplitude and direction. <br>- The real part corrects amplitude, while the imaginary part manages phase correction. <br>- Account for direction and the rate of changes in multidimensional space. <br>- Effective for tasks with high dynamic changes. <br>- Use phase to account for time intervals. <br>- Ensure better convergence in cyclic processes.</blockquote><p>Working with complex gradients makes learning more flexible and adaptive. They address tasks where spatial changes impact temporal dependencies and enhance the convergence of algorithms in unpredictable situations.</p><h4>Application in Robotics and Reinforcement Learning</h4><p>Complex gradients aid in modeling complex dependencies between the states and actions of an agent. In robotics, they account for changes in both speed and phases of movements.</p><p>The imaginary part of the gradient, which is responsible for phase changes, is valuable for tasks involving temporal delays. Complex gradients can model intricate changes in the environment and account for variations in both direction and intensity, which is useful for optimizing movement tasks.</p><h3>Mathematical Justification for Using Complex Gradients in Reinforcement Learning (RL)</h3><p>Reinforcement Learning (RL) has become an important area in machine learning, where agents learn to optimize their actions in an environment based on rewards. In recent years, the use of complex gradients has been explored to enhance RL algorithms. Complex gradients allow for a deeper understanding of the relationships between agent states and actions than traditional real gradients. In this lesson, we will discuss the mathematical foundations supporting the use of complex gradients in the context of RL.</p><h4>Overview of Gradients in the Context of RL</h4><p>In RL, agents aim to maximize expected rewards, often formulated through a value function V(s) or an action function Q(s, a). The gradients of these functions play a key role in updating agent strategies. For the value function, the gradient can be expressed as follows:</p><pre>V = sp.Function(&#39;V&#39;)(s)<br>grad_V = sp.Matrix([sp.diff(V, s)])</pre><p>However, when using complex gradients, there is an opportunity to analyze the dependence between states and actions more effectively. This opens new horizons for algorithms, allowing for the consideration of both real and imaginary aspects of the value function.</p><h4>Complex Gradients and Analytic Functions</h4><p>One of the key advantages of complex gradients is their connection to analytic functions. For a function f(z) on the complex plane, where z = x + iy, the gradient can be defined through partial derivatives:</p><pre>f = sp.Function(&#39;f&#39;)(z)<br>grad_f = sp.Matrix([sp.diff(f, z.real), sp.diff(f, z.imag)])</pre><p>The function must satisfy the Cauchy-Riemann conditions, ensuring additional properties such as continuity and differentiability. These properties can be leveraged to enhance the stability of RL algorithms. For example, the use of complex gradients can provide a smoother parameter space, leading to more efficient updates.</p><h4>Updating Strategies with Complex Gradients</h4><p>When an agent updates its strategies based on rewards, the use of complex gradients allows for consideration of broader aspects, including interactions between actions and states. This can be particularly useful in multidimensional spaces where interactions become complex. The weight updates in the agent’s neural network can be expressed as follows:</p><pre>theta = sp.Symbol(&#39;theta&#39;)<br>alpha = sp.Symbol(&#39;alpha&#39;)  # learning rate<br>reward = sp.Function(&#39;reward&#39;)(s, a)  # reward<br>Q = sp.Function(&#39;Q&#39;)(s, a)<br><br># Weight update using complex gradient<br>update = theta + alpha * (reward + sp.Max(Q) - Q) * grad_f<br>update</pre><p>Thus, updates based on complex gradients can improve the convergence of algorithms, providing more accurate steps toward the optimum.</p><h4>Comparison with Real Gradients</h4><p>Unlike real gradients, which may suffer from local minimum issues, complex gradients offer additional opportunities. Specifically, the use of complex numbers can help avoid certain problems associated with asymmetric gradient boundaries. This can be demonstrated through the use of complex conjugation:</p><pre>z_conj = sp.conjugate(z)<br>grad_conjugate = sp.diff(f, z_conj)</pre><p>Such representations help account for symmetry in problem-solving and can lead to more stable weight updates. This is particularly important in RL tasks where instability can result in poor agent performance.</p><h4>Application in Multitask Learning</h4><p>Complex gradients can be especially useful in the context of multitask learning, where an agent must handle multiple tasks simultaneously. Complex numbers allow for the integration of information from different tasks, which can enhance the overall learning process. For instance, an agent can use the same function to represent various tasks in complex form:</p><pre>task1 = sp.Function(&#39;task1&#39;)(z)<br>task2 = sp.Function(&#39;task2&#39;)(z)<br><br># Combining tasks into a complex function<br>combined_task = task1 + sp.I * task2<br>grad_combined = sp.diff(combined_task, z)</pre><p>This enables the creation of more general and powerful models that can adapt to different conditions and task requirements, leading to improved performance.</p><p>The mathematical justification for using complex gradients in reinforcement learning is based on their ability to more deeply consider the relationships between states and actions of agents. Complex gradients offer advantages in terms of smoothness, stability, and multitasking, making them particularly suitable for complex RL tasks. Implementing these concepts can significantly enhance the efficiency of learning algorithms, allowing agents to achieve better outcomes in challenging environments. Thus, the exploration and application of complex gradients open new horizons in the field of machine learning and artificial intelligence.</p><p><strong>Task:</strong> Optimization of the Cost Function in Reinforcement Learning Using Complex Gradients</p><pre># Complex states and actions of the agent<br>state_action = np.array([0.7 + 0.2j, 0.9 + 0.1j])<br><br># Weights for optimization<br>weights = np.array([0.6 + 0.3j, 0.4 + 0.2j])<br><br># Weighted sum for calculating Q-values<br>q_value = np.dot(weights, state_action)<br><br># Cost function for reinforcement learning<br>cost = np.abs(1 - q_value)<br><br># Complex gradient of the cost function<br>cost_gradient = np.conjugate(state_action) * (1 - cost)<br><br># Update weights based on the cost function gradient<br>learning_rate = 0.1<br>weights_new = weights + learning_rate * cost_gradient<br><br>print(f&quot;Updated weights: {weights_new}&quot;)</pre><p>The interaction of phase and amplitude changes in the complex gradient enhances the optimization process in complex environments, increasing the agent’s adaptability in highly dynamic conditions.</p><h3>Advantages of Complex Gradients in Reinforcement Learning</h3><p>Reinforcement Learning (RL) is a machine learning method where agents learn to make decisions based on rewards received from the environment. In recent years, the use of complex gradients has been explored to enhance RL algorithms. Complex gradients provide unique advantages that can lead to more effective learning, improved convergence, and adaptation to complex tasks. In this lesson, we will examine the key advantages of complex gradients in the context of reinforcement learning.</p><p><strong>Improved Convergence</strong></p><p>One of the main advantages of complex gradients is their ability to provide faster convergence of algorithms. Thanks to the additional properties of complex numbers, such as symmetry and analyticity, more efficient parameter updates can be achieved. When using complex gradients, the weight update can be expressed as follows:</p><pre>theta = sp.Symbol(&#39;theta&#39;)<br>alpha = sp.Symbol(&#39;alpha&#39;)  # learning rate<br>reward = sp.Function(&#39;reward&#39;)(s, a)<br>Q = sp.Function(&#39;Q&#39;)(s, a)<br><br># Weight update using complex gradient<br>update = theta + alpha * (reward + sp.Max(Q) - Q) * sp.diff(f, z)</pre><p>This structure allows agents to take more precise steps towards the optimum, which can, in turn, lead to faster attainment of desired outcomes.</p><p><strong>Resistance to Local Minima</strong></p><p>Complex gradients help avoid issues associated with local minima that often arise when using real gradients. Since complex gradients consider both the real and imaginary parts, they can provide a broader view of the parameter space. This allows agents to “jump” over local minima, ensuring more effective learning:</p><pre>z = sp.Symbol(&#39;z&#39;)  # complex number<br>grad = sp.diff(f, z)<br>conjugate_grad = sp.diff(f, sp.conjugate(z))</pre><p>Thus, the use of complex gradients can significantly enhance the performance of RL algorithms by reducing the likelihood of getting stuck in unsuitable solutions.</p><p><strong>Adaptation to Complex Tasks</strong></p><p>Complex gradients allow for better adaptation to complex and multidimensional tasks often encountered in RL. In such cases, interactions between variables can be intricate and nonlinear. Complex gradients can account for these interactions more effectively, enabling agents to better understand the structure of the task. For example, different tasks can be combined into a single complex function:</p><pre>task1 = sp.Function(&#39;task1&#39;)(z)<br>task2 = sp.Function(&#39;task2&#39;)(z)<br><br># Complex representation of tasks<br>combined_task = task1 + sp.I * task2<br>grad_combined = sp.diff(combined_task, z)</pre><p>This combination allows the agent to consider multiple factors, improving its learning capability.</p><p><strong>Improved Generalization Ability</strong></p><p>The use of complex gradients can enhance the generalization ability of algorithms, which is a key aspect of RL. Agents using complex representations can better process data, extracting common patterns from various sources. This is especially important in the context of multitask learning, where adaptation to changes in the environment is necessary. For example, a complex weight update might look like this:</p><pre>weights = sp.Matrix([theta1, theta2])<br>combined_reward = sp.Function(&#39;combined_reward&#39;)(s, a)<br><br># Weight update based on complex gradient<br>update_weights = weights + alpha * (combined_reward - Q) * grad_combined</pre><p>This generalization ability allows agents to act more effectively in various scenarios, thereby enhancing their overall learning efficiency.</p><p><strong>Opportunities for Advanced Architectures</strong></p><p>Complex gradients open new opportunities for the development of advanced architectures, such as deep neural networks with complex parameters. These architectures can leverage the advantages of complex numbers to improve data representation and increase computational efficiency. For example, using complex weights in a neural network enables the creation of more sophisticated models that can capture subtle aspects of the data:</p><pre>complex_weights = sp.Matrix([[sp.Symbol(&#39;w_real&#39;), sp.Symbol(&#39;w_imag&#39;)]])<br><br># Weight update in a neural network<br>complex_update = complex_weights + alpha * grad_combined</pre><p>This extension significantly enhances the power and flexibility of RL algorithms.</p><p><strong>Task:</strong> Optimization of Agent Actions in a Multidimensional Environment Using Complex Gradients)</p><pre># Complex states and actions of the agent in a multidimensional environment<br>state_action = np.array([0.8 + 0.3j, 0.6 + 0.4j])<br><br># Weights for optimization<br>weights = np.array([0.5 + 0.2j, 0.7 + 0.1j])<br><br># Weighted sum for calculating Q-values<br>q_value = np.dot(weights, state_action)<br><br># Complex gradient based on error<br>error_gradient = np.conjugate(state_action) * (1 - q_value)<br><br># Weight update based on complex gradient<br>learning_rate = 0.1<br>weights_new = weights + learning_rate * error_gradient<br><br>print(f&quot;Updated weights: {weights_new}&quot;)</pre><p>The use of complex gradients enhances the agent’s ability to generalize, especially in tasks with multidimensional relationships between states and actions. Complex gradients enable agents to adapt more precisely to changes in the environment, reducing the number of necessary learning steps.</p><p>In the next lesson, we’ll look at working with complex-valued data using multi-valued <a href="https://medium.com/@serhii.barskyi/aisenberg-neuron-in-complex-valued-reinforcement-learning-tasks-dc4a8f53cc1d">Aizenberg neurons</a> (MVN), and how Derivative-free learning methods can be effective in complex-valued reinforcement learning (CVRL).</p><p><strong>For one-on-one tutoring on machine Reinforcement Learning topics, please, contact: </strong><a href="https://neuverso.ai/"><strong>https://neuverso.ai/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=560379a978ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>