How to calculate sums across matrix diagonals in Tensorflow?Calling a function of a module by using its name (a string)How to merge two dictionaries in a single expression?How to remove an element from a list by index?What is a clean, pythonic way to have multiple constructors in Python?How to leave/exit/deactivate a Python virtualenvDifference between numpy.array shape (R, 1) and (R,)How to print the value of a Tensor object in TensorFlow?Get the diagonal of a matrix in TensorFlowBlock Diagonal Matrices in Tensorflowtensorflow - multiply a vector of matrices against each matrix in another vector

Redox reactions redefined

Crab Nebula short story from 1960s or '70s

Filtering fine silt/mud from water (not necessarily bacteria etc.)

Are L-functions uniquely determined by their values at negative integers?

Align by center of symbol

Too many spies!

Why do they not say "The Baby"

Is a public company able to check out who owns its shares in very detailed format?

Is killing off one of my queer characters homophobic?

Alternatives to using writing paper for writing practice

(algebraic topology) question about the cellular approximation theorem

Why does the Earth have a z-component at the start of the J2000 epoch?

What is the closed form of the following recursive function?

Do native speakers use ZVE or CPU?

Is this more than a packing puzzle?

What exactly is the Tension force?

Does entangle require vegetation?

What are some symbols representing peasants/oppressed persons fighting back?

Remove intersect line for one circle using venndiagram2sets

How can I legally visit the United States Minor Outlying Islands in the Pacific?

Why hasn't the U.S. government paid war reparations to any country it attacked?

What is the English equivalent of 干物女 (dried fish woman)?

What's the phrasal verb for carbonated drinks exploding out of the can after being shaken?

How long do Apple retain notifications to be pushed to iOS devices until they expire?



How to calculate sums across matrix diagonals in Tensorflow?


Calling a function of a module by using its name (a string)How to merge two dictionaries in a single expression?How to remove an element from a list by index?What is a clean, pythonic way to have multiple constructors in Python?How to leave/exit/deactivate a Python virtualenvDifference between numpy.array shape (R, 1) and (R,)How to print the value of a Tensor object in TensorFlow?Get the diagonal of a matrix in TensorFlowBlock Diagonal Matrices in Tensorflowtensorflow - multiply a vector of matrices against each matrix in another vector






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















Say, I have matrix 4x4 like:



1 2 3 4
5 6 7 8
4 3 2 1
8 7 6 5`


I want to get matrix 2*4-1 with elements like:



8
4+7
5+3+6
1+6+2+5
2+7+1
3+8
4


How can I do that in Tensorflow? With tensors, of course - I have tensor with shape [a,b,c,..,l,n,n] and want to get tensor with shape [a,b,c,...,l,2*n-1]. Is there any single function to do this or looping is the only way?










share|improve this question






























    2















    Say, I have matrix 4x4 like:



    1 2 3 4
    5 6 7 8
    4 3 2 1
    8 7 6 5`


    I want to get matrix 2*4-1 with elements like:



    8
    4+7
    5+3+6
    1+6+2+5
    2+7+1
    3+8
    4


    How can I do that in Tensorflow? With tensors, of course - I have tensor with shape [a,b,c,..,l,n,n] and want to get tensor with shape [a,b,c,...,l,2*n-1]. Is there any single function to do this or looping is the only way?










    share|improve this question


























      2












      2








      2








      Say, I have matrix 4x4 like:



      1 2 3 4
      5 6 7 8
      4 3 2 1
      8 7 6 5`


      I want to get matrix 2*4-1 with elements like:



      8
      4+7
      5+3+6
      1+6+2+5
      2+7+1
      3+8
      4


      How can I do that in Tensorflow? With tensors, of course - I have tensor with shape [a,b,c,..,l,n,n] and want to get tensor with shape [a,b,c,...,l,2*n-1]. Is there any single function to do this or looping is the only way?










      share|improve this question
















      Say, I have matrix 4x4 like:



      1 2 3 4
      5 6 7 8
      4 3 2 1
      8 7 6 5`


      I want to get matrix 2*4-1 with elements like:



      8
      4+7
      5+3+6
      1+6+2+5
      2+7+1
      3+8
      4


      How can I do that in Tensorflow? With tensors, of course - I have tensor with shape [a,b,c,..,l,n,n] and want to get tensor with shape [a,b,c,...,l,2*n-1]. Is there any single function to do this or looping is the only way?







      python tensorflow






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 6:35







      rx303

















      asked Mar 26 at 6:26









      rx303rx303

      314 bronze badges




      314 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          You can use tf.py_func to wrap a numpy function.



          import tensorflow as tf
          import numpy as np

          def np_all_trace_sum(a):
          n = a.shape[-1]
          all_trace_sum = [a.trace(i,axis1=-1,axis2=-2) for i in range(n-1,-n,-1)] # shape = (2*n-1,a,b,c,..,l)
          return np.moveaxis(all_trace_sum,0,-1) # shape = (a,b,c,..,l,2*n-1)

          A = tf.placeholder(shape=[None,None,4,4],dtype=tf.float32)
          result = tf.py_func(np_all_trace_sum, [A], tf.float32)

          a = np.array([[1,2,3,4],[5,6,7,8],[4,3,2,1],[8,7,6,5]])

          with tf.Session() as sess:
          print(sess.run(result,feed_dict=A:[[a,a,a],[a,a,a]]))

          [[[ 8. 11. 14. 14. 10. 11. 4.]
          [ 8. 11. 14. 14. 10. 11. 4.]
          [ 8. 11. 14. 14. 10. 11. 4.]]

          [[ 8. 11. 14. 14. 10. 11. 4.]
          [ 8. 11. 14. 14. 10. 11. 4.]
          [ 8. 11. 14. 14. 10. 11. 4.]]]





          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55350988%2fhow-to-calculate-sums-across-matrix-diagonals-in-tensorflow%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You can use tf.py_func to wrap a numpy function.



            import tensorflow as tf
            import numpy as np

            def np_all_trace_sum(a):
            n = a.shape[-1]
            all_trace_sum = [a.trace(i,axis1=-1,axis2=-2) for i in range(n-1,-n,-1)] # shape = (2*n-1,a,b,c,..,l)
            return np.moveaxis(all_trace_sum,0,-1) # shape = (a,b,c,..,l,2*n-1)

            A = tf.placeholder(shape=[None,None,4,4],dtype=tf.float32)
            result = tf.py_func(np_all_trace_sum, [A], tf.float32)

            a = np.array([[1,2,3,4],[5,6,7,8],[4,3,2,1],[8,7,6,5]])

            with tf.Session() as sess:
            print(sess.run(result,feed_dict=A:[[a,a,a],[a,a,a]]))

            [[[ 8. 11. 14. 14. 10. 11. 4.]
            [ 8. 11. 14. 14. 10. 11. 4.]
            [ 8. 11. 14. 14. 10. 11. 4.]]

            [[ 8. 11. 14. 14. 10. 11. 4.]
            [ 8. 11. 14. 14. 10. 11. 4.]
            [ 8. 11. 14. 14. 10. 11. 4.]]]





            share|improve this answer



























              1














              You can use tf.py_func to wrap a numpy function.



              import tensorflow as tf
              import numpy as np

              def np_all_trace_sum(a):
              n = a.shape[-1]
              all_trace_sum = [a.trace(i,axis1=-1,axis2=-2) for i in range(n-1,-n,-1)] # shape = (2*n-1,a,b,c,..,l)
              return np.moveaxis(all_trace_sum,0,-1) # shape = (a,b,c,..,l,2*n-1)

              A = tf.placeholder(shape=[None,None,4,4],dtype=tf.float32)
              result = tf.py_func(np_all_trace_sum, [A], tf.float32)

              a = np.array([[1,2,3,4],[5,6,7,8],[4,3,2,1],[8,7,6,5]])

              with tf.Session() as sess:
              print(sess.run(result,feed_dict=A:[[a,a,a],[a,a,a]]))

              [[[ 8. 11. 14. 14. 10. 11. 4.]
              [ 8. 11. 14. 14. 10. 11. 4.]
              [ 8. 11. 14. 14. 10. 11. 4.]]

              [[ 8. 11. 14. 14. 10. 11. 4.]
              [ 8. 11. 14. 14. 10. 11. 4.]
              [ 8. 11. 14. 14. 10. 11. 4.]]]





              share|improve this answer

























                1












                1








                1







                You can use tf.py_func to wrap a numpy function.



                import tensorflow as tf
                import numpy as np

                def np_all_trace_sum(a):
                n = a.shape[-1]
                all_trace_sum = [a.trace(i,axis1=-1,axis2=-2) for i in range(n-1,-n,-1)] # shape = (2*n-1,a,b,c,..,l)
                return np.moveaxis(all_trace_sum,0,-1) # shape = (a,b,c,..,l,2*n-1)

                A = tf.placeholder(shape=[None,None,4,4],dtype=tf.float32)
                result = tf.py_func(np_all_trace_sum, [A], tf.float32)

                a = np.array([[1,2,3,4],[5,6,7,8],[4,3,2,1],[8,7,6,5]])

                with tf.Session() as sess:
                print(sess.run(result,feed_dict=A:[[a,a,a],[a,a,a]]))

                [[[ 8. 11. 14. 14. 10. 11. 4.]
                [ 8. 11. 14. 14. 10. 11. 4.]
                [ 8. 11. 14. 14. 10. 11. 4.]]

                [[ 8. 11. 14. 14. 10. 11. 4.]
                [ 8. 11. 14. 14. 10. 11. 4.]
                [ 8. 11. 14. 14. 10. 11. 4.]]]





                share|improve this answer













                You can use tf.py_func to wrap a numpy function.



                import tensorflow as tf
                import numpy as np

                def np_all_trace_sum(a):
                n = a.shape[-1]
                all_trace_sum = [a.trace(i,axis1=-1,axis2=-2) for i in range(n-1,-n,-1)] # shape = (2*n-1,a,b,c,..,l)
                return np.moveaxis(all_trace_sum,0,-1) # shape = (a,b,c,..,l,2*n-1)

                A = tf.placeholder(shape=[None,None,4,4],dtype=tf.float32)
                result = tf.py_func(np_all_trace_sum, [A], tf.float32)

                a = np.array([[1,2,3,4],[5,6,7,8],[4,3,2,1],[8,7,6,5]])

                with tf.Session() as sess:
                print(sess.run(result,feed_dict=A:[[a,a,a],[a,a,a]]))

                [[[ 8. 11. 14. 14. 10. 11. 4.]
                [ 8. 11. 14. 14. 10. 11. 4.]
                [ 8. 11. 14. 14. 10. 11. 4.]]

                [[ 8. 11. 14. 14. 10. 11. 4.]
                [ 8. 11. 14. 14. 10. 11. 4.]
                [ 8. 11. 14. 14. 10. 11. 4.]]]






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 26 at 9:44









                giser_yuganggiser_yugang

                4,1472 gold badges9 silver badges30 bronze badges




                4,1472 gold badges9 silver badges30 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55350988%2fhow-to-calculate-sums-across-matrix-diagonals-in-tensorflow%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript